s3: Make srv_send_smb take an sconn instead of a sock fd
[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 #include "smbd/globals.h"
23
24 #if defined(WITH_AIO)
25
26 /* The signal we'll use to signify aio done. */
27 #ifndef RT_SIGNAL_AIO
28 #define RT_SIGNAL_AIO   (SIGRTMIN+3)
29 #endif
30
31 #ifndef HAVE_STRUCT_SIGEVENT_SIGEV_VALUE_SIVAL_PTR
32 #ifdef HAVE_STRUCT_SIGEVENT_SIGEV_VALUE_SIGVAL_PTR
33 #define sival_int       sigval_int
34 #define sival_ptr       sigval_ptr
35 #endif
36 #endif
37
38 /****************************************************************************
39  The buffer we keep around whilst an aio request is in process.
40 *****************************************************************************/
41
42 struct aio_extra {
43         struct aio_extra *next, *prev;
44         SMB_STRUCT_AIOCB acb;
45         files_struct *fsp;
46         struct smb_request *smbreq;
47         DATA_BLOB outbuf;
48         struct lock_struct lock;
49         bool write_through;
50         int (*handle_completion)(struct aio_extra *ex, int errcode);
51 };
52
53 /****************************************************************************
54  Initialize the signal handler for aio read/write.
55 *****************************************************************************/
56
57 static void smbd_aio_signal_handler(struct tevent_context *ev_ctx,
58                                     struct tevent_signal *se,
59                                     int signum, int count,
60                                     void *_info, void *private_data)
61 {
62         siginfo_t *info = (siginfo_t *)_info;
63         struct aio_extra *aio_ex = (struct aio_extra *)
64                                 info->si_value.sival_ptr;
65
66         smbd_aio_complete_aio_ex(aio_ex);
67 }
68
69
70 static bool initialize_async_io_handler(void)
71 {
72         static bool tried_signal_setup = false;
73
74         if (aio_signal_event) {
75                 return true;
76         }
77         if (tried_signal_setup) {
78                 return false;
79         }
80         tried_signal_setup = true;
81
82         aio_signal_event = tevent_add_signal(smbd_event_context(),
83                                              smbd_event_context(),
84                                              RT_SIGNAL_AIO, SA_SIGINFO,
85                                              smbd_aio_signal_handler,
86                                              NULL);
87         if (!aio_signal_event) {
88                 DEBUG(10, ("Failed to setup RT_SIGNAL_AIO handler\n"));
89                 return false;
90         }
91
92         /* tevent supports 100 signal with SA_SIGINFO */
93         aio_pending_size = 100;
94         return true;
95 }
96
97 static int handle_aio_read_complete(struct aio_extra *aio_ex, int errcode);
98 static int handle_aio_write_complete(struct aio_extra *aio_ex, int errcode);
99 static int handle_aio_smb2_read_complete(struct aio_extra *aio_ex, int errcode);
100 static int handle_aio_smb2_write_complete(struct aio_extra *aio_ex, int errcode);
101
102 static int aio_extra_destructor(struct aio_extra *aio_ex)
103 {
104         DLIST_REMOVE(aio_list_head, aio_ex);
105         return 0;
106 }
107
108 /****************************************************************************
109  Create the extended aio struct we must keep around for the lifetime
110  of the aio call.
111 *****************************************************************************/
112
113 static struct aio_extra *create_aio_extra(TALLOC_CTX *mem_ctx,
114                                         files_struct *fsp,
115                                         size_t buflen)
116 {
117         struct aio_extra *aio_ex = TALLOC_ZERO_P(mem_ctx, struct aio_extra);
118
119         if (!aio_ex) {
120                 return NULL;
121         }
122
123         /* The output buffer stored in the aio_ex is the start of
124            the smb return buffer. The buffer used in the acb
125            is the start of the reply data portion of that buffer. */
126
127         if (buflen) {
128                 aio_ex->outbuf = data_blob_talloc(aio_ex, NULL, buflen);
129                 if (!aio_ex->outbuf.data) {
130                         TALLOC_FREE(aio_ex);
131                         return NULL;
132                 }
133         }
134         DLIST_ADD(aio_list_head, aio_ex);
135         talloc_set_destructor(aio_ex, aio_extra_destructor);
136         aio_ex->fsp = fsp;
137         return aio_ex;
138 }
139
140 /****************************************************************************
141  Set up an aio request from a SMBreadX call.
142 *****************************************************************************/
143
144 NTSTATUS schedule_aio_read_and_X(connection_struct *conn,
145                              struct smb_request *smbreq,
146                              files_struct *fsp, SMB_OFF_T startpos,
147                              size_t smb_maxcnt)
148 {
149         struct aio_extra *aio_ex;
150         SMB_STRUCT_AIOCB *a;
151         size_t bufsize;
152         size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
153         int ret;
154
155         /* Ensure aio is initialized. */
156         if (!initialize_async_io_handler()) {
157                 return NT_STATUS_RETRY;
158         }
159
160         if (fsp->base_fsp != NULL) {
161                 /* No AIO on streams yet */
162                 DEBUG(10, ("AIO on streams not yet supported\n"));
163                 return NT_STATUS_RETRY;
164         }
165
166         if ((!min_aio_read_size || (smb_maxcnt < min_aio_read_size))
167             && !SMB_VFS_AIO_FORCE(fsp)) {
168                 /* Too small a read for aio request. */
169                 DEBUG(10,("schedule_aio_read_and_X: read size (%u) too small "
170                           "for minimum aio_read of %u\n",
171                           (unsigned int)smb_maxcnt,
172                           (unsigned int)min_aio_read_size ));
173                 return NT_STATUS_RETRY;
174         }
175
176         /* Only do this on non-chained and non-chaining reads not using the
177          * write cache. */
178         if (req_is_in_chain(smbreq) || (lp_write_cache_size(SNUM(conn)) != 0)) {
179                 return NT_STATUS_RETRY;
180         }
181
182         if (outstanding_aio_calls >= aio_pending_size) {
183                 DEBUG(10,("schedule_aio_read_and_X: Already have %d aio "
184                           "activities outstanding.\n",
185                           outstanding_aio_calls ));
186                 return NT_STATUS_RETRY;
187         }
188
189         /* The following is safe from integer wrap as we've already checked
190            smb_maxcnt is 128k or less. Wct is 12 for read replies */
191
192         bufsize = smb_size + 12 * 2 + smb_maxcnt;
193
194         if ((aio_ex = create_aio_extra(NULL, fsp, bufsize)) == NULL) {
195                 DEBUG(10,("schedule_aio_read_and_X: malloc fail.\n"));
196                 return NT_STATUS_NO_MEMORY;
197         }
198         aio_ex->handle_completion = handle_aio_read_complete;
199
200         construct_reply_common_req(smbreq, (char *)aio_ex->outbuf.data);
201         srv_set_message((char *)aio_ex->outbuf.data, 12, 0, True);
202         SCVAL(aio_ex->outbuf.data,smb_vwv0,0xFF); /* Never a chained reply. */
203
204         init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
205                 (uint64_t)startpos, (uint64_t)smb_maxcnt, READ_LOCK,
206                 &aio_ex->lock);
207
208         /* Take the lock until the AIO completes. */
209         if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
210                 TALLOC_FREE(aio_ex);
211                 return NT_STATUS_FILE_LOCK_CONFLICT;
212         }
213
214         a = &aio_ex->acb;
215
216         /* Now set up the aio record for the read call. */
217
218         a->aio_fildes = fsp->fh->fd;
219         a->aio_buf = smb_buf(aio_ex->outbuf.data);
220         a->aio_nbytes = smb_maxcnt;
221         a->aio_offset = startpos;
222         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
223         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
224         a->aio_sigevent.sigev_value.sival_ptr = aio_ex;
225
226         ret = SMB_VFS_AIO_READ(fsp, a);
227         if (ret == -1) {
228                 DEBUG(0,("schedule_aio_read_and_X: aio_read failed. "
229                          "Error %s\n", strerror(errno) ));
230                 SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
231                 TALLOC_FREE(aio_ex);
232                 return NT_STATUS_RETRY;
233         }
234
235         outstanding_aio_calls++;
236         aio_ex->smbreq = talloc_move(aio_ex, &smbreq);
237
238         DEBUG(10,("schedule_aio_read_and_X: scheduled aio_read for file %s, "
239                   "offset %.0f, len = %u (mid = %u)\n",
240                   fsp_str_dbg(fsp), (double)startpos, (unsigned int)smb_maxcnt,
241                   (unsigned int)aio_ex->smbreq->mid ));
242
243         return NT_STATUS_OK;
244 }
245
246 /****************************************************************************
247  Set up an aio request from a SMBwriteX call.
248 *****************************************************************************/
249
250 NTSTATUS schedule_aio_write_and_X(connection_struct *conn,
251                               struct smb_request *smbreq,
252                               files_struct *fsp, char *data,
253                               SMB_OFF_T startpos,
254                               size_t numtowrite)
255 {
256         struct aio_extra *aio_ex;
257         SMB_STRUCT_AIOCB *a;
258         size_t bufsize;
259         size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
260         int ret;
261
262         /* Ensure aio is initialized. */
263         if (!initialize_async_io_handler()) {
264                 return NT_STATUS_RETRY;
265         }
266
267         if (fsp->base_fsp != NULL) {
268                 /* No AIO on streams yet */
269                 DEBUG(10, ("AIO on streams not yet supported\n"));
270                 return NT_STATUS_RETRY;
271         }
272
273         if ((!min_aio_write_size || (numtowrite < min_aio_write_size))
274             && !SMB_VFS_AIO_FORCE(fsp)) {
275                 /* Too small a write for aio request. */
276                 DEBUG(10,("schedule_aio_write_and_X: write size (%u) too "
277                           "small for minimum aio_write of %u\n",
278                           (unsigned int)numtowrite,
279                           (unsigned int)min_aio_write_size ));
280                 return NT_STATUS_RETRY;
281         }
282
283         /* Only do this on non-chained and non-chaining writes not using the
284          * write cache. */
285         if (req_is_in_chain(smbreq) || (lp_write_cache_size(SNUM(conn)) != 0)) {
286                 return NT_STATUS_RETRY;
287         }
288
289         if (outstanding_aio_calls >= aio_pending_size) {
290                 DEBUG(3,("schedule_aio_write_and_X: Already have %d aio "
291                          "activities outstanding.\n",
292                           outstanding_aio_calls ));
293                 DEBUG(10,("schedule_aio_write_and_X: failed to schedule "
294                           "aio_write for file %s, offset %.0f, len = %u "
295                           "(mid = %u)\n",
296                           fsp_str_dbg(fsp), (double)startpos,
297                           (unsigned int)numtowrite,
298                           (unsigned int)smbreq->mid ));
299                 return NT_STATUS_RETRY;
300         }
301
302         bufsize = smb_size + 6*2;
303
304         if (!(aio_ex = create_aio_extra(NULL, fsp, bufsize))) {
305                 DEBUG(0,("schedule_aio_write_and_X: malloc fail.\n"));
306                 return NT_STATUS_NO_MEMORY;
307         }
308         aio_ex->handle_completion = handle_aio_write_complete;
309         aio_ex->write_through = BITSETW(smbreq->vwv+7,0);
310
311         construct_reply_common_req(smbreq, (char *)aio_ex->outbuf.data);
312         srv_set_message((char *)aio_ex->outbuf.data, 6, 0, True);
313         SCVAL(aio_ex->outbuf.data,smb_vwv0,0xFF); /* Never a chained reply. */
314
315         init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
316                 (uint64_t)startpos, (uint64_t)numtowrite, WRITE_LOCK,
317                 &aio_ex->lock);
318
319         /* Take the lock until the AIO completes. */
320         if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
321                 TALLOC_FREE(aio_ex);
322                 return NT_STATUS_FILE_LOCK_CONFLICT;
323         }
324
325         a = &aio_ex->acb;
326
327         /* Now set up the aio record for the write call. */
328
329         a->aio_fildes = fsp->fh->fd;
330         a->aio_buf = data;
331         a->aio_nbytes = numtowrite;
332         a->aio_offset = startpos;
333         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
334         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
335         a->aio_sigevent.sigev_value.sival_ptr = aio_ex;
336
337         ret = SMB_VFS_AIO_WRITE(fsp, a);
338         if (ret == -1) {
339                 DEBUG(3,("schedule_aio_wrote_and_X: aio_write failed. "
340                          "Error %s\n", strerror(errno) ));
341                 SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
342                 TALLOC_FREE(aio_ex);
343                 return NT_STATUS_RETRY;
344         }
345
346         outstanding_aio_calls++;
347         aio_ex->smbreq = talloc_move(aio_ex, &smbreq);
348
349         /* This should actually be improved to span the write. */
350         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WRITE);
351         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WRITE);
352
353         if (!aio_ex->write_through && !lp_syncalways(SNUM(fsp->conn))
354             && fsp->aio_write_behind) {
355                 /* Lie to the client and immediately claim we finished the
356                  * write. */
357                 SSVAL(aio_ex->outbuf.data,smb_vwv2,numtowrite);
358                 SSVAL(aio_ex->outbuf.data,smb_vwv4,(numtowrite>>16)&1);
359                 show_msg((char *)aio_ex->outbuf.data);
360                 if (!srv_send_smb(aio_ex->smbreq->sconn,
361                                 (char *)aio_ex->outbuf.data,
362                                 true, aio_ex->smbreq->seqnum+1,
363                                 IS_CONN_ENCRYPTED(fsp->conn),
364                                 &aio_ex->smbreq->pcd)) {
365                         exit_server_cleanly("schedule_aio_write_and_X: "
366                                             "srv_send_smb failed.");
367                 }
368                 DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write "
369                           "behind for file %s\n", fsp_str_dbg(fsp)));
370         }
371
372         DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write for file "
373                   "%s, offset %.0f, len = %u (mid = %u) "
374                   "outstanding_aio_calls = %d\n",
375                   fsp_str_dbg(fsp), (double)startpos, (unsigned int)numtowrite,
376                   (unsigned int)aio_ex->smbreq->mid, outstanding_aio_calls ));
377
378         return NT_STATUS_OK;
379 }
380
381 /****************************************************************************
382  Set up an aio request from a SMB2 read call.
383 *****************************************************************************/
384
385 NTSTATUS schedule_smb2_aio_read(connection_struct *conn,
386                                 struct smb_request *smbreq,
387                                 files_struct *fsp,
388                                 char *inbuf,
389                                 SMB_OFF_T startpos,
390                                 size_t smb_maxcnt)
391 {
392         struct aio_extra *aio_ex;
393         SMB_STRUCT_AIOCB *a;
394         size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
395         int ret;
396
397         /* Ensure aio is initialized. */
398         if (!initialize_async_io_handler()) {
399                 return NT_STATUS_RETRY;
400         }
401
402         if (fsp->base_fsp != NULL) {
403                 /* No AIO on streams yet */
404                 DEBUG(10, ("AIO on streams not yet supported\n"));
405                 return NT_STATUS_RETRY;
406         }
407
408         if ((!min_aio_read_size || (smb_maxcnt < min_aio_read_size))
409             && !SMB_VFS_AIO_FORCE(fsp)) {
410                 /* Too small a read for aio request. */
411                 DEBUG(10,("smb2: read size (%u) too small "
412                         "for minimum aio_read of %u\n",
413                         (unsigned int)smb_maxcnt,
414                         (unsigned int)min_aio_read_size ));
415                 return NT_STATUS_RETRY;
416         }
417
418         /* Only do this on reads not using the write cache. */
419         if (lp_write_cache_size(SNUM(conn)) != 0) {
420                 return NT_STATUS_RETRY;
421         }
422
423         if (outstanding_aio_calls >= aio_pending_size) {
424                 DEBUG(10,("smb2: Already have %d aio "
425                         "activities outstanding.\n",
426                         outstanding_aio_calls ));
427                 return NT_STATUS_RETRY;
428         }
429
430         if (!(aio_ex = create_aio_extra(smbreq->smb2req, fsp, 0))) {
431                 return NT_STATUS_NO_MEMORY;
432         }
433         aio_ex->handle_completion = handle_aio_smb2_read_complete;
434
435         init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
436                 (uint64_t)startpos, (uint64_t)smb_maxcnt, READ_LOCK,
437                 &aio_ex->lock);
438
439         /* Take the lock until the AIO completes. */
440         if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
441                 TALLOC_FREE(aio_ex);
442                 return NT_STATUS_FILE_LOCK_CONFLICT;
443         }
444
445         a = &aio_ex->acb;
446
447         /* Now set up the aio record for the read call. */
448
449         a->aio_fildes = fsp->fh->fd;
450         a->aio_buf = inbuf;
451         a->aio_nbytes = smb_maxcnt;
452         a->aio_offset = startpos;
453         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
454         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
455         a->aio_sigevent.sigev_value.sival_ptr = aio_ex;
456
457         ret = SMB_VFS_AIO_READ(fsp, a);
458         if (ret == -1) {
459                 DEBUG(0,("smb2: aio_read failed. "
460                         "Error %s\n", strerror(errno) ));
461                 SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
462                 TALLOC_FREE(aio_ex);
463                 return NT_STATUS_RETRY;
464         }
465
466         outstanding_aio_calls++;
467         /* We don't need talloc_move here as both aio_ex and
468          * smbreq are children of smbreq->smb2req. */
469         aio_ex->smbreq = smbreq;
470
471         DEBUG(10,("smb2: scheduled aio_read for file %s, "
472                 "offset %.0f, len = %u (mid = %u)\n",
473                 fsp_str_dbg(fsp), (double)startpos, (unsigned int)smb_maxcnt,
474                 (unsigned int)aio_ex->smbreq->mid ));
475
476         return NT_STATUS_OK;
477 }
478
479 /****************************************************************************
480  Set up an aio request from a SMB2write call.
481 *****************************************************************************/
482
483 NTSTATUS schedule_aio_smb2_write(connection_struct *conn,
484                                 struct smb_request *smbreq,
485                                 files_struct *fsp,
486                                 uint64_t in_offset,
487                                 DATA_BLOB in_data,
488                                 bool write_through)
489 {
490         struct aio_extra *aio_ex = NULL;
491         SMB_STRUCT_AIOCB *a = NULL;
492         size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
493         int ret;
494
495         /* Ensure aio is initialized. */
496         if (!initialize_async_io_handler()) {
497                 return NT_STATUS_RETRY;
498         }
499
500         if (fsp->base_fsp != NULL) {
501                 /* No AIO on streams yet */
502                 DEBUG(10, ("AIO on streams not yet supported\n"));
503                 return NT_STATUS_RETRY;
504         }
505
506         if ((!min_aio_write_size || (in_data.length < min_aio_write_size))
507             && !SMB_VFS_AIO_FORCE(fsp)) {
508                 /* Too small a write for aio request. */
509                 DEBUG(10,("smb2: write size (%u) too "
510                         "small for minimum aio_write of %u\n",
511                         (unsigned int)in_data.length,
512                         (unsigned int)min_aio_write_size ));
513                 return NT_STATUS_RETRY;
514         }
515
516         /* Only do this on writes not using the write cache. */
517         if (lp_write_cache_size(SNUM(conn)) != 0) {
518                 return NT_STATUS_RETRY;
519         }
520
521         if (outstanding_aio_calls >= aio_pending_size) {
522                 DEBUG(3,("smb2: Already have %d aio "
523                         "activities outstanding.\n",
524                         outstanding_aio_calls ));
525                 return NT_STATUS_RETRY;
526         }
527
528         if (!(aio_ex = create_aio_extra(smbreq->smb2req, fsp, 0))) {
529                 return NT_STATUS_NO_MEMORY;
530         }
531
532         aio_ex->handle_completion = handle_aio_smb2_write_complete;
533         aio_ex->write_through = write_through;
534
535         init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
536                 in_offset, (uint64_t)in_data.length, WRITE_LOCK,
537                 &aio_ex->lock);
538
539         /* Take the lock until the AIO completes. */
540         if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
541                 TALLOC_FREE(aio_ex);
542                 return NT_STATUS_FILE_LOCK_CONFLICT;
543         }
544
545         a = &aio_ex->acb;
546
547         /* Now set up the aio record for the write call. */
548
549         a->aio_fildes = fsp->fh->fd;
550         a->aio_buf = in_data.data;
551         a->aio_nbytes = in_data.length;
552         a->aio_offset = in_offset;
553         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
554         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
555         a->aio_sigevent.sigev_value.sival_ptr = aio_ex;
556
557         ret = SMB_VFS_AIO_WRITE(fsp, a);
558         if (ret == -1) {
559                 DEBUG(3,("smb2: aio_write failed. "
560                         "Error %s\n", strerror(errno) ));
561                 SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
562                 TALLOC_FREE(aio_ex);
563                 return NT_STATUS_RETRY;
564         }
565
566         outstanding_aio_calls++;
567         /* We don't need talloc_move here as both aio_ex and
568         * smbreq are children of smbreq->smb2req. */
569         aio_ex->smbreq = smbreq;
570
571         /* This should actually be improved to span the write. */
572         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WRITE);
573         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WRITE);
574
575         /*
576          * We don't want to do write behind due to ownership
577          * issues of the request structs. Maybe add it if I
578          * figure those out. JRA.
579          */
580
581         DEBUG(10,("smb2: scheduled aio_write for file "
582                 "%s, offset %.0f, len = %u (mid = %u) "
583                 "outstanding_aio_calls = %d\n",
584                 fsp_str_dbg(fsp),
585                 (double)in_offset,
586                 (unsigned int)in_data.length,
587                 (unsigned int)aio_ex->smbreq->mid,
588                 outstanding_aio_calls ));
589
590         return NT_STATUS_OK;
591 }
592
593 /****************************************************************************
594  Complete the read and return the data or error back to the client.
595  Returns errno or zero if all ok.
596 *****************************************************************************/
597
598 static int handle_aio_read_complete(struct aio_extra *aio_ex, int errcode)
599 {
600         int outsize;
601         char *outbuf = (char *)aio_ex->outbuf.data;
602         char *data = smb_buf(outbuf);
603         ssize_t nread = SMB_VFS_AIO_RETURN(aio_ex->fsp,&aio_ex->acb);
604
605         if (nread < 0) {
606                 /* We're relying here on the fact that if the fd is
607                    closed then the aio will complete and aio_return
608                    will return an error. Hopefully this is
609                    true.... JRA. */
610
611                 DEBUG( 3,( "handle_aio_read_complete: file %s nread == %d. "
612                            "Error = %s\n",
613                            fsp_str_dbg(aio_ex->fsp), (int)nread, strerror(errcode)));
614
615                 ERROR_NT(map_nt_error_from_unix(errcode));
616                 outsize = srv_set_message(outbuf,0,0,true);
617         } else {
618                 outsize = srv_set_message(outbuf,12,nread,False);
619                 SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be * -1. */
620                 SSVAL(outbuf,smb_vwv5,nread);
621                 SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
622                 SSVAL(outbuf,smb_vwv7,((nread >> 16) & 1));
623                 SSVAL(smb_buf(outbuf),-2,nread);
624
625                 aio_ex->fsp->fh->pos = aio_ex->acb.aio_offset + nread;
626                 aio_ex->fsp->fh->position_information = aio_ex->fsp->fh->pos;
627
628                 DEBUG( 3, ( "handle_aio_read_complete file %s max=%d "
629                             "nread=%d\n",
630                             fsp_str_dbg(aio_ex->fsp),
631                             (int)aio_ex->acb.aio_nbytes, (int)nread ) );
632
633         }
634         smb_setlen(outbuf,outsize - 4);
635         show_msg(outbuf);
636         if (!srv_send_smb(aio_ex->smbreq->sconn, outbuf,
637                         true, aio_ex->smbreq->seqnum+1,
638                         IS_CONN_ENCRYPTED(aio_ex->fsp->conn), NULL)) {
639                 exit_server_cleanly("handle_aio_read_complete: srv_send_smb "
640                                     "failed.");
641         }
642
643         DEBUG(10,("handle_aio_read_complete: scheduled aio_read completed "
644                   "for file %s, offset %.0f, len = %u\n",
645                   fsp_str_dbg(aio_ex->fsp), (double)aio_ex->acb.aio_offset,
646                   (unsigned int)nread ));
647
648         return errcode;
649 }
650
651 /****************************************************************************
652  Complete the write and return the data or error back to the client.
653  Returns error code or zero if all ok.
654 *****************************************************************************/
655
656 static int handle_aio_write_complete(struct aio_extra *aio_ex, int errcode)
657 {
658         files_struct *fsp = aio_ex->fsp;
659         char *outbuf = (char *)aio_ex->outbuf.data;
660         ssize_t numtowrite = aio_ex->acb.aio_nbytes;
661         ssize_t nwritten = SMB_VFS_AIO_RETURN(fsp,&aio_ex->acb);
662
663         if (fsp->aio_write_behind) {
664                 if (nwritten != numtowrite) {
665                         if (nwritten == -1) {
666                                 DEBUG(5,("handle_aio_write_complete: "
667                                          "aio_write_behind failed ! File %s "
668                                          "is corrupt ! Error %s\n",
669                                          fsp_str_dbg(fsp), strerror(errcode)));
670                         } else {
671                                 DEBUG(0,("handle_aio_write_complete: "
672                                          "aio_write_behind failed ! File %s "
673                                          "is corrupt ! Wanted %u bytes but "
674                                          "only wrote %d\n", fsp_str_dbg(fsp),
675                                          (unsigned int)numtowrite,
676                                          (int)nwritten ));
677                                 errcode = EIO;
678                         }
679                 } else {
680                         DEBUG(10,("handle_aio_write_complete: "
681                                   "aio_write_behind completed for file %s\n",
682                                   fsp_str_dbg(fsp)));
683                 }
684                 /* TODO: should no return 0 in case of an error !!! */
685                 return 0;
686         }
687
688         /* We don't need outsize or set_message here as we've already set the
689            fixed size length when we set up the aio call. */
690
691         if(nwritten == -1) {
692                 DEBUG( 3,( "handle_aio_write: file %s wanted %u bytes. "
693                            "nwritten == %d. Error = %s\n",
694                            fsp_str_dbg(fsp), (unsigned int)numtowrite,
695                            (int)nwritten, strerror(errcode) ));
696
697                 ERROR_NT(map_nt_error_from_unix(errcode));
698                 srv_set_message(outbuf,0,0,true);
699         } else {
700                 NTSTATUS status;
701
702                 SSVAL(outbuf,smb_vwv2,nwritten);
703                 SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
704                 if (nwritten < (ssize_t)numtowrite) {
705                         SCVAL(outbuf,smb_rcls,ERRHRD);
706                         SSVAL(outbuf,smb_err,ERRdiskfull);
707                 }
708
709                 DEBUG(3,("handle_aio_write: fnum=%d num=%d wrote=%d\n",
710                          fsp->fnum, (int)numtowrite, (int)nwritten));
711                 status = sync_file(fsp->conn,fsp, aio_ex->write_through);
712                 if (!NT_STATUS_IS_OK(status)) {
713                         errcode = errno;
714                         ERROR_BOTH(map_nt_error_from_unix(errcode),
715                                    ERRHRD, ERRdiskfull);
716                         srv_set_message(outbuf,0,0,true);
717                         DEBUG(5,("handle_aio_write: sync_file for %s returned %s\n",
718                                  fsp_str_dbg(fsp), nt_errstr(status)));
719                 }
720
721                 aio_ex->fsp->fh->pos = aio_ex->acb.aio_offset + nwritten;
722         }
723
724         show_msg(outbuf);
725         if (!srv_send_smb(aio_ex->smbreq->sconn, outbuf,
726                           true, aio_ex->smbreq->seqnum+1,
727                           IS_CONN_ENCRYPTED(fsp->conn),
728                           NULL)) {
729                 exit_server_cleanly("handle_aio_write_complete: "
730                                     "srv_send_smb failed.");
731         }
732
733         DEBUG(10,("handle_aio_write_complete: scheduled aio_write completed "
734                   "for file %s, offset %.0f, requested %u, written = %u\n",
735                   fsp_str_dbg(fsp), (double)aio_ex->acb.aio_offset,
736                   (unsigned int)numtowrite, (unsigned int)nwritten ));
737
738         return errcode;
739 }
740
741 /****************************************************************************
742  Complete the read and return the data or error back to the client.
743  Returns errno or zero if all ok.
744 *****************************************************************************/
745
746 static int handle_aio_smb2_read_complete(struct aio_extra *aio_ex, int errcode)
747 {
748         NTSTATUS status;
749         struct tevent_req *subreq = aio_ex->smbreq->smb2req->subreq;
750         ssize_t nread = SMB_VFS_AIO_RETURN(aio_ex->fsp,&aio_ex->acb);
751
752         /* Common error or success code processing for async or sync
753            read returns. */
754
755         status = smb2_read_complete(subreq, nread, errcode);
756
757         if (nread > 0) {
758                 aio_ex->fsp->fh->pos = aio_ex->acb.aio_offset + nread;
759                 aio_ex->fsp->fh->position_information = aio_ex->fsp->fh->pos;
760         }
761
762         DEBUG(10,("smb2: scheduled aio_read completed "
763                 "for file %s, offset %.0f, len = %u "
764                 "(errcode = %d, NTSTATUS = %s)\n",
765                 fsp_str_dbg(aio_ex->fsp),
766                 (double)aio_ex->acb.aio_offset,
767                 (unsigned int)nread,
768                 errcode,
769                 nt_errstr(status) ));
770
771         if (!NT_STATUS_IS_OK(status)) {
772                 tevent_req_nterror(subreq, status);
773         }
774
775         tevent_req_done(subreq);
776         return errcode;
777 }
778
779 /****************************************************************************
780  Complete the SMB2 write and return the data or error back to the client.
781  Returns error code or zero if all ok.
782 *****************************************************************************/
783
784 static int handle_aio_smb2_write_complete(struct aio_extra *aio_ex, int errcode)
785 {
786         files_struct *fsp = aio_ex->fsp;
787         ssize_t numtowrite = aio_ex->acb.aio_nbytes;
788         ssize_t nwritten = SMB_VFS_AIO_RETURN(fsp,&aio_ex->acb);
789         struct tevent_req *subreq = aio_ex->smbreq->smb2req->subreq;
790         NTSTATUS status;
791
792         status = smb2_write_complete(subreq, nwritten, errcode);
793
794         DEBUG(10,("smb2: scheduled aio_write completed "
795                 "for file %s, offset %.0f, requested %u, "
796                 "written = %u (errcode = %d, NTSTATUS = %s)\n",
797                 fsp_str_dbg(fsp),
798                 (double)aio_ex->acb.aio_offset,
799                 (unsigned int)numtowrite,
800                 (unsigned int)nwritten,
801                 errcode,
802                 nt_errstr(status) ));
803
804         if (!NT_STATUS_IS_OK(status)) {
805                 tevent_req_nterror(subreq, status);
806         }
807
808         tevent_req_done(subreq);
809         return errcode;
810 }
811
812 /****************************************************************************
813  Handle any aio completion. Returns True if finished (and sets *perr if err
814  was non-zero), False if not.
815 *****************************************************************************/
816
817 static bool handle_aio_completed(struct aio_extra *aio_ex, int *perr)
818 {
819         files_struct *fsp = NULL;
820         int err;
821
822         if(!aio_ex) {
823                 DEBUG(3, ("handle_aio_completed: Non-existing aio_ex passed\n"));
824                 return false;
825         }
826
827         fsp = aio_ex->fsp;
828
829         /* Ensure the operation has really completed. */
830         err = SMB_VFS_AIO_ERROR(fsp, &aio_ex->acb);
831         if (err == EINPROGRESS) {
832                 DEBUG(10,( "handle_aio_completed: operation mid %llu still in "
833                         "process for file %s\n",
834                         (unsigned long long)aio_ex->smbreq->mid,
835                         fsp_str_dbg(aio_ex->fsp)));
836                 return False;
837         }
838
839         /* Unlock now we're done. */
840         SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
841
842         if (err == ECANCELED) {
843                 /* If error is ECANCELED then don't return anything to the
844                  * client. */
845                 DEBUG(10,( "handle_aio_completed: operation mid %llu"
846                         " canceled\n",
847                         (unsigned long long)aio_ex->smbreq->mid));
848                 return True;
849         }
850
851         err = aio_ex->handle_completion(aio_ex, err);
852         if (err) {
853                 *perr = err; /* Only save non-zero errors. */
854         }
855
856         return True;
857 }
858
859 /****************************************************************************
860  Handle any aio completion inline.
861 *****************************************************************************/
862
863 void smbd_aio_complete_aio_ex(struct aio_extra *aio_ex)
864 {
865         files_struct *fsp = NULL;
866         int ret = 0;
867
868         outstanding_aio_calls--;
869
870         DEBUG(10,("smbd_aio_complete_mid: mid[%llu]\n",
871                 (unsigned long long)aio_ex->smbreq->mid));
872
873         fsp = aio_ex->fsp;
874         if (fsp == NULL) {
875                 /* file was closed whilst I/O was outstanding. Just
876                  * ignore. */
877                 DEBUG( 3,( "smbd_aio_complete_mid: file closed whilst "
878                         "aio outstanding (mid[%llu]).\n",
879                         (unsigned long long)aio_ex->smbreq->mid));
880                 return;
881         }
882
883         if (!handle_aio_completed(aio_ex, &ret)) {
884                 return;
885         }
886
887         TALLOC_FREE(aio_ex);
888 }
889
890 /****************************************************************************
891  We're doing write behind and the client closed the file. Wait up to 30
892  seconds (my arbitrary choice) for the aio to complete. Return 0 if all writes
893  completed, errno to return if not.
894 *****************************************************************************/
895
896 #define SMB_TIME_FOR_AIO_COMPLETE_WAIT 29
897
898 int wait_for_aio_completion(files_struct *fsp)
899 {
900         struct aio_extra *aio_ex;
901         const SMB_STRUCT_AIOCB **aiocb_list;
902         int aio_completion_count = 0;
903         time_t start_time = time(NULL);
904         int seconds_left;
905
906         for (seconds_left = SMB_TIME_FOR_AIO_COMPLETE_WAIT;
907              seconds_left >= 0;) {
908                 int err = 0;
909                 int i;
910                 struct timespec ts;
911
912                 aio_completion_count = 0;
913                 for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
914                         if (aio_ex->fsp == fsp) {
915                                 aio_completion_count++;
916                         }
917                 }
918
919                 if (!aio_completion_count) {
920                         return 0;
921                 }
922
923                 DEBUG(3,("wait_for_aio_completion: waiting for %d aio events "
924                          "to complete.\n", aio_completion_count ));
925
926                 aiocb_list = SMB_MALLOC_ARRAY(const SMB_STRUCT_AIOCB *,
927                                               aio_completion_count);
928                 if (!aiocb_list) {
929                         return ENOMEM;
930                 }
931
932                 for( i = 0, aio_ex = aio_list_head;
933                      aio_ex;
934                      aio_ex = aio_ex->next) {
935                         if (aio_ex->fsp == fsp) {
936                                 aiocb_list[i++] = &aio_ex->acb;
937                         }
938                 }
939
940                 /* Now wait up to seconds_left for completion. */
941                 ts.tv_sec = seconds_left;
942                 ts.tv_nsec = 0;
943
944                 DEBUG(10,("wait_for_aio_completion: %d events, doing a wait "
945                           "of %d seconds.\n",
946                           aio_completion_count, seconds_left ));
947
948                 err = SMB_VFS_AIO_SUSPEND(fsp, aiocb_list,
949                                           aio_completion_count, &ts);
950
951                 DEBUG(10,("wait_for_aio_completion: returned err = %d, "
952                           "errno = %s\n", err, strerror(errno) ));
953
954                 if (err == -1 && errno == EAGAIN) {
955                         DEBUG(0,("wait_for_aio_completion: aio_suspend timed "
956                                  "out waiting for %d events after a wait of "
957                                  "%d seconds\n", aio_completion_count,
958                                  seconds_left));
959                         /* Timeout. */
960                         cancel_aio_by_fsp(fsp);
961                         SAFE_FREE(aiocb_list);
962                         return EIO;
963                 }
964
965                 /* One or more events might have completed - process them if
966                  * so. */
967                 for( i = 0; i < aio_completion_count; i++) {
968                         aio_ex = (struct aio_extra *)aiocb_list[i]->aio_sigevent.sigev_value.sival_ptr;
969
970                         if (!handle_aio_completed(aio_ex, &err)) {
971                                 continue;
972                         }
973                         TALLOC_FREE(aio_ex);
974                 }
975
976                 SAFE_FREE(aiocb_list);
977                 seconds_left = SMB_TIME_FOR_AIO_COMPLETE_WAIT
978                         - (time(NULL) - start_time);
979         }
980
981         /* We timed out - we don't know why. Return ret if already an error,
982          * else EIO. */
983         DEBUG(10,("wait_for_aio_completion: aio_suspend timed out waiting "
984                   "for %d events\n",
985                   aio_completion_count));
986
987         return EIO;
988 }
989
990 /****************************************************************************
991  Cancel any outstanding aio requests. The client doesn't care about the reply.
992 *****************************************************************************/
993
994 void cancel_aio_by_fsp(files_struct *fsp)
995 {
996         struct aio_extra *aio_ex;
997
998         for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
999                 if (aio_ex->fsp == fsp) {
1000                         /* Unlock now we're done. */
1001                         SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
1002
1003                         /* Don't delete the aio_extra record as we may have
1004                            completed and don't yet know it. Just do the
1005                            aio_cancel call and return. */
1006                         SMB_VFS_AIO_CANCEL(fsp, &aio_ex->acb);
1007                         aio_ex->fsp = NULL; /* fsp will be closed when we
1008                                              * return. */
1009                 }
1010         }
1011 }
1012
1013 #else
1014 NTSTATUS schedule_aio_read_and_X(connection_struct *conn,
1015                              struct smb_request *smbreq,
1016                              files_struct *fsp, SMB_OFF_T startpos,
1017                              size_t smb_maxcnt)
1018 {
1019         return NT_STATUS_RETRY;
1020 }
1021
1022 NTSTATUS schedule_aio_write_and_X(connection_struct *conn,
1023                               struct smb_request *smbreq,
1024                               files_struct *fsp, char *data,
1025                               SMB_OFF_T startpos,
1026                               size_t numtowrite)
1027 {
1028         return NT_STATUS_RETRY;
1029 }
1030
1031 NTSTATUS schedule_smb2_aio_read(connection_struct *conn,
1032                                 struct smb_request *smbreq,
1033                                 files_struct *fsp,
1034                                 char *inbuf,
1035                                 SMB_OFF_T startpos,
1036                                 size_t smb_maxcnt)
1037 {
1038         return NT_STATUS_RETRY;
1039 }
1040
1041 NTSTATUS schedule_aio_smb2_write(connection_struct *conn,
1042                                 struct smb_request *smbreq,
1043                                 files_struct *fsp,
1044                                 uint64_t in_offset,
1045                                 DATA_BLOB in_data,
1046                                 bool write_through)
1047 {
1048         return NT_STATUS_RETRY;
1049 }
1050
1051 void cancel_aio_by_fsp(files_struct *fsp)
1052 {
1053 }
1054
1055 int wait_for_aio_completion(files_struct *fsp)
1056 {
1057         return 0;
1058 }
1059
1060 void smbd_aio_complete_mid(uint64_t mid);
1061
1062 #endif