1erl_driver(3)                 C Library Functions                erl_driver(3)
2
3
4

NAME

6       erl_driver - API functions for an Erlang driver.
7

DESCRIPTION

9       An  Erlang  driver is a library containing a set of native driver call‐
10       back functions that the  Erlang  Virtual  Machine  calls  when  certain
11       events  occur.  There  can  be  multiple  instances  of  a driver, each
12       instance is associated with an Erlang port.
13
14   Warning:
15       Use this functionality with extreme care.
16
17       A driver callback is executed as a direct extension of the native  code
18       of  the  VM. Execution is not made in a safe environment. The VM cannot
19       provide the same services as provided when executing Erlang code,  such
20       as  pre-emptive scheduling or memory protection. If the driver callback
21       function does not behave well, the whole VM will misbehave.
22
23         * A driver callback that crash will crash the whole VM.
24
25         * An erroneously implemented driver callback can cause a VM  internal
26           state  inconsistency, which can cause a crash of the VM, or miscel‐
27           laneous misbehaviors of the VM at any point after the call  to  the
28           driver callback.
29
30         * A  driver  callback  doing  lengthy  work before returning degrades
31           responsiveness of the VM and can cause miscellaneous strange behav‐
32           iors.  Such  strange  behaviors  include,  but  are not limited to,
33           extreme memory usage and bad  load  balancing  between  schedulers.
34           Strange  behaviors  that can occur because of lengthy work can also
35           vary between Erlang/OTP releases.
36
37       As from ERTS 5.5.3 the driver interface has been extended (see extended
38       marker). The extended interface introduces version management, the pos‐
39       sibility to pass capability flags (see  driver_flags)  to  the  runtime
40       system at driver initialization, and some new driver API functions.
41
42   Note:
43       As  from  ERTS  5.9 old drivers must be recompiled and use the extended
44       interface. They must also be adjusted to  the   64-bit  capable  driver
45       interface.
46
47
48       The driver calls back to the emulator, using the API functions declared
49       in erl_driver.h. They are used for outputting  data  from  the  driver,
50       using timers, and so on.
51
52       Each  driver  instance is associated with a port. Every port has a port
53       owner process. Communication with the port is normally done through the
54       port  owner  process.  Most of the functions take the port handle as an
55       argument. This identifies the driver instance. Notice  that  this  port
56       handle must be stored by the driver, it is not given when the driver is
57       called from the emulator (see driver_entry).
58
59       Some of the functions take a parameter of type ErlDrvBinary,  a  driver
60       binary.  It  is  to  be both allocated and freed by the caller. Using a
61       binary directly avoids one extra copying of data.
62
63       Many of the output functions have a "header buffer", with hbuf and hlen
64       parameters.  This  buffer is sent as a list before the binary (or list,
65       depending on port mode) that is sent. This is convenient when  matching
66       on messages received from the port. (Although in the latest Erlang ver‐
67       sions there is the binary syntax, which enables you  to  match  on  the
68       beginning of a binary.)
69
70       In  the  runtime  system with SMP support, drivers are locked either on
71       driver level or port level (driver instance level). By  default  driver
72       level locking will be used, that is, only one emulator thread will exe‐
73       cute code in the driver at a time. If port level locking is used,  mul‐
74       tiple emulator threads can execute code in the driver at the same time.
75       Only one thread at a time will call driver callbacks  corresponding  to
76       the   same  port,  though.  To  enable  port  level  locking,  set  the
77       ERL_DRV_FLAG_USE_PORT_LOCKING driver flag in the driver_entry  used  by
78       the  driver.  When  port  level  locking  is used, the driver writer is
79       responsible for synchronizing all accesses to data shared by the  ports
80       (driver instances).
81
82       Most drivers written before the runtime system with SMP support existed
83       can run in the runtime system with SMP support, without  being  rewrit‐
84       ten, if driver level locking is used.
85
86   Note:
87       It  is  assumed  that  drivers  do not access other drivers. If drivers
88       access each other, they must provide their own  mechanism  for  thread-
89       safe  synchronization.  Such  "inter-driver  communication" is strongly
90       discouraged.
91
92
93       Previously, in the runtime system without SMP support, specific  driver
94       callbacks were always called from the same thread. This is not the case
95       in the runtime system with SMP support. Regardless  of  locking  scheme
96       used, calls to driver callbacks can be made from different threads. For
97       example, two consecutive calls to exactly the same callback for exactly
98       the  same port can be made from two different threads. This is for most
99       drivers not a problem, but it can be. Drivers that depend on all  call‐
100       backs that are called in the same thread, must be rewritten before they
101       are used in the runtime system with SMP support.
102
103   Note:
104       Regardless of locking scheme used, calls to  driver  callbacks  can  be
105       made from different threads.
106
107
108       Most functions in this API are not thread-safe, that is, they cannot be
109       called from any thread. Functions that are not  documented  as  thread-
110       safe  can  only  be  called  from  driver  callbacks  or function calls
111       descending from a driver callback call. Notice  that  driver  callbacks
112       can  be  called from different threads. This, however, is not a problem
113       for any function in this API, as the emulator has  control  over  these
114       threads.
115
116   Warning:
117       Functions not explicitly documented as thread-safe are not thread safe.
118       Also notice that some functions are only thread-safe  when  used  in  a
119       runtime system with SMP support.
120
121       A  function not explicitly documented as thread-safe can, at some point
122       in time, have a thread-safe implementation in the runtime system.  Such
123       an  implementation can however change to a thread unsafe implementation
124       at any time without any notice.
125
126       Only use functions explicitly documented as thread-safe from  arbitrary
127       threads.
128
129
130       As  mentioned  in the warning text at the beginning of this section, it
131       is of vital importance that a driver callback returns relatively  fast.
132       It  is  difficult to give an exact maximum amount of time that a driver
133       callback is allowed to work, but usually a well-behaving  driver  call‐
134       back is to return within 1 millisecond. This can be achieved using dif‐
135       ferent approaches. If you have full control over the code to execute in
136       the  driver callback, the best approach is to divide the work into mul‐
137       tiple chunks of work, and trigger multiple calls to the time-out  call‐
138       back  using  zero  time-outs. Function erl_drv_consume_timeslice can be
139       useful to determine when to trigger such time-out callback calls.  How‐
140       ever,  sometimes  it  cannot  be implemented this way, for example when
141       calling third-party libraries. In this case, you typically want to dis‐
142       patch  the  work to another thread. Information about thread primitives
143       is provided below.
144

FUNCTIONALITY

146       All functions that a driver needs  to  do  with  Erlang  are  performed
147       through  driver  API functions. Functions exist for the following func‐
148       tionality:
149
150         Timer functions:
151           Control the timer that a driver can use. The timer has the emulator
152           call  the  timeout  entry function after a specified time. Only one
153           timer is available for each driver instance.
154
155         Queue handling:
156           Every driver instance has an associated queue. This queue is a Sys‐
157           IOVec, which works as a buffer. It is mostly used for the driver to
158           buffer data that is to be written to a device, it is a byte stream.
159           If  the  port owner process closes the driver, and the queue is not
160           empty, the driver is not closed. This enables the driver  to  flush
161           its buffers before closing.
162
163           The  queue  can be manipulated from any threads if a port data lock
164           is used. For more information, see ErlDrvPDL.
165
166         Output functions:
167           With these functions, the driver sends data back to  the  emulator.
168           The  data  is  received  as messages by the port owner process, see
169           erlang:open_port/2. The vector function and the function  taking  a
170           driver  binary  are  faster, as they avoid copying the data buffer.
171           There is also a fast way of sending terms from the driver,  without
172           going through the binary term format.
173
174         Failure:
175           The  driver  can  exit and signal errors up to Erlang. This is only
176           for severe errors, when the driver cannot possibly keep open.
177
178         Asynchronous calls:
179           Erlang/OTP R7B and later versions have provision  for  asynchronous
180           function  calls,  using  a thread pool provided by Erlang. There is
181           also a select call, which can be used for asynchronous drivers.
182
183         Multi-threading:
184           A POSIX thread like API for multi-threading is provided. The Erlang
185           driver  thread API only provides a subset of the functionality pro‐
186           vided by the POSIX thread API. The subset provided is more or  less
187           the basic functionality needed for multi-threaded programming:
188
189           * Threads
190
191           * Mutexes
192
193           *
194              Condition variables
195
196           *
197              Read/write locks
198
199           *
200              Thread-specific data
201
202           The  Erlang  driver  thread API can be used in conjunction with the
203           POSIX thread API on UN-ices and with the Windows native thread  API
204           on Windows. The Erlang driver thread API has the advantage of being
205           portable, but there can exist situations  where  you  want  to  use
206           functionality  from  the  POSIX  thread  API  or the Windows native
207           thread API.
208
209           The Erlang driver thread API only returns error codes  when  it  is
210           reasonable to recover from an error condition. If it is not reason‐
211           able to recover from an error condition, the whole  runtime  system
212           is  terminated.  For example, if a create mutex operation fails, an
213           error code is returned, but if a lock operation on a  mutex  fails,
214           the whole runtime system is terminated.
215
216           Notice  that there is no "condition variable wait with time-out" in
217           the  Erlang  driver  thread  API.  This  because  of  issues   with
218           pthread_cond_timedwait.  When the system clock suddenly is changed,
219           it is not always guaranteed that you will wake up from the call  as
220           expected. An Erlang runtime system must be able to cope with sudden
221           changes of the system clock. Therefore, we have omitted it from the
222           Erlang  driver thread API. In the Erlang driver case, time-outs can
223           and are to be handled with the timer functionality  of  the  Erlang
224           driver API.
225
226           In  order for the Erlang driver thread API to function, thread sup‐
227           port must be enabled in the runtime system. An  Erlang  driver  can
228           check  if  thread  support is enabled by use of driver_system_info.
229           Notice that some functions in the Erlang driver API are thread-safe
230           only when the runtime system has SMP support, also this information
231           can be retrieved through driver_system_info. Also notice that  many
232           functions  in the Erlang driver API are not thread-safe, regardless
233           of whether SMP support is enabled or not. If a function is not doc‐
234           umented as thread-safe, it is not thread-safe.
235
236     Note:
237         When  executing  in an emulator thread, it is very important that you
238         unlock all locks you have locked before letting  the  thread  out  of
239         your  control;  otherwise  you  are very likely to deadlock the whole
240         emulator.
241
242         If you need to use thread-specific data in an emulator  thread,  only
243         have the thread-specific data set while the thread is under your con‐
244         trol, and clear the thread-specific data before you  let  the  thread
245         out of your control.
246
247
248           In the future, debug functionality will probably be integrated with
249           the Erlang driver thread API. All functions  that  create  entities
250           take a name argument. Currently the name argument is unused, but it
251           will be used when the debug functionality is  implemented.  If  you
252           name  all  entities  created  well, the debug functionality will be
253           able to give you better error reports.
254
255         Adding/removing drivers:
256           A driver can add and later remove drivers.
257
258         Monitoring processes:
259           A driver can monitor a process that does not own a port.
260
261         Version management:
262           Version management  is  enabled  for  drivers  that  have  set  the
263           extended_marker      field     of     their     driver_entry     to
264           ERL_DRV_EXTENDED_MARKER. erl_driver.h defines:
265
266           * ERL_DRV_EXTENDED_MARKER
267
268           * ERL_DRV_EXTENDED_MAJOR_VERSION, which is incremented when  driver
269             incompatible  changes are made to the Erlang runtime system. Nor‐
270             mally    it    suffices     to     recompile     drivers     when
271             ERL_DRV_EXTENDED_MAJOR_VERSION  has  changed,  but  it can, under
272             rare circumstances, mean that drivers must be slightly  modified.
273             If so, this will of course be documented.
274
275           * ERL_DRV_EXTENDED_MINOR_VERSION,  which  is  incremented  when new
276             features are added. The runtime system uses the minor version  of
277             the driver to determine what features to use.
278
279           The  runtime  system normally refuses to load a driver if the major
280           versions differ, or if the major versions are equal and  the  minor
281           version used by the driver is greater than the one used by the run‐
282           time system. Old drivers with  lower  major  versions  are  however
283           allowed  after  a  bump  of  the  major version during a transition
284           period of two major releases. Such old drivers can,  however,  fail
285           if deprecated features are used.
286
287           The  emulator  refuses  to  load  a  driver  that  does not use the
288           extended driver interface, to allow for 64-bit capable drivers,  as
289           incompatible  type  changes  for the callbacks output, control, and
290           call were introduced in Erlang/OTP R15B. A driver written with  the
291           old  types  would  compile  with  warnings  and  when called return
292           garbage sizes to the emulator, causing it to read random memory and
293           create huge incorrect result blobs.
294
295           Therefore  it  is not enough to only recompile drivers written with
296           version management for pre R15B types; the types must be changed in
297           the  driver  suggesting  other  rewrites, especially regarding size
298           variables. Investigate all warnings when recompiling.
299
300           Also,    the    API    driver    functions    driver_output*    and
301           driver_vec_to_buf,  driver_alloc/realloc*,  and  the driver_* queue
302           functions were changed to have larger length arguments  and  return
303           values. This is a lesser problem, as code that passes smaller types
304           gets them auto-converted in the calls, and as long  as  the  driver
305           does  not  handle  sizes  that  overflow  an  int, all will work as
306           before.
307
308         Time measurement:
309           Support for time measurement in drivers:
310
311           * ErlDrvTime
312
313           * ErlDrvTimeUnit
314
315           * erl_drv_monotonic_time
316
317           * erl_drv_time_offset
318
319           * erl_drv_convert_time_unit
320

REWRITES FOR 64-BIT DRIVER INTERFACE

322       ERTS 5.9 introduced two new integer  types,  ErlDrvSizeT  and  ErlDrvS‐
323       SizeT, which can hold 64-bit sizes if necessary.
324
325       To  not  update  a  driver  and  only recompile, it probably works when
326       building for a 32-bit machine creating a false sense of security. Hope‐
327       fully  that will generate many important warnings. But when recompiling
328       the same driver later on for a 64-bit machine, there will  be  warnings
329       and  almost certainly crashes. So it is a bad idea to postpone updating
330       the driver and not fixing the warnings.
331
332       When recompiling with gcc, use flag -Wstrict-prototypes to  get  better
333       warnings. Try to find a similar flag if you use another compiler.
334
335       The  following is a checklist for rewriting a pre ERTS 5.9 driver, most
336       important first:
337
338         Return types for driver callbacks:
339           Rrewrite driver callback control to use  return  type  ErlDrvSSizeT
340           instead of int.
341
342           Rewrite  driver  callback  call  to  use  return  type ErlDrvSSizeT
343           instead of int.
344
345     Note:
346         These changes are essential not to crash the emulator or worse  cause
347         malfunction.  Without them a driver can return garbage in the high 32
348         bits to the emulator, causing it to build a huge result  from  random
349         bytes, either crashing on memory allocation or succeeding with a ran‐
350         dom result from the driver call.
351
352
353         Arguments to driver callbacks:
354           Driver callback output now gets ErlDrvSizeT as 3rd argument instead
355           of previously int.
356
357           Driver  callback  control now gets ErlDrvSizeT as 4th and 6th argu‐
358           ments instead of previously int.
359
360           Driver callback call now gets ErlDrvSizeT as 4th and 6th  arguments
361           instead of previously int.
362
363           Sane  compiler's  calling  conventions  probably make these changes
364           necessary only for a driver to  handle  data  chunks  that  require
365           64-bit size fields (mostly larger than 2 GB, as that is what an int
366           of 32 bits can hold). But it is possible to think of non-sane call‐
367           ing  conventions  that  would  make the driver callbacks mix up the
368           arguments causing malfunction.
369
370     Note:
371         The argument type change is from signed to unsigned. This  can  cause
372         problems  for, for example, loop termination conditions or error con‐
373         ditions if you only change the types all over the place.
374
375
376         Larger size field in ErlIOVec:
377           The size field in ErlIOVec has been  changed  to  ErlDrvSizeT  from
378           int. Check all code that use that field.
379
380           Automatic  type-casting probably makes these changes necessary only
381           for a driver that encounters sizes > 32 bits.
382
383     Note:
384         The size field changed from signed to unsigned. This can cause  prob‐
385         lems  for,  for  example, loop termination conditions or error condi‐
386         tions if you only change the types all over the place.
387
388
389         Arguments and return values in the driver API:
390           Many driver API functions have changed argument type and/or  return
391           value to ErlDrvSizeT from mostly int. Automatic type-casting proba‐
392           bly makes these changes necessary only for a driver that encounters
393           sizes > 32 bits.
394
395           driver_output:
396             3rd argument
397
398           driver_output2:
399             3rd and 5th arguments
400
401           driver_output_binary:
402             3rd, 5th, and 6th arguments
403
404           driver_outputv:
405             3rd and 5th arguments
406
407           driver_vec_to_buf:
408             3rd argument and return value
409
410           driver_alloc:
411             1st argument
412
413           driver_realloc:
414             2nd argument
415
416           driver_alloc_binary:
417             1st argument
418
419           driver_realloc_binary:
420             2nd argument
421
422           driver_enq:
423             3rd argument
424
425           driver_pushq:
426             3rd argument
427
428           driver_deq:
429             2nd argument and return value
430
431           driver_sizeq:
432             Return value
433
434           driver_enq_bin:
435             3rd and 4th arguments
436
437           driver_pushq_bin:
438             3rd and 4th arguments
439
440           driver_enqv:
441             3rd argument
442
443           driver_pushqv:
444             3rd argument
445
446           driver_peekqv:
447             Return value
448
449     Note:
450         This  is  a  change  from signed to unsigned. This can cause problems
451         for, for example, loop termination conditions and error conditions if
452         you only change the types all over the place.
453
454

DATA TYPES

456         ErlDrvSizeT:
457           An unsigned integer type to be used as size_t.
458
459         ErlDrvSSizeT:
460           A signed integer type, the size of ErlDrvSizeT.
461
462         ErlDrvSysInfo:
463
464
465         typedef struct ErlDrvSysInfo {
466            int driver_major_version;
467            int driver_minor_version;
468            char *erts_version;
469            char *otp_release;
470            int thread_support;
471            int smp_support;
472            int async_threads;
473            int scheduler_threads;
474            int nif_major_version;
475            int nif_minor_version;
476            int dirty_scheduler_support;
477         } ErlDrvSysInfo;
478
479           The  ErlDrvSysInfo  structure  is  used  for storage of information
480           about the Erlang runtime system. driver_system_info writes the sys‐
481           tem  information  when passed a reference to a ErlDrvSysInfo struc‐
482           ture. The fields in the structure are as follows:
483
484           driver_major_version:
485             The value of ERL_DRV_EXTENDED_MAJOR_VERSION when the runtime sys‐
486             tem  was  compiled.  This  value  is  the  same  as  the value of
487             ERL_DRV_EXTENDED_MAJOR_VERSION used when  compiling  the  driver;
488             otherwise  the  runtime  system  would  have  refused to load the
489             driver.
490
491           driver_minor_version:
492             The value of ERL_DRV_EXTENDED_MINOR_VERSION when the runtime sys‐
493             tem  was  compiled.  This  value  can  differ  from  the value of
494             ERL_DRV_EXTENDED_MINOR_VERSION used when compiling the driver.
495
496           erts_version:
497             A string containing the version number of the runtime system (the
498             same as returned by erlang:system_info(version)).
499
500           otp_release:
501             A  string containing the OTP release number (the same as returned
502             by erlang:system_info(otp_release)).
503
504           thread_support:
505             A value != 0 if the runtime system has thread support;  otherwise
506             0.
507
508           smp_support:
509             A value != 0 if the runtime system has SMP support; otherwise 0.
510
511           async_threads:
512             The  number  of  async  threads  in the async thread pool used by
513             driver_async   (the   same    as    returned    by    erlang:sys‐
514             tem_info(thread_pool_size)).
515
516           scheduler_threads:
517             The  number  of scheduler threads used by the runtime system (the
518             same as returned by erlang:system_info(schedulers)).
519
520           nif_major_version:
521             The value of ERL_NIF_MAJOR_VERSION when the  runtime  system  was
522             compiled.
523
524           nif_minor_version:
525             The  value  of  ERL_NIF_MINOR_VERSION when the runtime system was
526             compiled.
527
528           dirty_scheduler_support:
529             A value != 0 if the runtime system has support for  dirty  sched‐
530             uler threads; otherwise 0.
531
532         ErlDrvBinary:
533
534
535         typedef struct ErlDrvBinary {
536            ErlDrvSint orig_size;
537            char orig_bytes[];
538         } ErlDrvBinary;
539
540           The  ErlDrvBinary structure is a binary, as sent between the emula‐
541           tor and the  driver.  All  binaries  are  reference  counted;  when
542           driver_binary_free  is  called, the reference count is decremented,
543           when it reaches zero, the binary is deallocated. orig_size  is  the
544           binary  size  and  orig_bytes is the buffer. ErlDrvBinary has not a
545           fixed size, its size is orig_size + 2 * sizeof(int).
546
547     Note:
548         The refc field has been removed. The reference count of an  ErlDrvBi‐
549         nary  is now stored elsewhere. The reference count of an ErlDrvBinary
550         can      be      accessed       through       driver_binary_get_refc,
551         driver_binary_inc_refc, and driver_binary_dec_refc.
552
553
554           Some  driver calls, such as driver_enq_binary, increment the driver
555           reference count, and others, such as driver_deq decrement it.
556
557           Using a driver binary instead of a normal buffer is  often  faster,
558           as  the  emulator  needs  not to copy the data, only the pointer is
559           used.
560
561           A driver binary allocated in the driver, with  driver_alloc_binary,
562           is  to  be  freed  in  the  driver  (unless  otherwise stated) with
563           driver_free_binary. (Notice that this does not necessarily  deallo‐
564           cate  it, if the driver is still referred in the emulator, the ref-
565           count will not go to zero.)
566
567           Driver binaries are used in the driver_output2  and  driver_outputv
568           calls,  and  in  the  queue.  Also the driver callback outputv uses
569           driver binaries.
570
571           If the driver for some reason wants to keep a driver binary around,
572           for  example  in  a  static  variable, the reference count is to be
573           incremented, and the binary can later be freed in  the  stop  call‐
574           back, with driver_free_binary.
575
576           Notice that as a driver binary is shared by the driver and the emu‐
577           lator. A binary received from the emulator or sent to the  emulator
578           must not be changed by the driver.
579
580           Since  ERTS  5.5  (Erlang/OTP R11B), orig_bytes is guaranteed to be
581           properly aligned for storage of an array of doubles (usually 8-byte
582           aligned).
583
584         ErlDrvData:
585           A  handle  to driver-specific data, passed to the driver callbacks.
586           It is a pointer, and is most often type cast to a specific  pointer
587           in the driver.
588
589         SysIOVec:
590           A  system  I/O  vector,  as  used  by writev on Unix and WSASend on
591           Win32. It is used in ErlIOVec.
592
593         ErlIOVec:
594
595
596         typedef struct ErlIOVec {
597           int vsize;
598           ErlDrvSizeT size;
599           SysIOVec* iov;
600           ErlDrvBinary** binv;
601         } ErlIOVec;
602
603           The I/O vector used by the emulator and drivers is a list of  bina‐
604           ries,  with  a SysIOVec pointing to the buffers of the binaries. It
605           is used in driver_outputv and the outputv  driver  callback.  Also,
606           the driver queue is an ErlIOVec.
607
608         ErlDrvMonitor:
609           When  a  driver creates a monitor for a process, a ErlDrvMonitor is
610           filled in. This is an opaque data type that can be assigned to, but
611           not  compared without using the supplied compare function (that is,
612           it behaves like a struct).
613
614           The driver writer is to provide the memory for storing the  monitor
615           when calling driver_monitor_process. The address of the data is not
616           stored outside of the driver, so ErlDrvMonitor can be used  as  any
617           other  data,  it  can be copied, moved in memory, forgotten, and so
618           on.
619
620         ErlDrvNowData:
621           The ErlDrvNowData structure holds a time stamp consisting of  three
622           values  measured  from  some arbitrary point in the past. The three
623           structure members are:
624
625           megasecs:
626             The number of whole megaseconds elapsed since the arbitrary point
627             in time
628
629           secs:
630             The  number of whole seconds elapsed since the arbitrary point in
631             time
632
633           microsecs:
634             The number of whole  microseconds  elapsed  since  the  arbitrary
635             point in time
636
637         ErlDrvPDL:
638           If  certain  port-specific data must be accessed from other threads
639           than those calling the driver callbacks, a port data  lock  can  be
640           used to synchronize the operations on the data. Currently, the only
641           port-specific data that the emulator associates with the port  data
642           lock is the driver queue.
643
644           Normally  a  driver  instance  has no port data lock. If the driver
645           instance wants to use a port data lock, it  must  create  the  port
646           data lock by calling driver_pdl_create.
647
648     Note:
649         Once  the port data lock has been created, every access to data asso‐
650         ciated with the port data lock must be done while the port data  lock
651         is   locked.   The   port   data  lock  is  locked  and  unlocked  by
652         driver_pdl_lock, and driver_pdl_unlock, respectively.
653
654
655           A port data lock is reference counted, and when the reference count
656           reaches zero, it is destroyed. The emulator at least increments the
657           reference count once when the lock is  created  and  decrements  it
658           once  the  port  associated  with the lock terminates. The emulator
659           also increments the reference count when an async job  is  enqueued
660           and  decrements  it  when  an async job has been invoked. Also, the
661           driver is responsible for ensuring that the  reference  count  does
662           not  reach  zero  before the last use of the lock by the driver has
663           been made. The reference count can be read, incremented, and decre‐
664           mented    by    driver_pdl_get_refc,    driver_pdl_inc_refc,    and
665           driver_pdl_dec_refc, respectively.
666
667         ErlDrvTid:
668           Thread identifier.
669
670           See      also      erl_drv_thread_create,      erl_drv_thread_exit,
671           erl_drv_thread_join, erl_drv_thread_self, and erl_drv_equal_tids.
672
673         ErlDrvThreadOpts:
674
675
676         int suggested_stack_size;
677
678           Thread  options structure passed to erl_drv_thread_create. The fol‐
679           lowing fields exists:
680
681           suggested_stack_size:
682             A suggestion, in kilowords, on how large a stack to use. A  value
683             < 0 means default size.
684
685           See  also  erl_drv_thread_opts_create, erl_drv_thread_opts_destroy,
686           and erl_drv_thread_create.
687
688         ErlDrvMutex:
689           Mutual exclusion lock. Used  for  synchronizing  access  to  shared
690           data. Only one thread at a time can lock a mutex.
691
692           See      also      erl_drv_mutex_create,     erl_drv_mutex_destroy,
693           erl_drv_mutex_lock,           erl_drv_mutex_trylock,            and
694           erl_drv_mutex_unlock.
695
696         ErlDrvCond:
697           Condition variable. Used when threads must wait for a specific con‐
698           dition to appear before continuing execution.  Condition  variables
699           must be used with associated mutexes.
700
701           See       also      erl_drv_cond_create,      erl_drv_cond_destroy,
702           erl_drv_cond_signal, erl_drv_cond_broadcast, and erl_drv_cond_wait.
703
704         ErlDrvRWLock:
705           Read/write lock. Used to allow multiple threads to read shared data
706           while  only  allowing  one  thread to write the same data. Multiple
707           threads can read lock an rwlock at the same time,  while  only  one
708           thread can read/write lock an rwlock at a time.
709
710           See     also     erl_drv_rwlock_create,     erl_drv_rwlock_destroy,
711           erl_drv_rwlock_rlock, erl_drv_rwlock_tryrlock,  erl_drv_rwlock_run‐
712           lock,    erl_drv_rwlock_rwlock,    erl_drv_rwlock_tryrwlock,    and
713           erl_drv_rwlock_rwunlock.
714
715         ErlDrvTSDKey:
716           Key that thread-specific data can be associated with.
717
718           See    also    erl_drv_tsd_key_create,     erl_drv_tsd_key_destroy,
719           erl_drv_tsd_set, and erl_drv_tsd_get.
720
721         ErlDrvTime:
722           A signed 64-bit integer type for time representation.
723
724         ErlDrvTimeUnit:
725           An enumeration of time units supported by the driver API:
726
727           ERL_DRV_SEC:
728             Seconds
729
730           ERL_DRV_MSEC:
731             Milliseconds
732
733           ERL_DRV_USEC:
734             Microseconds
735
736           ERL_DRV_NSEC:
737             Nanoseconds
738

EXPORTS

740       void add_driver_entry(ErlDrvEntry
741               *de)
742
743              Adds  a driver entry to the list of drivers known by Erlang. The
744              init function of parameter de is called.
745
746          Note:
747              To use this function for adding drivers residing in  dynamically
748              loaded  code  is  dangerous.  If  the  driver code for the added
749              driver resides in the same dynamically loaded module  (that  is,
750              .so file) as a normal dynamically loaded driver (loaded with the
751              erl_ddll interface), the caller is  to  call  driver_lock_driver
752              before adding driver entries.
753
754              Use of this function is generally deprecated.
755
756
757       void *driver_alloc(ErlDrvSizeT size)
758
759              Allocates  a  memory  block  of  the size specified in size, and
760              returns it. This fails only on out of memory, in which case NULL
761              is returned. (This is most often a wrapper for malloc).
762
763              Memory  allocated  must be explicitly freed with a corresponding
764              call to driver_free (unless otherwise stated).
765
766              This function is thread-safe.
767
768       ErlDrvBinary *driver_alloc_binary(ErlDrvSizeT size)
769
770              Allocates a driver binary with a memory block of at  least  size
771              bytes,  and  returns a pointer to it, or NULL on failure (out of
772              memory). When a driver binary has been sent to the emulator,  it
773              must  not be changed. Every allocated binary is to be freed by a
774              corresponding  call  to  driver_free_binary  (unless   otherwise
775              stated).
776
777              Notice  that  a driver binary has an internal reference counter.
778              This means that calling driver_free_binary, it may not  actually
779              dispose  of  it. If it is sent to the emulator, it can be refer‐
780              enced there.
781
782              The driver binary has a field, orig_bytes, which marks the start
783              of the data in the binary.
784
785              This function is thread-safe.
786
787       long driver_async(ErlDrvPort port, unsigned
788               int* key, void (*async_invoke)(void*), void* async_data, void
789               (*async_free)(void*))
790
791              Performs  an  asynchronous  call.  The  function async_invoke is
792              invoked in a thread separate  from  the  emulator  thread.  This
793              enables  the  driver  to perform time-consuming, blocking opera‐
794              tions without blocking the emulator.
795
796              The async thread pool size can be set with command-line argument
797              +A  in  erl(1). If an async thread pool is unavailable, the call
798              is made synchronously in the thread  calling  driver_async.  The
799              current  number of async threads in the async thread pool can be
800              retrieved through driver_system_info.
801
802              If a thread pool is available, a thread is used. If argument key
803              is  NULL,  the  threads  from the pool are used in a round-robin
804              way, each call to driver_async uses the next thread in the pool.
805              With  argument  key  set, this behavior is changed. The two same
806              values of *key always get the same thread.
807
808              To ensure that a driver instance always uses  the  same  thread,
809              the following call can be used:
810
811              unsigned int myKey = driver_async_port_key(myPort);
812
813              r = driver_async(myPort, &myKey, myData, myFunc);
814
815              It is enough to initialize myKey once for each driver instance.
816
817              If a thread is already working, the calls are queued up and exe‐
818              cuted in order. Using the same thread for each  driver  instance
819              ensures that the calls are made in sequence.
820
821              The async_data is the argument to the functions async_invoke and
822              async_free. It is typically a pointer to a structure  containing
823              a pipe or event that can be used to signal that the async opera‐
824              tion completed. The data is to be freed in async_free.
825
826              When the async operation is done, ready_async driver entry func‐
827              tion  is called. If ready_async is NULL in the driver entry, the
828              async_free function is called instead.
829
830              The return value is -1 if the driver_async call fails.
831
832          Note:
833              As from ERTS 5.5.4.3 the default stack size for threads  in  the
834              async-thread  pool  is  16  kilowords,  that  is, 64 kilobyte on
835              32-bit architectures. This small default size  has  been  chosen
836              because  the  amount  of  async-threads  can be quite large. The
837              default  stack  size  is  enough  for  drivers  delivered   with
838              Erlang/OTP,  but  is  possibly  not sufficiently large for other
839              dynamically linked-in drivers that use  the  driver_async  func‐
840              tionality.  A  suggested  stack  size  for threads in the async-
841              thread pool can be configured through command-line  argument  +a
842              in erl(1).
843
844
845       unsigned int driver_async_port_key(ErlDrvPort
846               port)
847
848              Calculates  a  key  for  later use in driver_async. The keys are
849              evenly distributed so that a fair mapping between port  IDs  and
850              async thread IDs is achieved.
851
852          Note:
853              Before  Erlang/OTP  R16, the port ID could be used as a key with
854              proper casting, but after the rewrite  of  the  port  subsystem,
855              this  is no longer the case. With this function, you can achieve
856              the same distribution based on port  IDs  as  before  Erlang/OTP
857              R16.
858
859
860       long driver_binary_dec_refc(ErlDrvBinary *bin)
861
862              Decrements  the reference count on bin and returns the reference
863              count reached after the decrement.
864
865              This function is thread-safe.
866
867          Note:
868              The reference count of driver binary is normally  to  be  decre‐
869              mented by calling driver_free_binary.
870
871              driver_binary_dec_refc does not free the binary if the reference
872              count reaches zero. Only use driver_binary_dec_refc when you are
873              sure not to reach a reference count of zero.
874
875
876       long driver_binary_get_refc(ErlDrvBinary *bin)
877
878              Returns the current reference count on bin.
879
880              This function is thread-safe.
881
882       long driver_binary_inc_refc(ErlDrvBinary *bin)
883
884              Increments  the reference count on bin and returns the reference
885              count reached after the increment.
886
887              This function is thread-safe.
888
889       ErlDrvTermData driver_caller(ErlDrvPort
890               port)
891
892              Returns the process ID of the process that made the current call
893              to  the driver. The process ID can be used with driver_send_term
894              to send back data to  the  caller.  driver_caller  only  returns
895              valid  data  when  currently  executing  in one of the following
896              driver callbacks:
897
898                start:
899                  Called from erlang:open_port/2.
900
901                output:
902                  Called from erlang:send/2 and erlang:port_command/2.
903
904                outputv:
905                  Called from erlang:send/2 and erlang:port_command/2.
906
907                control:
908                  Called from erlang:port_control/3.
909
910                call:
911                  Called from erlang:port_call/3.
912
913              Notice that this function is not thread-safe, not even when  the
914              emulator with SMP support is used.
915
916       int driver_cancel_timer(ErlDrvPort port)
917
918              Cancels a timer set with driver_set_timer.
919
920              The return value is 0.
921
922       int driver_compare_monitors(const ErlDrvMonitor
923               *monitor1, const ErlDrvMonitor *monitor2)
924
925              Compares  two  ErlDrvMonitors.  Can  also  be used to imply some
926              artificial order on monitors, for whatever reason.
927
928              Returns 0 if monitor1 and monitor2 are equal, < 0 if monitor1  <
929              monitor2, and > 0 if monitor1 > monitor2.
930
931       ErlDrvTermData driver_connected(ErlDrvPort
932               port)
933
934              Returns the port owner process.
935
936              Notice  that this function is not thread-safe, not even when the
937              emulator with SMP support is used.
938
939       ErlDrvPort driver_create_port(ErlDrvPort port,
940               ErlDrvTermData owner_pid, char* name,
941               ErlDrvData drv_data)
942
943              Creates a new port executing the same driver code  as  the  port
944              creating the new port.
945
946                port:
947                  The  port  handle of the port (driver instance) creating the
948                  new port.
949
950                owner_pid:
951                  The process ID of the Erlang process to become owner of  the
952                  new  port.  This process will be linked to the new port. You
953                  usually want to use driver_caller(port) as owner_pid.
954
955                name:
956                  The port name of the new port. You usually want to  use  the
957                  same  port name as the driver name (driver_name field of the
958                  driver_entry).
959
960                drv_data:
961                  The driver-defined handle that is passed in later  calls  to
962                  driver  callbacks.  Notice that the driver start callback is
963                  not called for this new driver instance. The  driver-defined
964                  handle is normally created in the driver start callback when
965                  a port is created through erlang:open_port/2.
966
967              The caller of driver_create_port is allowed  to  manipulate  the
968              newly  created  port  when driver_create_port has returned. When
969              port level locking is used, the creating port is only allowed to
970              manipulate the newly created port until the current driver call‐
971              back, which was called by the emulator, returns.
972
973       int driver_demonitor_process(ErlDrvPort port,
974               const ErlDrvMonitor *monitor)
975
976              Cancels a monitor created earlier.
977
978              Returns 0 if a monitor was removed and > 0  if  the  monitor  no
979              longer exists.
980
981       ErlDrvSizeT driver_deq(ErlDrvPort port,
982               ErlDrvSizeT size)
983
984              Dequeues  data  by moving the head pointer forward in the driver
985              queue by size bytes. The data in the queue is deallocated.
986
987              Returns the number of bytes remaining in the queue  on  success,
988              otherwise -1.
989
990              This  function can be called from any thread if a port data lock
991              associated with the port is locked by the calling thread  during
992              the call.
993
994       int driver_enq(ErlDrvPort port, char* buf,
995               ErlDrvSizeT len)
996
997              Enqueues  data  in  the  driver queue. The data in buf is copied
998              (len bytes) and placed at the  end  of  the  driver  queue.  The
999              driver queue is normally used in a FIFO way.
1000
1001              The  driver queue is available to queue output from the emulator
1002              to the driver (data from the driver to the emulator is queued by
1003              the  emulator in normal Erlang message queues). This can be use‐
1004              ful if the driver must wait for slow devices,  and  so  on,  and
1005              wants  to yield back to the emulator. The driver queue is imple‐
1006              mented as an ErlIOVec.
1007
1008              When the queue contains data, the driver does  not  close  until
1009              the queue is empty.
1010
1011              The return value is 0.
1012
1013              This  function can be called from any thread if a port data lock
1014              associated with the port is locked by the calling thread  during
1015              the call.
1016
1017       int driver_enq_bin(ErlDrvPort port,
1018               ErlDrvBinary *bin, ErlDrvSizeT offset, ErlDrvSizeT len)
1019
1020              Enqueues a driver binary in the driver queue. The data in bin at
1021              offset with length len is placed at the end of the  queue.  This
1022              function  is  most often faster than driver_enq, because no data
1023              must be copied.
1024
1025              This function can be called from any thread if a port data  lock
1026              associated  with the port is locked by the calling thread during
1027              the call.
1028
1029              The return value is 0.
1030
1031       int driver_enqv(ErlDrvPort port, ErlIOVec *ev,
1032               ErlDrvSizeT skip)
1033
1034              Enqueues the data in ev, skipping the first skip bytes of it, at
1035              the  end  of  the  driver  queue.  It is faster than driver_enq,
1036              because no data must be copied.
1037
1038              The return value is 0.
1039
1040              This function can be called from any thread if a port data  lock
1041              associated  with the port is locked by the calling thread during
1042              the call.
1043
1044       int driver_failure(ErlDrvPort port, int
1045               error)
1046       int driver_failure_atom(ErlDrvPort port, char
1047               *string)
1048       int driver_failure_posix(ErlDrvPort port, int
1049               error)
1050
1051              Signals to Erlang that the driver has encountered an  error  and
1052              is  to  be  closed.  The  port  is closed and the tuple {'EXIT',
1053              error, Err} is sent to the port owner process, where error is an
1054              error  atom (driver_failure_atom and driver_failure_posix) or an
1055              integer (driver_failure).
1056
1057              The driver is to fail only when in severe error situations, when
1058              the  driver cannot possibly keep open, for example, buffer allo‐
1059              cation gets out of memory. For normal errors it is  more  appro‐
1060              priate to send error codes with driver_output.
1061
1062              The return value is 0.
1063
1064       int driver_failure_eof(ErlDrvPort
1065               port)
1066
1067              Signals  to Erlang that the driver has encountered an EOF and is
1068              to be closed, unless the port was opened  with  option  eof,  in
1069              which case eof is sent to the port. Otherwise the port is closed
1070              and an 'EXIT' message is sent to the port owner process.
1071
1072              The return value is 0.
1073
1074       void driver_free(void *ptr)
1075
1076              Frees the memory pointed to by ptr. The memory is to  have  been
1077              allocated with driver_alloc. All allocated memory is to be deal‐
1078              located, only once. There is no garbage collection in drivers.
1079
1080              This function is thread-safe.
1081
1082       void driver_free_binary(ErlDrvBinary *bin)
1083
1084              Frees  a  driver   binary   bin,   allocated   previously   with
1085              driver_alloc_binary.   As   binaries  in  Erlang  are  reference
1086              counted, the binary can still be around.
1087
1088              This function is thread-safe.
1089
1090       ErlDrvTermData driver_get_monitored_process(ErlDrvPort port, const
1091               ErlDrvMonitor *monitor)
1092
1093              Returns the process ID associated with a living monitor. It  can
1094              be  used in the process_exit callback to get the process identi‐
1095              fication for the exiting process.
1096
1097              Returns driver_term_nil if the monitor no longer exists.
1098
1099       int driver_get_now(ErlDrvNowData *now)
1100
1101          Warning:
1102              This function is deprecated. Do not use  it.  Use  erl_drv_mono‐
1103              tonic_time  (perhaps  in  combination  with erl_drv_time_offset)
1104              instead.
1105
1106
1107              Reads a time stamp into the memory pointed to by parameter  now.
1108              For information about specific fields, see ErlDrvNowData.
1109
1110              The  return  value  is  0, unless the now pointer is invalid, in
1111              which case it is < 0.
1112
1113       int driver_lock_driver(ErlDrvPort
1114               port)
1115
1116              Locks the driver used by the port port in memory for the rest of
1117              the  emulator  process'  lifetime.  After  this call, the driver
1118              behaves as one of Erlang's statically linked-in drivers.
1119
1120       ErlDrvTermData driver_mk_atom(char*
1121               string)
1122
1123              Returns an atom given a name string. The  atom  is  created  and
1124              does  not  change,  so the return value can be saved and reused,
1125              which is faster than looking up the atom several times.
1126
1127              Notice that this function is not thread-safe, not even when  the
1128              emulator with SMP support is used.
1129
1130       ErlDrvTermData driver_mk_port(ErlDrvPort
1131               port)
1132
1133              Converts  a  port  handle  to  the Erlang term format, usable in
1134              erl_drv_output_term and erl_drv_send_term.
1135
1136              Notice that this function is not thread-safe, not even when  the
1137              emulator with SMP support is used.
1138
1139       int driver_monitor_process(ErlDrvPort port,
1140               ErlDrvTermData process, ErlDrvMonitor *monitor)
1141
1142              Starts  monitoring  a  process  from a driver. When a process is
1143              monitored, a process exit results in  a  call  to  the  provided
1144              process_exit  callback in the ErlDrvEntry structure. The ErlDrv‐
1145              Monitor structure is filled in, for later removal or compare.
1146
1147              Parameter process is to be the return value of an  earlier  call
1148              to driver_caller or driver_connected call.
1149
1150              Returns 0 on success, < 0 if no callback is provided, and > 0 if
1151              the process is no longer alive.
1152
1153       int driver_output(ErlDrvPort port, char *buf,
1154               ErlDrvSizeT len)
1155
1156              Sends data from the driver up  to  the  emulator.  The  data  is
1157              received  as  terms  or binary data, depending on how the driver
1158              port was opened.
1159
1160              The data is queued in the port  owner  process'  message  queue.
1161              Notice  that  this does not yield to the emulator (as the driver
1162              and the emulator run in the same thread).
1163
1164              Parameter buf points to the data to send, and len is the  number
1165              of bytes.
1166
1167              The  return  value for all output functions is 0 for normal use.
1168              If the driver is used for distribution, it can fail  and  return
1169              -1.
1170
1171       int driver_output_binary(ErlDrvPort port, char
1172               *hbuf, ErlDrvSizeT hlen, ErlDrvBinary* bin, ErlDrvSizeT offset,
1173               ErlDrvSizeT len)
1174
1175              Sends  data to a port owner process from a driver binary. It has
1176              a header buffer (hbuf and hlen) just like driver_output2. Param‐
1177              eter hbuf can be NULL.
1178
1179              Parameter  offset  is  an  offset into the binary and len is the
1180              number of bytes to send.
1181
1182              Driver binaries are created with driver_alloc_binary.
1183
1184              The data in the header is sent as a list and the  binary  as  an
1185              Erlang binary in the tail of the list.
1186
1187              For  example, if hlen is 2, the port owner process receives [H1,
1188              H2 | <<T>>].
1189
1190              The return value is 0 for normal use.
1191
1192              Notice that, using the  binary  syntax  in  Erlang,  the  driver
1193              application  can  match  the header directly from the binary, so
1194              the header can be put in the binary, and hlen can be set to 0.
1195
1196       int driver_output_term(ErlDrvPort port,
1197               ErlDrvTermData* term, int n)
1198
1199          Warning:
1200              This function is deprecated. Use erl_drv_output_terminstead.
1201
1202
1203              Parameters term and n work as in erl_drv_output_term.
1204
1205              Notice that this function is not thread-safe, not even when  the
1206              emulator with SMP support is used.
1207
1208       int driver_output2(ErlDrvPort port, char *hbuf,
1209               ErlDrvSizeT hlen, char *buf, ErlDrvSizeT len)
1210
1211              First  sends hbuf (length in hlen) data as a list, regardless of
1212              port settings. Then sends buf as a binary or list. For  example,
1213              if hlen is 3, the port owner process receives [H1, H2, H3 | T].
1214
1215              The  point  of  sending  data as a list header, is to facilitate
1216              matching on the data received.
1217
1218              The return value is 0 for normal use.
1219
1220       int driver_outputv(ErlDrvPort port, char* hbuf,
1221               ErlDrvSizeT hlen, ErlIOVec *ev, ErlDrvSizeT skip)
1222
1223              Sends data from an I/O vector, ev, to the port owner process. It
1224              has a header buffer (hbuf and hlen), just like driver_output2.
1225
1226              Parameter  skip  is  a  number of bytes to skip of the ev vector
1227              from the head.
1228
1229              You get vectors of ErlIOVec type  from  the  driver  queue  (see
1230              below), and the outputv driver entry function. You can also make
1231              them yourself, if you want to send several ErlDrvBinary  buffers
1232              at once. Often it is faster to use driver_output or .
1233
1234              For  example,  if  hlen  is 2 and ev points to an array of three
1235              binaries, the port  owner  process  receives  [H1,  H2,  <<B1>>,
1236              <<B2>> | <<B3>>].
1237
1238              The return value is 0 for normal use.
1239
1240              The   comment   for   driver_output_binary   also   applies  for
1241              driver_outputv.
1242
1243       ErlDrvPDL driver_pdl_create(ErlDrvPort port)
1244
1245              Creates a port data lock associated with the port.
1246
1247          Note:
1248              Once a port data lock has been created, it must be locked during
1249              all operations on the driver queue of the port.
1250
1251
1252              Returns  a  newly  created  port data lock on success, otherwise
1253              NULL. The function fails if port is invalid or if  a  port  data
1254              lock already has been associated with the port.
1255
1256       long driver_pdl_dec_refc(ErlDrvPDL
1257               pdl)
1258
1259              Decrements  the  reference count of the port data lock passed as
1260              argument (pdl).
1261
1262              The current reference count after the decrement  has  been  per‐
1263              formed is returned.
1264
1265              This function is thread-safe.
1266
1267       long driver_pdl_get_refc(ErlDrvPDL pdl)
1268
1269              Returns the current reference count of the port data lock passed
1270              as argument (pdl).
1271
1272              This function is thread-safe.
1273
1274       long driver_pdl_inc_refc(ErlDrvPDL pdl)
1275
1276              Increments the reference count of the port data lock  passed  as
1277              argument (pdl).
1278
1279              The  current  reference  count after the increment has been per‐
1280              formed is returned.
1281
1282              This function is thread-safe.
1283
1284       void driver_pdl_lock(ErlDrvPDL pdl)
1285
1286              Locks the port data lock passed as argument (pdl).
1287
1288              This function is thread-safe.
1289
1290       void driver_pdl_unlock(ErlDrvPDL pdl)
1291
1292              Unlocks the port data lock passed as argument (pdl).
1293
1294              This function is thread-safe.
1295
1296       SysIOVec *driver_peekq(ErlDrvPort port, int
1297               *vlen)
1298
1299              Retrieves the driver queue as a pointer  to  an  array  of  Sys‐
1300              IOVecs.  It also returns the number of elements in vlen. This is
1301              one of two ways to get data out of the queue.
1302
1303              Nothing is removed from the queue by this function, that must be
1304              done with driver_deq.
1305
1306              The  returned array is suitable to use with the Unix system call
1307              writev.
1308
1309              This function can be called from any thread if a port data  lock
1310              associated  with the port is locked by the calling thread during
1311              the call.
1312
1313       ErlDrvSizeT driver_peekqv(ErlDrvPort port,
1314               ErlIOVec *ev)
1315
1316              Retrieves the driver queue into a supplied ErlIOVec ev. It  also
1317              returns  the queue size. This is one of two ways to get data out
1318              of the queue.
1319
1320              If ev is NULL, all ones that is -1 type cast to ErlDrvSizeT  are
1321              returned.
1322
1323              Nothing is removed from the queue by this function, that must be
1324              done with driver_deq.
1325
1326              This function can be called from any thread if a port data  lock
1327              associated  with the port is locked by the calling thread during
1328              the call.
1329
1330       int driver_pushq(ErlDrvPort port, char* buf,
1331               ErlDrvSizeT len)
1332
1333              Puts data at the head of the driver queue. The data  in  buf  is
1334              copied (len bytes) and placed at the beginning of the queue.
1335
1336              The return value is 0.
1337
1338              This  function can be called from any thread if a port data lock
1339              associated with the port is locked by the calling thread  during
1340              the call.
1341
1342       int driver_pushq_bin(ErlDrvPort port,
1343               ErlDrvBinary *bin, ErlDrvSizeT offset, ErlDrvSizeT len)
1344
1345              Puts  data  in  the binary bin, at offset with length len at the
1346              head  of  the  driver  queue.  It  is  most  often  faster  than
1347              driver_pushq, because no data must be copied.
1348
1349              This  function can be called from any thread if a port data lock
1350              associated with the port is locked by the calling thread  during
1351              the call.
1352
1353              The return value is 0.
1354
1355       int driver_pushqv(ErlDrvPort port, ErlIOVec
1356               *ev, ErlDrvSizeT skip)
1357
1358              Puts the data in ev, skipping the first skip bytes of it, at the
1359              head of the  driver  queue.  It  is  faster  than  driver_pushq,
1360              because no data must be copied.
1361
1362              The return value is 0.
1363
1364              This  function can be called from any thread if a port data lock
1365              associated with the port is locked by the calling thread  during
1366              the call.
1367
1368       int driver_read_timer(ErlDrvPort port, unsigned
1369               long *time_left)
1370
1371              Reads  the  current  time  of  a timer, and places the result in
1372              time_left. This is the time in milliseconds, before the time-out
1373              occurs.
1374
1375              The return value is 0.
1376
1377       void *driver_realloc(void *ptr, ErlDrvSizeT size)
1378
1379              Resizes  a memory block, either in place, or by allocating a new
1380              block, copying the data, and freeing the old block. A pointer is
1381              returned  to the reallocated memory. On failure (out of memory),
1382              NULL is returned. (This is most often a wrapper for realloc.)
1383
1384              This function is thread-safe.
1385
1386       ErlDrvBinary  *driver_realloc_binary(ErlDrvBinary   *bin,   ErlDrvSizeT
1387       size)
1388
1389
1390              Resizes a driver binary, while keeping the data.
1391
1392              Returns  the  resized  driver binary on success. Returns NULL on
1393              failure (out of memory).
1394
1395              This function is thread-safe.
1396
1397       int driver_select(ErlDrvPort port, ErlDrvEvent
1398               event, int mode, int on)
1399
1400              This function is used by drivers to provide  the  emulator  with
1401              events  to  check  for.  This  enables  the emulator to call the
1402              driver when something has occurred asynchronously.
1403
1404              Parameter event identifies an OS-specific event object. On  Unix
1405              systems,  the  functions  select/poll are used. The event object
1406              must be a socket or pipe (or other object that  select/poll  can
1407              use).  On Windows, the Win32 API function WaitForMultipleObjects
1408              is used. This places other restrictions on the event object; see
1409              the Win32 SDK documentation.
1410
1411              Parameter  on  is  to be 1 for setting events and 0 for clearing
1412              them.
1413
1414              Parameter mode is a  bitwise  OR  combination  of  ERL_DRV_READ,
1415              ERL_DRV_WRITE, and ERL_DRV_USE. The first two specify whether to
1416              wait for read events and/or write events.  A  fired  read  event
1417              calls ready_input and a fired write event calls ready_output.
1418
1419          Note:
1420              Some  OS  (Windows)  do not differentiate between read and write
1421              events. The callback for a fired event then only depends on  the
1422              value of mode.
1423
1424
1425              ERL_DRV_USE  specifies if we are using the event object or if we
1426              want to close it. On an emulator with SMP  support,  it  is  not
1427              safe  to  clear all events and then close the event object after
1428              driver_select has returned. Another thread can  still  be  using
1429              the  event  object  internally. To safely close an event object,
1430              call driver_select with ERL_DRV_USE and on==0, which clears  all
1431              events  and  then either calls stop_select or schedules it to be
1432              called when it is safe to close the event object. ERL_DRV_USE is
1433              to  be set together with the first event for an event object. It
1434              is harmless to set ERL_DRV_USE even if it already has been done.
1435              Clearing  all  events but keeping ERL_DRV_USE set indicates that
1436              we are using the event object and probably will set  events  for
1437              it again.
1438
1439          Note:
1440              ERL_DRV_USE  was added in Erlang/OTP R13. Old drivers still work
1441              as  before,  but  it  is  recommended  to  update  them  to  use
1442              ERL_DRV_USE  and  stop_select  to  ensure that event objects are
1443              closed in a safe way.
1444
1445
1446              The return value is 0, unless ready_input/ready_output is  NULL,
1447              in which case it is -1.
1448
1449       int driver_send_term(ErlDrvPort port,
1450               ErlDrvTermData receiver, ErlDrvTermData* term, int n)
1451
1452          Warning:
1453              This function is deprecated. Use erl_drv_send_term instead.
1454
1455
1456          Note:
1457              The  parameters  of  this function cannot be properly checked by
1458              the runtime system when executed by arbitrary threads. This  can
1459              cause the function not to fail when it should.
1460
1461
1462              Parameters term and n work as in erl_drv_output_term.
1463
1464              This  function  is  only  thread-safe when the emulator with SMP
1465              support is used.
1466
1467       int driver_set_timer(ErlDrvPort port, unsigned
1468               long time)
1469
1470              Sets a timer on the driver, which will count down and  call  the
1471              driver  when it is timed out. Parameter time is the time in mil‐
1472              liseconds before the timer expires.
1473
1474              When the timer reaches 0 and expires, the driver entry  function
1475              timeout is called.
1476
1477              Notice  that only one timer exists on each driver instance; set‐
1478              ting a new timer replaces an older one.
1479
1480              Return value is 0, unless the timeout driver function  is  NULL,
1481              in which case it is -1.
1482
1483       ErlDrvSizeT driver_sizeq(ErlDrvPort port)
1484
1485              Returns the number of bytes currently in the driver queue.
1486
1487              This  function can be called from any thread if a port data lock
1488              associated with the port is locked by the calling thread  during
1489              the call.
1490
1491       void driver_system_info(ErlDrvSysInfo
1492               *sys_info_ptr, size_t size)
1493
1494              Writes information about the Erlang runtime system into the Erl‐
1495              DrvSysInfo structure referred to by the first argument. The sec‐
1496              ond  argument  is to be the size of the ErlDrvSysInfo structure,
1497              that is, sizeof(ErlDrvSysInfo).
1498
1499              For information about specific fields, see ErlDrvSysInfo.
1500
1501       ErlDrvSizeT driver_vec_to_buf(ErlIOVec *ev,
1502               char *buf, ErlDrvSizeT len)
1503
1504              Collects several segments of data, referenced by ev, by  copying
1505              them in order to the buffer buf, of the size len.
1506
1507              If  the  data  is  to  be sent from the driver to the port owner
1508              process, it is faster to use driver_outputv.
1509
1510              The return value is the space left in the buffer, that is, if ev
1511              contains  less  than  len  bytes it is the difference, and if ev
1512              contains len bytes or more, it is 0. This is faster if there  is
1513              more  than  one  header byte, as the binary syntax can construct
1514              integers directly from the binary.
1515
1516       void erl_drv_busy_msgq_limits(ErlDrvPort port,
1517               ErlDrvSizeT *low, ErlDrvSizeT *high)
1518
1519              Sets and gets limits that will be used for controlling the  busy
1520              state of the port message queue.
1521
1522              The  port message queue is set into a busy state when the amount
1523              of command data queued on the message  queue  reaches  the  high
1524              limit.  The port message queue is set into a not busy state when
1525              the amount of command data queued on  the  message  queue  falls
1526              below the low limit. Command data is in this context data passed
1527              to the port using either Port  !  {Owner,  {command,  Data}}  or
1528              port_command/[2,3].  Notice that these limits only concerns com‐
1529              mand data that have not yet reached the port. The busy port fea‐
1530              ture can be used for data that has reached the port.
1531
1532              Valid limits are values in the range [ERL_DRV_BUSY_MSGQ_LIM_MIN,
1533              ERL_DRV_BUSY_MSGQ_LIM_MAX]. Limits are automatically adjusted to
1534              be  sane.  That  is,  the  system adjusts values so that the low
1535              limit used is lower than or equal to the  high  limit  used.  By
1536              default the high limit is 8 kB and the low limit is 4 kB.
1537
1538              By passing a pointer to an integer variable containing the value
1539              ERL_DRV_BUSY_MSGQ_READ_ONLY, the currently used  limit  is  read
1540              and written back to the integer variable. A new limit can be set
1541              by passing a pointer to an integer variable containing  a  valid
1542              limit.  The  passed  value is written to the internal limit. The
1543              internal limit is then adjusted. After this the  adjusted  limit
1544              is written back to the integer variable from which the new value
1545              was read. Values are in bytes.
1546
1547              The busy message queue feature can be disabled either by setting
1548              the  ERL_DRV_FLAG_NO_BUSY_MSGQ  driver  flag in the driver_entry
1549              used  by  the  driver,  or  by  calling   this   function   with
1550              ERL_DRV_BUSY_MSGQ_DISABLED as a limit (either low or high). When
1551              this feature has been disabled, it cannot be enabled again. When
1552              reading  the limits, both are ERL_DRV_BUSY_MSGQ_DISABLED if this
1553              feature has been disabled.
1554
1555              Processes sending command data to  the  port  are  suspended  if
1556              either  the  port  is busy or if the port message queue is busy.
1557              Suspended processes are resumed when neither  the  port  or  the
1558              port message queue is busy.
1559
1560              For    information    about   busy   port   functionality,   see
1561              set_busy_port.
1562
1563       void erl_drv_cond_broadcast(ErlDrvCond
1564               *cnd)
1565
1566              Broadcasts on a condition variable. That is,  if  other  threads
1567              are waiting on the condition variable being broadcast on, all of
1568              them are woken.
1569
1570              cnd is a pointer to a condition variable to broadcast on.
1571
1572              This function is thread-safe.
1573
1574       ErlDrvCond *erl_drv_cond_create(char
1575               *name)
1576
1577              Creates a condition variable and returns a pointer to it.
1578
1579              name is a string identifying the created condition variable.  It
1580              is  used  to  identify  the condition variable in planned future
1581              debug functionality.
1582
1583              Returns NULL on failure. The driver creating the condition vari‐
1584              able  is  responsible  for  destroying  it  before the driver is
1585              unloaded.
1586
1587              This function is thread-safe.
1588
1589       void erl_drv_cond_destroy(ErlDrvCond
1590               *cnd)
1591
1592              Destroys   a   condition   variable   previously   created    by
1593              erl_drv_cond_create.
1594
1595              cnd is a pointer to a condition variable to destroy.
1596
1597              This function is thread-safe.
1598
1599       char *erl_drv_cond_name(ErlDrvCond
1600               *cnd)
1601
1602              Returns a pointer to the name of the condition.
1603
1604              cnd is a pointer to an initialized condition.
1605
1606          Note:
1607              This function is intended for debugging purposes only.
1608
1609
1610       void erl_drv_cond_signal(ErlDrvCond
1611               *cnd)
1612
1613              Signals  on  a condition variable. That is, if other threads are
1614              waiting on the condition variable being signaled, one of them is
1615              woken.
1616
1617              cnd is a pointer to a condition variable to signal on.
1618
1619              This function is thread-safe.
1620
1621       void erl_drv_cond_wait(ErlDrvCond *cnd,
1622               ErlDrvMutex *mtx)
1623
1624              Waits  on  a  condition  variable. The calling thread is blocked
1625              until another thread wakes it by signaling  or  broadcasting  on
1626              the condition variable. Before the calling thread is blocked, it
1627              unlocks the mutex passed as argument. When the calling thread is
1628              woken,  it  locks  the same mutex before returning. That is, the
1629              mutex currently must be locked by the calling thread when  call‐
1630              ing this function.
1631
1632              cnd  is  a  pointer to a condition variable to wait on. mtx is a
1633              pointer to a mutex to unlock while waiting.
1634
1635          Note:
1636              erl_drv_cond_wait can return even if  no  one  has  signaled  or
1637              broadcast    on    the    condition   variable.   Code   calling
1638              erl_drv_cond_wait is always to be prepared for erl_drv_cond_wait
1639              returning  even if the condition that the thread was waiting for
1640              has   not   occurred.   That    is,    when    returning    from
1641              erl_drv_cond_wait,  always  check if the condition has occurred,
1642              and if not call erl_drv_cond_wait again.
1643
1644
1645              This function is thread-safe.
1646
1647       int erl_drv_consume_timeslice(ErlDrvPort port,
1648               int percent)
1649
1650              Gives the runtime system a hint about how much CPU time the cur‐
1651              rent  driver  callback call has consumed since the last hint, or
1652              since the the start of the callback if no previous hint has been
1653              given.
1654
1655                port:
1656                  Port handle of the executing port.
1657
1658                percent:
1659                  Approximate  consumed  fraction of a full time-slice in per‐
1660                  cent.
1661
1662              The time is specified as a fraction, in percent, of a full time-
1663              slice  that a port is allowed to execute before it is to surren‐
1664              der the CPU to other runnable ports or processes. Valid range is
1665              [1,  100]. The scheduling time-slice is not an exact entity, but
1666              can usually be approximated to about 1 millisecond.
1667
1668              Notice that it is up to the runtime system to determine  if  and
1669              how  to  use this information. Implementations on some platforms
1670              can use other means to determine the consumed  fraction  of  the
1671              time-slice. Lengthy driver callbacks should, regardless of this,
1672              frequently call this function to determine if it is  allowed  to
1673              continue execution or not.
1674
1675              This  function  returns  a  non-zero value if the time-slice has
1676              been exhausted, and zero if the callback is allowed to  continue
1677              execution.  If a non-zero value is returned, the driver callback
1678              is to return as soon as possible in order for  the  port  to  be
1679              able to yield.
1680
1681              This  function is provided to better support co-operative sched‐
1682              uling, improve system responsiveness, and to make it  easier  to
1683              prevent  misbehaviors of the VM because of a port monopolizing a
1684              scheduler thread. It can be used when dividing lengthy work into
1685              some  repeated  driver  callback  calls, without the need to use
1686              threads.
1687
1688              See also the important warning text at  the  beginning  of  this
1689              manual page.
1690
1691       ErlDrvTime erl_drv_convert_time_unit(ErlDrvTime
1692               val, ErlDrvTimeUnit from, ErlDrvTimeUnit to)
1693
1694              Converts  the  val  value of time unit from to the corresponding
1695              value of time unit to. The result is  rounded  using  the  floor
1696              function.
1697
1698                val:
1699                  Value to convert time unit for.
1700
1701                from:
1702                  Time unit of val.
1703
1704                to:
1705                  Time unit of returned value.
1706
1707              Returns  ERL_DRV_TIME_ERROR  if called with an invalid time unit
1708              argument.
1709
1710              See also ErlDrvTime and ErlDrvTimeUnit.
1711
1712       int erl_drv_equal_tids(ErlDrvTid tid1,
1713               ErlDrvTid tid2)
1714
1715              Compares two thread identifiers, tid1 and tid2, for equality.
1716
1717              Returns 0 it they are not equal, and a value not equal to  0  if
1718              they are equal.
1719
1720          Note:
1721              A  thread  identifier  can be reused very quickly after a thread
1722              has terminated. Therefore, if a thread corresponding to  one  of
1723              the  involved thread identifiers has terminated since the thread
1724              identifier was saved, the result of erl_drv_equal_tids does pos‐
1725              sibly not give the expected result.
1726
1727
1728              This function is thread-safe.
1729
1730       int erl_drv_getenv(const char *key, char
1731               *value, size_t *value_size)
1732
1733              Retrieves the value of an environment variable.
1734
1735                key:
1736                  A NULL-terminated string containing the name of the environ‐
1737                  ment variable.
1738
1739                value:
1740                  A pointer to an output buffer.
1741
1742                value_size:
1743                  A pointer to an integer. The integer is used both for  pass‐
1744                  ing input and output sizes (see below).
1745
1746              When this function is called, *value_size is to contain the size
1747              of the value buffer.
1748
1749              On success, 0 is returned, the value of the environment variable
1750              has  been  written to the value buffer, and *value_size contains
1751              the string length (excluding the terminating NULL character)  of
1752              the value written to the value buffer.
1753
1754              On  failure,  that is, no such environment variable was found, a
1755              value < 0 is returned. When the size of the value buffer is  too
1756              small,  a  value > 0 is returned and *value_size has been set to
1757              the buffer size needed.
1758
1759          Warning:
1760              Do not use libc's getenv or similar C library interfaces from  a
1761              driver.
1762
1763
1764              This function is thread-safe.
1765
1766       void erl_drv_init_ack(ErlDrvPort port,
1767               ErlDrvData res)
1768
1769              Acknowledges the start of the port.
1770
1771                port:
1772                  The  port  handle  of  the  port (driver instance) doing the
1773                  acknowledgment.
1774
1775                res:
1776                  The result of the port initialization. Can be the same  val‐
1777                  ues  as the return value of start, that is, any of the error
1778                  codes or the ErlDrvData that is to be used for this port.
1779
1780              When this function is  called  the  initiating  erlang:open_port
1781              call  is returned as if the start function had just been called.
1782              It can only be used when flag ERL_DRV_FLAG_USE_INIT_ACK has been
1783              set on the linked-in driver.
1784
1785       ErlDrvTime erl_drv_monotonic_time(ErlDrvTimeUnit time_unit)
1786
1787              Returns   Erlang monotonic time. Notice that negative values are
1788              not uncommon.
1789
1790              time_unit is time unit of returned value.
1791
1792              Returns ERL_DRV_TIME_ERROR if called with an invalid  time  unit
1793              argument,  or  if  called  from a thread that is not a scheduler
1794              thread.
1795
1796              See also ErlDrvTime and ErlDrvTimeUnit.
1797
1798       ErlDrvMutex *erl_drv_mutex_create(char
1799               *name)
1800
1801              Creates a mutex and returns a pointer to it.
1802
1803              name is a string identifying the created mutex. It  is  used  to
1804              identify the mutex in planned future debug functionality.
1805
1806              Returns  NULL  on  failure.  The  driver  creating  the mutex is
1807              responsible for destroying it before the driver is unloaded.
1808
1809              This function is thread-safe.
1810
1811       void erl_drv_mutex_destroy(ErlDrvMutex
1812               *mtx)
1813
1814              Destroys a mutex previously created by erl_drv_mutex_create. The
1815              mutex must be in an unlocked state before it is destroyed.
1816
1817              mtx is a pointer to a mutex to destroy.
1818
1819              This function is thread-safe.
1820
1821       void erl_drv_mutex_lock(ErlDrvMutex
1822               *mtx)
1823
1824              Locks a mutex. The calling thread is blocked until the mutex has
1825              been locked. A thread that has currently locked the mutex cannot
1826              lock the same mutex again.
1827
1828              mtx is a pointer to a mutex to lock.
1829
1830          Warning:
1831              If  you  leave a mutex locked in an emulator thread when you let
1832              the thread out of your control, you will  very  likely  deadlock
1833              the whole emulator.
1834
1835
1836              This function is thread-safe.
1837
1838       char *erl_drv_mutex_name(ErlDrvMutex
1839               *mtx)
1840
1841              Returns a pointer to the mutex name.
1842
1843              mtx is a pointer to an initialized mutex.
1844
1845          Note:
1846              This function is intended for debugging purposes only.
1847
1848
1849       int erl_drv_mutex_trylock(ErlDrvMutex
1850               *mtx)
1851
1852              Tries  to  lock  a mutex. A thread that has currently locked the
1853              mutex cannot try to lock the same mutex again.
1854
1855              mtx is a pointer to a mutex to try to lock.
1856
1857              Returns 0 on success, otherwise EBUSY.
1858
1859          Warning:
1860              If you leave a mutex locked in an emulator thread when  you  let
1861              the  thread  out  of your control, you will very likely deadlock
1862              the whole emulator.
1863
1864
1865              This function is thread-safe.
1866
1867       void erl_drv_mutex_unlock(ErlDrvMutex
1868               *mtx)
1869
1870              Unlocks a mutex. The mutex currently must be locked by the call‐
1871              ing thread.
1872
1873              mtx is a pointer to a mutex to unlock.
1874
1875              This function is thread-safe.
1876
1877       int erl_drv_output_term(ErlDrvTermData port,
1878               ErlDrvTermData* term, int n)
1879
1880              Sends  data  in the special driver term format to the port owner
1881              process. This is a fast way to deliver term data from a  driver.
1882              It  needs  no  binary  conversion,  so  the  port  owner process
1883              receives data as  normal  Erlang  terms.  The  erl_drv_send_term
1884              functions  can  be  used for sending to any process on the local
1885              node.
1886
1887          Note:
1888              Parameter port is not an ordinary port handle, but a port handle
1889              converted using driver_mk_port.
1890
1891
1892              Parameter  term points to an array of ErlDrvTermData with n ele‐
1893              ments. This array contains terms described in  the  driver  term
1894              format.  Every  term  consists of 1-4 elements in the array. The
1895              first term has a term type and then  arguments.  Parameter  port
1896              specifies the sending port.
1897
1898              Tuples, maps, and lists (except strings, see below) are built in
1899              reverse polish notation, so that to build a tuple, the  elements
1900              are  specified  first,  and  then  the tuple term, with a count.
1901              Likewise for lists and maps.
1902
1903                * A tuple must be specified with the number of elements.  (The
1904                  elements precede the ERL_DRV_TUPLE term.)
1905
1906                * A  map  must be specified with the number of key-value pairs
1907                  N. The key-value pairs must precede the ERL_DRV_MAP in  this
1908                  order:   key1,value1,key2,value2,...,keyN,valueN.  Duplicate
1909                  keys are not allowed.
1910
1911                * A list must  be  specified  with  the  number  of  elements,
1912                  including  the  tail,  which  is  the  last  term  preceding
1913                  ERL_DRV_LIST.
1914
1915              The special term ERL_DRV_STRING_CONS is used to  "splice"  in  a
1916              string  in  a list, a string specified this way is not a list in
1917              itself, but the elements are elements of the surrounding list.
1918
1919              Term type            Arguments
1920              ---------            ---------
1921              ERL_DRV_NIL
1922              ERL_DRV_ATOM         ErlDrvTermData atom (from driver_mk_atom(char *string))
1923              ERL_DRV_INT          ErlDrvSInt integer
1924              ERL_DRV_UINT         ErlDrvUInt integer
1925              ERL_DRV_INT64        ErlDrvSInt64 *integer_ptr
1926              ERL_DRV_UINT64       ErlDrvUInt64 *integer_ptr
1927              ERL_DRV_PORT         ErlDrvTermData port (from driver_mk_port(ErlDrvPort port))
1928              ERL_DRV_BINARY       ErlDrvBinary *bin, ErlDrvUInt len, ErlDrvUInt offset
1929              ERL_DRV_BUF2BINARY   char *buf, ErlDrvUInt len
1930              ERL_DRV_STRING       char *str, int len
1931              ERL_DRV_TUPLE        int sz
1932              ERL_DRV_LIST         int sz
1933              ERL_DRV_PID          ErlDrvTermData pid (from driver_connected(ErlDrvPort port)
1934                                   or driver_caller(ErlDrvPort port))
1935              ERL_DRV_STRING_CONS  char *str, int len
1936              ERL_DRV_FLOAT        double *dbl
1937              ERL_DRV_EXT2TERM     char *buf, ErlDrvUInt len
1938              ERL_DRV_MAP          int sz
1939
1940              The unsigned integer data type ErlDrvUInt and the signed integer
1941              data type ErlDrvSInt are 64 bits wide on a 64-bit runtime system
1942              and 32 bits wide on a 32-bit runtime system.  They  were  intro‐
1943              duced  in ERTS 5.6 and replaced some of the int arguments in the
1944              list above.
1945
1946              The unsigned integer data type ErlDrvUInt64 and the signed inte‐
1947              ger  data  type  ErlDrvSInt64 are always 64 bits wide. They were
1948              introduced in ERTS 5.7.4.
1949
1950              To build the tuple {tcp, Port, [100 |  Binary]},  the  following
1951              call can be made.
1952
1953              ErlDrvBinary* bin = ...
1954              ErlDrvPort port = ...
1955              ErlDrvTermData spec[] = {
1956                  ERL_DRV_ATOM, driver_mk_atom("tcp"),
1957                  ERL_DRV_PORT, driver_mk_port(drvport),
1958                      ERL_DRV_INT, 100,
1959                      ERL_DRV_BINARY, bin, 50, 0,
1960                      ERL_DRV_LIST, 2,
1961                  ERL_DRV_TUPLE, 3,
1962              };
1963              erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));
1964
1965              Here bin is a driver binary of length at least 50 and drvport is
1966              a port handle. Notice that ERL_DRV_LIST comes after the elements
1967              of the list, likewise ERL_DRV_TUPLE.
1968
1969              The  ERL_DRV_STRING_CONS  term is a way to construct strings. It
1970              works    differently    from    how    ERL_DRV_STRING     works.
1971              ERL_DRV_STRING_CONS  builds  a  string list in reverse order (as
1972              opposed to how ERL_DRV_LIST works),  concatenating  the  strings
1973              added   to   a   list.   The   tail  must  be  specified  before
1974              ERL_DRV_STRING_CONS.
1975
1976              ERL_DRV_STRING constructs a string, and ends it. (So it  is  the
1977              same as ERL_DRV_NIL followed by ERL_DRV_STRING_CONS.)
1978
1979              /* to send [x, "abc", y] to the port: */
1980              ErlDrvTermData spec[] = {
1981                  ERL_DRV_ATOM, driver_mk_atom("x"),
1982                  ERL_DRV_STRING, (ErlDrvTermData)"abc", 3,
1983                  ERL_DRV_ATOM, driver_mk_atom("y"),
1984                  ERL_DRV_NIL,
1985                  ERL_DRV_LIST, 4
1986              };
1987              erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));
1988
1989              /* to send "abc123" to the port: */
1990              ErlDrvTermData spec[] = {
1991                  ERL_DRV_NIL,        /* with STRING_CONS, the tail comes first */
1992                  ERL_DRV_STRING_CONS, (ErlDrvTermData)"123", 3,
1993                  ERL_DRV_STRING_CONS, (ErlDrvTermData)"abc", 3,
1994              };
1995              erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));
1996
1997              The  ERL_DRV_EXT2TERM  term  type  is  used  for  passing a term
1998              encoded with the external format, that is, a term that has  been
1999              encoded  by  erlang:term_to_binary,  erl_interface:ei(3), and so
2000              on. For example, if binp is a pointer to  an  ErlDrvBinary  that
2001              contains  term  {17, 4711} encoded with the external format, and
2002              you want to wrap it in a two-tuple with the tag my_tag, that is,
2003              {my_tag, {17, 4711}}, you can do as follows:
2004
2005              ErlDrvTermData spec[] = {
2006                      ERL_DRV_ATOM, driver_mk_atom("my_tag"),
2007                      ERL_DRV_EXT2TERM, (ErlDrvTermData) binp->orig_bytes, binp->orig_size
2008                  ERL_DRV_TUPLE, 2,
2009              };
2010              erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));
2011
2012              To build the map #{key1 => 100, key2 => {200, 300}}, the follow‐
2013              ing call can be made.
2014
2015              ErlDrvPort port = ...
2016              ErlDrvTermData spec[] = {
2017                  ERL_DRV_ATOM, driver_mk_atom("key1"),
2018                      ERL_DRV_INT, 100,
2019                  ERL_DRV_ATOM, driver_mk_atom("key2"),
2020                      ERL_DRV_INT, 200,
2021                      ERL_DRV_INT, 300,
2022                  ERL_DRV_TUPLE, 2,
2023                  ERL_DRV_MAP, 2
2024              };
2025              erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));
2026
2027              If you want to pass a binary and do not already have the content
2028              of  the  binary  in  an ErlDrvBinary, you can benefit from using
2029              ERL_DRV_BUF2BINARY instead of creating an  ErlDrvBinary  through
2030              driver_alloc_binary   and   then   pass   the   binary   through
2031              ERL_DRV_BINARY. The  runtime  system  often  allocates  binaries
2032              smarter  if  ERL_DRV_BUF2BINARY is used. However, if the content
2033              of the binary to pass already resides in an ErlDrvBinary, it  is
2034              normally  better to pass the binary using ERL_DRV_BINARY and the
2035              ErlDrvBinary in question.
2036
2037              The ERL_DRV_UINT, ERL_DRV_BUF2BINARY, and ERL_DRV_EXT2TERM  term
2038              types were introduced in ERTS 5.6.
2039
2040              This  function  is  only  thread-safe when the emulator with SMP
2041              support is used.
2042
2043       int erl_drv_putenv(const char *key, char
2044               *value)
2045
2046              Sets the value of an environment variable.
2047
2048              key is a NULL-terminated string containing the name of the envi‐
2049              ronment variable.
2050
2051              value  is  a  NULL-terminated string containing the new value of
2052              the environment variable.
2053
2054              Returns 0 on success, otherwise a value != 0.
2055
2056          Note:
2057              The result of passing the empty string ("") as a value is  plat‐
2058              form-dependent.  On  some platforms the variable value is set to
2059              the empty string, on others the environment variable is removed.
2060
2061
2062          Warning:
2063              Do not use libc's putenv or similar C library interfaces from  a
2064              driver.
2065
2066
2067              This function is thread-safe.
2068
2069       ErlDrvRWLock *erl_drv_rwlock_create(char
2070               *name)
2071
2072              Creates an rwlock and returns a pointer to it.
2073
2074              name  is  a string identifying the created rwlock. It is used to
2075              identify the rwlock in planned future debug functionality.
2076
2077              Returns NULL on failure.  The  driver  creating  the  rwlock  is
2078              responsible for destroying it before the driver is unloaded.
2079
2080              This function is thread-safe.
2081
2082       void erl_drv_rwlock_destroy(ErlDrvRWLock
2083               *rwlck)
2084
2085              Destroys  an rwlock previously created by erl_drv_rwlock_create.
2086              The rwlock must be in an unlocked state before it is destroyed.
2087
2088              rwlck is a pointer to an rwlock to destroy.
2089
2090              This function is thread-safe.
2091
2092       char *erl_drv_rwlock_name(ErlDrvRWLock
2093               *rwlck)
2094
2095              Returns a pointer to the name of the rwlock.
2096
2097              rwlck is a pointer to an initialized rwlock.
2098
2099          Note:
2100              This function is intended for debugging purposes only.
2101
2102
2103       void erl_drv_rwlock_rlock(ErlDrvRWLock
2104               *rwlck)
2105
2106              Read locks an rwlock. The calling thread is  blocked  until  the
2107              rwlock has been read locked. A thread that currently has read or
2108              read/write locked the rwlock cannot lock the same rwlock again.
2109
2110              rwlck is a pointer to the rwlock to read lock.
2111
2112          Warning:
2113              If you leave an rwlock locked in an emulator thread when you let
2114              the  thread  out  of your control, you will very likely deadlock
2115              the whole emulator.
2116
2117
2118              This function is thread-safe.
2119
2120       void erl_drv_rwlock_runlock(ErlDrvRWLock
2121               *rwlck)
2122
2123              Read unlocks an rwlock. The rwlock currently must be read locked
2124              by the calling thread.
2125
2126              rwlck is a pointer to an rwlock to read unlock.
2127
2128              This function is thread-safe.
2129
2130       void erl_drv_rwlock_rwlock(ErlDrvRWLock
2131               *rwlck)
2132
2133              Read/write  locks an rwlock. The calling thread is blocked until
2134              the rwlock has been read/write locked. A thread  that  currently
2135              has  read  or  read/write locked the rwlock cannot lock the same
2136              rwlock again.
2137
2138              rwlck is a pointer to an rwlock to read/write lock.
2139
2140          Warning:
2141              If you leave an rwlock locked in an emulator thread when you let
2142              the  thread  out  of your control, you will very likely deadlock
2143              the whole emulator.
2144
2145
2146              This function is thread-safe.
2147
2148       void erl_drv_rwlock_rwunlock(ErlDrvRWLock
2149               *rwlck)
2150
2151              Read/write unlocks an  rwlock.  The  rwlock  currently  must  be
2152              read/write locked by the calling thread.
2153
2154              rwlck is a pointer to an rwlock to read/write unlock.
2155
2156              This function is thread-safe.
2157
2158       int erl_drv_rwlock_tryrlock(ErlDrvRWLock
2159               *rwlck)
2160
2161              Tries to read lock an rwlock.
2162
2163              rwlck is a pointer to an rwlock to try to read lock.
2164
2165              Returns  0  on success, otherwise EBUSY. A thread that currently
2166              has read or read/write locked the rwlock cannot try to lock  the
2167              same rwlock again.
2168
2169          Warning:
2170              If you leave an rwlock locked in an emulator thread when you let
2171              the thread out of your control, you will  very  likely  deadlock
2172              the whole emulator.
2173
2174
2175              This function is thread-safe.
2176
2177       int erl_drv_rwlock_tryrwlock(ErlDrvRWLock
2178               *rwlck)
2179
2180              Tries  to read/write lock an rwlock. A thread that currently has
2181              read or read/write locked the rwlock cannot try to lock the same
2182              rwlock again.
2183
2184              rwlckis pointer to an rwlock to try to read/write lock.
2185
2186              Returns 0 on success, otherwise EBUSY.
2187
2188          Warning:
2189              If you leave an rwlock locked in an emulator thread when you let
2190              the thread out of your control, you will  very  likely  deadlock
2191              the whole emulator.
2192
2193
2194              This function is thread-safe.
2195
2196       int erl_drv_send_term(ErlDrvTermData port,
2197               ErlDrvTermData receiver, ErlDrvTermData* term, int n)
2198
2199              This function is the only way for a driver to send data to other
2200              processes than the port owner process. Parameter receiver speci‐
2201              fies the process to receive the data.
2202
2203          Note:
2204              Parameter port is not an ordinary port handle, but a port handle
2205              converted using driver_mk_port.
2206
2207
2208              Parameters port, term, and n work as in erl_drv_output_term.
2209
2210              This function is only thread-safe when  the  emulator  with  SMP
2211              support is used.
2212
2213       void erl_drv_set_os_pid(ErlDrvPort port,
2214               ErlDrvSInt pid)
2215
2216              Sets the os_pid seen when doing erlang:port_info/2 on this port.
2217
2218              port is the port handle of the port (driver instance) to set the
2219              pid on. pidis the pid to set.
2220
2221       int erl_drv_thread_create(char *name, ErlDrvTid
2222               *tid, void * (*func)(void *), void *arg, ErlDrvThreadOpts
2223               *opts)
2224
2225              Creates a new thread.
2226
2227                name:
2228                  A string identifying the created thread. It is used to iden‐
2229                  tify the thread in planned future debug functionality.
2230
2231                tid:
2232                  A pointer to a thread identifier variable.
2233
2234                func:
2235                  A pointer to a function to execute in the created thread.
2236
2237                arg:
2238                  A pointer to argument to the func function.
2239
2240                opts:
2241                  A pointer to thread options to use or NULL.
2242
2243              Returns  0  on  success, otherwise an errno value is returned to
2244              indicate the error. The newly created thread begins executing in
2245              the function pointed to by func, and func is passed arg as argu‐
2246              ment. When erl_drv_thread_create returns, the thread  identifier
2247              of  the  newly  created thread is available in *tid. opts can be
2248              either a NULL pointer,  or  a  pointer  to  an  ErlDrvThreadOpts
2249              structure.  If opts is a NULL pointer, default options are used,
2250              otherwise the passed options are used.
2251
2252          Warning:
2253              You are not allowed to allocate the  ErlDrvThreadOpts  structure
2254              by   yourself.   It   must   be  allocated  and  initialized  by
2255              erl_drv_thread_opts_create.
2256
2257
2258              The created thread terminates either when  func  returns  or  if
2259              erl_drv_thread_exit  is  called by the thread. The exit value of
2260              the thread is either returned from func or passed as argument to
2261              erl_drv_thread_exit. The driver creating the thread is responsi‐
2262              ble for joining the thread, through erl_drv_thread_join,  before
2263              the  driver  is  unloaded. "Detached" threads cannot be created,
2264              that is, threads that do not need to be joined.
2265
2266          Warning:
2267              All created threads must be joined by the driver  before  it  is
2268              unloaded. If the driver fails to join all threads created before
2269              it is unloaded, the runtime system most likely crashes when  the
2270              driver code is unloaded.
2271
2272
2273              This function is thread-safe.
2274
2275       void erl_drv_thread_exit(void
2276               *exit_value)
2277
2278              Terminates  the  calling  thread  with  the exit value passed as
2279              argument. exit_value is a pointer to an exit value or NULL.
2280
2281              You  are  only  allowed  to  terminate  threads   created   with
2282              erl_drv_thread_create.
2283
2284              The  exit value can later be retrieved by another thread through
2285              erl_drv_thread_join.
2286
2287              This function is thread-safe.
2288
2289       int erl_drv_thread_join(ErlDrvTid tid, void
2290               **exit_value)
2291
2292              Joins the calling thread with another thread, that is, the call‐
2293              ing  thread  is  blocked  until the thread identified by tid has
2294              terminated.
2295
2296              tid is the thread identifier of the thread to  join.  exit_value
2297              is a pointer to a pointer to an exit value, or NULL.
2298
2299              Returns  0  on  success, otherwise an errno value is returned to
2300              indicate the error.
2301
2302              A thread can only be joined once. The behavior of  joining  more
2303              than  once  is  undefined,  an  emulator  crash  is  likely.  If
2304              exit_value == NULL, the exit value of the terminated  thread  is
2305              ignored,  otherwise  the  exit value of the terminated thread is
2306              stored at *exit_value.
2307
2308              This function is thread-safe.
2309
2310       char *erl_drv_thread_name(ErlDrvTid
2311               tid)
2312
2313              Returns a pointer to the name of the thread.
2314
2315              tid is a thread identifier.
2316
2317          Note:
2318              This function is intended for debugging purposes only.
2319
2320
2321       ErlDrvThreadOpts *erl_drv_thread_opts_create(char *name)
2322
2323              Allocates and initializes a thread option structure.
2324
2325              name is a string identifying the created thread options.  It  is
2326              used  to  identify  the  thread  options in planned future debug
2327              functionality.
2328
2329              Returns NULL on failure. A thread option structure is  used  for
2330              passing  options  to  erl_drv_thread_create. If the structure is
2331              not modified before it is passed to  erl_drv_thread_create,  the
2332              default values are used.
2333
2334          Warning:
2335              You  are  not allowed to allocate the ErlDrvThreadOpts structure
2336              by  yourself.  It  must  be   allocated   and   initialized   by
2337              erl_drv_thread_opts_create.
2338
2339
2340              This function is thread-safe.
2341
2342       void erl_drv_thread_opts_destroy(ErlDrvThreadOpts *opts)
2343
2344              Destroys     thread     options     previously     created    by
2345              erl_drv_thread_opts_create.
2346
2347              opts is a pointer to thread options to destroy.
2348
2349              This function is thread-safe.
2350
2351       ErlDrvTid erl_drv_thread_self(void)
2352
2353              Returns the thread identifier of the calling thread.
2354
2355              This function is thread-safe.
2356
2357       ErlDrvTime erl_drv_time_offset(ErlDrvTimeUnit
2358               time_unit)
2359
2360              Returns the current time offset between  Erlang  monotonic  time
2361              and   Erlang  system time converted into the time_unit passed as
2362              argument.
2363
2364              time_unit is time unit of returned value.
2365
2366              Returns ERL_DRV_TIME_ERROR if called with an invalid  time  unit
2367              argument,  or  if  called  from a thread that is not a scheduler
2368              thread.
2369
2370              See also ErlDrvTime and ErlDrvTimeUnit.
2371
2372       void *erl_drv_tsd_get(ErlDrvTSDKey
2373               key)
2374
2375              Returns the thread-specific data associated  with  key  for  the
2376              calling thread.
2377
2378              key is a thread-specific data key.
2379
2380              Returns  NULL  if  no  data has been associated with key for the
2381              calling thread.
2382
2383              This function is thread-safe.
2384
2385       int erl_drv_tsd_key_create(char *name,
2386               ErlDrvTSDKey *key)
2387
2388              Creates a thread-specific data key.
2389
2390              name is a string identifying the created  key.  It  is  used  to
2391              identify the key in planned future debug functionality.
2392
2393              key is a pointer to a thread-specific data key variable.
2394
2395              Returns  0  on  success, otherwise an errno value is returned to
2396              indicate the error. The driver creating the key  is  responsible
2397              for destroying it before the driver is unloaded.
2398
2399              This function is thread-safe.
2400
2401       void erl_drv_tsd_key_destroy(ErlDrvTSDKey
2402               key)
2403
2404              Destroys  a  thread-specific  data  key  previously  created  by
2405              erl_drv_tsd_key_create. All thread-specific data using this  key
2406              in  all threads must be cleared (see erl_drv_tsd_set) before the
2407              call to erl_drv_tsd_key_destroy.
2408
2409              key is a thread-specific data key to destroy.
2410
2411          Warning:
2412              A destroyed key is very likely to be reused soon. Therefore,  if
2413              you  fail  to clear the thread-specific data using this key in a
2414              thread before destroying the key, you will very likely get unex‐
2415              pected errors in other parts of the system.
2416
2417
2418              This function is thread-safe.
2419
2420       void erl_drv_tsd_set(ErlDrvTSDKey key, void
2421               *data)
2422
2423              Sets  thread-specific  data  associated with key for the calling
2424              thread. You are only allowed to  set  thread-specific  data  for
2425              threads while they are fully under your control. For example, if
2426              you set thread-specific data in a thread calling a driver  call‐
2427              back  function, it must be cleared, that is, set to NULL, before
2428              returning from the driver callback function.
2429
2430              key is a thread-specific data key.
2431
2432              data is a pointer to data to associate with key in  the  calling
2433              thread.
2434
2435          Warning:
2436              If  you fail to clear thread-specific data in an emulator thread
2437              before letting it out of your control, you might never  be  able
2438              to  clear  this data with later unexpected errors in other parts
2439              of the system as a result.
2440
2441
2442              This function is thread-safe.
2443
2444       char *erl_errno_id(int error)
2445
2446              Returns the atom name of the Erlang error, given the error  num‐
2447              ber  in error. The error atoms are einval, enoent, and so on. It
2448              can be used to make error terms from the driver.
2449
2450       int remove_driver_entry(ErlDrvEntry
2451               *de)
2452
2453              Removes   a   driver   entry   de    previously    added    with
2454              add_driver_entry.
2455
2456              Driver  entries added by the erl_ddll Erlang interface cannot be
2457              removed by using this interface.
2458
2459       void set_busy_port(ErlDrvPort port, int
2460               on)
2461
2462              Sets and unsets the busy state of the port. If on  is  non-zero,
2463              the  port  is set to busy. If it is zero, the port is set to not
2464              busy. You typically want to combine this feature with the   busy
2465              port message queue functionality.
2466
2467              Processes  sending  command  data  to  the port are suspended if
2468              either the port or the port message  queue  is  busy.  Suspended
2469              processes  are resumed when neither the port or the port message
2470              queue is busy. Command data is in this context  data  passed  to
2471              the  port  using  either  Port  !  {Owner,  {command,  Data}} or
2472              port_command/[2,3].
2473
2474              If the  ERL_DRV_FLAG_SOFT_BUSY has been set in the driver_entry,
2475              data  can  be  forced  into  the driver through erlang:port_com‐
2476              mand(Port, Data, [force]) even if the driver has  signaled  that
2477              it is busy.
2478
2479              For information about busy port message queue functionality, see
2480              erl_drv_busy_msgq_limits.
2481
2482       void set_port_control_flags(ErlDrvPort port,
2483               int flags)
2484
2485              Sets flags for how the control driver entry function will return
2486              data  to the port owner process. (The control function is called
2487              from erlang:port_control/3.)
2488
2489              Currently there are only two  meaningful  values  for  flags:  0
2490              means   that   data   is  returned  in  a  list,  and  PORT_CON‐
2491              TROL_FLAG_BINARY means data is returned as a  binary  from  con‐
2492              trol.
2493

SEE ALSO

2495       driver_entry(3),  erlang(3),  erl_ddll(3),  section How to Implement an
2496       Alternative Carrier for the Erlang Distribution> in the User's Guide
2497
2498
2499
2500Ericsson AB                      erts 9.3.3.10                   erl_driver(3)
Impressum