Merge commit 'samba/v3-2-test' into v3-2-stable
[bbaumbach/samba-autobuild/.git] / source3 / smbd / aio.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 3.0
4    async_io read handling using POSIX async io.
5    Copyright (C) Jeremy Allison 2005.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22
23 #if defined(WITH_AIO)
24
25 /* The signal we'll use to signify aio done. */
26 #ifndef RT_SIGNAL_AIO
27 #define RT_SIGNAL_AIO (SIGRTMIN+3)
28 #endif
29
30 /****************************************************************************
31  The buffer we keep around whilst an aio request is in process.
32 *****************************************************************************/
33
34 struct aio_extra {
35         struct aio_extra *next, *prev;
36         SMB_STRUCT_AIOCB acb;
37         files_struct *fsp;
38         bool read_req;
39         uint16 mid;
40         char *inbuf;
41         char *outbuf;
42 };
43
44 static struct aio_extra *aio_list_head;
45
46 /****************************************************************************
47  Create the extended aio struct we must keep around for the lifetime
48  of the aio_read call.
49 *****************************************************************************/
50
51 static struct aio_extra *create_aio_ex_read(files_struct *fsp, size_t buflen,
52                                             uint16 mid)
53 {
54         struct aio_extra *aio_ex = SMB_MALLOC_P(struct aio_extra);
55
56         if (!aio_ex) {
57                 return NULL;
58         }
59         ZERO_STRUCTP(aio_ex);
60         /* The output buffer stored in the aio_ex is the start of
61            the smb return buffer. The buffer used in the acb
62            is the start of the reply data portion of that buffer. */
63         aio_ex->outbuf = SMB_MALLOC_ARRAY(char, buflen);
64         if (!aio_ex->outbuf) {
65                 SAFE_FREE(aio_ex);
66                 return NULL;
67         }
68         DLIST_ADD(aio_list_head, aio_ex);
69         aio_ex->fsp = fsp;
70         aio_ex->read_req = True;
71         aio_ex->mid = mid;
72         return aio_ex;
73 }
74
75 /****************************************************************************
76  Create the extended aio struct we must keep around for the lifetime
77  of the aio_write call.
78 *****************************************************************************/
79
80 static struct aio_extra *create_aio_ex_write(files_struct *fsp,
81                                              size_t inbuflen,
82                                              size_t outbuflen,
83                                              uint16 mid)
84 {
85         struct aio_extra *aio_ex = SMB_MALLOC_P(struct aio_extra);
86
87         if (!aio_ex) {
88                 return NULL;
89         }
90         ZERO_STRUCTP(aio_ex);
91
92         /* We need space for an output reply of outbuflen bytes. */
93         aio_ex->outbuf = SMB_MALLOC_ARRAY(char, outbuflen);
94         if (!aio_ex->outbuf) {
95                 SAFE_FREE(aio_ex);
96                 return NULL;
97         }
98
99         if (!(aio_ex->inbuf = SMB_MALLOC_ARRAY(char, inbuflen))) {
100                 SAFE_FREE(aio_ex->outbuf);
101                 SAFE_FREE(aio_ex);
102                 return NULL;
103         }
104
105         DLIST_ADD(aio_list_head, aio_ex);
106         aio_ex->fsp = fsp;
107         aio_ex->read_req = False;
108         aio_ex->mid = mid;
109         return aio_ex;
110 }
111
112 /****************************************************************************
113  Delete the extended aio struct.
114 *****************************************************************************/
115
116 static void delete_aio_ex(struct aio_extra *aio_ex)
117 {
118         DLIST_REMOVE(aio_list_head, aio_ex);
119         SAFE_FREE(aio_ex->inbuf);
120         SAFE_FREE(aio_ex->outbuf);
121         SAFE_FREE(aio_ex);
122 }
123
124 /****************************************************************************
125  Given the aiocb struct find the extended aio struct containing it.
126 *****************************************************************************/
127
128 static struct aio_extra *find_aio_ex(uint16 mid)
129 {
130         struct aio_extra *p;
131
132         for( p = aio_list_head; p; p = p->next) {
133                 if (mid == p->mid) {
134                         return p;
135                 }
136         }
137         return NULL;
138 }
139
140 /****************************************************************************
141  We can have these many aio buffers in flight.
142 *****************************************************************************/
143
144 #define AIO_PENDING_SIZE 10
145 static sig_atomic_t signals_received;
146 static int outstanding_aio_calls;
147 static uint16 aio_pending_array[AIO_PENDING_SIZE];
148
149 /****************************************************************************
150  Signal handler when an aio request completes.
151 *****************************************************************************/
152
153 static void signal_handler(int sig, siginfo_t *info, void *unused)
154 {
155         if (signals_received < AIO_PENDING_SIZE) {
156                 aio_pending_array[signals_received] = info->si_value.sival_int;
157                 signals_received++;
158         } /* Else signal is lost. */
159         sys_select_signal(RT_SIGNAL_AIO);
160 }
161
162 /****************************************************************************
163  Is there a signal waiting ?
164 *****************************************************************************/
165
166 bool aio_finished(void)
167 {
168         return (signals_received != 0);
169 }
170
171 /****************************************************************************
172  Initialize the signal handler for aio read/write.
173 *****************************************************************************/
174
175 void initialize_async_io_handler(void)
176 {
177         struct sigaction act;
178
179         ZERO_STRUCT(act);
180         act.sa_sigaction = signal_handler;
181         act.sa_flags = SA_SIGINFO;
182         sigemptyset( &act.sa_mask );
183         if (sigaction(RT_SIGNAL_AIO, &act, NULL) != 0) {
184                 DEBUG(0,("Failed to setup RT_SIGNAL_AIO handler\n"));
185         }
186
187         /* the signal can start off blocked due to a bug in bash */
188         BlockSignals(False, RT_SIGNAL_AIO);
189 }
190
191 /****************************************************************************
192  Set up an aio request from a SMBreadX call.
193 *****************************************************************************/
194
195 bool schedule_aio_read_and_X(connection_struct *conn,
196                              struct smb_request *req,
197                              files_struct *fsp, SMB_OFF_T startpos,
198                              size_t smb_maxcnt)
199 {
200         struct aio_extra *aio_ex;
201         SMB_STRUCT_AIOCB *a;
202         size_t bufsize;
203         size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
204
205         if (!min_aio_read_size || (smb_maxcnt < min_aio_read_size)) {
206                 /* Too small a read for aio request. */
207                 DEBUG(10,("schedule_aio_read_and_X: read size (%u) too small "
208                           "for minimum aio_read of %u\n",
209                           (unsigned int)smb_maxcnt,
210                           (unsigned int)min_aio_read_size ));
211                 return False;
212         }
213
214         /* Only do this on non-chained and non-chaining reads not using the
215          * write cache. */
216         if (chain_size !=0 || (CVAL(req->inbuf,smb_vwv0) != 0xFF)
217             || (lp_write_cache_size(SNUM(conn)) != 0) ) {
218                 return False;
219         }
220
221         if (outstanding_aio_calls >= AIO_PENDING_SIZE) {
222                 DEBUG(10,("schedule_aio_read_and_X: Already have %d aio "
223                           "activities outstanding.\n",
224                           outstanding_aio_calls ));
225                 return False;
226         }
227
228         /* The following is safe from integer wrap as we've already checked
229            smb_maxcnt is 128k or less. Wct is 12 for read replies */
230
231         bufsize = smb_size + 12 * 2 + smb_maxcnt;
232
233         if ((aio_ex = create_aio_ex_read(fsp, bufsize, req->mid)) == NULL) {
234                 DEBUG(10,("schedule_aio_read_and_X: malloc fail.\n"));
235                 return False;
236         }
237
238         construct_reply_common((char *)req->inbuf, aio_ex->outbuf);
239         srv_set_message(aio_ex->outbuf, 12, 0, True);
240         SCVAL(aio_ex->outbuf,smb_vwv0,0xFF); /* Never a chained reply. */
241
242         a = &aio_ex->acb;
243
244         /* Now set up the aio record for the read call. */
245         
246         a->aio_fildes = fsp->fh->fd;
247         a->aio_buf = smb_buf(aio_ex->outbuf);
248         a->aio_nbytes = smb_maxcnt;
249         a->aio_offset = startpos;
250         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
251         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
252         a->aio_sigevent.sigev_value.sival_int = aio_ex->mid;
253
254         if (SMB_VFS_AIO_READ(fsp,a) == -1) {
255                 DEBUG(0,("schedule_aio_read_and_X: aio_read failed. "
256                          "Error %s\n", strerror(errno) ));
257                 delete_aio_ex(aio_ex);
258                 return False;
259         }
260
261         DEBUG(10,("schedule_aio_read_and_X: scheduled aio_read for file %s, "
262                   "offset %.0f, len = %u (mid = %u)\n",
263                   fsp->fsp_name, (double)startpos, (unsigned int)smb_maxcnt,
264                   (unsigned int)aio_ex->mid ));
265
266         srv_defer_sign_response(aio_ex->mid);
267         outstanding_aio_calls++;
268         return True;
269 }
270
271 /****************************************************************************
272  Set up an aio request from a SMBwriteX call.
273 *****************************************************************************/
274
275 bool schedule_aio_write_and_X(connection_struct *conn,
276                               struct smb_request *req,
277                               files_struct *fsp, char *data,
278                               SMB_OFF_T startpos,
279                               size_t numtowrite)
280 {
281         struct aio_extra *aio_ex;
282         SMB_STRUCT_AIOCB *a;
283         size_t inbufsize, outbufsize;
284         bool write_through = BITSETW(req->inbuf+smb_vwv7,0);
285         size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
286
287         if (!min_aio_write_size || (numtowrite < min_aio_write_size)) {
288                 /* Too small a write for aio request. */
289                 DEBUG(10,("schedule_aio_write_and_X: write size (%u) too "
290                           "small for minimum aio_write of %u\n",
291                           (unsigned int)numtowrite,
292                           (unsigned int)min_aio_write_size ));
293                 return False;
294         }
295
296         /* Only do this on non-chained and non-chaining reads not using the
297          * write cache. */
298         if (chain_size !=0 || (CVAL(req->inbuf,smb_vwv0) != 0xFF)
299             || (lp_write_cache_size(SNUM(conn)) != 0) ) {
300                 return False;
301         }
302
303         if (outstanding_aio_calls >= AIO_PENDING_SIZE) {
304                 DEBUG(3,("schedule_aio_write_and_X: Already have %d aio "
305                          "activities outstanding.\n",
306                           outstanding_aio_calls ));
307                 DEBUG(10,("schedule_aio_write_and_X: failed to schedule "
308                           "aio_write for file %s, offset %.0f, len = %u "
309                           "(mid = %u)\n",
310                           fsp->fsp_name, (double)startpos,
311                           (unsigned int)numtowrite,
312                           (unsigned int)req->mid ));
313                 return False;
314         }
315
316         inbufsize =  smb_len(req->inbuf) + 4;
317         reply_outbuf(req, 6, 0);
318         outbufsize = smb_len(req->outbuf) + 4;
319         if (!(aio_ex = create_aio_ex_write(fsp, inbufsize, outbufsize,
320                                            req->mid))) {
321                 DEBUG(0,("schedule_aio_write_and_X: malloc fail.\n"));
322                 return False;
323         }
324
325         /* Copy the SMB header already setup in outbuf. */
326         memcpy(aio_ex->inbuf, req->inbuf, inbufsize);
327
328         /* Copy the SMB header already setup in outbuf. */
329         memcpy(aio_ex->outbuf, req->outbuf, outbufsize);
330         TALLOC_FREE(req->outbuf);
331         SCVAL(aio_ex->outbuf,smb_vwv0,0xFF); /* Never a chained reply. */
332
333         a = &aio_ex->acb;
334
335         /* Now set up the aio record for the write call. */
336         
337         a->aio_fildes = fsp->fh->fd;
338         a->aio_buf = aio_ex->inbuf + (PTR_DIFF(data, req->inbuf));
339         a->aio_nbytes = numtowrite;
340         a->aio_offset = startpos;
341         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
342         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
343         a->aio_sigevent.sigev_value.sival_int = aio_ex->mid;
344
345         if (SMB_VFS_AIO_WRITE(fsp,a) == -1) {
346                 DEBUG(3,("schedule_aio_wrote_and_X: aio_write failed. "
347                          "Error %s\n", strerror(errno) ));
348                 delete_aio_ex(aio_ex);
349                 return False;
350         }
351
352         if (!write_through && !lp_syncalways(SNUM(fsp->conn))
353             && fsp->aio_write_behind) {
354                 /* Lie to the client and immediately claim we finished the
355                  * write. */
356                 SSVAL(aio_ex->outbuf,smb_vwv2,numtowrite);
357                 SSVAL(aio_ex->outbuf,smb_vwv4,(numtowrite>>16)&1);
358                 show_msg(aio_ex->outbuf);
359                 if (!srv_send_smb(smbd_server_fd(),aio_ex->outbuf,
360                                 IS_CONN_ENCRYPTED(fsp->conn))) {
361                         exit_server_cleanly("handle_aio_write: srv_send_smb "
362                                             "failed.");
363                 }
364                 DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write "
365                           "behind for file %s\n", fsp->fsp_name ));
366         } else {
367                 srv_defer_sign_response(aio_ex->mid);
368         }
369         outstanding_aio_calls++;
370
371         DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write for file "
372                   "%s, offset %.0f, len = %u (mid = %u) "
373                   "outstanding_aio_calls = %d\n",
374                   fsp->fsp_name, (double)startpos, (unsigned int)numtowrite,
375                   (unsigned int)aio_ex->mid, outstanding_aio_calls ));
376
377         return True;
378 }
379
380
381 /****************************************************************************
382  Complete the read and return the data or error back to the client.
383  Returns errno or zero if all ok.
384 *****************************************************************************/
385
386 static int handle_aio_read_complete(struct aio_extra *aio_ex)
387 {
388         int ret = 0;
389         int outsize;
390         char *outbuf = aio_ex->outbuf;
391         char *data = smb_buf(outbuf);
392         ssize_t nread = SMB_VFS_AIO_RETURN(aio_ex->fsp,&aio_ex->acb);
393
394         if (nread < 0) {
395                 /* We're relying here on the fact that if the fd is
396                    closed then the aio will complete and aio_return
397                    will return an error. Hopefully this is
398                    true.... JRA. */
399
400                 /* If errno is ECANCELED then don't return anything to the
401                  * client. */
402                 if (errno == ECANCELED) {
403                         srv_cancel_sign_response(aio_ex->mid);
404                         return 0;
405                 }
406
407                 DEBUG( 3,( "handle_aio_read_complete: file %s nread == -1. "
408                            "Error = %s\n",
409                            aio_ex->fsp->fsp_name, strerror(errno) ));
410
411                 ret = errno;
412                 ERROR_NT(map_nt_error_from_unix(ret));
413                 outsize = srv_set_message(outbuf,0,0,true);
414         } else {
415                 outsize = srv_set_message(outbuf,12,nread,False);
416                 SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be * -1. */
417                 SSVAL(outbuf,smb_vwv5,nread);
418                 SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
419                 SSVAL(outbuf,smb_vwv7,((nread >> 16) & 1));
420                 SSVAL(smb_buf(outbuf),-2,nread);
421
422                 DEBUG( 3, ( "handle_aio_read_complete file %s max=%d "
423                             "nread=%d\n",
424                             aio_ex->fsp->fsp_name,
425                             (int)aio_ex->acb.aio_nbytes, (int)nread ) );
426
427         }
428         smb_setlen(outbuf,outsize - 4);
429         show_msg(outbuf);
430         if (!srv_send_smb(smbd_server_fd(),outbuf,
431                         IS_CONN_ENCRYPTED(aio_ex->fsp->conn))) {
432                 exit_server_cleanly("handle_aio_read_complete: srv_send_smb "
433                                     "failed.");
434         }
435
436         DEBUG(10,("handle_aio_read_complete: scheduled aio_read completed "
437                   "for file %s, offset %.0f, len = %u\n",
438                   aio_ex->fsp->fsp_name, (double)aio_ex->acb.aio_offset,
439                   (unsigned int)nread ));
440
441         return ret;
442 }
443
444 /****************************************************************************
445  Complete the write and return the data or error back to the client.
446  Returns errno or zero if all ok.
447 *****************************************************************************/
448
449 static int handle_aio_write_complete(struct aio_extra *aio_ex)
450 {
451         int ret = 0;
452         files_struct *fsp = aio_ex->fsp;
453         char *outbuf = aio_ex->outbuf;
454         ssize_t numtowrite = aio_ex->acb.aio_nbytes;
455         ssize_t nwritten = SMB_VFS_AIO_RETURN(fsp,&aio_ex->acb);
456
457         if (fsp->aio_write_behind) {
458                 if (nwritten != numtowrite) {
459                         if (nwritten == -1) {
460                                 DEBUG(5,("handle_aio_write_complete: "
461                                          "aio_write_behind failed ! File %s "
462                                          "is corrupt ! Error %s\n",
463                                          fsp->fsp_name, strerror(errno) ));
464                                 ret = errno;
465                         } else {
466                                 DEBUG(0,("handle_aio_write_complete: "
467                                          "aio_write_behind failed ! File %s "
468                                          "is corrupt ! Wanted %u bytes but "
469                                          "only wrote %d\n", fsp->fsp_name,
470                                          (unsigned int)numtowrite,
471                                          (int)nwritten ));
472                                 ret = EIO;
473                         }
474                 } else {
475                         DEBUG(10,("handle_aio_write_complete: "
476                                   "aio_write_behind completed for file %s\n",
477                                   fsp->fsp_name ));
478                 }
479                 return 0;
480         }
481
482         /* We don't need outsize or set_message here as we've already set the
483            fixed size length when we set up the aio call. */
484
485         if(nwritten == -1) {
486                 DEBUG( 3,( "handle_aio_write: file %s wanted %u bytes. "
487                            "nwritten == %d. Error = %s\n",
488                            fsp->fsp_name, (unsigned int)numtowrite,
489                            (int)nwritten, strerror(errno) ));
490
491                 /* If errno is ECANCELED then don't return anything to the
492                  * client. */
493                 if (errno == ECANCELED) {
494                         srv_cancel_sign_response(aio_ex->mid);
495                         return 0;
496                 }
497
498                 ret = errno;
499                 ERROR_BOTH(map_nt_error_from_unix(ret), ERRHRD, ERRdiskfull);
500                 srv_set_message(outbuf,0,0,true);
501         } else {
502                 bool write_through = BITSETW(aio_ex->inbuf+smb_vwv7,0);
503                 NTSTATUS status;
504
505                 SSVAL(outbuf,smb_vwv2,nwritten);
506                 SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
507                 if (nwritten < (ssize_t)numtowrite) {
508                         SCVAL(outbuf,smb_rcls,ERRHRD);
509                         SSVAL(outbuf,smb_err,ERRdiskfull);
510                 }
511
512                 DEBUG(3,("handle_aio_write: fnum=%d num=%d wrote=%d\n",
513                          fsp->fnum, (int)numtowrite, (int)nwritten));
514                 status = sync_file(fsp->conn,fsp, write_through);
515                 if (!NT_STATUS_IS_OK(status)) {
516                         ret = errno;
517                         ERROR_BOTH(map_nt_error_from_unix(ret),
518                                    ERRHRD, ERRdiskfull);
519                         srv_set_message(outbuf,0,0,true);
520                         DEBUG(5,("handle_aio_write: sync_file for %s returned %s\n",
521                                 fsp->fsp_name, nt_errstr(status) ));
522                 }
523         }
524
525         show_msg(outbuf);
526         if (!srv_send_smb(smbd_server_fd(),outbuf,IS_CONN_ENCRYPTED(fsp->conn))) {
527                 exit_server_cleanly("handle_aio_write: srv_send_smb failed.");
528         }
529
530         DEBUG(10,("handle_aio_write_complete: scheduled aio_write completed "
531                   "for file %s, offset %.0f, requested %u, written = %u\n",
532                   fsp->fsp_name, (double)aio_ex->acb.aio_offset,
533                   (unsigned int)numtowrite, (unsigned int)nwritten ));
534
535         return ret;
536 }
537
538 /****************************************************************************
539  Handle any aio completion. Returns True if finished (and sets *perr if err
540  was non-zero), False if not.
541 *****************************************************************************/
542
543 static bool handle_aio_completed(struct aio_extra *aio_ex, int *perr)
544 {
545         int err;
546
547         /* Ensure the operation has really completed. */
548         if (SMB_VFS_AIO_ERROR(aio_ex->fsp, &aio_ex->acb) == EINPROGRESS) {
549                 DEBUG(10,( "handle_aio_completed: operation mid %u still in "
550                            "process for file %s\n",
551                            aio_ex->mid, aio_ex->fsp->fsp_name ));
552                 return False;
553         }
554
555         if (aio_ex->read_req) {
556                 err = handle_aio_read_complete(aio_ex);
557         } else {
558                 err = handle_aio_write_complete(aio_ex);
559         }
560
561         if (err) {
562                 *perr = err; /* Only save non-zero errors. */
563         }
564
565         return True;
566 }
567
568 /****************************************************************************
569  Handle any aio completion inline.
570  Returns non-zero errno if fail or zero if all ok.
571 *****************************************************************************/
572
573 int process_aio_queue(void)
574 {
575         int i;
576         int ret = 0;
577
578         BlockSignals(True, RT_SIGNAL_AIO);
579
580         DEBUG(10,("process_aio_queue: signals_received = %d\n",
581                   (int)signals_received));
582         DEBUG(10,("process_aio_queue: outstanding_aio_calls = %d\n",
583                   outstanding_aio_calls));
584
585         if (!signals_received) {
586                 BlockSignals(False, RT_SIGNAL_AIO);
587                 return 0;
588         }
589
590         /* Drain all the complete aio_reads. */
591         for (i = 0; i < signals_received; i++) {
592                 uint16 mid = aio_pending_array[i];
593                 files_struct *fsp = NULL;
594                 struct aio_extra *aio_ex = find_aio_ex(mid);
595
596                 if (!aio_ex) {
597                         DEBUG(3,("process_aio_queue: Can't find record to "
598                                  "match mid %u.\n", (unsigned int)mid));
599                         srv_cancel_sign_response(mid);
600                         continue;
601                 }
602
603                 fsp = aio_ex->fsp;
604                 if (fsp == NULL) {
605                         /* file was closed whilst I/O was outstanding. Just
606                          * ignore. */
607                         DEBUG( 3,( "process_aio_queue: file closed whilst "
608                                    "aio outstanding.\n"));
609                         srv_cancel_sign_response(mid);
610                         continue;
611                 }
612
613                 if (!handle_aio_completed(aio_ex, &ret)) {
614                         continue;
615                 }
616
617                 delete_aio_ex(aio_ex);
618         }
619
620         outstanding_aio_calls -= signals_received;
621         signals_received = 0;
622         BlockSignals(False, RT_SIGNAL_AIO);
623         return ret;
624 }
625
626 /****************************************************************************
627  We're doing write behind and the client closed the file. Wait up to 30
628  seconds (my arbitrary choice) for the aio to complete. Return 0 if all writes
629  completed, errno to return if not.
630 *****************************************************************************/
631
632 #define SMB_TIME_FOR_AIO_COMPLETE_WAIT 29
633
634 int wait_for_aio_completion(files_struct *fsp)
635 {
636         struct aio_extra *aio_ex;
637         const SMB_STRUCT_AIOCB **aiocb_list;
638         int aio_completion_count = 0;
639         time_t start_time = time(NULL);
640         int seconds_left;
641
642         for (seconds_left = SMB_TIME_FOR_AIO_COMPLETE_WAIT;
643              seconds_left >= 0;) {
644                 int err = 0;
645                 int i;
646                 struct timespec ts;
647
648                 aio_completion_count = 0;
649                 for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
650                         if (aio_ex->fsp == fsp) {
651                                 aio_completion_count++;
652                         }
653                 }
654
655                 if (!aio_completion_count) {
656                         return 0;
657                 }
658
659                 DEBUG(3,("wait_for_aio_completion: waiting for %d aio events "
660                          "to complete.\n", aio_completion_count ));
661
662                 aiocb_list = SMB_MALLOC_ARRAY(const SMB_STRUCT_AIOCB *,
663                                               aio_completion_count);
664                 if (!aiocb_list) {
665                         return ENOMEM;
666                 }
667
668                 for( i = 0, aio_ex = aio_list_head;
669                      aio_ex;
670                      aio_ex = aio_ex->next) {
671                         if (aio_ex->fsp == fsp) {
672                                 aiocb_list[i++] = &aio_ex->acb;
673                         }
674                 }
675
676                 /* Now wait up to seconds_left for completion. */
677                 ts.tv_sec = seconds_left;
678                 ts.tv_nsec = 0;
679
680                 DEBUG(10,("wait_for_aio_completion: %d events, doing a wait "
681                           "of %d seconds.\n",
682                           aio_completion_count, seconds_left ));
683
684                 err = SMB_VFS_AIO_SUSPEND(fsp, aiocb_list,
685                                           aio_completion_count, &ts);
686
687                 DEBUG(10,("wait_for_aio_completion: returned err = %d, "
688                           "errno = %s\n", err, strerror(errno) ));
689                 
690                 if (err == -1 && errno == EAGAIN) {
691                         DEBUG(0,("wait_for_aio_completion: aio_suspend timed "
692                                  "out waiting for %d events after a wait of "
693                                  "%d seconds\n", aio_completion_count,
694                                  seconds_left));
695                         /* Timeout. */
696                         cancel_aio_by_fsp(fsp);
697                         SAFE_FREE(aiocb_list);
698                         return EIO;
699                 }
700
701                 /* One or more events might have completed - process them if
702                  * so. */
703                 for( i = 0; i < aio_completion_count; i++) {
704                         uint16 mid = aiocb_list[i]->aio_sigevent.sigev_value.sival_int;
705
706                         aio_ex = find_aio_ex(mid);
707
708                         if (!aio_ex) {
709                                 DEBUG(0, ("wait_for_aio_completion: mid %u "
710                                           "doesn't match an aio record\n",
711                                           (unsigned int)mid ));
712                                 continue;
713                         }
714
715                         if (!handle_aio_completed(aio_ex, &err)) {
716                                 continue;
717                         }
718                         delete_aio_ex(aio_ex);
719                 }
720
721                 SAFE_FREE(aiocb_list);
722                 seconds_left = SMB_TIME_FOR_AIO_COMPLETE_WAIT
723                         - (time(NULL) - start_time);
724         }
725
726         /* We timed out - we don't know why. Return ret if already an error,
727          * else EIO. */
728         DEBUG(10,("wait_for_aio_completion: aio_suspend timed out waiting "
729                   "for %d events\n",
730                   aio_completion_count));
731
732         return EIO;
733 }
734
735 /****************************************************************************
736  Cancel any outstanding aio requests. The client doesn't care about the reply.
737 *****************************************************************************/
738
739 void cancel_aio_by_fsp(files_struct *fsp)
740 {
741         struct aio_extra *aio_ex;
742
743         for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
744                 if (aio_ex->fsp == fsp) {
745                         /* Don't delete the aio_extra record as we may have
746                            completed and don't yet know it. Just do the
747                            aio_cancel call and return. */
748                         SMB_VFS_AIO_CANCEL(fsp, &aio_ex->acb);
749                         aio_ex->fsp = NULL; /* fsp will be closed when we
750                                              * return. */
751                 }
752         }
753 }
754
755 #else
756 bool aio_finished(void)
757 {
758         return False;
759 }
760
761 void initialize_async_io_handler(void)
762 {
763 }
764
765 int process_aio_queue(void)
766 {
767         return False;
768 }
769
770 bool schedule_aio_read_and_X(connection_struct *conn,
771                              struct smb_request *req,
772                              files_struct *fsp, SMB_OFF_T startpos,
773                              size_t smb_maxcnt)
774 {
775         return False;
776 }
777
778 bool schedule_aio_write_and_X(connection_struct *conn,
779                               struct smb_request *req,
780                               files_struct *fsp, char *data,
781                               SMB_OFF_T startpos,
782                               size_t numtowrite)
783 {
784         return False;
785 }
786
787 void cancel_aio_by_fsp(files_struct *fsp)
788 {
789 }
790
791 int wait_for_aio_completion(files_struct *fsp)
792 {
793         return ENOSYS;
794 }
795 #endif