eb8ed6799f1c3e9179b2888f58cc55f25ba42474
[ira/wip.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                                 TALLOC_CTX *ctx,
389                                 DATA_BLOB *preadbuf,
390                                 SMB_OFF_T startpos,
391                                 size_t smb_maxcnt)
392 {
393         struct aio_extra *aio_ex;
394         SMB_STRUCT_AIOCB *a;
395         size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
396         int ret;
397
398         /* Ensure aio is initialized. */
399         if (!initialize_async_io_handler()) {
400                 return NT_STATUS_RETRY;
401         }
402
403         if (fsp->base_fsp != NULL) {
404                 /* No AIO on streams yet */
405                 DEBUG(10, ("AIO on streams not yet supported\n"));
406                 return NT_STATUS_RETRY;
407         }
408
409         if ((!min_aio_read_size || (smb_maxcnt < min_aio_read_size))
410             && !SMB_VFS_AIO_FORCE(fsp)) {
411                 /* Too small a read for aio request. */
412                 DEBUG(10,("smb2: read size (%u) too small "
413                         "for minimum aio_read of %u\n",
414                         (unsigned int)smb_maxcnt,
415                         (unsigned int)min_aio_read_size ));
416                 return NT_STATUS_RETRY;
417         }
418
419         /* Only do this on reads not using the write cache. */
420         if (lp_write_cache_size(SNUM(conn)) != 0) {
421                 return NT_STATUS_RETRY;
422         }
423
424         if (outstanding_aio_calls >= aio_pending_size) {
425                 DEBUG(10,("smb2: Already have %d aio "
426                         "activities outstanding.\n",
427                         outstanding_aio_calls ));
428                 return NT_STATUS_RETRY;
429         }
430
431         /* Create the out buffer. */
432         *preadbuf = data_blob_talloc(ctx, NULL, smb_maxcnt);
433         if (preadbuf->data == NULL) {
434                 return NT_STATUS_NO_MEMORY;
435         }
436
437         if (!(aio_ex = create_aio_extra(smbreq->smb2req, fsp, 0))) {
438                 return NT_STATUS_NO_MEMORY;
439         }
440         aio_ex->handle_completion = handle_aio_smb2_read_complete;
441
442         init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
443                 (uint64_t)startpos, (uint64_t)smb_maxcnt, READ_LOCK,
444                 &aio_ex->lock);
445
446         /* Take the lock until the AIO completes. */
447         if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
448                 TALLOC_FREE(aio_ex);
449                 return NT_STATUS_FILE_LOCK_CONFLICT;
450         }
451
452         a = &aio_ex->acb;
453
454         /* Now set up the aio record for the read call. */
455
456         a->aio_fildes = fsp->fh->fd;
457         a->aio_buf = preadbuf->data;
458         a->aio_nbytes = smb_maxcnt;
459         a->aio_offset = startpos;
460         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
461         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
462         a->aio_sigevent.sigev_value.sival_ptr = aio_ex;
463
464         ret = SMB_VFS_AIO_READ(fsp, a);
465         if (ret == -1) {
466                 DEBUG(0,("smb2: aio_read failed. "
467                         "Error %s\n", strerror(errno) ));
468                 SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
469                 TALLOC_FREE(aio_ex);
470                 return NT_STATUS_RETRY;
471         }
472
473         outstanding_aio_calls++;
474         /* We don't need talloc_move here as both aio_ex and
475          * smbreq are children of smbreq->smb2req. */
476         aio_ex->smbreq = smbreq;
477
478         DEBUG(10,("smb2: scheduled aio_read for file %s, "
479                 "offset %.0f, len = %u (mid = %u)\n",
480                 fsp_str_dbg(fsp), (double)startpos, (unsigned int)smb_maxcnt,
481                 (unsigned int)aio_ex->smbreq->mid ));
482
483         return NT_STATUS_OK;
484 }
485
486 /****************************************************************************
487  Set up an aio request from a SMB2write call.
488 *****************************************************************************/
489
490 NTSTATUS schedule_aio_smb2_write(connection_struct *conn,
491                                 struct smb_request *smbreq,
492                                 files_struct *fsp,
493                                 uint64_t in_offset,
494                                 DATA_BLOB in_data,
495                                 bool write_through)
496 {
497         struct aio_extra *aio_ex = NULL;
498         SMB_STRUCT_AIOCB *a = NULL;
499         size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
500         int ret;
501
502         /* Ensure aio is initialized. */
503         if (!initialize_async_io_handler()) {
504                 return NT_STATUS_RETRY;
505         }
506
507         if (fsp->base_fsp != NULL) {
508                 /* No AIO on streams yet */
509                 DEBUG(10, ("AIO on streams not yet supported\n"));
510                 return NT_STATUS_RETRY;
511         }
512
513         if ((!min_aio_write_size || (in_data.length < min_aio_write_size))
514             && !SMB_VFS_AIO_FORCE(fsp)) {
515                 /* Too small a write for aio request. */
516                 DEBUG(10,("smb2: write size (%u) too "
517                         "small for minimum aio_write of %u\n",
518                         (unsigned int)in_data.length,
519                         (unsigned int)min_aio_write_size ));
520                 return NT_STATUS_RETRY;
521         }
522
523         /* Only do this on writes not using the write cache. */
524         if (lp_write_cache_size(SNUM(conn)) != 0) {
525                 return NT_STATUS_RETRY;
526         }
527
528         if (outstanding_aio_calls >= aio_pending_size) {
529                 DEBUG(3,("smb2: Already have %d aio "
530                         "activities outstanding.\n",
531                         outstanding_aio_calls ));
532                 return NT_STATUS_RETRY;
533         }
534
535         if (!(aio_ex = create_aio_extra(smbreq->smb2req, fsp, 0))) {
536                 return NT_STATUS_NO_MEMORY;
537         }
538
539         aio_ex->handle_completion = handle_aio_smb2_write_complete;
540         aio_ex->write_through = write_through;
541
542         init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
543                 in_offset, (uint64_t)in_data.length, WRITE_LOCK,
544                 &aio_ex->lock);
545
546         /* Take the lock until the AIO completes. */
547         if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
548                 TALLOC_FREE(aio_ex);
549                 return NT_STATUS_FILE_LOCK_CONFLICT;
550         }
551
552         a = &aio_ex->acb;
553
554         /* Now set up the aio record for the write call. */
555
556         a->aio_fildes = fsp->fh->fd;
557         a->aio_buf = in_data.data;
558         a->aio_nbytes = in_data.length;
559         a->aio_offset = in_offset;
560         a->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
561         a->aio_sigevent.sigev_signo  = RT_SIGNAL_AIO;
562         a->aio_sigevent.sigev_value.sival_ptr = aio_ex;
563
564         ret = SMB_VFS_AIO_WRITE(fsp, a);
565         if (ret == -1) {
566                 DEBUG(3,("smb2: aio_write failed. "
567                         "Error %s\n", strerror(errno) ));
568                 SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
569                 TALLOC_FREE(aio_ex);
570                 return NT_STATUS_RETRY;
571         }
572
573         outstanding_aio_calls++;
574         /* We don't need talloc_move here as both aio_ex and
575         * smbreq are children of smbreq->smb2req. */
576         aio_ex->smbreq = smbreq;
577
578         /* This should actually be improved to span the write. */
579         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WRITE);
580         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WRITE);
581
582         /*
583          * We don't want to do write behind due to ownership
584          * issues of the request structs. Maybe add it if I
585          * figure those out. JRA.
586          */
587
588         DEBUG(10,("smb2: scheduled aio_write for file "
589                 "%s, offset %.0f, len = %u (mid = %u) "
590                 "outstanding_aio_calls = %d\n",
591                 fsp_str_dbg(fsp),
592                 (double)in_offset,
593                 (unsigned int)in_data.length,
594                 (unsigned int)aio_ex->smbreq->mid,
595                 outstanding_aio_calls ));
596
597         return NT_STATUS_OK;
598 }
599
600 /****************************************************************************
601  Complete the read and return the data or error back to the client.
602  Returns errno or zero if all ok.
603 *****************************************************************************/
604
605 static int handle_aio_read_complete(struct aio_extra *aio_ex, int errcode)
606 {
607         int outsize;
608         char *outbuf = (char *)aio_ex->outbuf.data;
609         char *data = smb_buf(outbuf);
610         ssize_t nread = SMB_VFS_AIO_RETURN(aio_ex->fsp,&aio_ex->acb);
611
612         if (nread < 0) {
613                 /* We're relying here on the fact that if the fd is
614                    closed then the aio will complete and aio_return
615                    will return an error. Hopefully this is
616                    true.... JRA. */
617
618                 DEBUG( 3,( "handle_aio_read_complete: file %s nread == %d. "
619                            "Error = %s\n",
620                            fsp_str_dbg(aio_ex->fsp), (int)nread, strerror(errcode)));
621
622                 ERROR_NT(map_nt_error_from_unix(errcode));
623                 outsize = srv_set_message(outbuf,0,0,true);
624         } else {
625                 outsize = srv_set_message(outbuf,12,nread,False);
626                 SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be * -1. */
627                 SSVAL(outbuf,smb_vwv5,nread);
628                 SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
629                 SSVAL(outbuf,smb_vwv7,((nread >> 16) & 1));
630                 SSVAL(smb_buf(outbuf),-2,nread);
631
632                 aio_ex->fsp->fh->pos = aio_ex->acb.aio_offset + nread;
633                 aio_ex->fsp->fh->position_information = aio_ex->fsp->fh->pos;
634
635                 DEBUG( 3, ( "handle_aio_read_complete file %s max=%d "
636                             "nread=%d\n",
637                             fsp_str_dbg(aio_ex->fsp),
638                             (int)aio_ex->acb.aio_nbytes, (int)nread ) );
639
640         }
641         smb_setlen(outbuf,outsize - 4);
642         show_msg(outbuf);
643         if (!srv_send_smb(aio_ex->smbreq->sconn, outbuf,
644                         true, aio_ex->smbreq->seqnum+1,
645                         IS_CONN_ENCRYPTED(aio_ex->fsp->conn), NULL)) {
646                 exit_server_cleanly("handle_aio_read_complete: srv_send_smb "
647                                     "failed.");
648         }
649
650         DEBUG(10,("handle_aio_read_complete: scheduled aio_read completed "
651                   "for file %s, offset %.0f, len = %u\n",
652                   fsp_str_dbg(aio_ex->fsp), (double)aio_ex->acb.aio_offset,
653                   (unsigned int)nread ));
654
655         return errcode;
656 }
657
658 /****************************************************************************
659  Complete the write and return the data or error back to the client.
660  Returns error code or zero if all ok.
661 *****************************************************************************/
662
663 static int handle_aio_write_complete(struct aio_extra *aio_ex, int errcode)
664 {
665         files_struct *fsp = aio_ex->fsp;
666         char *outbuf = (char *)aio_ex->outbuf.data;
667         ssize_t numtowrite = aio_ex->acb.aio_nbytes;
668         ssize_t nwritten = SMB_VFS_AIO_RETURN(fsp,&aio_ex->acb);
669
670         if (fsp->aio_write_behind) {
671                 if (nwritten != numtowrite) {
672                         if (nwritten == -1) {
673                                 DEBUG(5,("handle_aio_write_complete: "
674                                          "aio_write_behind failed ! File %s "
675                                          "is corrupt ! Error %s\n",
676                                          fsp_str_dbg(fsp), strerror(errcode)));
677                         } else {
678                                 DEBUG(0,("handle_aio_write_complete: "
679                                          "aio_write_behind failed ! File %s "
680                                          "is corrupt ! Wanted %u bytes but "
681                                          "only wrote %d\n", fsp_str_dbg(fsp),
682                                          (unsigned int)numtowrite,
683                                          (int)nwritten ));
684                                 errcode = EIO;
685                         }
686                 } else {
687                         DEBUG(10,("handle_aio_write_complete: "
688                                   "aio_write_behind completed for file %s\n",
689                                   fsp_str_dbg(fsp)));
690                 }
691                 /* TODO: should no return 0 in case of an error !!! */
692                 return 0;
693         }
694
695         /* We don't need outsize or set_message here as we've already set the
696            fixed size length when we set up the aio call. */
697
698         if(nwritten == -1) {
699                 DEBUG( 3,( "handle_aio_write: file %s wanted %u bytes. "
700                            "nwritten == %d. Error = %s\n",
701                            fsp_str_dbg(fsp), (unsigned int)numtowrite,
702                            (int)nwritten, strerror(errcode) ));
703
704                 ERROR_NT(map_nt_error_from_unix(errcode));
705                 srv_set_message(outbuf,0,0,true);
706         } else {
707                 NTSTATUS status;
708
709                 SSVAL(outbuf,smb_vwv2,nwritten);
710                 SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
711                 if (nwritten < (ssize_t)numtowrite) {
712                         SCVAL(outbuf,smb_rcls,ERRHRD);
713                         SSVAL(outbuf,smb_err,ERRdiskfull);
714                 }
715
716                 DEBUG(3,("handle_aio_write: fnum=%d num=%d wrote=%d\n",
717                          fsp->fnum, (int)numtowrite, (int)nwritten));
718                 status = sync_file(fsp->conn,fsp, aio_ex->write_through);
719                 if (!NT_STATUS_IS_OK(status)) {
720                         errcode = errno;
721                         ERROR_BOTH(map_nt_error_from_unix(errcode),
722                                    ERRHRD, ERRdiskfull);
723                         srv_set_message(outbuf,0,0,true);
724                         DEBUG(5,("handle_aio_write: sync_file for %s returned %s\n",
725                                  fsp_str_dbg(fsp), nt_errstr(status)));
726                 }
727
728                 aio_ex->fsp->fh->pos = aio_ex->acb.aio_offset + nwritten;
729         }
730
731         show_msg(outbuf);
732         if (!srv_send_smb(aio_ex->smbreq->sconn, outbuf,
733                           true, aio_ex->smbreq->seqnum+1,
734                           IS_CONN_ENCRYPTED(fsp->conn),
735                           NULL)) {
736                 exit_server_cleanly("handle_aio_write_complete: "
737                                     "srv_send_smb failed.");
738         }
739
740         DEBUG(10,("handle_aio_write_complete: scheduled aio_write completed "
741                   "for file %s, offset %.0f, requested %u, written = %u\n",
742                   fsp_str_dbg(fsp), (double)aio_ex->acb.aio_offset,
743                   (unsigned int)numtowrite, (unsigned int)nwritten ));
744
745         return errcode;
746 }
747
748 /****************************************************************************
749  Complete the read and return the data or error back to the client.
750  Returns errno or zero if all ok.
751 *****************************************************************************/
752
753 static int handle_aio_smb2_read_complete(struct aio_extra *aio_ex, int errcode)
754 {
755         NTSTATUS status;
756         struct tevent_req *subreq = aio_ex->smbreq->smb2req->subreq;
757         ssize_t nread = SMB_VFS_AIO_RETURN(aio_ex->fsp,&aio_ex->acb);
758
759         /* Common error or success code processing for async or sync
760            read returns. */
761
762         status = smb2_read_complete(subreq, nread, errcode);
763
764         if (nread > 0) {
765                 aio_ex->fsp->fh->pos = aio_ex->acb.aio_offset + nread;
766                 aio_ex->fsp->fh->position_information = aio_ex->fsp->fh->pos;
767         }
768
769         DEBUG(10,("smb2: scheduled aio_read completed "
770                 "for file %s, offset %.0f, len = %u "
771                 "(errcode = %d, NTSTATUS = %s)\n",
772                 fsp_str_dbg(aio_ex->fsp),
773                 (double)aio_ex->acb.aio_offset,
774                 (unsigned int)nread,
775                 errcode,
776                 nt_errstr(status) ));
777
778         if (!NT_STATUS_IS_OK(status)) {
779                 tevent_req_nterror(subreq, status);
780         }
781
782         tevent_req_done(subreq);
783         return errcode;
784 }
785
786 /****************************************************************************
787  Complete the SMB2 write and return the data or error back to the client.
788  Returns error code or zero if all ok.
789 *****************************************************************************/
790
791 static int handle_aio_smb2_write_complete(struct aio_extra *aio_ex, int errcode)
792 {
793         files_struct *fsp = aio_ex->fsp;
794         ssize_t numtowrite = aio_ex->acb.aio_nbytes;
795         ssize_t nwritten = SMB_VFS_AIO_RETURN(fsp,&aio_ex->acb);
796         struct tevent_req *subreq = aio_ex->smbreq->smb2req->subreq;
797         NTSTATUS status;
798
799         status = smb2_write_complete(subreq, nwritten, errcode);
800
801         DEBUG(10,("smb2: scheduled aio_write completed "
802                 "for file %s, offset %.0f, requested %u, "
803                 "written = %u (errcode = %d, NTSTATUS = %s)\n",
804                 fsp_str_dbg(fsp),
805                 (double)aio_ex->acb.aio_offset,
806                 (unsigned int)numtowrite,
807                 (unsigned int)nwritten,
808                 errcode,
809                 nt_errstr(status) ));
810
811         if (!NT_STATUS_IS_OK(status)) {
812                 tevent_req_nterror(subreq, status);
813         }
814
815         tevent_req_done(subreq);
816         return errcode;
817 }
818
819 /****************************************************************************
820  Handle any aio completion. Returns True if finished (and sets *perr if err
821  was non-zero), False if not.
822 *****************************************************************************/
823
824 static bool handle_aio_completed(struct aio_extra *aio_ex, int *perr)
825 {
826         files_struct *fsp = NULL;
827         int err;
828
829         if(!aio_ex) {
830                 DEBUG(3, ("handle_aio_completed: Non-existing aio_ex passed\n"));
831                 return false;
832         }
833
834         fsp = aio_ex->fsp;
835
836         /* Ensure the operation has really completed. */
837         err = SMB_VFS_AIO_ERROR(fsp, &aio_ex->acb);
838         if (err == EINPROGRESS) {
839                 DEBUG(10,( "handle_aio_completed: operation mid %llu still in "
840                         "process for file %s\n",
841                         (unsigned long long)aio_ex->smbreq->mid,
842                         fsp_str_dbg(aio_ex->fsp)));
843                 return False;
844         }
845
846         /* Unlock now we're done. */
847         SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
848
849         if (err == ECANCELED) {
850                 /* If error is ECANCELED then don't return anything to the
851                  * client. */
852                 DEBUG(10,( "handle_aio_completed: operation mid %llu"
853                         " canceled\n",
854                         (unsigned long long)aio_ex->smbreq->mid));
855                 return True;
856         }
857
858         err = aio_ex->handle_completion(aio_ex, err);
859         if (err) {
860                 *perr = err; /* Only save non-zero errors. */
861         }
862
863         return True;
864 }
865
866 /****************************************************************************
867  Handle any aio completion inline.
868 *****************************************************************************/
869
870 void smbd_aio_complete_aio_ex(struct aio_extra *aio_ex)
871 {
872         files_struct *fsp = NULL;
873         int ret = 0;
874
875         outstanding_aio_calls--;
876
877         DEBUG(10,("smbd_aio_complete_mid: mid[%llu]\n",
878                 (unsigned long long)aio_ex->smbreq->mid));
879
880         fsp = aio_ex->fsp;
881         if (fsp == NULL) {
882                 /* file was closed whilst I/O was outstanding. Just
883                  * ignore. */
884                 DEBUG( 3,( "smbd_aio_complete_mid: file closed whilst "
885                         "aio outstanding (mid[%llu]).\n",
886                         (unsigned long long)aio_ex->smbreq->mid));
887                 return;
888         }
889
890         if (!handle_aio_completed(aio_ex, &ret)) {
891                 return;
892         }
893
894         TALLOC_FREE(aio_ex);
895 }
896
897 /****************************************************************************
898  We're doing write behind and the client closed the file. Wait up to 30
899  seconds (my arbitrary choice) for the aio to complete. Return 0 if all writes
900  completed, errno to return if not.
901 *****************************************************************************/
902
903 #define SMB_TIME_FOR_AIO_COMPLETE_WAIT 29
904
905 int wait_for_aio_completion(files_struct *fsp)
906 {
907         struct aio_extra *aio_ex;
908         const SMB_STRUCT_AIOCB **aiocb_list;
909         int aio_completion_count = 0;
910         time_t start_time = time_mono(NULL);
911         int seconds_left;
912
913         for (seconds_left = SMB_TIME_FOR_AIO_COMPLETE_WAIT;
914              seconds_left >= 0;) {
915                 int err = 0;
916                 int i;
917                 struct timespec ts;
918
919                 aio_completion_count = 0;
920                 for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
921                         if (aio_ex->fsp == fsp) {
922                                 aio_completion_count++;
923                         }
924                 }
925
926                 if (!aio_completion_count) {
927                         return 0;
928                 }
929
930                 DEBUG(3,("wait_for_aio_completion: waiting for %d aio events "
931                          "to complete.\n", aio_completion_count ));
932
933                 aiocb_list = SMB_MALLOC_ARRAY(const SMB_STRUCT_AIOCB *,
934                                               aio_completion_count);
935                 if (!aiocb_list) {
936                         return ENOMEM;
937                 }
938
939                 for( i = 0, aio_ex = aio_list_head;
940                      aio_ex;
941                      aio_ex = aio_ex->next) {
942                         if (aio_ex->fsp == fsp) {
943                                 aiocb_list[i++] = &aio_ex->acb;
944                         }
945                 }
946
947                 /* Now wait up to seconds_left for completion. */
948                 ts.tv_sec = seconds_left;
949                 ts.tv_nsec = 0;
950
951                 DEBUG(10,("wait_for_aio_completion: %d events, doing a wait "
952                           "of %d seconds.\n",
953                           aio_completion_count, seconds_left ));
954
955                 err = SMB_VFS_AIO_SUSPEND(fsp, aiocb_list,
956                                           aio_completion_count, &ts);
957
958                 DEBUG(10,("wait_for_aio_completion: returned err = %d, "
959                           "errno = %s\n", err, strerror(errno) ));
960
961                 if (err == -1 && errno == EAGAIN) {
962                         DEBUG(0,("wait_for_aio_completion: aio_suspend timed "
963                                  "out waiting for %d events after a wait of "
964                                  "%d seconds\n", aio_completion_count,
965                                  seconds_left));
966                         /* Timeout. */
967                         cancel_aio_by_fsp(fsp);
968                         SAFE_FREE(aiocb_list);
969                         return EIO;
970                 }
971
972                 /* One or more events might have completed - process them if
973                  * so. */
974                 for( i = 0; i < aio_completion_count; i++) {
975                         aio_ex = (struct aio_extra *)aiocb_list[i]->aio_sigevent.sigev_value.sival_ptr;
976
977                         if (!handle_aio_completed(aio_ex, &err)) {
978                                 continue;
979                         }
980                         TALLOC_FREE(aio_ex);
981                 }
982
983                 SAFE_FREE(aiocb_list);
984                 seconds_left = SMB_TIME_FOR_AIO_COMPLETE_WAIT
985                         - (time_mono(NULL) - start_time);
986         }
987
988         /* We timed out - we don't know why. Return ret if already an error,
989          * else EIO. */
990         DEBUG(10,("wait_for_aio_completion: aio_suspend timed out waiting "
991                   "for %d events\n",
992                   aio_completion_count));
993
994         return EIO;
995 }
996
997 /****************************************************************************
998  Cancel any outstanding aio requests. The client doesn't care about the reply.
999 *****************************************************************************/
1000
1001 void cancel_aio_by_fsp(files_struct *fsp)
1002 {
1003         struct aio_extra *aio_ex;
1004
1005         for( aio_ex = aio_list_head; aio_ex; aio_ex = aio_ex->next) {
1006                 if (aio_ex->fsp == fsp) {
1007                         /* Unlock now we're done. */
1008                         SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
1009
1010                         /* Don't delete the aio_extra record as we may have
1011                            completed and don't yet know it. Just do the
1012                            aio_cancel call and return. */
1013                         SMB_VFS_AIO_CANCEL(fsp, &aio_ex->acb);
1014                         aio_ex->fsp = NULL; /* fsp will be closed when we
1015                                              * return. */
1016                 }
1017         }
1018 }
1019
1020 #else
1021 NTSTATUS schedule_aio_read_and_X(connection_struct *conn,
1022                              struct smb_request *smbreq,
1023                              files_struct *fsp, SMB_OFF_T startpos,
1024                              size_t smb_maxcnt)
1025 {
1026         return NT_STATUS_RETRY;
1027 }
1028
1029 NTSTATUS schedule_aio_write_and_X(connection_struct *conn,
1030                               struct smb_request *smbreq,
1031                               files_struct *fsp, char *data,
1032                               SMB_OFF_T startpos,
1033                               size_t numtowrite)
1034 {
1035         return NT_STATUS_RETRY;
1036 }
1037
1038 NTSTATUS schedule_smb2_aio_read(connection_struct *conn,
1039                                 struct smb_request *smbreq,
1040                                 files_struct *fsp,
1041                                 TALLOC_CTX *ctx,
1042                                 DATA_BLOB *preadbuf,
1043                                 SMB_OFF_T startpos,
1044                                 size_t smb_maxcnt)
1045 {
1046         return NT_STATUS_RETRY;
1047 }
1048
1049 NTSTATUS schedule_aio_smb2_write(connection_struct *conn,
1050                                 struct smb_request *smbreq,
1051                                 files_struct *fsp,
1052                                 uint64_t in_offset,
1053                                 DATA_BLOB in_data,
1054                                 bool write_through)
1055 {
1056         return NT_STATUS_RETRY;
1057 }
1058
1059 void cancel_aio_by_fsp(files_struct *fsp)
1060 {
1061 }
1062
1063 int wait_for_aio_completion(files_struct *fsp)
1064 {
1065         return 0;
1066 }
1067
1068 void smbd_aio_complete_mid(uint64_t mid);
1069
1070 #endif