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

FUNCTIONALITY

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

REWRITES FOR 64-BIT DRIVER INTERFACE

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

DATA TYPES

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

EXPORTS

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

SEE ALSO

2518       driver_entry(3), erlang(3), erl_ddll(3), section How  to  Implement  an
2519       Alternative Carrier for the Erlang Distribution in the User's Guide
2520
2521
2522
2523Ericsson AB                      erts 11.2.2.2                   erl_driver(3)
Impressum