81fdc97df47ac07aedb1776588ff1b1cd90733c8
[openssl.git] / doc / crypto / ASYNC_start_job.pod
1 =pod
2
3 =head1 NAME
4
5 ASYNC_init_thread, ASYNC_cleanup_thread, ASYNC_start_job, ASYNC_pause_job,
6 ASYNC_in_job, ASYNC_get_wait_fd, ASYNC_set_wait_fd, ASYNC_clear_wait_fd,
7 ASYNC_get_current_job, ASYNC_block_pause, ASYNC_unblock_pause - asynchronous job
8 management functions
9
10 =head1 SYNOPSIS
11
12  #include <openssl/async.h>
13
14  int ASYNC_init_thread(size_t max_size, size_t init_size);
15  void ASYNC_cleanup_thread(void);
16
17  int ASYNC_start_job(ASYNC_JOB **job, ASYNC_WAIT_CTX *ctx, int *ret,
18                      int (*func)(void *), void *args, size_t size);
19  int ASYNC_pause_job(void);
20
21  ASYNC_JOB *ASYNC_get_current_job(void);
22  ASYNC_WAIT_CTX *ASYNC_get_wait_ctx(ASYNC_JOB *job);
23  void ASYNC_block_pause(void);
24  void ASYNC_unblock_pause(void);
25
26 =head1 DESCRIPTION
27
28 OpenSSL implements asynchronous capabilities through an ASYNC_JOB. This
29 represents code that can be started and executes until some event occurs. At
30 that point the code can be paused and control returns to user code until some
31 subsequent event indicates that the job can be resumed.
32
33 The creation of an ASYNC_JOB is a relatively expensive operation. Therefore, for
34 efficiency reasons, jobs can be created up front and reused many times. They are
35 held in a pool until they are needed, at which point they are removed from the
36 pool, used, and then returned to the pool when the job completes. If the user
37 application is multi-threaded, then ASYNC_init_thread() may be called for each
38 thread that will initiate asynchronous jobs. Before
39 user code exits per-thread resources need to be cleaned up. This will normally
40 occur automatically (see L<OPENSSL_init_crypto(3)>) but may be explicitly
41 initiated by using ASYNC_cleanup_thread(). No asynchronous jobs must be
42 outstanding for the thread when ASYNC_cleanup_thread() is called. Failing to
43 ensure this will result in memory leaks.
44
45 The B<max_size> argument limits the number of ASYNC_JOBs that will be held in
46 the pool. If B<max_size> is set to 0 then no upper limit is set. When an
47 ASYNC_JOB is needed but there are none available in the pool already then one
48 will be automatically created, as long as the total of ASYNC_JOBs managed by the
49 pool does not exceed B<max_size>. When the pool is first initialised
50 B<init_size> ASYNC_JOBs will be created immediately. If ASYNC_init_thread() is
51 not called before the pool is first used then it will be called automatically
52 with a B<max_size> of 0 (no upper limit) and an B<init_size> of 0 (no ASYNC_JOBs
53 created up front).
54
55 An asynchronous job is started by calling the ASYNC_start_job() function.
56 Initially B<*job> should be NULL. B<ctx> should point to an ASYNC_WAIT_CTX
57 object created through the L<ASYNC_WAIT_CTX_new(3)> function. B<ret> should
58 point to a location where the return value of the asynchronous function should
59 be stored on completion of the job. B<func> represents the function that should
60 be started asynchronously. The data pointed to by B<args> and of size B<size>
61 will be copied and then passed as an argument to B<func> when the job starts.
62 ASYNC_start_job will return one of the following values:
63
64 =over 4
65
66 =item B<ASYNC_ERR>
67
68 An error occurred trying to start the job. Check the OpenSSL error queue (e.g.
69 see L<ERR_print_errors(3)>) for more details.
70
71 =item B<ASYNC_NO_JOBS>
72
73 There are no jobs currently available in the pool. This call can be retried
74 again at a later time.
75
76 =item B<ASYNC_PAUSE>
77
78 The job was successfully started but was "paused" before it completed (see
79 ASYNC_pause_job() below). A handle to the job is placed in B<*job>. Other work
80 can be performed (if desired) and the job restarted at a later time. To restart
81 a job call ASYNC_start_job() again passing the job handle in B<*job>. The
82 B<func>, B<args> and B<size> parameters will be ignored when restarting a job.
83 When restarting a job ASYNC_start_job() B<must> be called from the same thread
84 that the job was originally started from.
85
86 =item B<ASYNC_FINISH>
87
88 The job completed. B<*job> will be NULL and the return value from B<func> will
89 be placed in B<*ret>.
90
91 =back
92
93 At any one time there can be a maximum of one job actively running per thread
94 (you can have many that are paused). ASYNC_get_current_job() can be used to get
95 a pointer to the currently executing ASYNC_JOB. If no job is currently executing
96 then this will return NULL.
97
98 If executing within the context of a job (i.e. having been called directly or
99 indirectly by the function "func" passed as an argument to ASYNC_start_job())
100 then ASYNC_pause_job() will immediately return control to the calling
101 application with ASYNC_PAUSE returned from the ASYNC_start_job() call. A
102 subsequent call to ASYNC_start_job passing in the relevant ASYNC_JOB in the
103 B<*job> parameter will resume execution from the ASYNC_pause_job() call. If
104 ASYNC_pause_job() is called whilst not within the context of a job then no
105 action is taken and ASYNC_pause_job() returns immediately.
106
107 ASYNC_get_wait_ctx() can be used to get a pointer to the ASYNC_WAIT_CTX
108 for the B<job>. ASYNC_WAIT_CTXs can have a "wait" file descriptor associated
109 with them. Applications can wait for the file descriptor to be ready for "read"
110 using a system function call such as select or poll (being ready for "read"
111 indicates that the job should be resumed). If no file descriptor is made
112 available then an application will have to priodically "poll" the job by
113 attempting to restart it to see if it is ready to continue.
114
115 An example of typical usage might be an async capable engine. User code would
116 initiate cryptographic operations. The engine would initiate those operations
117 asynchronously and then call L<ASYNC_WAIT_CTX_set_wait_fd(3)> followed by
118 ASYNC_pause_job() to return control to the user code. The user code can then
119 perform other tasks or wait for the job to be ready by calling "select" or other
120 similar function on the wait file descriptor. The engine can signal to the user
121 code that the job should be resumed by making the wait file descriptor
122 "readable". Once resumed the engine should clear the wake signal on the wait
123 file descriptor.
124
125 The ASYNC_block_pause() function will prevent the currently active job from
126 pausing. The block will remain in place until a subsequent call to
127 ASYNC_unblock_pause(). These functions can be nested, e.g. if you call
128 ASYNC_block_pause() twice then you must call ASYNC_unblock_pause() twice in
129 order to reenable pausing. If these functions are called while there is no
130 currently active job then they have no effect. This functionality can be useful
131 to avoid deadlock scenarios. For example during the execution of an ASYNC_JOB an
132 application acquires a lock. It then calls some cryptographic function which
133 invokes ASYNC_pause_job(). This returns control back to the code that created
134 the ASYNC_JOB. If that code then attempts to acquire the same lock before
135 resuming the original job then a deadlock can occur. By calling
136 ASYNC_block_pause() immediately after aquiring the lock and
137 ASYNC_unblock_pause() immediately before releasing it then this situation cannot
138 occur.
139
140 =head1 RETURN VALUES
141
142 ASYNC_init_thread returns 1 on success or 0 otherwise.
143
144 ASYNC_start_job returns one of ASYNC_ERR, ASYNC_NO_JOBS, ASYNC_PAUSE or
145 ASYNC_FINISH as described above.
146
147 ASYNC_pause_job returns 0 if an error occurred or 1 on success. If called when
148 not within the context of an ASYNC_JOB then this is counted as success so 1 is
149 returned.
150
151 ASYNC_get_current_job returns a pointer to the currently executing ASYNC_JOB or
152 NULL if not within the context of a job.
153
154 ASYNC_get_wait_ctx() returns a pointer to the ASYNC_WAIT_CTX for the job.
155
156 =head1 EXAMPLE
157
158 The following example demonstrates how to use most of the core async APIs:
159
160  #include <stdio.h>
161  #include <unistd.h>
162  #include <openssl/async.h>
163  #include <openssl/crypto.h>
164
165  #define WAIT_SIGNAL_CHAR   'X'
166
167  int unique = 0;
168
169  void cleanup(ASYNC_WAIT_CTX *ctx, const void *key, OSSL_ASYNC_FD r, void *vw)
170  {
171      OSSL_ASYNC_FD *w = (OSSL_ASYNC_FD *)vw;
172      close(r);
173      close(*w);
174      OPENSSL_free(w);
175  }
176
177  int jobfunc(void *arg)
178  {
179      ASYNC_JOB *currjob;
180      unsigned char *msg;
181      int pipefds[2] = {0, 0};
182      OSSL_ASYNC_FD *wptr;
183      char buf = WAIT_SIGNAL_CHAR;
184
185      currjob = ASYNC_get_current_job();
186      if (currjob != NULL) {
187          printf("Executing within a job\n");
188      } else {
189          printf("Not executing within a job - should not happen\n");
190          return 0;
191      }
192
193      msg = (unsigned char *)arg;
194      printf("Passed in message is: %s\n", msg);
195
196      if (pipe(pipefds) != 0) {
197          printf("Failed to create pipe\n");
198          return 0;
199      }
200      wptr = OPENSSL_malloc(sizeof(OSSL_ASYNC_FD));
201      if (wptr == NULL) {
202          printf("Failed to malloc\n");
203          return 0;
204      }
205      *wptr = pipefds[1];
206      ASYNC_WAIT_CTX_set_wait_fd(ASYNC_get_wait_ctx(currjob), &unique,
207                                 pipefds[0], wptr, cleanup);
208
209      /*
210       * Normally some external event would cause this to happen at some
211       * later point - but we do it here for demo purposes, i.e.
212       * immediately signalling that the job is ready to be woken up after
213       * we return to main via ASYNC_pause_job().
214       */
215      write(pipefds[1], &buf, 1);
216
217      /* Return control back to main */
218      ASYNC_pause_job();
219
220      /* Clear the wake signal */
221      read(pipefds[0], &buf, 1);
222
223      printf ("Resumed the job after a pause\n");
224
225      return 1;
226  }
227
228  int main(void)
229  {
230      ASYNC_JOB *job = NULL;
231      ASYNC_WAIT_CTX *ctx = NULL;
232      int ret;
233      OSSL_ASYNC_FD waitfd;
234      fd_set waitfdset;
235      size_t numfds;
236      unsigned char msg[13] = "Hello world!";
237
238      printf("Starting...\n");
239
240      ctx = ASYNC_WAIT_CTX_new();
241      if (ctx == NULL) {
242          printf("Failed to create ASYNC_WAIT_CTX\n");
243          abort();
244      }
245
246      for (;;) {
247          switch(ASYNC_start_job(&job, ctx, &ret, jobfunc, msg, sizeof(msg))) {
248          case ASYNC_ERR:
249          case ASYNC_NO_JOBS:
250                  printf("An error occurred\n");
251                  goto end;
252          case ASYNC_PAUSE:
253                  printf("Job was paused\n");
254                  break;
255          case ASYNC_FINISH:
256                  printf("Job finished with return value %d\n", ret);
257                  goto end;
258          }
259
260          /* Wait for the job to be woken */
261          printf("Waiting for the job to be woken up\n");
262         
263          if (!ASYNC_WAIT_CTX_get_all_fds(ctx, NULL, &numfds)
264                  || numfds > 1) {
265              printf("Unexpected number of fds\n");
266              abort();
267          }
268          ASYNC_WAIT_CTX_get_all_fds(ctx, &waitfd, &numfds);
269          FD_ZERO(&waitfdset);
270          FD_SET(waitfd, &waitfdset);
271          select(waitfd + 1, &waitfdset, NULL, NULL, NULL);
272      }
273
274  end:
275      ASYNC_WAIT_CTX_free(ctx);
276      printf("Finishing\n");
277
278      return 0;
279  }
280
281 The expected output from executing the above example program is:
282
283  Starting...
284  Executing within a job
285  Passed in message is: Hello world!
286  Job was paused
287  Waiting for the job to be woken up
288  Resumed the job after a pause
289  Job finished with return value 1
290  Finishing
291
292 =head1 SEE ALSO
293
294 L<crypto(3)>, L<ERR_print_errors(3)>
295
296 =head1 HISTORY
297
298 ASYNC_init, ASYNC_init_thread, ASYNC_cleanup, ASYNC_cleanup_thread,
299 ASYNC_start_job, ASYNC_pause_job, ASYNC_get_wait_fd, ASYNC_get_current_job,
300 ASYNC_wake, ASYNC_clear_wake were first added to OpenSSL 1.1.0.
301
302 =cut