r24332: schedule_aio_read_and_X does not need InBuf/OutBuf
[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 #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,
52                                                 size_t buflen,
53                                                 uint16 mid,
54                                                 const uint8 *inbuf)
55 {
56         struct aio_extra *aio_ex = SMB_MALLOC_P(struct aio_extra);
57
58         if (!aio_ex) {
59                 return NULL;
60         }
61         ZERO_STRUCTP(aio_ex);
62         /* The output buffer stored in the aio_ex is the start of
63            the smb return buffer. The buffer used in the acb
64            is the start of the reply data portion of that buffer. */
65         aio_ex->outbuf = SMB_MALLOC_ARRAY(char, buflen);
66         if (!aio_ex->outbuf) {
67                 SAFE_FREE(aio_ex);
68                 return NULL;
69         }
70         /* Save the first 8 bytes of inbuf for possible enc data. */
71         aio_ex->inbuf = SMB_MALLOC_ARRAY(char, 8);
72         if (!aio_ex->inbuf) {
73                 SAFE_FREE(aio_ex->outbuf);
74                 SAFE_FREE(aio_ex);
75                 return NULL;
76         }
77         memcpy(aio_ex->inbuf, inbuf, 8);
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 #define AIO_PENDING_SIZE 10
155 static sig_atomic_t signals_received;
156 static int outstanding_aio_calls;
157 static uint16 aio_pending_array[AIO_PENDING_SIZE];
158
159 /****************************************************************************
160  Signal handler when an aio request completes.
161 *****************************************************************************/
162
163 static void signal_handler(int sig, siginfo_t *info, void *unused)
164 {
165         if (signals_received < AIO_PENDING_SIZE) {
166                 aio_pending_array[signals_received] = info->si_value.sival_int;
167                 signals_received++;
168         } /* Else signal is lost. */
169         sys_select_signal(RT_SIGNAL_AIO);
170 }
171
172 /****************************************************************************
173  Is there a signal waiting ?
174 *****************************************************************************/
175
176 BOOL aio_finished(void)
177 {
178         return (signals_received != 0);
179 }
180
181 /****************************************************************************
182  Initialize the signal handler for aio read/write.
183 *****************************************************************************/
184
185 void initialize_async_io_handler(void)
186 {
187         struct sigaction act;
188
189         ZERO_STRUCT(act);
190         act.sa_sigaction = signal_handler;
191         act.sa_flags = SA_SIGINFO;
192         sigemptyset( &act.sa_mask );
193         if (sigaction(RT_SIGNAL_AIO, &act, NULL) != 0) {
194                 DEBUG(0,("Failed to setup RT_SIGNAL_AIO handler\n"));
195         }
196
197         /* the signal can start off blocked due to a bug in bash */
198         BlockSignals(False, RT_SIGNAL_AIO);
199 }
200
201 /****************************************************************************
202  Set up an aio request from a SMBreadX call.
203 *****************************************************************************/
204
205 BOOL schedule_aio_read_and_X(connection_struct *conn,
206                              struct smb_request *req,
207                              files_struct *fsp, SMB_OFF_T startpos,
208                              size_t smb_maxcnt)
209 {
210         struct aio_extra *aio_ex;
211         SMB_STRUCT_AIOCB *a;
212         size_t bufsize;
213         size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
214
215         if (!min_aio_read_size || (smb_maxcnt < min_aio_read_size)) {
216                 /* Too small a read for aio request. */
217                 DEBUG(10,("schedule_aio_read_and_X: read size (%u) too small "
218                           "for minimum aio_read of %u\n",
219                           (unsigned int)smb_maxcnt,
220                           (unsigned int)min_aio_read_size ));
221                 return False;
222         }
223
224         /* Only do this on non-chained and non-chaining reads not using the
225          * write cache. */
226         if (chain_size !=0 || (CVAL(req->inbuf,smb_vwv0) != 0xFF)
227             || (lp_write_cache_size(SNUM(conn)) != 0) ) {
228                 return False;
229         }
230
231         if (outstanding_aio_calls >= AIO_PENDING_SIZE) {
232                 DEBUG(10,("schedule_aio_read_and_X: Already have %d aio "
233                           "activities outstanding.\n",
234                           outstanding_aio_calls ));
235                 return False;
236         }
237
238         /* The following is safe from integer wrap as we've already checked
239            smb_maxcnt is 128k or less. Wct is 12 for read replies */
240
241         bufsize = smb_size + 12 * 2 + smb_maxcnt;
242
243         if (!(aio_ex = create_aio_ex_read(fsp, bufsize, req->mid,
244                                           req->inbuf))) {
245                 DEBUG(10,("schedule_aio_read_and_X: malloc fail.\n"));
246                 return False;
247         }
248
249         construct_reply_common((char *)req->inbuf, aio_ex->outbuf);
250         set_message((char *)req->inbuf, aio_ex->outbuf, 12, 0, True);
251         SCVAL(aio_ex->outbuf,smb_vwv0,0xFF); /* Never a chained reply. */
252
253         a = &aio_ex->acb;
254
255         /* Now set up the aio record for the read call. */
256         
257         a->aio_fildes = fsp->fh->fd;
258         a->aio_buf = smb_buf(aio_ex->outbuf);
259         a->aio_nbytes = smb_maxcnt;
260         a->aio_offset = startpos;
261         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
262         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
263         a->aio_sigevent.sigev_value.sival_int = aio_ex->mid;
264
265         if (SMB_VFS_AIO_READ(fsp,a) == -1) {
266                 DEBUG(0,("schedule_aio_read_and_X: aio_read failed. "
267                          "Error %s\n", strerror(errno) ));
268                 delete_aio_ex(aio_ex);
269                 return False;
270         }
271
272         DEBUG(10,("schedule_aio_read_and_X: scheduled aio_read for file %s, "
273                   "offset %.0f, len = %u (mid = %u)\n",
274                   fsp->fsp_name, (double)startpos, (unsigned int)smb_maxcnt,
275                   (unsigned int)aio_ex->mid ));
276
277         srv_defer_sign_response(aio_ex->mid);
278         outstanding_aio_calls++;
279         return True;
280 }
281
282 /****************************************************************************
283  Set up an aio request from a SMBwriteX call.
284 *****************************************************************************/
285
286 BOOL schedule_aio_write_and_X(connection_struct *conn,
287                               struct smb_request *req,
288                               files_struct *fsp, char *data,
289                               SMB_OFF_T startpos,
290                               size_t numtowrite)
291 {
292         struct aio_extra *aio_ex;
293         SMB_STRUCT_AIOCB *a;
294         size_t inbufsize, outbufsize;
295         size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
296
297         if (!min_aio_write_size || (numtowrite < min_aio_write_size)) {
298                 /* Too small a write for aio request. */
299                 DEBUG(10,("schedule_aio_write_and_X: write size (%u) too "
300                           "small for minimum aio_write of %u\n",
301                           (unsigned int)numtowrite,
302                           (unsigned int)min_aio_write_size ));
303                 return False;
304         }
305
306         /* Only do this on non-chained and non-chaining reads not using the
307          * write cache. */
308         if (chain_size !=0 || (CVAL(req->inbuf,smb_vwv0) != 0xFF)
309             || (lp_write_cache_size(SNUM(conn)) != 0) ) {
310                 return False;
311         }
312
313         if (outstanding_aio_calls >= AIO_PENDING_SIZE) {
314                 DEBUG(3,("schedule_aio_write_and_X: Already have %d aio "
315                          "activities outstanding.\n",
316                           outstanding_aio_calls ));
317                 DEBUG(10,("schedule_aio_write_and_X: failed to schedule "
318                           "aio_write for file %s, offset %.0f, len = %u "
319                           "(mid = %u)\n",
320                           fsp->fsp_name, (double)startpos,
321                           (unsigned int)numtowrite,
322                           (unsigned int)req->mid ));
323                 return False;
324         }
325
326         inbufsize =  smb_len(req->inbuf) + 4;
327         reply_outbuf(req, 6, 0);
328         outbufsize = smb_len(req->outbuf) + 4;
329         if (!(aio_ex = create_aio_ex_write(fsp, inbufsize, outbufsize,
330                                            req->mid))) {
331                 DEBUG(0,("schedule_aio_write_and_X: malloc fail.\n"));
332                 return False;
333         }
334
335         /* Copy the SMB header already setup in outbuf. */
336         memcpy(aio_ex->inbuf, req->inbuf, inbufsize);
337
338         /* Copy the SMB header already setup in outbuf. */
339         memcpy(aio_ex->outbuf, req->outbuf, outbufsize);
340         TALLOC_FREE(req->outbuf);
341         SCVAL(aio_ex->outbuf,smb_vwv0,0xFF); /* Never a chained reply. */
342
343         a = &aio_ex->acb;
344
345         /* Now set up the aio record for the write call. */
346         
347         a->aio_fildes = fsp->fh->fd;
348         a->aio_buf = aio_ex->inbuf + (PTR_DIFF(data, req->inbuf));
349         a->aio_nbytes = numtowrite;
350         a->aio_offset = startpos;
351         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
352         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
353         a->aio_sigevent.sigev_value.sival_int = aio_ex->mid;
354
355         if (SMB_VFS_AIO_WRITE(fsp,a) == -1) {
356                 DEBUG(3,("schedule_aio_wrote_and_X: aio_write failed. "
357                          "Error %s\n", strerror(errno) ));
358                 delete_aio_ex(aio_ex);
359                 return False;
360         }
361
362         srv_defer_sign_response(aio_ex->mid);
363         outstanding_aio_calls++;
364
365         DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write for file "
366                   "%s, offset %.0f, len = %u (mid = %u) "
367                   "outstanding_aio_calls = %d\n",
368                   fsp->fsp_name, (double)startpos, (unsigned int)numtowrite,
369                   (unsigned int)aio_ex->mid, outstanding_aio_calls ));
370
371         return True;
372 }
373
374
375 /****************************************************************************
376  Complete the read and return the data or error back to the client.
377  Returns errno or zero if all ok.
378 *****************************************************************************/
379
380 static int handle_aio_read_complete(struct aio_extra *aio_ex)
381 {
382         int ret = 0;
383         int outsize;
384         char *outbuf = aio_ex->outbuf;
385         char *inbuf = aio_ex->inbuf;
386         char *data = smb_buf(outbuf);
387         ssize_t nread = SMB_VFS_AIO_RETURN(aio_ex->fsp,&aio_ex->acb);
388
389         if (nread < 0) {
390                 /* We're relying here on the fact that if the fd is
391                    closed then the aio will complete and aio_return
392                    will return an error. Hopefully this is
393                    true.... JRA. */
394
395                 /* If errno is ECANCELED then don't return anything to the
396                  * client. */
397                 if (errno == ECANCELED) {
398                         srv_cancel_sign_response(aio_ex->mid);
399                         return 0;
400                 }
401
402                 DEBUG( 3,( "handle_aio_read_complete: file %s nread == -1. "
403                            "Error = %s\n",
404                            aio_ex->fsp->fsp_name, strerror(errno) ));
405
406                 outsize = (UNIXERROR(ERRDOS,ERRnoaccess));
407                 ret = errno;
408         } else {
409                 outsize = set_message(inbuf,outbuf,12,nread,False);
410                 SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be * -1. */
411                 SSVAL(outbuf,smb_vwv5,nread);
412                 SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
413                 SSVAL(outbuf,smb_vwv7,((nread >> 16) & 1));
414                 SSVAL(smb_buf(outbuf),-2,nread);
415
416                 DEBUG( 3, ( "handle_aio_read_complete file %s max=%d "
417                             "nread=%d\n",
418                             aio_ex->fsp->fsp_name,
419                             (int)aio_ex->acb.aio_nbytes, (int)nread ) );
420
421         }
422         smb_setlen(inbuf,outbuf,outsize - 4);
423         show_msg(outbuf);
424         if (!send_smb(smbd_server_fd(),outbuf)) {
425                 exit_server_cleanly("handle_aio_read_complete: send_smb "
426                                     "failed.");
427         }
428
429         DEBUG(10,("handle_aio_read_complete: scheduled aio_read completed "
430                   "for file %s, offset %.0f, len = %u\n",
431                   aio_ex->fsp->fsp_name, (double)aio_ex->acb.aio_offset,
432                   (unsigned int)nread ));
433
434         return ret;
435 }
436
437 /****************************************************************************
438  Complete the write and return the data or error back to the client.
439  Returns errno or zero if all ok.
440 *****************************************************************************/
441
442 static int handle_aio_write_complete(struct aio_extra *aio_ex)
443 {
444         int ret = 0;
445         files_struct *fsp = aio_ex->fsp;
446         char *outbuf = aio_ex->outbuf;
447         char *inbuf = aio_ex->inbuf;
448         ssize_t numtowrite = aio_ex->acb.aio_nbytes;
449         ssize_t nwritten = SMB_VFS_AIO_RETURN(fsp,&aio_ex->acb);
450
451         /* We don't need outsize or set_message here as we've already set the
452            fixed size length when we set up the aio call. */
453
454         if(nwritten == -1) {
455                 DEBUG( 3,( "handle_aio_write: file %s wanted %u bytes. "
456                            "nwritten == %d. Error = %s\n",
457                            fsp->fsp_name, (unsigned int)numtowrite,
458                            (int)nwritten, strerror(errno) ));
459
460                 /* If errno is ECANCELED then don't return anything to the
461                  * client. */
462                 if (errno == ECANCELED) {
463                         srv_cancel_sign_response(aio_ex->mid);
464                         return 0;
465                 }
466
467                 UNIXERROR(ERRHRD,ERRdiskfull);
468                 ret = errno;
469         } else {
470                 BOOL write_through = BITSETW(aio_ex->inbuf+smb_vwv7,0);
471                 NTSTATUS status;
472
473                 SSVAL(outbuf,smb_vwv2,nwritten);
474                 SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
475                 if (nwritten < (ssize_t)numtowrite) {
476                         SCVAL(outbuf,smb_rcls,ERRHRD);
477                         SSVAL(outbuf,smb_err,ERRdiskfull);
478                 }
479
480                 DEBUG(3,("handle_aio_write: fnum=%d num=%d wrote=%d\n",
481                          fsp->fnum, (int)numtowrite, (int)nwritten));
482                 status = sync_file(fsp->conn,fsp, write_through);
483                 if (!NT_STATUS_IS_OK(status)) {
484                         UNIXERROR(ERRHRD,ERRdiskfull);
485                         ret = errno;
486                         DEBUG(5,("handle_aio_write: sync_file for %s returned %s\n",
487                                 fsp->fsp_name, nt_errstr(status) ));
488                 }
489         }
490
491         show_msg(outbuf);
492         if (!send_smb(smbd_server_fd(),outbuf)) {
493                 exit_server_cleanly("handle_aio_write: send_smb failed.");
494         }
495
496         DEBUG(10,("handle_aio_write_complete: scheduled aio_write completed "
497                   "for file %s, offset %.0f, requested %u, written = %u\n",
498                   fsp->fsp_name, (double)aio_ex->acb.aio_offset,
499                   (unsigned int)numtowrite, (unsigned int)nwritten ));
500
501         return ret;
502 }
503
504 /****************************************************************************
505  Handle any aio completion. Returns True if finished (and sets *perr if err
506  was non-zero), False if not.
507 *****************************************************************************/
508
509 static BOOL handle_aio_completed(struct aio_extra *aio_ex, int *perr)
510 {
511         int err;
512
513         /* Ensure the operation has really completed. */
514         if (SMB_VFS_AIO_ERROR(aio_ex->fsp, &aio_ex->acb) == EINPROGRESS) {
515                 DEBUG(10,( "handle_aio_completed: operation mid %u still in "
516                            "process for file %s\n",
517                            aio_ex->mid, aio_ex->fsp->fsp_name ));
518                 return False;
519         }
520
521         if (aio_ex->read_req) {
522                 err = handle_aio_read_complete(aio_ex);
523         } else {
524                 err = handle_aio_write_complete(aio_ex);
525         }
526
527         if (err) {
528                 *perr = err; /* Only save non-zero errors. */
529         }
530
531         return True;
532 }
533
534 /****************************************************************************
535  Handle any aio completion inline.
536  Returns non-zero errno if fail or zero if all ok.
537 *****************************************************************************/
538
539 int process_aio_queue(void)
540 {
541         int i;
542         int ret = 0;
543
544         BlockSignals(True, RT_SIGNAL_AIO);
545
546         DEBUG(10,("process_aio_queue: signals_received = %d\n",
547                   (int)signals_received));
548         DEBUG(10,("process_aio_queue: outstanding_aio_calls = %d\n",
549                   outstanding_aio_calls));
550
551         if (!signals_received) {
552                 BlockSignals(False, RT_SIGNAL_AIO);
553                 return 0;
554         }
555
556         /* Drain all the complete aio_reads. */
557         for (i = 0; i < signals_received; i++) {
558                 uint16 mid = aio_pending_array[i];
559                 files_struct *fsp = NULL;
560                 struct aio_extra *aio_ex = find_aio_ex(mid);
561
562                 if (!aio_ex) {
563                         DEBUG(3,("process_aio_queue: Can't find record to "
564                                  "match mid %u.\n", (unsigned int)mid));
565                         srv_cancel_sign_response(mid);
566                         continue;
567                 }
568
569                 fsp = aio_ex->fsp;
570                 if (fsp == NULL) {
571                         /* file was closed whilst I/O was outstanding. Just
572                          * ignore. */
573                         DEBUG( 3,( "process_aio_queue: file closed whilst "
574                                    "aio outstanding.\n"));
575                         srv_cancel_sign_response(mid);
576                         continue;
577                 }
578
579                 if (!handle_aio_completed(aio_ex, &ret)) {
580                         continue;
581                 }
582
583                 delete_aio_ex(aio_ex);
584         }
585
586         outstanding_aio_calls -= signals_received;
587         signals_received = 0;
588         BlockSignals(False, RT_SIGNAL_AIO);
589         return ret;
590 }
591
592 /****************************************************************************
593  Cancel any outstanding aio requests. The client doesn't care about the reply.
594 *****************************************************************************/
595
596 void cancel_aio_by_fsp(files_struct *fsp)
597 {
598         struct aio_extra *aio_ex;
599
600         for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
601                 if (aio_ex->fsp == fsp) {
602                         /* Don't delete the aio_extra record as we may have
603                            completed and don't yet know it. Just do the
604                            aio_cancel call and return. */
605                         SMB_VFS_AIO_CANCEL(fsp,fsp->fh->fd, &aio_ex->acb);
606                         aio_ex->fsp = NULL; /* fsp will be closed when we
607                                              * return. */
608                 }
609         }
610 }
611
612 #else
613 BOOL aio_finished(void)
614 {
615         return False;
616 }
617
618 void initialize_async_io_handler(void)
619 {
620 }
621
622 int process_aio_queue(void)
623 {
624         return False;
625 }
626
627 BOOL schedule_aio_read_and_X(connection_struct *conn,
628                              struct smb_request *req,
629                              files_struct *fsp, SMB_OFF_T startpos,
630                              size_t smb_maxcnt)
631 {
632         return False;
633 }
634
635 BOOL schedule_aio_write_and_X(connection_struct *conn,
636                               struct smb_request *req,
637                               files_struct *fsp, char *data,
638                               SMB_OFF_T startpos,
639                               size_t numtowrite)
640 {
641         return False;
642 }
643
644 void cancel_aio_by_fsp(files_struct *fsp)
645 {
646 }
647
648 #endif