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

NAME

6       erl_driver - API functions for an Erlang driver.
7

DESCRIPTION

9       An  Erlang  driver is a library containing a set of native driver call‐
10       back functions that the  Erlang  Virtual  Machine  calls  when  certain
11       events  occur.  There  can  be  multiple  instances  of  a driver, each
12       instance is associated with an Erlang port.
13
14   Warning:
15       Use this functionality with extreme care.
16
17       A driver callback is executed as a direct extension of the native  code
18       of  the  VM. Execution is not made in a safe environment. The VM cannot
19       provide the same services as provided when executing Erlang code,  such
20       as  pre-emptive scheduling or memory protection. If the driver callback
21       function does not behave well, the whole VM will misbehave.
22
23         * A driver callback that crash will crash the whole VM.
24
25         * An erroneously implemented driver callback can cause a VM  internal
26           state  inconsistency, which can cause a crash of the VM, or miscel‐
27           laneous misbehaviors of the VM at any point after the call  to  the
28           driver callback.
29
30         * A  driver  callback  doing  lengthy  work before returning degrades
31           responsiveness of the VM and can cause miscellaneous strange behav‐
32           iors.  Such  strange  behaviors  include,  but  are not limited to,
33           extreme memory usage and bad  load  balancing  between  schedulers.
34           Strange  behaviors  that can occur because of lengthy work can also
35           vary between Erlang/OTP releases.
36
37       As from ERTS 5.5.3 the driver interface has been extended (see extended
38       marker). The extended interface introduces version management, the pos‐
39       sibility to pass capability flags (see  driver_flags)  to  the  runtime
40       system at driver initialization, and some new driver API functions.
41
42   Note:
43       As  from  ERTS  5.9 old drivers must be recompiled and use the extended
44       interface. They must also be adjusted to  the   64-bit  capable  driver
45       interface.
46
47
48       The driver calls back to the emulator, using the API functions declared
49       in erl_driver.h. They are used for outputting  data  from  the  driver,
50       using timers, and so on.
51
52       Each  driver  instance is associated with a port. Every port has a port
53       owner process. Communication with the port is normally done through the
54       port  owner  process.  Most of the functions take the port handle as an
55       argument. This identifies the driver instance. Notice  that  this  port
56       handle must be stored by the driver, it is not given when the driver is
57       called from the emulator (see driver_entry).
58
59       Some of the functions take a parameter of type ErlDrvBinary,  a  driver
60       binary.  It  is  to  be both allocated and freed by the caller. Using a
61       binary directly avoids one extra copying of data.
62
63       Many of the output functions have a "header buffer", with hbuf and hlen
64       parameters.  This  buffer is sent as a list before the binary (or list,
65       depending on port mode) that is sent. This is convenient when  matching
66       on messages received from the port. (Although in the latest Erlang ver‐
67       sions there is the binary syntax, which enables you  to  match  on  the
68       beginning of a binary.)
69
70       In  the  runtime  system with SMP support, drivers are locked either on
71       driver level or port level (driver instance level). By  default  driver
72       level locking will be used, that is, only one emulator thread will exe‐
73       cute code in the driver at a time. If port level locking is used,  mul‐
74       tiple emulator threads can execute code in the driver at the same time.
75       Only one thread at a time will call driver callbacks  corresponding  to
76       the   same  port,  though.  To  enable  port  level  locking,  set  the
77       ERL_DRV_FLAG_USE_PORT_LOCKING driver flag in the driver_entry  used  by
78       the  driver.  When  port  level  locking  is used, the driver writer is
79       responsible for synchronizing all accesses to data shared by the  ports
80       (driver instances).
81
82       Most drivers written before the runtime system with SMP support existed
83       can run in the runtime system with SMP support, without  being  rewrit‐
84       ten, if driver level locking is used.
85
86   Note:
87       It  is  assumed  that  drivers  do not access other drivers. If drivers
88       access each other, they must provide their own  mechanism  for  thread-
89       safe  synchronization.  Such  "inter-driver  communication" is strongly
90       discouraged.
91
92
93       Previously, in the runtime system without SMP support, specific  driver
94       callbacks were always called from the same thread. This is not the case
95       in the runtime system with SMP support. Regardless  of  locking  scheme
96       used, calls to driver callbacks can be made from different threads. For
97       example, two consecutive calls to exactly the same callback for exactly
98       the  same port can be made from two different threads. This is for most
99       drivers not a problem, but it can be. Drivers that depend on all  call‐
100       backs that are called in the same thread, must be rewritten before they
101       are used in the runtime system with SMP support.
102
103   Note:
104       Regardless of locking scheme used, calls to  driver  callbacks  can  be
105       made from different threads.
106
107
108       Most functions in this API are not thread-safe, that is, they cannot be
109       called from 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
169           erlang:open_port/2. The vector function and the function  taking  a
170           driver  binary  are  faster, as they avoid copying the data buffer.
171           There is also a fast way of sending terms from the driver,  without
172           going through the binary term format.
173
174         Failure:
175           The  driver  can  exit and signal errors up to Erlang. This is only
176           for severe errors, when the driver cannot possibly keep open.
177
178         Asynchronous calls:
179           Erlang/OTP R7B and later versions have provision  for  asynchronous
180           function  calls,  using  a thread pool provided by Erlang. There is
181           also a select call, which can be used for asynchronous drivers.
182
183         Multi-threading:
184           A POSIX thread like API for multi-threading is provided. The Erlang
185           driver  thread API only provides a subset of the functionality pro‐
186           vided by the POSIX thread API. The subset provided is more or  less
187           the basic functionality needed for multi-threaded programming:
188
189           * Threads
190
191           * Mutexes
192
193           *
194              Condition variables
195
196           *
197              Read/write locks
198
199           *
200              Thread-specific data
201
202           The  Erlang  driver  thread API can be used in conjunction with the
203           POSIX thread API on UN-ices and with the Windows native thread  API
204           on Windows. The Erlang driver thread API has the advantage of being
205           portable, but there can exist situations  where  you  want  to  use
206           functionality  from  the  POSIX  thread  API  or the Windows native
207           thread API.
208
209           The Erlang driver thread API only returns error codes  when  it  is
210           reasonable to recover from an error condition. If it is not reason‐
211           able to recover from an error condition, the whole  runtime  system
212           is  terminated.  For example, if a create mutex operation fails, an
213           error code is returned, but if a lock operation on a  mutex  fails,
214           the whole runtime system is terminated.
215
216           Notice  that there is no "condition variable wait with time-out" in
217           the  Erlang  driver  thread  API.  This  because  of  issues   with
218           pthread_cond_timedwait.  When the system clock suddenly is changed,
219           it is not always guaranteed that you will wake up from the call  as
220           expected. An Erlang runtime system must be able to cope with sudden
221           changes of the system clock. Therefore, we have omitted it from the
222           Erlang  driver thread API. In the Erlang driver case, time-outs can
223           and are to be handled with the timer functionality  of  the  Erlang
224           driver API.
225
226           In  order for the Erlang driver thread API to function, thread sup‐
227           port must be enabled in the runtime system. An  Erlang  driver  can
228           check  if  thread  support is enabled by use of driver_system_info.
229           Notice that some functions in the Erlang driver API are thread-safe
230           only when the runtime system has SMP support, also this information
231           can be retrieved through driver_system_info. Also notice that  many
232           functions  in the Erlang driver API are not thread-safe, regardless
233           of whether SMP support is enabled or not. If a function is not doc‐
234           umented as thread-safe, it is not thread-safe.
235
236     Note:
237         When  executing  in an emulator thread, it is very important that you
238         unlock all locks you have locked before letting  the  thread  out  of
239         your  control;  otherwise  you  are very likely to deadlock the whole
240         emulator.
241
242         If you need to use thread-specific data in an emulator  thread,  only
243         have the thread-specific data set while the thread is under your con‐
244         trol, and clear the thread-specific data before you  let  the  thread
245         out of your control.
246
247
248           In the future, debug functionality will probably be integrated with
249           the Erlang driver thread API. All functions  that  create  entities
250           take a name argument. Currently the name argument is unused, but it
251           will be used when the debug functionality is  implemented.  If  you
252           name  all  entities  created  well, the debug functionality will be
253           able to give you better error reports.
254
255         Adding/removing drivers:
256           A driver can add and later remove drivers.
257
258         Monitoring processes:
259           A driver can monitor a process that does not own a port.
260
261         Version management:
262           Version management  is  enabled  for  drivers  that  have  set  the
263           extended_marker      field     of     their     driver_entry     to
264           ERL_DRV_EXTENDED_MARKER. erl_driver.h defines:
265
266           * ERL_DRV_EXTENDED_MARKER
267
268           * ERL_DRV_EXTENDED_MAJOR_VERSION, which is incremented when  driver
269             incompatible  changes are made to the Erlang runtime system. Nor‐
270             mally    it    suffices     to     recompile     drivers     when
271             ERL_DRV_EXTENDED_MAJOR_VERSION  has  changed,  but  it can, under
272             rare circumstances, mean that drivers must be slightly  modified.
273             If so, this will of course be documented.
274
275           * ERL_DRV_EXTENDED_MINOR_VERSION,  which  is  incremented  when new
276             features are added. The runtime system uses the minor version  of
277             the driver to determine what features to use.
278
279           The  runtime  system normally refuses to load a driver if the major
280           versions differ, or if the major versions are equal and  the  minor
281           version used by the driver is greater than the one used by the run‐
282           time system. Old drivers with  lower  major  versions  are  however
283           allowed  after  a  bump  of  the  major version during a transition
284           period of two major releases. Such old drivers can,  however,  fail
285           if deprecated features are used.
286
287           The  emulator  refuses  to  load  a  driver  that  does not use the
288           extended driver interface, to allow for 64-bit capable drivers,  as
289           incompatible  type  changes  for the callbacks output, control, and
290           call were introduced in Erlang/OTP R15B. A driver written with  the
291           old  types  would  compile  with  warnings  and  when called return
292           garbage sizes to the emulator, causing it to read random memory and
293           create huge incorrect result blobs.
294
295           Therefore  it  is not enough to only recompile drivers written with
296           version management for pre R15B types; the types must be changed in
297           the  driver  suggesting  other  rewrites, especially regarding size
298           variables. Investigate all warnings when recompiling.
299
300           Also,    the    API    driver    functions    driver_output*    and
301           driver_vec_to_buf,  driver_alloc/realloc*,  and  the driver_* queue
302           functions were changed to have larger length arguments  and  return
303           values. This is a lesser problem, as code that passes smaller types
304           gets them auto-converted in the calls, and as long  as  the  driver
305           does  not  handle  sizes  that  overflow  an  int, all will work as
306           before.
307
308         Time measurement:
309           Support for time measurement in drivers:
310
311           * ErlDrvTime
312
313           * ErlDrvTimeUnit
314
315           * erl_drv_monotonic_time
316
317           * erl_drv_time_offset
318
319           * erl_drv_convert_time_unit
320

REWRITES FOR 64-BIT DRIVER INTERFACE

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

DATA TYPES

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

EXPORTS

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

SEE ALSO

2503       driver_entry(3),  erlang(3),  erl_ddll(3),  section How to Implement an
2504       Alternative Carrier for the Erlang Distribution in the User's Guide
2505
2506
2507
2508Ericsson AB                      erts 10.3.5.2                   erl_driver(3)
Impressum