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