s3:vfs fix children cleanup in aio_fork
[obnox/samba-ctdb.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         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                               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                 child = next;
249         }
250
251         if (list->children != NULL) {
252                 /*
253                  * Re-schedule the next cleanup round
254                  */
255                 list->cleanup_event = event_add_timed(smbd_event_context(), list,
256                                                       timeval_add(&now, 30, 0),
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, data);
288                 if (data->cleanup_event == NULL) {
289                         TALLOC_FREE(data);
290                         return NULL;
291                 }
292         }
293
294         if (!SMB_VFS_HANDLE_TEST_DATA(handle)) {
295                 SMB_VFS_HANDLE_SET_DATA(handle, data, free_aio_children,
296                                         struct aio_child_list, return False);
297         }
298
299         return data;
300 }
301
302 static void aio_child_loop(int sockfd, struct mmap_area *map)
303 {
304         while (true) {
305                 int fd = -1;
306                 ssize_t ret;
307                 struct rw_cmd cmd_struct;
308                 struct rw_ret ret_struct;
309
310                 ret = read_fd(sockfd, &cmd_struct, sizeof(cmd_struct), &fd);
311                 if (ret != sizeof(cmd_struct)) {
312                         DEBUG(10, ("read_fd returned %d: %s\n", (int)ret,
313                                    strerror(errno)));
314                         exit(1);
315                 }
316
317                 DEBUG(10, ("aio_child_loop: %s %d bytes at %d from fd %d\n",
318                            cmd_struct.read_cmd ? "read" : "write",
319                            (int)cmd_struct.n, (int)cmd_struct.offset, fd));
320
321 #ifdef ENABLE_BUILD_FARM_HACKS
322                 {
323                         /*
324                          * In the build farm, we want erratic behaviour for
325                          * async I/O times
326                          */
327                         uint8_t randval;
328                         unsigned msecs;
329                         /*
330                          * use generate_random_buffer, we just forked from a
331                          * common parent state
332                          */
333                         generate_random_buffer(&randval, sizeof(randval));
334                         msecs = randval + 20;
335                         DEBUG(10, ("delaying for %u msecs\n", msecs));
336                         smb_msleep(msecs);
337                 }
338 #endif
339
340
341                 ZERO_STRUCT(ret_struct);
342
343                 if (cmd_struct.read_cmd) {
344                         ret_struct.size = sys_pread(
345                                 fd, (void *)map->ptr, cmd_struct.n,
346                                 cmd_struct.offset);
347                 }
348                 else {
349                         ret_struct.size = sys_pwrite(
350                                 fd, (void *)map->ptr, cmd_struct.n,
351                                 cmd_struct.offset);
352                 }
353
354                 DEBUG(10, ("aio_child_loop: syscall returned %d\n",
355                            (int)ret_struct.size));
356
357                 if (ret_struct.size == -1) {
358                         ret_struct.ret_errno = errno;
359                 }
360
361                 /*
362                  * Close the fd before telling our parent we're done. The
363                  * parent might close and re-open the file very quickly, and
364                  * with system-level share modes (GPFS) we would get an
365                  * unjustified SHARING_VIOLATION.
366                  */
367                 close(fd);
368
369                 ret = write_data(sockfd, (char *)&ret_struct,
370                                  sizeof(ret_struct));
371                 if (ret != sizeof(ret_struct)) {
372                         DEBUG(10, ("could not write ret_struct: %s\n",
373                                    strerror(errno)));
374                         exit(2);
375                 }
376         }
377 }
378
379 static void handle_aio_completion(struct event_context *event_ctx,
380                                   struct fd_event *event, uint16 flags,
381                                   void *p)
382 {
383         struct aio_child *child = (struct aio_child *)p;
384         uint16 mid;
385
386         DEBUG(10, ("handle_aio_completion called with flags=%d\n", flags));
387
388         if ((flags & EVENT_FD_READ) == 0) {
389                 return;
390         }
391
392         if (!NT_STATUS_IS_OK(read_data(child->sockfd,
393                                        (char *)&child->retval,
394                                        sizeof(child->retval)))) {
395                 DEBUG(0, ("aio child %d died\n", (int)child->pid));
396                 child->retval.size = -1;
397                 child->retval.ret_errno = EIO;
398         }
399
400         if (child->cancelled) {
401                 child->aiocb = NULL;
402                 child->cancelled = false;
403                 return;
404         }
405
406         if (child->read_cmd && (child->retval.size > 0)) {
407                 SMB_ASSERT(child->retval.size <= child->aiocb->aio_nbytes);
408                 memcpy((void *)child->aiocb->aio_buf, (void *)child->map->ptr,
409                        child->retval.size);
410         }
411
412         mid = child->aiocb->aio_sigevent.sigev_value.sival_int;
413
414         DEBUG(10, ("mid %d finished\n", (int)mid));
415
416         smbd_aio_complete_mid(mid);
417 }
418
419 static int aio_child_destructor(struct aio_child *child)
420 {
421         SMB_ASSERT((child->aiocb == NULL) || child->cancelled);
422         close(child->sockfd);
423         DLIST_REMOVE(child->list->children, child);
424         return 0;
425 }
426
427 /*
428  * We have to close all fd's in open files, we might incorrectly hold a system
429  * level share mode on a file.
430  */
431
432 static struct files_struct *close_fsp_fd(struct files_struct *fsp,
433                                          void *private_data)
434 {
435         if ((fsp->fh != NULL) && (fsp->fh->fd != -1)) {
436                 close(fsp->fh->fd);
437                 fsp->fh->fd = -1;
438         }
439         return NULL;
440 }
441
442 static NTSTATUS create_aio_child(struct aio_child_list *children,
443                                  size_t map_size,
444                                  struct aio_child **presult)
445 {
446         struct aio_child *result;
447         int fdpair[2];
448         NTSTATUS status;
449
450         fdpair[0] = fdpair[1] = -1;
451
452         result = TALLOC_ZERO_P(children, struct aio_child);
453         NT_STATUS_HAVE_NO_MEMORY(result);
454
455         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) == -1) {
456                 status = map_nt_error_from_unix(errno);
457                 DEBUG(10, ("socketpair() failed: %s\n", strerror(errno)));
458                 goto fail;
459         }
460
461         DEBUG(10, ("fdpair = %d/%d\n", fdpair[0], fdpair[1]));
462
463         result->map = mmap_area_init(result, map_size);
464         if (result->map == NULL) {
465                 status = map_nt_error_from_unix(errno);
466                 DEBUG(0, ("Could not create mmap area\n"));
467                 goto fail;
468         }
469
470         result->pid = sys_fork();
471         if (result->pid == -1) {
472                 status = map_nt_error_from_unix(errno);
473                 DEBUG(0, ("fork failed: %s\n", strerror(errno)));
474                 goto fail;
475         }
476
477         if (result->pid == 0) {
478                 close(fdpair[0]);
479                 result->sockfd = fdpair[1];
480                 files_forall(close_fsp_fd, NULL);
481                 aio_child_loop(result->sockfd, result->map);
482         }
483
484         DEBUG(10, ("Child %d created\n", result->pid));
485
486         result->sockfd = fdpair[0];
487         close(fdpair[1]);
488
489         result->sock_event = event_add_fd(smbd_event_context(), result,
490                                           result->sockfd, EVENT_FD_READ,
491                                           handle_aio_completion,
492                                           result);
493         if (result->sock_event == NULL) {
494                 status = NT_STATUS_NO_MEMORY;
495                 DEBUG(0, ("event_add_fd failed\n"));
496                 goto fail;
497         }
498
499         result->list = children;
500         DLIST_ADD(children->children, result);
501
502         talloc_set_destructor(result, aio_child_destructor);
503
504         *presult = result;
505
506         return NT_STATUS_OK;
507
508  fail:
509         if (fdpair[0] != -1) close(fdpair[0]);
510         if (fdpair[1] != -1) close(fdpair[1]);
511         TALLOC_FREE(result);
512
513         return status;
514 }
515
516 static NTSTATUS get_idle_child(struct vfs_handle_struct *handle,
517                                struct aio_child **pchild)
518 {
519         struct aio_child_list *children;
520         struct aio_child *child;
521         NTSTATUS status;
522
523         children = init_aio_children(handle);
524         if (children == NULL) {
525                 return NT_STATUS_NO_MEMORY;
526         }
527
528         for (child = children->children; child != NULL; child = child->next) {
529                 if (child->aiocb == NULL) {
530                         /* idle */
531                         break;
532                 }
533         }
534
535         if (child == NULL) {
536                 DEBUG(10, ("no idle child found, creating new one\n"));
537
538                 status = create_aio_child(children, 128*1024, &child);
539                 if (!NT_STATUS_IS_OK(status)) {
540                         DEBUG(10, ("create_aio_child failed: %s\n",
541                                    nt_errstr(status)));
542                         return status;
543                 }
544         }
545
546         child->dont_delete = true;
547
548         *pchild = child;
549         return NT_STATUS_OK;
550 }
551
552 static int aio_fork_read(struct vfs_handle_struct *handle,
553                          struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb)
554 {
555         struct aio_child *child;
556         struct rw_cmd cmd;
557         ssize_t ret;
558         NTSTATUS status;
559
560         if (aiocb->aio_nbytes > 128*1024) {
561                 /* TODO: support variable buffers */
562                 errno = EINVAL;
563                 return -1;
564         }
565
566         status = get_idle_child(handle, &child);
567         if (!NT_STATUS_IS_OK(status)) {
568                 DEBUG(10, ("Could not get an idle child\n"));
569                 return -1;
570         }
571
572         child->read_cmd = true;
573         child->aiocb = aiocb;
574         child->retval.ret_errno = EINPROGRESS;
575
576         ZERO_STRUCT(cmd);
577         cmd.n = aiocb->aio_nbytes;
578         cmd.offset = aiocb->aio_offset;
579         cmd.read_cmd = child->read_cmd;
580
581         DEBUG(10, ("sending fd %d to child %d\n", fsp->fh->fd,
582                    (int)child->pid));
583
584         ret = write_fd(child->sockfd, &cmd, sizeof(cmd), fsp->fh->fd);
585         if (ret == -1) {
586                 DEBUG(10, ("write_fd failed: %s\n", strerror(errno)));
587                 return -1;
588         }
589
590         return 0;
591 }
592
593 static int aio_fork_write(struct vfs_handle_struct *handle,
594                           struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb)
595 {
596         struct aio_child *child;
597         struct rw_cmd cmd;
598         ssize_t ret;
599         NTSTATUS status;
600
601         if (aiocb->aio_nbytes > 128*1024) {
602                 /* TODO: support variable buffers */
603                 errno = EINVAL;
604                 return -1;
605         }
606
607         status = get_idle_child(handle, &child);
608         if (!NT_STATUS_IS_OK(status)) {
609                 DEBUG(10, ("Could not get an idle child\n"));
610                 return -1;
611         }
612
613         child->read_cmd = false;
614         child->aiocb = aiocb;
615         child->retval.ret_errno = EINPROGRESS;
616
617         memcpy((void *)child->map->ptr, (void *)aiocb->aio_buf,
618                aiocb->aio_nbytes);
619
620         ZERO_STRUCT(cmd);
621         cmd.n = aiocb->aio_nbytes;
622         cmd.offset = aiocb->aio_offset;
623         cmd.read_cmd = child->read_cmd;
624
625         DEBUG(10, ("sending fd %d to child %d\n", fsp->fh->fd,
626                    (int)child->pid));
627
628         ret = write_fd(child->sockfd, &cmd, sizeof(cmd), fsp->fh->fd);
629         if (ret == -1) {
630                 DEBUG(10, ("write_fd failed: %s\n", strerror(errno)));
631                 return -1;
632         }
633
634         return 0;
635 }
636
637 static struct aio_child *aio_fork_find_child(struct vfs_handle_struct *handle,
638                                              SMB_STRUCT_AIOCB *aiocb)
639 {
640         struct aio_child_list *children;
641         struct aio_child *child;
642
643         children = init_aio_children(handle);
644         if (children == NULL) {
645                 return NULL;
646         }
647
648         for (child = children->children; child != NULL; child = child->next) {
649                 if (child->aiocb == aiocb) {
650                         return child;
651                 }
652         }
653
654         return NULL;
655 }
656
657 static ssize_t aio_fork_return_fn(struct vfs_handle_struct *handle,
658                                   struct files_struct *fsp,
659                                   SMB_STRUCT_AIOCB *aiocb)
660 {
661         struct aio_child *child = aio_fork_find_child(handle, aiocb);
662
663         if (child == NULL) {
664                 errno = EINVAL;
665                 DEBUG(0, ("returning EINVAL\n"));
666                 return -1;
667         }
668
669         child->aiocb = NULL;
670
671         if (child->retval.size == -1) {
672                 errno = child->retval.ret_errno;
673         }
674
675         return child->retval.size;
676 }
677
678 static int aio_fork_cancel(struct vfs_handle_struct *handle,
679                            struct files_struct *fsp,
680                            SMB_STRUCT_AIOCB *aiocb)
681 {
682         struct aio_child_list *children;
683         struct aio_child *child;
684
685         children = init_aio_children(handle);
686         if (children == NULL) {
687                 errno = EINVAL;
688                 return -1;
689         }
690
691         for (child = children->children; child != NULL; child = child->next) {
692                 if (child->aiocb == NULL) {
693                         continue;
694                 }
695                 if (child->aiocb->aio_fildes != fsp->fh->fd) {
696                         continue;
697                 }
698                 if ((aiocb != NULL) && (child->aiocb != aiocb)) {
699                         continue;
700                 }
701
702                 /*
703                  * We let the child do its job, but we discard the result when
704                  * it's finished.
705                  */
706
707                 child->cancelled = true;
708         }
709
710         return AIO_CANCELED;
711 }
712
713 static int aio_fork_error_fn(struct vfs_handle_struct *handle,
714                              struct files_struct *fsp,
715                              SMB_STRUCT_AIOCB *aiocb)
716 {
717         struct aio_child *child = aio_fork_find_child(handle, aiocb);
718
719         if (child == NULL) {
720                 errno = EINVAL;
721                 return -1;
722         }
723
724         return child->retval.ret_errno;
725 }
726
727 /* VFS operations structure */
728
729 static vfs_op_tuple aio_fork_ops[] = {
730         {SMB_VFS_OP(aio_fork_read),     SMB_VFS_OP_AIO_READ,
731          SMB_VFS_LAYER_TRANSPARENT},
732         {SMB_VFS_OP(aio_fork_write),    SMB_VFS_OP_AIO_WRITE,
733          SMB_VFS_LAYER_TRANSPARENT},
734         {SMB_VFS_OP(aio_fork_return_fn), SMB_VFS_OP_AIO_RETURN,
735          SMB_VFS_LAYER_TRANSPARENT},
736         {SMB_VFS_OP(aio_fork_cancel),   SMB_VFS_OP_AIO_CANCEL,
737          SMB_VFS_LAYER_TRANSPARENT},
738         {SMB_VFS_OP(aio_fork_error_fn), SMB_VFS_OP_AIO_ERROR,
739          SMB_VFS_LAYER_TRANSPARENT},
740         {SMB_VFS_OP(NULL),              SMB_VFS_OP_NOOP,
741          SMB_VFS_LAYER_NOOP}
742 };
743
744 NTSTATUS vfs_aio_fork_init(void);
745 NTSTATUS vfs_aio_fork_init(void)
746 {
747         return smb_register_vfs(SMB_VFS_INTERFACE_VERSION,
748                                 "aio_fork", aio_fork_ops);
749 }