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 in‐
12       stance 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 re‐
31           sponsiveness of the VM and can cause miscellaneous  strange  behav‐
32           iors.  Such  strange behaviors include, but are not limited to, ex‐
33           treme 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 in‐
45       terface.
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, us‐
50       ing 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 bi‐
61       nary 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 be‐
68       ginning of a binary.)
69
70       Drivers  are  locked  either  on driver level or port level (driver in‐
71       stance level). By default driver level locking will be used,  that  is,
72       only  one emulator thread will execute code in the driver at a time. If
73       port level locking is used, multiple emulator threads can execute  code
74       in  the  driver  at  the same time. Only one thread at a time will call
75       driver callbacks corresponding to the same port, though. To enable port
76       level locking, set the ERL_DRV_FLAG_USE_PORT_LOCKING driver flag in the
77       driver_entry used by the driver. When port level locking is  used,  the
78       driver  writer  is  responsible  for synchronizing all accesses to data
79       shared by the ports (driver instances).
80
81       Most drivers written before the runtime system with SMP support existed
82       can  run  in the runtime system with SMP support, without being rewrit‐
83       ten, if driver level locking is used.
84
85   Note:
86       It is assumed that drivers do not access other drivers. If drivers  ac‐
87       cess  each other, they must provide their own mechanism for thread-safe
88       synchronization. Such "inter-driver communication" is strongly discour‐
89       aged.
90
91
92   Note:
93       Regardless  of  locking  scheme  used, calls to driver callbacks can be
94       made from different threads.
95
96
97       Most functions in this API are not thread-safe, that is, they cannot be
98       called  from  arbitrary  threads.  Functions that are not documented as
99       thread-safe can only be called from driver callbacks or function  calls
100       descending  from  a  driver callback call. Notice that driver callbacks
101       can be called from different threads. This, however, is not  a  problem
102       for  any  function  in this API, as the emulator has control over these
103       threads.
104
105   Warning:
106       Functions not explicitly documented as thread-safe are not thread safe.
107
108       A function not explicitly documented as thread-safe can, at some  point
109       in  time, have a thread-safe implementation in the runtime system. Such
110       an implementation can however change to a thread unsafe  implementation
111       at any time without any notice.
112
113       Only  use functions explicitly documented as thread-safe from arbitrary
114       threads.
115
116
117       As mentioned in the warning text at the beginning of this  section,  it
118       is  of vital importance that a driver callback returns relatively fast.
119       It is difficult to give an exact maximum amount of time that  a  driver
120       callback  is  allowed to work, but usually a well-behaving driver call‐
121       back is to return within 1 millisecond. This can be achieved using dif‐
122       ferent approaches. If you have full control over the code to execute in
123       the driver callback, the best approach is to divide the work into  mul‐
124       tiple  chunks of work, and trigger multiple calls to the time-out call‐
125       back using zero time-outs. Function  erl_drv_consume_timeslice  can  be
126       useful  to determine when to trigger such time-out callback calls. How‐
127       ever, sometimes it cannot be implemented this  way,  for  example  when
128       calling third-party libraries. In this case, you typically want to dis‐
129       patch the work to another thread. Information about  thread  primitives
130       is provided below.
131

FUNCTIONALITY

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

REWRITES FOR 64-BIT DRIVER INTERFACE

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

DATA TYPES

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

EXPORTS

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

SEE ALSO

2490       driver_entry(3), erlang(3), erl_ddll(3), section How  to  Implement  an
2491       Alternative Carrier for the Erlang Distribution in the User's Guide
2492
2493
2494
2495Ericsson AB                       erts 12.1.5                    erl_driver(3)
Impressum