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