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