r23784: use the GPLv3 boilerplate as recommended by the FSF and the license text
[amitay/samba.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 char *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                              char *inbuf, char *outbuf,
207                              int length, int len_outbuf,
208                              files_struct *fsp, SMB_OFF_T startpos,
209                              size_t smb_maxcnt)
210 {
211         struct aio_extra *aio_ex;
212         SMB_STRUCT_AIOCB *a;
213         size_t bufsize;
214         size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
215
216         if (!min_aio_read_size || (smb_maxcnt < min_aio_read_size)) {
217                 /* Too small a read for aio request. */
218                 DEBUG(10,("schedule_aio_read_and_X: read size (%u) too small "
219                           "for minimum aio_read of %u\n",
220                           (unsigned int)smb_maxcnt,
221                           (unsigned int)min_aio_read_size ));
222                 return False;
223         }
224
225         /* Only do this on non-chained and non-chaining reads not using the
226          * write cache. */
227         if (chain_size !=0 || (CVAL(inbuf,smb_vwv0) != 0xFF)
228             || (lp_write_cache_size(SNUM(conn)) != 0) ) {
229                 return False;
230         }
231
232         if (outstanding_aio_calls >= AIO_PENDING_SIZE) {
233                 DEBUG(10,("schedule_aio_read_and_X: Already have %d aio "
234                           "activities outstanding.\n",
235                           outstanding_aio_calls ));
236                 return False;
237         }
238
239         /* The following is safe from integer wrap as we've already
240            checked smb_maxcnt is 128k or less. */
241         bufsize = PTR_DIFF(smb_buf(outbuf),outbuf) + smb_maxcnt;
242
243         if ((aio_ex = create_aio_ex_read(fsp, bufsize,
244                                          SVAL(inbuf,smb_mid), inbuf)) == NULL) {
245                 DEBUG(10,("schedule_aio_read_and_X: malloc fail.\n"));
246                 return False;
247         }
248
249         /* Copy the SMB header already setup in outbuf. */
250         memcpy(aio_ex->outbuf, outbuf, smb_buf(outbuf) - outbuf);
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                                 char *inbuf, char *outbuf,
288                                 int length, int len_outbuf,
289                                 files_struct *fsp, char *data,
290                                 SMB_OFF_T startpos,
291                                 size_t numtowrite)
292 {
293         struct aio_extra *aio_ex;
294         SMB_STRUCT_AIOCB *a;
295         size_t inbufsize, outbufsize;
296         size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
297
298         if (!min_aio_write_size || (numtowrite < min_aio_write_size)) {
299                 /* Too small a write for aio request. */
300                 DEBUG(10,("schedule_aio_write_and_X: write size (%u) too "
301                           "small for minimum aio_write of %u\n",
302                           (unsigned int)numtowrite,
303                           (unsigned int)min_aio_write_size ));
304                 return False;
305         }
306
307         /* Only do this on non-chained and non-chaining reads not using the
308          * write cache. */
309         if (chain_size !=0 || (CVAL(inbuf,smb_vwv0) != 0xFF)
310             || (lp_write_cache_size(SNUM(conn)) != 0) ) {
311                 return False;
312         }
313
314         if (outstanding_aio_calls >= AIO_PENDING_SIZE) {
315                 DEBUG(3,("schedule_aio_write_and_X: Already have %d aio "
316                          "activities outstanding.\n",
317                           outstanding_aio_calls ));
318                 DEBUG(10,("schedule_aio_write_and_X: failed to schedule "
319                           "aio_write for file %s, offset %.0f, len = %u "
320                           "(mid = %u)\n",
321                           fsp->fsp_name, (double)startpos,
322                           (unsigned int)numtowrite,
323                           (unsigned int)SVAL(inbuf,smb_mid) ));
324                 return False;
325         }
326
327         inbufsize =  smb_len(inbuf) + 4;
328         outbufsize = smb_len(outbuf) + 4;
329         if (!(aio_ex = create_aio_ex_write(fsp, inbufsize, outbufsize,
330                                            SVAL(inbuf,smb_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, inbuf, inbufsize);
337
338         /* Copy the SMB header already setup in outbuf. */
339         memcpy(aio_ex->outbuf, outbuf, outbufsize);
340         SCVAL(aio_ex->outbuf,smb_vwv0,0xFF); /* Never a chained reply. */
341
342         a = &aio_ex->acb;
343
344         /* Now set up the aio record for the write call. */
345         
346         a->aio_fildes = fsp->fh->fd;
347         a->aio_buf = aio_ex->inbuf + (PTR_DIFF(data, inbuf));
348         a->aio_nbytes = numtowrite;
349         a->aio_offset = startpos;
350         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
351         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
352         a->aio_sigevent.sigev_value.sival_int = aio_ex->mid;
353
354         if (SMB_VFS_AIO_WRITE(fsp,a) == -1) {
355                 DEBUG(3,("schedule_aio_wrote_and_X: aio_write failed. "
356                          "Error %s\n", strerror(errno) ));
357                 delete_aio_ex(aio_ex);
358                 return False;
359         }
360
361         srv_defer_sign_response(aio_ex->mid);
362         outstanding_aio_calls++;
363
364         DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write for file "
365                   "%s, offset %.0f, len = %u (mid = %u) "
366                   "outstanding_aio_calls = %d\n",
367                   fsp->fsp_name, (double)startpos, (unsigned int)numtowrite,
368                   (unsigned int)aio_ex->mid, outstanding_aio_calls ));
369
370         return True;
371 }
372
373
374 /****************************************************************************
375  Complete the read and return the data or error back to the client.
376  Returns errno or zero if all ok.
377 *****************************************************************************/
378
379 static int handle_aio_read_complete(struct aio_extra *aio_ex)
380 {
381         int ret = 0;
382         int outsize;
383         char *outbuf = aio_ex->outbuf;
384         char *inbuf = aio_ex->inbuf;
385         char *data = smb_buf(outbuf);
386         ssize_t nread = SMB_VFS_AIO_RETURN(aio_ex->fsp,&aio_ex->acb);
387
388         if (nread < 0) {
389                 /* We're relying here on the fact that if the fd is
390                    closed then the aio will complete and aio_return
391                    will return an error. Hopefully this is
392                    true.... JRA. */
393
394                 /* If errno is ECANCELED then don't return anything to the
395                  * client. */
396                 if (errno == ECANCELED) {
397                         srv_cancel_sign_response(aio_ex->mid);
398                         return 0;
399                 }
400
401                 DEBUG( 3,( "handle_aio_read_complete: file %s nread == -1. "
402                            "Error = %s\n",
403                            aio_ex->fsp->fsp_name, strerror(errno) ));
404
405                 outsize = (UNIXERROR(ERRDOS,ERRnoaccess));
406                 ret = errno;
407         } else {
408                 outsize = set_message(inbuf,outbuf,12,nread,False);
409                 SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be * -1. */
410                 SSVAL(outbuf,smb_vwv5,nread);
411                 SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
412                 SSVAL(outbuf,smb_vwv7,((nread >> 16) & 1));
413                 SSVAL(smb_buf(outbuf),-2,nread);
414
415                 DEBUG( 3, ( "handle_aio_read_complete file %s max=%d "
416                             "nread=%d\n",
417                             aio_ex->fsp->fsp_name,
418                             aio_ex->acb.aio_nbytes, (int)nread ) );
419
420         }
421         smb_setlen(inbuf,outbuf,outsize - 4);
422         show_msg(outbuf);
423         if (!send_smb(smbd_server_fd(),outbuf)) {
424                 exit_server_cleanly("handle_aio_read_complete: send_smb "
425                                     "failed.");
426         }
427
428         DEBUG(10,("handle_aio_read_complete: scheduled aio_read completed "
429                   "for file %s, offset %.0f, len = %u\n",
430                   aio_ex->fsp->fsp_name, (double)aio_ex->acb.aio_offset,
431                   (unsigned int)nread ));
432
433         return ret;
434 }
435
436 /****************************************************************************
437  Complete the write and return the data or error back to the client.
438  Returns errno or zero if all ok.
439 *****************************************************************************/
440
441 static int handle_aio_write_complete(struct aio_extra *aio_ex)
442 {
443         int ret = 0;
444         files_struct *fsp = aio_ex->fsp;
445         char *outbuf = aio_ex->outbuf;
446         char *inbuf = aio_ex->inbuf;
447         ssize_t numtowrite = aio_ex->acb.aio_nbytes;
448         ssize_t nwritten = SMB_VFS_AIO_RETURN(fsp,&aio_ex->acb);
449
450         /* We don't need outsize or set_message here as we've already set the
451            fixed size length when we set up the aio call. */
452
453         if(nwritten == -1) {
454                 DEBUG( 3,( "handle_aio_write: file %s wanted %u bytes. "
455                            "nwritten == %d. Error = %s\n",
456                            fsp->fsp_name, (unsigned int)numtowrite,
457                            (int)nwritten, strerror(errno) ));
458
459                 /* If errno is ECANCELED then don't return anything to the
460                  * client. */
461                 if (errno == ECANCELED) {
462                         srv_cancel_sign_response(aio_ex->mid);
463                         return 0;
464                 }
465
466                 UNIXERROR(ERRHRD,ERRdiskfull);
467                 ret = errno;
468         } else {
469                 BOOL write_through = BITSETW(aio_ex->inbuf+smb_vwv7,0);
470                 NTSTATUS status;
471
472                 SSVAL(outbuf,smb_vwv2,nwritten);
473                 SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
474                 if (nwritten < (ssize_t)numtowrite) {
475                         SCVAL(outbuf,smb_rcls,ERRHRD);
476                         SSVAL(outbuf,smb_err,ERRdiskfull);
477                 }
478
479                 DEBUG(3,("handle_aio_write: fnum=%d num=%d wrote=%d\n",
480                          fsp->fnum, (int)numtowrite, (int)nwritten));
481                 status = sync_file(fsp->conn,fsp, write_through);
482                 if (!NT_STATUS_IS_OK(status)) {
483                         UNIXERROR(ERRHRD,ERRdiskfull);
484                         ret = errno;
485                         DEBUG(5,("handle_aio_write: sync_file for %s returned %s\n",
486                                 fsp->fsp_name, nt_errstr(status) ));
487                 }
488         }
489
490         show_msg(outbuf);
491         if (!send_smb(smbd_server_fd(),outbuf)) {
492                 exit_server_cleanly("handle_aio_write: send_smb failed.");
493         }
494
495         DEBUG(10,("handle_aio_write_complete: scheduled aio_write completed "
496                   "for file %s, offset %.0f, requested %u, written = %u\n",
497                   fsp->fsp_name, (double)aio_ex->acb.aio_offset,
498                   (unsigned int)numtowrite, (unsigned int)nwritten ));
499
500         return ret;
501 }
502
503 /****************************************************************************
504  Handle any aio completion. Returns True if finished (and sets *perr if err
505  was non-zero), False if not.
506 *****************************************************************************/
507
508 static BOOL handle_aio_completed(struct aio_extra *aio_ex, int *perr)
509 {
510         int err;
511
512         /* Ensure the operation has really completed. */
513         if (SMB_VFS_AIO_ERROR(aio_ex->fsp, &aio_ex->acb) == EINPROGRESS) {
514                 DEBUG(10,( "handle_aio_completed: operation mid %u still in "
515                            "process for file %s\n",
516                            aio_ex->mid, aio_ex->fsp->fsp_name ));
517                 return False;
518         }
519
520         if (aio_ex->read_req) {
521                 err = handle_aio_read_complete(aio_ex);
522         } else {
523                 err = handle_aio_write_complete(aio_ex);
524         }
525
526         if (err) {
527                 *perr = err; /* Only save non-zero errors. */
528         }
529
530         return True;
531 }
532
533 /****************************************************************************
534  Handle any aio completion inline.
535  Returns non-zero errno if fail or zero if all ok.
536 *****************************************************************************/
537
538 int process_aio_queue(void)
539 {
540         int i;
541         int ret = 0;
542
543         BlockSignals(True, RT_SIGNAL_AIO);
544
545         DEBUG(10,("process_aio_queue: signals_received = %d\n",
546                   (int)signals_received));
547         DEBUG(10,("process_aio_queue: outstanding_aio_calls = %d\n",
548                   outstanding_aio_calls));
549
550         if (!signals_received) {
551                 BlockSignals(False, RT_SIGNAL_AIO);
552                 return 0;
553         }
554
555         /* Drain all the complete aio_reads. */
556         for (i = 0; i < signals_received; i++) {
557                 uint16 mid = aio_pending_array[i];
558                 files_struct *fsp = NULL;
559                 struct aio_extra *aio_ex = find_aio_ex(mid);
560
561                 if (!aio_ex) {
562                         DEBUG(3,("process_aio_queue: Can't find record to "
563                                  "match mid %u.\n", (unsigned int)mid));
564                         srv_cancel_sign_response(mid);
565                         continue;
566                 }
567
568                 fsp = aio_ex->fsp;
569                 if (fsp == NULL) {
570                         /* file was closed whilst I/O was outstanding. Just
571                          * ignore. */
572                         DEBUG( 3,( "process_aio_queue: file closed whilst "
573                                    "aio outstanding.\n"));
574                         srv_cancel_sign_response(mid);
575                         continue;
576                 }
577
578                 if (!handle_aio_completed(aio_ex, &ret)) {
579                         continue;
580                 }
581
582                 delete_aio_ex(aio_ex);
583         }
584
585         outstanding_aio_calls -= signals_received;
586         signals_received = 0;
587         BlockSignals(False, RT_SIGNAL_AIO);
588         return ret;
589 }
590
591 /****************************************************************************
592  Cancel any outstanding aio requests. The client doesn't care about the reply.
593 *****************************************************************************/
594
595 void cancel_aio_by_fsp(files_struct *fsp)
596 {
597         struct aio_extra *aio_ex;
598
599         for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
600                 if (aio_ex->fsp == fsp) {
601                         /* Don't delete the aio_extra record as we may have
602                            completed and don't yet know it. Just do the
603                            aio_cancel call and return. */
604                         SMB_VFS_AIO_CANCEL(fsp,fsp->fh->fd, &aio_ex->acb);
605                         aio_ex->fsp = NULL; /* fsp will be closed when we
606                                              * return. */
607                 }
608         }
609 }
610
611 #else
612 BOOL aio_finished(void)
613 {
614         return False;
615 }
616
617 void initialize_async_io_handler(void)
618 {
619 }
620
621 int process_aio_queue(void)
622 {
623         return False;
624 }
625
626 BOOL schedule_aio_read_and_X(connection_struct *conn,
627                              char *inbuf, char *outbuf,
628                              int length, int len_outbuf,
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                                 char *inbuf, char *outbuf,
637                                 int length, int len_outbuf,
638                                 files_struct *fsp, char *data,
639                                 SMB_OFF_T startpos,
640                                 size_t numtowrite)
641 {
642         return False;
643 }
644
645 void cancel_aio_by_fsp(files_struct *fsp)
646 {
647 }
648
649 #endif