Merge commit 'origin/v3-2-test' into v3-2-stable
[kai/samba.git] / source3 / modules / vfs_aio_fork.c
1 /*
2  * Simulate the Posix AIO using mmap/fork
3  *
4  * Copyright (C) Volker Lendecke 2008
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #include "includes.h"
22
23 struct mmap_area {
24         size_t size;
25         volatile void *ptr;
26 };
27
28 static int mmap_area_destructor(struct mmap_area *area)
29 {
30         munmap((void *)area->ptr, area->size);
31         return 0;
32 }
33
34 static struct mmap_area *mmap_area_init(TALLOC_CTX *mem_ctx, size_t size)
35 {
36         struct mmap_area *result;
37         int fd;
38
39         result = talloc(mem_ctx, struct mmap_area);
40         if (result == NULL) {
41                 DEBUG(0, ("talloc failed\n"));
42                 goto fail;
43         }
44
45         fd = open("/dev/zero", O_RDWR);
46         if (fd == -1) {
47                 DEBUG(3, ("open(\"/dev/zero\") failed: %s\n",
48                           strerror(errno)));
49                 goto fail;
50         }
51
52         result->ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
53                            MAP_SHARED|MAP_FILE, fd, 0);
54         if (result->ptr == MAP_FAILED) {
55                 DEBUG(1, ("mmap failed: %s\n", strerror(errno)));
56                 goto fail;
57         }
58
59         result->size = size;
60         talloc_set_destructor(result, mmap_area_destructor);
61
62         return result;
63
64 fail:
65         TALLOC_FREE(result);
66         return NULL;
67 }
68
69 struct rw_cmd {
70         size_t n;
71         SMB_OFF_T offset;
72         bool read_cmd;
73 };
74
75 struct rw_ret {
76         ssize_t size;
77         int ret_errno;
78 };
79
80 struct aio_child_list;
81
82 struct aio_child {
83         struct aio_child *prev, *next;
84         struct aio_child_list *list;
85         SMB_STRUCT_AIOCB *aiocb;
86         pid_t pid;
87         int sockfd;
88         struct fd_event *sock_event;
89         struct rw_ret retval;
90         struct mmap_area *map;  /* ==NULL means write request */
91         bool dont_delete;       /* Marked as in use since last cleanup */
92         bool cancelled;
93         bool read_cmd;
94 };
95
96 struct aio_child_list {
97         struct aio_child *children;
98         struct timed_event *cleanup_event;
99 };
100
101 static void free_aio_children(void **p)
102 {
103         TALLOC_FREE(*p);
104 }
105
106 static ssize_t read_fd(int fd, void *ptr, size_t nbytes, int *recvfd)
107 {
108         struct msghdr msg;
109         struct iovec iov[1];
110         ssize_t n;
111 #ifndef HAVE_MSGHDR_MSG_CONTROL
112         int newfd;
113 #endif
114
115 #ifdef  HAVE_MSGHDR_MSG_CONTROL
116         union {
117           struct cmsghdr        cm;
118           char                          control[CMSG_SPACE(sizeof(int))];
119         } control_un;
120         struct cmsghdr  *cmptr;
121
122         msg.msg_control = control_un.control;
123         msg.msg_controllen = sizeof(control_un.control);
124 #else
125 #if HAVE_MSGHDR_MSG_ACCTRIGHTS
126         msg.msg_accrights = (caddr_t) &newfd;
127         msg.msg_accrightslen = sizeof(int);
128 #else
129 #error Can not pass file descriptors
130 #endif
131 #endif
132
133         msg.msg_name = NULL;
134         msg.msg_namelen = 0;
135
136         iov[0].iov_base = ptr;
137         iov[0].iov_len = nbytes;
138         msg.msg_iov = iov;
139         msg.msg_iovlen = 1;
140
141         if ( (n = recvmsg(fd, &msg, 0)) <= 0) {
142                 return(n);
143         }
144
145 #ifdef  HAVE_MSGHDR_MSG_CONTROL
146         if ((cmptr = CMSG_FIRSTHDR(&msg)) != NULL
147             && cmptr->cmsg_len == CMSG_LEN(sizeof(int))) {
148                 if (cmptr->cmsg_level != SOL_SOCKET) {
149                         DEBUG(10, ("control level != SOL_SOCKET"));
150                         errno = EINVAL;
151                         return -1;
152                 }
153                 if (cmptr->cmsg_type != SCM_RIGHTS) {
154                         DEBUG(10, ("control type != SCM_RIGHTS"));
155                         errno = EINVAL;
156                         return -1;
157                 }
158                 *recvfd = *((int *) CMSG_DATA(cmptr));
159         } else {
160                 *recvfd = -1;           /* descriptor was not passed */
161         }
162 #else
163         if (msg.msg_accrightslen == sizeof(int)) {
164                 *recvfd = newfd;
165         }
166         else {
167                 *recvfd = -1;           /* descriptor was not passed */
168         }
169 #endif
170
171         return(n);
172 }
173
174 static ssize_t write_fd(int fd, void *ptr, size_t nbytes, int sendfd)
175 {
176         struct msghdr   msg;
177         struct iovec    iov[1];
178
179 #ifdef  HAVE_MSGHDR_MSG_CONTROL
180         union {
181                 struct cmsghdr  cm;
182                 char control[CMSG_SPACE(sizeof(int))];
183         } control_un;
184         struct cmsghdr  *cmptr;
185
186         ZERO_STRUCT(msg);
187         ZERO_STRUCT(control_un);
188
189         msg.msg_control = control_un.control;
190         msg.msg_controllen = sizeof(control_un.control);
191
192         cmptr = CMSG_FIRSTHDR(&msg);
193         cmptr->cmsg_len = CMSG_LEN(sizeof(int));
194         cmptr->cmsg_level = SOL_SOCKET;
195         cmptr->cmsg_type = SCM_RIGHTS;
196         *((int *) CMSG_DATA(cmptr)) = sendfd;
197 #else
198         ZERO_STRUCT(msg);
199         msg.msg_accrights = (caddr_t) &sendfd;
200         msg.msg_accrightslen = sizeof(int);
201 #endif
202
203         msg.msg_name = NULL;
204         msg.msg_namelen = 0;
205
206         ZERO_STRUCT(iov);
207         iov[0].iov_base = ptr;
208         iov[0].iov_len = nbytes;
209         msg.msg_iov = iov;
210         msg.msg_iovlen = 1;
211
212         return (sendmsg(fd, &msg, 0));
213 }
214
215 static void aio_child_cleanup(struct event_context *event_ctx,
216                               struct timed_event *te,
217                               const struct timeval *now,
218                               void *private_data)
219 {
220         struct aio_child_list *list = talloc_get_type_abort(
221                 private_data, struct aio_child_list);
222         struct aio_child *child, *next;
223
224         TALLOC_FREE(list->cleanup_event);
225
226         for (child = list->children; child != NULL; child = next) {
227                 next = child->next;
228
229                 if (child->aiocb != NULL) {
230                         DEBUG(10, ("child %d currently active\n",
231                                    (int)child->pid));
232                         continue;
233                 }
234
235                 if (child->dont_delete) {
236                         DEBUG(10, ("Child %d was active since last cleanup\n",
237                                    (int)child->pid));
238                         child->dont_delete = false;
239                         continue;
240                 }
241
242                 DEBUG(10, ("Child %d idle for more than 30 seconds, "
243                            "deleting\n", (int)child->pid));
244
245                 TALLOC_FREE(child);
246         }
247
248         if (list->children != NULL) {
249                 /*
250                  * Re-schedule the next cleanup round
251                  */
252                 list->cleanup_event = event_add_timed(smbd_event_context(), list,
253                                                       timeval_add(now, 30, 0),
254                                                       "aio_child_cleanup",
255                                                       aio_child_cleanup, list);
256
257         }
258 }
259
260 static struct aio_child_list *init_aio_children(struct vfs_handle_struct *handle)
261 {
262         struct aio_child_list *data = NULL;
263
264         if (SMB_VFS_HANDLE_TEST_DATA(handle)) {
265                 SMB_VFS_HANDLE_GET_DATA(handle, data, struct aio_child_list,
266                                         return NULL);
267         }
268
269         if (data == NULL) {
270                 data = TALLOC_ZERO_P(NULL, struct aio_child_list);
271                 if (data == NULL) {
272                         return NULL;
273                 }
274         }
275
276         /*
277          * Regardless of whether the child_list had been around or not, make
278          * sure that we have a cleanup timed event. This timed event will
279          * delete itself when it finds that no children are around anymore.
280          */
281
282         if (data->cleanup_event == NULL) {
283                 data->cleanup_event = event_add_timed(smbd_event_context(), data,
284                                                       timeval_current_ofs(30, 0),
285                                                       "aio_child_cleanup",
286                                                       aio_child_cleanup, data);
287                 if (data->cleanup_event == NULL) {
288                         TALLOC_FREE(data);
289                         return NULL;
290                 }
291         }
292
293         if (!SMB_VFS_HANDLE_TEST_DATA(handle)) {
294                 SMB_VFS_HANDLE_SET_DATA(handle, data, free_aio_children,
295                                         struct aio_child_list, return False);
296         }
297
298         return data;
299 }
300
301 static void aio_child_loop(int sockfd, struct mmap_area *map)
302 {
303         while (true) {
304                 int fd = -1;
305                 ssize_t ret;
306                 struct rw_cmd cmd_struct;
307                 struct rw_ret ret_struct;
308
309                 ret = read_fd(sockfd, &cmd_struct, sizeof(cmd_struct), &fd);
310                 if (ret != sizeof(cmd_struct)) {
311                         DEBUG(10, ("read_fd returned %d: %s\n", (int)ret,
312                                    strerror(errno)));
313                         exit(1);
314                 }
315
316                 DEBUG(10, ("aio_child_loop: %s %d bytes at %d from fd %d\n",
317                            cmd_struct.read_cmd ? "read" : "write",
318                            (int)cmd_struct.n, (int)cmd_struct.offset, fd));
319
320 #ifdef ENABLE_BUILD_FARM_HACKS
321                 {
322                         /*
323                          * In the build farm, we want erratic behaviour for
324                          * async I/O times
325                          */
326                         uint8_t randval;
327                         unsigned msecs;
328                         /*
329                          * use generate_random_buffer, we just forked from a
330                          * common parent state
331                          */
332                         generate_random_buffer(&randval, sizeof(randval));
333                         msecs = randval + 20;
334                         DEBUG(10, ("delaying for %u msecs\n", msecs));
335                         smb_msleep(msecs);
336                 }
337 #endif
338
339
340                 ZERO_STRUCT(ret_struct);
341
342                 if (cmd_struct.read_cmd) {
343                         ret_struct.size = sys_pread(
344                                 fd, (void *)map->ptr, cmd_struct.n,
345                                 cmd_struct.offset);
346                 }
347                 else {
348                         ret_struct.size = sys_pwrite(
349                                 fd, (void *)map->ptr, cmd_struct.n,
350                                 cmd_struct.offset);
351                 }
352
353                 DEBUG(10, ("aio_child_loop: syscall returned %d\n",
354                            (int)ret_struct.size));
355
356                 if (ret_struct.size == -1) {
357                         ret_struct.ret_errno = errno;
358                 }
359
360                 ret = write_data(sockfd, (char *)&ret_struct,
361                                  sizeof(ret_struct));
362                 if (ret != sizeof(ret_struct)) {
363                         DEBUG(10, ("could not write ret_struct: %s\n",
364                                    strerror(errno)));
365                         exit(2);
366                 }
367
368                 close(fd);
369         }
370 }
371
372 static void handle_aio_completion(struct event_context *event_ctx,
373                                   struct fd_event *event, uint16 flags,
374                                   void *p)
375 {
376         struct aio_child *child = (struct aio_child *)p;
377         uint16 mid;
378
379         DEBUG(10, ("handle_aio_completion called with flags=%d\n", flags));
380
381         if ((flags & EVENT_FD_READ) == 0) {
382                 return;
383         }
384
385         if (!NT_STATUS_IS_OK(read_data(child->sockfd,
386                                        (char *)&child->retval,
387                                        sizeof(child->retval)))) {
388                 DEBUG(0, ("aio child %d died\n", (int)child->pid));
389                 child->retval.size = -1;
390                 child->retval.ret_errno = EIO;
391         }
392
393         if (child->cancelled) {
394                 child->aiocb = NULL;
395                 child->cancelled = false;
396                 return;
397         }
398
399         if (child->read_cmd && (child->retval.size > 0)) {
400                 SMB_ASSERT(child->retval.size <= child->aiocb->aio_nbytes);
401                 memcpy((void *)child->aiocb->aio_buf, (void *)child->map->ptr,
402                        child->retval.size);
403         }
404
405         mid = child->aiocb->aio_sigevent.sigev_value.sival_int;
406
407         DEBUG(10, ("mid %d finished\n", (int)mid));
408
409         aio_request_done(mid);
410         process_aio_queue();
411 }
412
413 static int aio_child_destructor(struct aio_child *child)
414 {
415         SMB_ASSERT((child->aiocb == NULL) || child->cancelled);
416         close(child->sockfd);
417         DLIST_REMOVE(child->list->children, child);
418         return 0;
419 }
420
421 static NTSTATUS create_aio_child(struct aio_child_list *children,
422                                  size_t map_size,
423                                  struct aio_child **presult)
424 {
425         struct aio_child *result;
426         int fdpair[2];
427         NTSTATUS status;
428
429         fdpair[0] = fdpair[1] = -1;
430
431         result = TALLOC_ZERO_P(children, struct aio_child);
432         NT_STATUS_HAVE_NO_MEMORY(result);
433
434         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) == -1) {
435                 status = map_nt_error_from_unix(errno);
436                 DEBUG(10, ("socketpair() failed: %s\n", strerror(errno)));
437                 TALLOC_FREE(result);
438                 goto fail;
439         }
440
441         DEBUG(10, ("fdpair = %d/%d\n", fdpair[0], fdpair[1]));
442
443         result->map = mmap_area_init(result, map_size);
444         if (result->map == NULL) {
445                 status = map_nt_error_from_unix(errno);
446                 DEBUG(0, ("Could not create mmap area\n"));
447                 goto fail;
448         }
449
450         result->pid = sys_fork();
451         if (result->pid == -1) {
452                 status = map_nt_error_from_unix(errno);
453                 DEBUG(0, ("fork failed: %s\n", strerror(errno)));
454                 goto fail;
455         }
456
457         if (result->pid == 0) {
458                 close(fdpair[0]);
459                 result->sockfd = fdpair[1];
460                 aio_child_loop(result->sockfd, result->map);
461         }
462
463         DEBUG(10, ("Child %d created\n", result->pid));
464
465         result->sockfd = fdpair[0];
466         close(fdpair[1]);
467
468         result->sock_event = event_add_fd(smbd_event_context(), result,
469                                           result->sockfd, EVENT_FD_READ,
470                                           handle_aio_completion,
471                                           result);
472         if (result->sock_event == NULL) {
473                 status = NT_STATUS_NO_MEMORY;
474                 DEBUG(0, ("event_add_fd failed\n"));
475                 goto fail;
476         }
477
478         result->list = children;
479         DLIST_ADD(children->children, result);
480
481         talloc_set_destructor(result, aio_child_destructor);
482
483         *presult = result;
484
485         return NT_STATUS_OK;
486
487  fail:
488         if (fdpair[0] != -1) close(fdpair[0]);
489         if (fdpair[1] != -1) close(fdpair[1]);
490         TALLOC_FREE(result);
491
492         return status;
493 }
494
495 static NTSTATUS get_idle_child(struct vfs_handle_struct *handle,
496                                struct aio_child **pchild)
497 {
498         struct aio_child_list *children;
499         struct aio_child *child;
500         NTSTATUS status;
501
502         children = init_aio_children(handle);
503         if (children == NULL) {
504                 return NT_STATUS_NO_MEMORY;
505         }
506
507         for (child = children->children; child != NULL; child = child->next) {
508                 if (child->aiocb == NULL) {
509                         /* idle */
510                         break;
511                 }
512         }
513
514         if (child == NULL) {
515                 DEBUG(10, ("no idle child found, creating new one\n"));
516
517                 status = create_aio_child(children, 128*1024, &child);
518                 if (!NT_STATUS_IS_OK(status)) {
519                         DEBUG(10, ("create_aio_child failed: %s\n",
520                                    nt_errstr(status)));
521                         return status;
522                 }
523         }
524
525         child->dont_delete = true;
526
527         *pchild = child;
528         return NT_STATUS_OK;
529 }
530
531 static int aio_fork_read(struct vfs_handle_struct *handle,
532                          struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb)
533 {
534         struct aio_child *child;
535         struct rw_cmd cmd;
536         ssize_t ret;
537         NTSTATUS status;
538
539         if (aiocb->aio_nbytes > 128*1024) {
540                 /* TODO: support variable buffers */
541                 errno = EINVAL;
542                 return -1;
543         }
544
545         status = get_idle_child(handle, &child);
546         if (!NT_STATUS_IS_OK(status)) {
547                 DEBUG(10, ("Could not get an idle child\n"));
548                 return -1;
549         }
550
551         child->read_cmd = true;
552         child->aiocb = aiocb;
553         child->retval.ret_errno = EINPROGRESS;
554
555         ZERO_STRUCT(cmd);
556         cmd.n = aiocb->aio_nbytes;
557         cmd.offset = aiocb->aio_offset;
558         cmd.read_cmd = child->read_cmd;
559
560         DEBUG(10, ("sending fd %d to child %d\n", fsp->fh->fd,
561                    (int)child->pid));
562
563         ret = write_fd(child->sockfd, &cmd, sizeof(cmd), fsp->fh->fd);
564         if (ret == -1) {
565                 DEBUG(10, ("write_fd failed: %s\n", strerror(errno)));
566                 return -1;
567         }
568
569         return 0;
570 }
571
572 static int aio_fork_write(struct vfs_handle_struct *handle,
573                           struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb)
574 {
575         struct aio_child *child;
576         struct rw_cmd cmd;
577         ssize_t ret;
578         NTSTATUS status;
579
580         if (aiocb->aio_nbytes > 128*1024) {
581                 /* TODO: support variable buffers */
582                 errno = EINVAL;
583                 return -1;
584         }
585
586         status = get_idle_child(handle, &child);
587         if (!NT_STATUS_IS_OK(status)) {
588                 DEBUG(10, ("Could not get an idle child\n"));
589                 return -1;
590         }
591
592         child->read_cmd = false;
593         child->aiocb = aiocb;
594         child->retval.ret_errno = EINPROGRESS;
595
596         memcpy((void *)child->map->ptr, (void *)aiocb->aio_buf,
597                aiocb->aio_nbytes);
598
599         ZERO_STRUCT(cmd);
600         cmd.n = aiocb->aio_nbytes;
601         cmd.offset = aiocb->aio_offset;
602         cmd.read_cmd = child->read_cmd;
603
604         DEBUG(10, ("sending fd %d to child %d\n", fsp->fh->fd,
605                    (int)child->pid));
606
607         ret = write_fd(child->sockfd, &cmd, sizeof(cmd), fsp->fh->fd);
608         if (ret == -1) {
609                 DEBUG(10, ("write_fd failed: %s\n", strerror(errno)));
610                 return -1;
611         }
612
613         return 0;
614 }
615
616 static struct aio_child *aio_fork_find_child(struct vfs_handle_struct *handle,
617                                              SMB_STRUCT_AIOCB *aiocb)
618 {
619         struct aio_child_list *children;
620         struct aio_child *child;
621
622         children = init_aio_children(handle);
623         if (children == NULL) {
624                 return NULL;
625         }
626
627         for (child = children->children; child != NULL; child = child->next) {
628                 if (child->aiocb == aiocb) {
629                         return child;
630                 }
631         }
632
633         return NULL;
634 }
635
636 static ssize_t aio_fork_return_fn(struct vfs_handle_struct *handle,
637                                   struct files_struct *fsp,
638                                   SMB_STRUCT_AIOCB *aiocb)
639 {
640         struct aio_child *child = aio_fork_find_child(handle, aiocb);
641
642         if (child == NULL) {
643                 errno = EINVAL;
644                 DEBUG(0, ("returning EINVAL\n"));
645                 return -1;
646         }
647
648         child->aiocb = NULL;
649
650         if (child->retval.size == -1) {
651                 errno = child->retval.ret_errno;
652         }
653
654         return child->retval.size;
655 }
656
657 static int aio_fork_cancel(struct vfs_handle_struct *handle,
658                            struct files_struct *fsp,
659                            SMB_STRUCT_AIOCB *aiocb)
660 {
661         struct aio_child_list *children;
662         struct aio_child *child;
663
664         children = init_aio_children(handle);
665         if (children == NULL) {
666                 errno = EINVAL;
667                 return -1;
668         }
669
670         for (child = children->children; child != NULL; child = child->next) {
671                 if (child->aiocb == NULL) {
672                         continue;
673                 }
674                 if (child->aiocb->aio_fildes != fsp->fh->fd) {
675                         continue;
676                 }
677                 if ((aiocb != NULL) && (child->aiocb != aiocb)) {
678                         continue;
679                 }
680
681                 /*
682                  * We let the child do its job, but we discard the result when
683                  * it's finished.
684                  */
685
686                 child->cancelled = true;
687         }
688
689         return AIO_CANCELED;
690 }
691
692 static int aio_fork_error_fn(struct vfs_handle_struct *handle,
693                              struct files_struct *fsp,
694                              SMB_STRUCT_AIOCB *aiocb)
695 {
696         struct aio_child *child = aio_fork_find_child(handle, aiocb);
697
698         if (child == NULL) {
699                 errno = EINVAL;
700                 return -1;
701         }
702
703         return child->retval.ret_errno;
704 }
705
706 /* VFS operations structure */
707
708 static vfs_op_tuple aio_fork_ops[] = {
709         {SMB_VFS_OP(aio_fork_read),     SMB_VFS_OP_AIO_READ,
710          SMB_VFS_LAYER_TRANSPARENT},
711         {SMB_VFS_OP(aio_fork_write),    SMB_VFS_OP_AIO_WRITE,
712          SMB_VFS_LAYER_TRANSPARENT},
713         {SMB_VFS_OP(aio_fork_return_fn), SMB_VFS_OP_AIO_RETURN,
714          SMB_VFS_LAYER_TRANSPARENT},
715         {SMB_VFS_OP(aio_fork_cancel),   SMB_VFS_OP_AIO_CANCEL,
716          SMB_VFS_LAYER_TRANSPARENT},
717         {SMB_VFS_OP(aio_fork_error_fn), SMB_VFS_OP_AIO_ERROR,
718          SMB_VFS_LAYER_TRANSPARENT},
719         {SMB_VFS_OP(NULL),              SMB_VFS_OP_NOOP,
720          SMB_VFS_LAYER_NOOP}
721 };
722
723 NTSTATUS vfs_aio_fork_init(void);
724 NTSTATUS vfs_aio_fork_init(void)
725 {
726         return smb_register_vfs(SMB_VFS_INTERFACE_VERSION,
727                                 "aio_fork", aio_fork_ops);
728 }