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