]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/compat/linux/linux_event.c
Linux epoll: Check both read and write kqueue events existence in EPOLL_CTL_ADD
[FreeBSD/FreeBSD.git] / sys / compat / linux / linux_event.c
1 /*-
2  * Copyright (c) 2007 Roman Divacky
3  * Copyright (c) 2014 Dmitry Chagin
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_compat.h"
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/imgact.h>
36 #include <sys/kernel.h>
37 #include <sys/limits.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/callout.h>
41 #include <sys/capsicum.h>
42 #include <sys/types.h>
43 #include <sys/user.h>
44 #include <sys/file.h>
45 #include <sys/filedesc.h>
46 #include <sys/filio.h>
47 #include <sys/errno.h>
48 #include <sys/event.h>
49 #include <sys/poll.h>
50 #include <sys/proc.h>
51 #include <sys/selinfo.h>
52 #include <sys/sx.h>
53 #include <sys/syscallsubr.h>
54 #include <sys/timespec.h>
55
56 #ifdef COMPAT_LINUX32
57 #include <machine/../linux32/linux.h>
58 #include <machine/../linux32/linux32_proto.h>
59 #else
60 #include <machine/../linux/linux.h>
61 #include <machine/../linux/linux_proto.h>
62 #endif
63
64 #include <compat/linux/linux_emul.h>
65 #include <compat/linux/linux_event.h>
66 #include <compat/linux/linux_file.h>
67 #include <compat/linux/linux_timer.h>
68 #include <compat/linux/linux_util.h>
69
70 /*
71  * epoll defines 'struct epoll_event' with the field 'data' as 64 bits
72  * on all architectures. But on 32 bit architectures BSD 'struct kevent' only
73  * has 32 bit opaque pointer as 'udata' field. So we can't pass epoll supplied
74  * data verbatuim. Therefore we allocate 64-bit memory block to pass
75  * user supplied data for every file descriptor.
76  */
77
78 typedef uint64_t        epoll_udata_t;
79
80 struct epoll_emuldata {
81         uint32_t        fdc;            /* epoll udata max index */
82         epoll_udata_t   udata[1];       /* epoll user data vector */
83 };
84
85 #define EPOLL_DEF_SZ            16
86 #define EPOLL_SIZE(fdn)                 \
87         (sizeof(struct epoll_emuldata)+(fdn) * sizeof(epoll_udata_t))
88
89 struct epoll_event {
90         uint32_t        events;
91         epoll_udata_t   data;
92 }
93 #if defined(__amd64__)
94 __attribute__((packed))
95 #endif
96 ;
97
98 #define LINUX_MAX_EVENTS        (INT_MAX / sizeof(struct epoll_event))
99
100 static void     epoll_fd_install(struct thread *td, int fd, epoll_udata_t udata);
101 static int      epoll_to_kevent(struct thread *td, int fd,
102                     struct epoll_event *l_event, struct kevent *kevent,
103                     int *nkevents);
104 static void     kevent_to_epoll(struct kevent *kevent, struct epoll_event *l_event);
105 static int      epoll_kev_copyout(void *arg, struct kevent *kevp, int count);
106 static int      epoll_kev_copyin(void *arg, struct kevent *kevp, int count);
107 static int      epoll_register_kevent(struct thread *td, struct file *epfp,
108                     int fd, int filter, unsigned int flags);
109 static int      epoll_fd_registered(struct thread *td, struct file *epfp,
110                     int fd);
111 static int      epoll_delete_all_events(struct thread *td, struct file *epfp,
112                     int fd);
113
114 struct epoll_copyin_args {
115         struct kevent   *changelist;
116 };
117
118 struct epoll_copyout_args {
119         struct epoll_event      *leventlist;
120         struct proc             *p;
121         uint32_t                count;
122         int                     error;
123 };
124
125 /* eventfd */
126 typedef uint64_t        eventfd_t;
127
128 static fo_rdwr_t        eventfd_read;
129 static fo_rdwr_t        eventfd_write;
130 static fo_ioctl_t       eventfd_ioctl;
131 static fo_poll_t        eventfd_poll;
132 static fo_kqfilter_t    eventfd_kqfilter;
133 static fo_stat_t        eventfd_stat;
134 static fo_close_t       eventfd_close;
135 static fo_fill_kinfo_t  eventfd_fill_kinfo;
136
137 static struct fileops eventfdops = {
138         .fo_read = eventfd_read,
139         .fo_write = eventfd_write,
140         .fo_truncate = invfo_truncate,
141         .fo_ioctl = eventfd_ioctl,
142         .fo_poll = eventfd_poll,
143         .fo_kqfilter = eventfd_kqfilter,
144         .fo_stat = eventfd_stat,
145         .fo_close = eventfd_close,
146         .fo_chmod = invfo_chmod,
147         .fo_chown = invfo_chown,
148         .fo_sendfile = invfo_sendfile,
149         .fo_fill_kinfo = eventfd_fill_kinfo,
150         .fo_flags = DFLAG_PASSABLE
151 };
152
153 static void     filt_eventfddetach(struct knote *kn);
154 static int      filt_eventfdread(struct knote *kn, long hint);
155 static int      filt_eventfdwrite(struct knote *kn, long hint);
156
157 static struct filterops eventfd_rfiltops = {
158         .f_isfd = 1,
159         .f_detach = filt_eventfddetach,
160         .f_event = filt_eventfdread
161 };
162 static struct filterops eventfd_wfiltops = {
163         .f_isfd = 1,
164         .f_detach = filt_eventfddetach,
165         .f_event = filt_eventfdwrite
166 };
167
168 /* timerfd */
169 typedef uint64_t        timerfd_t;
170
171 static fo_rdwr_t        timerfd_read;
172 static fo_poll_t        timerfd_poll;
173 static fo_kqfilter_t    timerfd_kqfilter;
174 static fo_stat_t        timerfd_stat;
175 static fo_close_t       timerfd_close;
176 static fo_fill_kinfo_t  timerfd_fill_kinfo;
177
178 static struct fileops timerfdops = {
179         .fo_read = timerfd_read,
180         .fo_write = invfo_rdwr,
181         .fo_truncate = invfo_truncate,
182         .fo_ioctl = eventfd_ioctl,
183         .fo_poll = timerfd_poll,
184         .fo_kqfilter = timerfd_kqfilter,
185         .fo_stat = timerfd_stat,
186         .fo_close = timerfd_close,
187         .fo_chmod = invfo_chmod,
188         .fo_chown = invfo_chown,
189         .fo_sendfile = invfo_sendfile,
190         .fo_fill_kinfo = timerfd_fill_kinfo,
191         .fo_flags = DFLAG_PASSABLE
192 };
193
194 static void     filt_timerfddetach(struct knote *kn);
195 static int      filt_timerfdread(struct knote *kn, long hint);
196
197 static struct filterops timerfd_rfiltops = {
198         .f_isfd = 1,
199         .f_detach = filt_timerfddetach,
200         .f_event = filt_timerfdread
201 };
202
203 struct eventfd {
204         eventfd_t       efd_count;
205         uint32_t        efd_flags;
206         struct selinfo  efd_sel;
207         struct mtx      efd_lock;
208 };
209
210 struct timerfd {
211         clockid_t       tfd_clockid;
212         struct itimerspec tfd_time;
213         struct callout  tfd_callout;
214         timerfd_t       tfd_count;
215         bool            tfd_canceled;
216         struct selinfo  tfd_sel;
217         struct mtx      tfd_lock;
218 };
219
220 static int      eventfd_create(struct thread *td, uint32_t initval, int flags);
221 static void     linux_timerfd_expire(void *);
222 static void     linux_timerfd_curval(struct timerfd *, struct itimerspec *);
223
224
225 static void
226 epoll_fd_install(struct thread *td, int fd, epoll_udata_t udata)
227 {
228         struct linux_pemuldata *pem;
229         struct epoll_emuldata *emd;
230         struct proc *p;
231
232         p = td->td_proc;
233
234         pem = pem_find(p);
235         KASSERT(pem != NULL, ("epoll proc emuldata not found.\n"));
236
237         LINUX_PEM_XLOCK(pem);
238         if (pem->epoll == NULL) {
239                 emd = malloc(EPOLL_SIZE(fd), M_EPOLL, M_WAITOK);
240                 emd->fdc = fd;
241                 pem->epoll = emd;
242         } else {
243                 emd = pem->epoll;
244                 if (fd > emd->fdc) {
245                         emd = realloc(emd, EPOLL_SIZE(fd), M_EPOLL, M_WAITOK);
246                         emd->fdc = fd;
247                         pem->epoll = emd;
248                 }
249         }
250         emd->udata[fd] = udata;
251         LINUX_PEM_XUNLOCK(pem);
252 }
253
254 static int
255 epoll_create_common(struct thread *td, int flags)
256 {
257         int error;
258
259         error = kern_kqueue(td, flags, NULL);
260         if (error != 0)
261                 return (error);
262
263         epoll_fd_install(td, EPOLL_DEF_SZ, 0);
264
265         return (0);
266 }
267
268 #ifdef LINUX_LEGACY_SYSCALLS
269 int
270 linux_epoll_create(struct thread *td, struct linux_epoll_create_args *args)
271 {
272
273         /*
274          * args->size is unused. Linux just tests it
275          * and then forgets it as well.
276          */
277         if (args->size <= 0)
278                 return (EINVAL);
279
280         return (epoll_create_common(td, 0));
281 }
282 #endif
283
284 int
285 linux_epoll_create1(struct thread *td, struct linux_epoll_create1_args *args)
286 {
287         int flags;
288
289         if ((args->flags & ~(LINUX_O_CLOEXEC)) != 0)
290                 return (EINVAL);
291
292         flags = 0;
293         if ((args->flags & LINUX_O_CLOEXEC) != 0)
294                 flags |= O_CLOEXEC;
295
296         return (epoll_create_common(td, flags));
297 }
298
299 /* Structure converting function from epoll to kevent. */
300 static int
301 epoll_to_kevent(struct thread *td, int fd, struct epoll_event *l_event,
302     struct kevent *kevent, int *nkevents)
303 {
304         uint32_t levents = l_event->events;
305         struct linux_pemuldata *pem;
306         struct proc *p;
307         unsigned short kev_flags = EV_ADD | EV_ENABLE;
308
309         /* flags related to how event is registered */
310         if ((levents & LINUX_EPOLLONESHOT) != 0)
311                 kev_flags |= EV_DISPATCH;
312         if ((levents & LINUX_EPOLLET) != 0)
313                 kev_flags |= EV_CLEAR;
314         if ((levents & LINUX_EPOLLERR) != 0)
315                 kev_flags |= EV_ERROR;
316         if ((levents & LINUX_EPOLLRDHUP) != 0)
317                 kev_flags |= EV_EOF;
318
319         /* flags related to what event is registered */
320         if ((levents & LINUX_EPOLL_EVRD) != 0) {
321                 EV_SET(kevent++, fd, EVFILT_READ, kev_flags, 0, 0, 0);
322                 ++(*nkevents);
323         }
324         if ((levents & LINUX_EPOLL_EVWR) != 0) {
325                 EV_SET(kevent++, fd, EVFILT_WRITE, kev_flags, 0, 0, 0);
326                 ++(*nkevents);
327         }
328
329         if ((levents & ~(LINUX_EPOLL_EVSUP)) != 0) {
330                 p = td->td_proc;
331
332                 pem = pem_find(p);
333                 KASSERT(pem != NULL, ("epoll proc emuldata not found.\n"));
334                 KASSERT(pem->epoll != NULL, ("epoll proc epolldata not found.\n"));
335
336                 LINUX_PEM_XLOCK(pem);
337                 if ((pem->flags & LINUX_XUNSUP_EPOLL) == 0) {
338                         pem->flags |= LINUX_XUNSUP_EPOLL;
339                         LINUX_PEM_XUNLOCK(pem);
340                         linux_msg(td, "epoll_ctl unsupported flags: 0x%x\n",
341                             levents);
342                 } else
343                         LINUX_PEM_XUNLOCK(pem);
344                 return (EINVAL);
345         }
346
347         return (0);
348 }
349
350 /*
351  * Structure converting function from kevent to epoll. In a case
352  * this is called on error in registration we store the error in
353  * event->data and pick it up later in linux_epoll_ctl().
354  */
355 static void
356 kevent_to_epoll(struct kevent *kevent, struct epoll_event *l_event)
357 {
358
359         if ((kevent->flags & EV_ERROR) != 0) {
360                 l_event->events = LINUX_EPOLLERR;
361                 return;
362         }
363
364         /* XXX EPOLLPRI, EPOLLHUP */
365         switch (kevent->filter) {
366         case EVFILT_READ:
367                 l_event->events = LINUX_EPOLLIN;
368                 if ((kevent->flags & EV_EOF) != 0)
369                         l_event->events |= LINUX_EPOLLRDHUP;
370         break;
371         case EVFILT_WRITE:
372                 l_event->events = LINUX_EPOLLOUT;
373         break;
374         }
375 }
376
377 /*
378  * Copyout callback used by kevent. This converts kevent
379  * events to epoll events and copies them back to the
380  * userspace. This is also called on error on registering
381  * of the filter.
382  */
383 static int
384 epoll_kev_copyout(void *arg, struct kevent *kevp, int count)
385 {
386         struct epoll_copyout_args *args;
387         struct linux_pemuldata *pem;
388         struct epoll_emuldata *emd;
389         struct epoll_event *eep;
390         int error, fd, i;
391
392         args = (struct epoll_copyout_args*) arg;
393         eep = malloc(sizeof(*eep) * count, M_EPOLL, M_WAITOK | M_ZERO);
394
395         pem = pem_find(args->p);
396         KASSERT(pem != NULL, ("epoll proc emuldata not found.\n"));
397         LINUX_PEM_SLOCK(pem);
398         emd = pem->epoll;
399         KASSERT(emd != NULL, ("epoll proc epolldata not found.\n"));
400
401         for (i = 0; i < count; i++) {
402                 kevent_to_epoll(&kevp[i], &eep[i]);
403
404                 fd = kevp[i].ident;
405                 KASSERT(fd <= emd->fdc, ("epoll user data vector"
406                                                     " is too small.\n"));
407                 eep[i].data = emd->udata[fd];
408         }
409         LINUX_PEM_SUNLOCK(pem);
410
411         error = copyout(eep, args->leventlist, count * sizeof(*eep));
412         if (error == 0) {
413                 args->leventlist += count;
414                 args->count += count;
415         } else if (args->error == 0)
416                 args->error = error;
417
418         free(eep, M_EPOLL);
419         return (error);
420 }
421
422 /*
423  * Copyin callback used by kevent. This copies already
424  * converted filters from kernel memory to the kevent
425  * internal kernel memory. Hence the memcpy instead of
426  * copyin.
427  */
428 static int
429 epoll_kev_copyin(void *arg, struct kevent *kevp, int count)
430 {
431         struct epoll_copyin_args *args;
432
433         args = (struct epoll_copyin_args*) arg;
434
435         memcpy(kevp, args->changelist, count * sizeof(*kevp));
436         args->changelist += count;
437
438         return (0);
439 }
440
441 /*
442  * Load epoll filter, convert it to kevent filter
443  * and load it into kevent subsystem.
444  */
445 int
446 linux_epoll_ctl(struct thread *td, struct linux_epoll_ctl_args *args)
447 {
448         struct file *epfp, *fp;
449         struct epoll_copyin_args ciargs;
450         struct kevent kev[2];
451         struct kevent_copyops k_ops = { &ciargs,
452                                         NULL,
453                                         epoll_kev_copyin};
454         struct epoll_event le;
455         cap_rights_t rights;
456         int nchanges = 0;
457         int error;
458
459         if (args->op != LINUX_EPOLL_CTL_DEL) {
460                 error = copyin(args->event, &le, sizeof(le));
461                 if (error != 0)
462                         return (error);
463         }
464
465         error = fget(td, args->epfd,
466             cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &epfp);
467         if (error != 0)
468                 return (error);
469         if (epfp->f_type != DTYPE_KQUEUE) {
470                 error = EINVAL;
471                 goto leave1;
472         }
473
474          /* Protect user data vector from incorrectly supplied fd. */
475         error = fget(td, args->fd, cap_rights_init(&rights, CAP_POLL_EVENT), &fp);
476         if (error != 0)
477                 goto leave1;
478
479         /* Linux disallows spying on himself */
480         if (epfp == fp) {
481                 error = EINVAL;
482                 goto leave0;
483         }
484
485         ciargs.changelist = kev;
486
487         if (args->op != LINUX_EPOLL_CTL_DEL) {
488                 error = epoll_to_kevent(td, args->fd, &le, kev, &nchanges);
489                 if (error != 0)
490                         goto leave0;
491         }
492
493         switch (args->op) {
494         case LINUX_EPOLL_CTL_MOD:
495                 error = epoll_delete_all_events(td, epfp, args->fd);
496                 if (error != 0)
497                         goto leave0;
498                 break;
499
500         case LINUX_EPOLL_CTL_ADD:
501                 if (epoll_fd_registered(td, epfp, args->fd)) {
502                         error = EEXIST;
503                         goto leave0;
504                 }
505                 break;
506
507         case LINUX_EPOLL_CTL_DEL:
508                 /* CTL_DEL means unregister this fd with this epoll */
509                 error = epoll_delete_all_events(td, epfp, args->fd);
510                 goto leave0;
511
512         default:
513                 error = EINVAL;
514                 goto leave0;
515         }
516
517         epoll_fd_install(td, args->fd, le.data);
518
519         error = kern_kevent_fp(td, epfp, nchanges, 0, &k_ops, NULL);
520
521 leave0:
522         fdrop(fp, td);
523
524 leave1:
525         fdrop(epfp, td);
526         return (error);
527 }
528
529 /*
530  * Wait for a filter to be triggered on the epoll file descriptor.
531  */
532 static int
533 linux_epoll_wait_common(struct thread *td, int epfd, struct epoll_event *events,
534     int maxevents, int timeout, sigset_t *uset)
535 {
536         struct epoll_copyout_args coargs;
537         struct kevent_copyops k_ops = { &coargs,
538                                         epoll_kev_copyout,
539                                         NULL};
540         struct timespec ts, *tsp;
541         cap_rights_t rights;
542         struct file *epfp;
543         sigset_t omask;
544         int error;
545
546         if (maxevents <= 0 || maxevents > LINUX_MAX_EVENTS)
547                 return (EINVAL);
548
549         error = fget(td, epfd,
550             cap_rights_init(&rights, CAP_KQUEUE_EVENT), &epfp);
551         if (error != 0)
552                 return (error);
553         if (epfp->f_type != DTYPE_KQUEUE) {
554                 error = EINVAL;
555                 goto leave1;
556         }
557         if (uset != NULL) {
558                 error = kern_sigprocmask(td, SIG_SETMASK, uset,
559                     &omask, 0);
560                 if (error != 0)
561                         goto leave1;
562                 td->td_pflags |= TDP_OLDMASK;
563                 /*
564                  * Make sure that ast() is called on return to
565                  * usermode and TDP_OLDMASK is cleared, restoring old
566                  * sigmask.
567                  */
568                 thread_lock(td);
569                 td->td_flags |= TDF_ASTPENDING;
570                 thread_unlock(td);
571         }
572
573
574         coargs.leventlist = events;
575         coargs.p = td->td_proc;
576         coargs.count = 0;
577         coargs.error = 0;
578
579         if (timeout != -1) {
580                 if (timeout < 0) {
581                         error = EINVAL;
582                         goto leave0;
583                 }
584                 /* Convert from milliseconds to timespec. */
585                 ts.tv_sec = timeout / 1000;
586                 ts.tv_nsec = (timeout % 1000) * 1000000;
587                 tsp = &ts;
588         } else {
589                 tsp = NULL;
590         }
591
592         error = kern_kevent_fp(td, epfp, 0, maxevents, &k_ops, tsp);
593         if (error == 0 && coargs.error != 0)
594                 error = coargs.error;
595
596         /*
597          * kern_kevent might return ENOMEM which is not expected from epoll_wait.
598          * Maybe we should translate that but I don't think it matters at all.
599          */
600         if (error == 0)
601                 td->td_retval[0] = coargs.count;
602
603 leave0:
604         if (uset != NULL)
605                 error = kern_sigprocmask(td, SIG_SETMASK, &omask,
606                     NULL, 0);
607 leave1:
608         fdrop(epfp, td);
609         return (error);
610 }
611
612 #ifdef LINUX_LEGACY_SYSCALLS
613 int
614 linux_epoll_wait(struct thread *td, struct linux_epoll_wait_args *args)
615 {
616
617         return (linux_epoll_wait_common(td, args->epfd, args->events,
618             args->maxevents, args->timeout, NULL));
619 }
620 #endif
621
622 int
623 linux_epoll_pwait(struct thread *td, struct linux_epoll_pwait_args *args)
624 {
625         sigset_t mask, *pmask;
626         l_sigset_t lmask;
627         int error;
628
629         if (args->mask != NULL) {
630                 if (args->sigsetsize != sizeof(l_sigset_t))
631                         return (EINVAL);
632                 error = copyin(args->mask, &lmask, sizeof(l_sigset_t));
633                 if (error != 0)
634                         return (error);
635                 linux_to_bsd_sigset(&lmask, &mask);
636                 pmask = &mask;
637         } else
638                 pmask = NULL;
639         return (linux_epoll_wait_common(td, args->epfd, args->events,
640             args->maxevents, args->timeout, pmask));
641 }
642
643 static int
644 epoll_register_kevent(struct thread *td, struct file *epfp, int fd, int filter,
645     unsigned int flags)
646 {
647         struct epoll_copyin_args ciargs;
648         struct kevent kev;
649         struct kevent_copyops k_ops = { &ciargs,
650                                         NULL,
651                                         epoll_kev_copyin};
652
653         ciargs.changelist = &kev;
654         EV_SET(&kev, fd, filter, flags, 0, 0, 0);
655
656         return (kern_kevent_fp(td, epfp, 1, 0, &k_ops, NULL));
657 }
658
659 static int
660 epoll_fd_registered(struct thread *td, struct file *epfp, int fd)
661 {
662         /*
663          * Set empty filter flags to avoid accidental modification of already
664          * registered events. In the case of event re-registration:
665          * 1. If event does not exists kevent() does nothing and returns ENOENT
666          * 2. If event does exists, it's enabled/disabled state is preserved
667          *    but fflags, data and udata fields are overwritten. So we can not
668          *    set socket lowats and store user's context pointer in udata.
669          */
670         if (epoll_register_kevent(td, epfp, fd, EVFILT_READ, 0) != ENOENT ||
671             epoll_register_kevent(td, epfp, fd, EVFILT_WRITE, 0) != ENOENT)
672                 return (1);
673
674         return (0);
675 }
676
677 static int
678 epoll_delete_all_events(struct thread *td, struct file *epfp, int fd)
679 {
680         int error1, error2;
681
682         error1 = epoll_register_kevent(td, epfp, fd, EVFILT_READ, EV_DELETE);
683         error2 = epoll_register_kevent(td, epfp, fd, EVFILT_WRITE, EV_DELETE);
684
685         /* return 0 if at least one result positive */
686         return (error1 == 0 ? 0 : error2);
687 }
688
689 static int
690 eventfd_create(struct thread *td, uint32_t initval, int flags)
691 {
692         struct filedesc *fdp;
693         struct eventfd *efd;
694         struct file *fp;
695         int fflags, fd, error;
696
697         fflags = 0;
698         if ((flags & LINUX_O_CLOEXEC) != 0)
699                 fflags |= O_CLOEXEC;
700
701         fdp = td->td_proc->p_fd;
702         error = falloc(td, &fp, &fd, fflags);
703         if (error != 0)
704                 return (error);
705
706         efd = malloc(sizeof(*efd), M_EPOLL, M_WAITOK | M_ZERO);
707         efd->efd_flags = flags;
708         efd->efd_count = initval;
709         mtx_init(&efd->efd_lock, "eventfd", NULL, MTX_DEF);
710
711         knlist_init_mtx(&efd->efd_sel.si_note, &efd->efd_lock);
712
713         fflags = FREAD | FWRITE;
714         if ((flags & LINUX_O_NONBLOCK) != 0)
715                 fflags |= FNONBLOCK;
716
717         finit(fp, fflags, DTYPE_LINUXEFD, efd, &eventfdops);
718         fdrop(fp, td);
719
720         td->td_retval[0] = fd;
721         return (error);
722 }
723
724 #ifdef LINUX_LEGACY_SYSCALLS
725 int
726 linux_eventfd(struct thread *td, struct linux_eventfd_args *args)
727 {
728
729         return (eventfd_create(td, args->initval, 0));
730 }
731 #endif
732
733 int
734 linux_eventfd2(struct thread *td, struct linux_eventfd2_args *args)
735 {
736
737         if ((args->flags & ~(LINUX_O_CLOEXEC|LINUX_O_NONBLOCK|LINUX_EFD_SEMAPHORE)) != 0)
738                 return (EINVAL);
739
740         return (eventfd_create(td, args->initval, args->flags));
741 }
742
743 static int
744 eventfd_close(struct file *fp, struct thread *td)
745 {
746         struct eventfd *efd;
747
748         efd = fp->f_data;
749         if (fp->f_type != DTYPE_LINUXEFD || efd == NULL)
750                 return (EINVAL);
751
752         seldrain(&efd->efd_sel);
753         knlist_destroy(&efd->efd_sel.si_note);
754
755         fp->f_ops = &badfileops;
756         mtx_destroy(&efd->efd_lock);
757         free(efd, M_EPOLL);
758
759         return (0);
760 }
761
762 static int
763 eventfd_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
764     int flags, struct thread *td)
765 {
766         struct eventfd *efd;
767         eventfd_t count;
768         int error;
769
770         efd = fp->f_data;
771         if (fp->f_type != DTYPE_LINUXEFD || efd == NULL)
772                 return (EINVAL);
773
774         if (uio->uio_resid < sizeof(eventfd_t))
775                 return (EINVAL);
776
777         error = 0;
778         mtx_lock(&efd->efd_lock);
779 retry:
780         if (efd->efd_count == 0) {
781                 if ((fp->f_flag & FNONBLOCK) != 0) {
782                         mtx_unlock(&efd->efd_lock);
783                         return (EAGAIN);
784                 }
785                 error = mtx_sleep(&efd->efd_count, &efd->efd_lock, PCATCH, "lefdrd", 0);
786                 if (error == 0)
787                         goto retry;
788         }
789         if (error == 0) {
790                 if ((efd->efd_flags & LINUX_EFD_SEMAPHORE) != 0) {
791                         count = 1;
792                         --efd->efd_count;
793                 } else {
794                         count = efd->efd_count;
795                         efd->efd_count = 0;
796                 }
797                 KNOTE_LOCKED(&efd->efd_sel.si_note, 0);
798                 selwakeup(&efd->efd_sel);
799                 wakeup(&efd->efd_count);
800                 mtx_unlock(&efd->efd_lock);
801                 error = uiomove(&count, sizeof(eventfd_t), uio);
802         } else
803                 mtx_unlock(&efd->efd_lock);
804
805         return (error);
806 }
807
808 static int
809 eventfd_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
810      int flags, struct thread *td)
811 {
812         struct eventfd *efd;
813         eventfd_t count;
814         int error;
815
816         efd = fp->f_data;
817         if (fp->f_type != DTYPE_LINUXEFD || efd == NULL)
818                 return (EINVAL);
819
820         if (uio->uio_resid < sizeof(eventfd_t))
821                 return (EINVAL);
822
823         error = uiomove(&count, sizeof(eventfd_t), uio);
824         if (error != 0)
825                 return (error);
826         if (count == UINT64_MAX)
827                 return (EINVAL);
828
829         mtx_lock(&efd->efd_lock);
830 retry:
831         if (UINT64_MAX - efd->efd_count <= count) {
832                 if ((fp->f_flag & FNONBLOCK) != 0) {
833                         mtx_unlock(&efd->efd_lock);
834                         /* Do not not return the number of bytes written */
835                         uio->uio_resid += sizeof(eventfd_t);
836                         return (EAGAIN);
837                 }
838                 error = mtx_sleep(&efd->efd_count, &efd->efd_lock,
839                     PCATCH, "lefdwr", 0);
840                 if (error == 0)
841                         goto retry;
842         }
843         if (error == 0) {
844                 efd->efd_count += count;
845                 KNOTE_LOCKED(&efd->efd_sel.si_note, 0);
846                 selwakeup(&efd->efd_sel);
847                 wakeup(&efd->efd_count);
848         }
849         mtx_unlock(&efd->efd_lock);
850
851         return (error);
852 }
853
854 static int
855 eventfd_poll(struct file *fp, int events, struct ucred *active_cred,
856     struct thread *td)
857 {
858         struct eventfd *efd;
859         int revents = 0;
860
861         efd = fp->f_data;
862         if (fp->f_type != DTYPE_LINUXEFD || efd == NULL)
863                 return (POLLERR);
864
865         mtx_lock(&efd->efd_lock);
866         if ((events & (POLLIN|POLLRDNORM)) && efd->efd_count > 0)
867                 revents |= events & (POLLIN|POLLRDNORM);
868         if ((events & (POLLOUT|POLLWRNORM)) && UINT64_MAX - 1 > efd->efd_count)
869                 revents |= events & (POLLOUT|POLLWRNORM);
870         if (revents == 0)
871                 selrecord(td, &efd->efd_sel);
872         mtx_unlock(&efd->efd_lock);
873
874         return (revents);
875 }
876
877 /*ARGSUSED*/
878 static int
879 eventfd_kqfilter(struct file *fp, struct knote *kn)
880 {
881         struct eventfd *efd;
882
883         efd = fp->f_data;
884         if (fp->f_type != DTYPE_LINUXEFD || efd == NULL)
885                 return (EINVAL);
886
887         mtx_lock(&efd->efd_lock);
888         switch (kn->kn_filter) {
889         case EVFILT_READ:
890                 kn->kn_fop = &eventfd_rfiltops;
891                 break;
892         case EVFILT_WRITE:
893                 kn->kn_fop = &eventfd_wfiltops;
894                 break;
895         default:
896                 mtx_unlock(&efd->efd_lock);
897                 return (EINVAL);
898         }
899
900         kn->kn_hook = efd;
901         knlist_add(&efd->efd_sel.si_note, kn, 1);
902         mtx_unlock(&efd->efd_lock);
903
904         return (0);
905 }
906
907 static void
908 filt_eventfddetach(struct knote *kn)
909 {
910         struct eventfd *efd = kn->kn_hook;
911
912         mtx_lock(&efd->efd_lock);
913         knlist_remove(&efd->efd_sel.si_note, kn, 1);
914         mtx_unlock(&efd->efd_lock);
915 }
916
917 /*ARGSUSED*/
918 static int
919 filt_eventfdread(struct knote *kn, long hint)
920 {
921         struct eventfd *efd = kn->kn_hook;
922         int ret;
923
924         mtx_assert(&efd->efd_lock, MA_OWNED);
925         ret = (efd->efd_count > 0);
926
927         return (ret);
928 }
929
930 /*ARGSUSED*/
931 static int
932 filt_eventfdwrite(struct knote *kn, long hint)
933 {
934         struct eventfd *efd = kn->kn_hook;
935         int ret;
936
937         mtx_assert(&efd->efd_lock, MA_OWNED);
938         ret = (UINT64_MAX - 1 > efd->efd_count);
939
940         return (ret);
941 }
942
943 /*ARGSUSED*/
944 static int
945 eventfd_ioctl(struct file *fp, u_long cmd, void *data,
946     struct ucred *active_cred, struct thread *td)
947 {
948
949         if (fp->f_data == NULL || (fp->f_type != DTYPE_LINUXEFD &&
950             fp->f_type != DTYPE_LINUXTFD))
951                 return (EINVAL);
952
953         switch (cmd)
954         {
955         case FIONBIO:
956                 if ((*(int *)data))
957                         atomic_set_int(&fp->f_flag, FNONBLOCK);
958                 else
959                         atomic_clear_int(&fp->f_flag, FNONBLOCK);
960         case FIOASYNC:
961                 return (0);
962         default:
963                 return (ENXIO);
964         }
965 }
966
967 /*ARGSUSED*/
968 static int
969 eventfd_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
970     struct thread *td)
971 {
972
973         return (ENXIO);
974 }
975
976 /*ARGSUSED*/
977 static int
978 eventfd_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
979 {
980
981         kif->kf_type = KF_TYPE_UNKNOWN;
982         return (0);
983 }
984
985 int
986 linux_timerfd_create(struct thread *td, struct linux_timerfd_create_args *args)
987 {
988         struct filedesc *fdp;
989         struct timerfd *tfd;
990         struct file *fp;
991         clockid_t clockid;
992         int fflags, fd, error;
993
994         if ((args->flags & ~LINUX_TFD_CREATE_FLAGS) != 0)
995                 return (EINVAL);
996
997         error = linux_to_native_clockid(&clockid, args->clockid);
998         if (error != 0)
999                 return (error);
1000         if (clockid != CLOCK_REALTIME && clockid != CLOCK_MONOTONIC)
1001                 return (EINVAL);
1002
1003         fflags = 0;
1004         if ((args->flags & LINUX_TFD_CLOEXEC) != 0)
1005                 fflags |= O_CLOEXEC;
1006
1007         fdp = td->td_proc->p_fd;
1008         error = falloc(td, &fp, &fd, fflags);
1009         if (error != 0)
1010                 return (error);
1011
1012         tfd = malloc(sizeof(*tfd), M_EPOLL, M_WAITOK | M_ZERO);
1013         tfd->tfd_clockid = clockid;
1014         mtx_init(&tfd->tfd_lock, "timerfd", NULL, MTX_DEF);
1015
1016         callout_init_mtx(&tfd->tfd_callout, &tfd->tfd_lock, 0);
1017         knlist_init_mtx(&tfd->tfd_sel.si_note, &tfd->tfd_lock);
1018
1019         fflags = FREAD;
1020         if ((args->flags & LINUX_O_NONBLOCK) != 0)
1021                 fflags |= FNONBLOCK;
1022
1023         finit(fp, fflags, DTYPE_LINUXTFD, tfd, &timerfdops);
1024         fdrop(fp, td);
1025
1026         td->td_retval[0] = fd;
1027         return (error);
1028 }
1029
1030 static int
1031 timerfd_close(struct file *fp, struct thread *td)
1032 {
1033         struct timerfd *tfd;
1034
1035         tfd = fp->f_data;
1036         if (fp->f_type != DTYPE_LINUXTFD || tfd == NULL)
1037                 return (EINVAL);
1038
1039         timespecclear(&tfd->tfd_time.it_value);
1040         timespecclear(&tfd->tfd_time.it_interval);
1041
1042         mtx_lock(&tfd->tfd_lock);
1043         callout_drain(&tfd->tfd_callout);
1044         mtx_unlock(&tfd->tfd_lock);
1045
1046         seldrain(&tfd->tfd_sel);
1047         knlist_destroy(&tfd->tfd_sel.si_note);
1048
1049         fp->f_ops = &badfileops;
1050         mtx_destroy(&tfd->tfd_lock);
1051         free(tfd, M_EPOLL);
1052
1053         return (0);
1054 }
1055
1056 static int
1057 timerfd_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1058     int flags, struct thread *td)
1059 {
1060         struct timerfd *tfd;
1061         timerfd_t count;
1062         int error;
1063
1064         tfd = fp->f_data;
1065         if (fp->f_type != DTYPE_LINUXTFD || tfd == NULL)
1066                 return (EINVAL);
1067
1068         if (uio->uio_resid < sizeof(timerfd_t))
1069                 return (EINVAL);
1070
1071         error = 0;
1072         mtx_lock(&tfd->tfd_lock);
1073 retry:
1074         if (tfd->tfd_canceled) {
1075                 tfd->tfd_count = 0;
1076                 mtx_unlock(&tfd->tfd_lock);
1077                 return (ECANCELED);
1078         }
1079         if (tfd->tfd_count == 0) {
1080                 if ((fp->f_flag & FNONBLOCK) != 0) {
1081                         mtx_unlock(&tfd->tfd_lock);
1082                         return (EAGAIN);
1083                 }
1084                 error = mtx_sleep(&tfd->tfd_count, &tfd->tfd_lock, PCATCH, "ltfdrd", 0);
1085                 if (error == 0)
1086                         goto retry;
1087         }
1088         if (error == 0) {
1089                 count = tfd->tfd_count;
1090                 tfd->tfd_count = 0;
1091                 mtx_unlock(&tfd->tfd_lock);
1092                 error = uiomove(&count, sizeof(timerfd_t), uio);
1093         } else
1094                 mtx_unlock(&tfd->tfd_lock);
1095
1096         return (error);
1097 }
1098
1099 static int
1100 timerfd_poll(struct file *fp, int events, struct ucred *active_cred,
1101     struct thread *td)
1102 {
1103         struct timerfd *tfd;
1104         int revents = 0;
1105
1106         tfd = fp->f_data;
1107         if (fp->f_type != DTYPE_LINUXTFD || tfd == NULL)
1108                 return (POLLERR);
1109
1110         mtx_lock(&tfd->tfd_lock);
1111         if ((events & (POLLIN|POLLRDNORM)) && tfd->tfd_count > 0)
1112                 revents |= events & (POLLIN|POLLRDNORM);
1113         if (revents == 0)
1114                 selrecord(td, &tfd->tfd_sel);
1115         mtx_unlock(&tfd->tfd_lock);
1116
1117         return (revents);
1118 }
1119
1120 /*ARGSUSED*/
1121 static int
1122 timerfd_kqfilter(struct file *fp, struct knote *kn)
1123 {
1124         struct timerfd *tfd;
1125
1126         tfd = fp->f_data;
1127         if (fp->f_type != DTYPE_LINUXTFD || tfd == NULL)
1128                 return (EINVAL);
1129
1130         if (kn->kn_filter == EVFILT_READ)
1131                 kn->kn_fop = &timerfd_rfiltops;
1132         else
1133                 return (EINVAL);
1134
1135         kn->kn_hook = tfd;
1136         knlist_add(&tfd->tfd_sel.si_note, kn, 0);
1137
1138         return (0);
1139 }
1140
1141 static void
1142 filt_timerfddetach(struct knote *kn)
1143 {
1144         struct timerfd *tfd = kn->kn_hook;
1145
1146         mtx_lock(&tfd->tfd_lock);
1147         knlist_remove(&tfd->tfd_sel.si_note, kn, 1);
1148         mtx_unlock(&tfd->tfd_lock);
1149 }
1150
1151 /*ARGSUSED*/
1152 static int
1153 filt_timerfdread(struct knote *kn, long hint)
1154 {
1155         struct timerfd *tfd = kn->kn_hook;
1156
1157         return (tfd->tfd_count > 0);
1158 }
1159
1160 /*ARGSUSED*/
1161 static int
1162 timerfd_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1163     struct thread *td)
1164 {
1165
1166         return (ENXIO);
1167 }
1168
1169 /*ARGSUSED*/
1170 static int
1171 timerfd_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1172 {
1173
1174         kif->kf_type = KF_TYPE_UNKNOWN;
1175         return (0);
1176 }
1177
1178 static void
1179 linux_timerfd_clocktime(struct timerfd *tfd, struct timespec *ts)
1180 {
1181
1182         if (tfd->tfd_clockid == CLOCK_REALTIME)
1183                 getnanotime(ts);
1184         else    /* CLOCK_MONOTONIC */
1185                 getnanouptime(ts);
1186 }
1187
1188 static void
1189 linux_timerfd_curval(struct timerfd *tfd, struct itimerspec *ots)
1190 {
1191         struct timespec cts;
1192
1193         linux_timerfd_clocktime(tfd, &cts);
1194         *ots = tfd->tfd_time;
1195         if (ots->it_value.tv_sec != 0 || ots->it_value.tv_nsec != 0) {
1196                 timespecsub(&ots->it_value, &cts, &ots->it_value);
1197                 if (ots->it_value.tv_sec < 0 ||
1198                     (ots->it_value.tv_sec == 0 &&
1199                      ots->it_value.tv_nsec == 0)) {
1200                         ots->it_value.tv_sec  = 0;
1201                         ots->it_value.tv_nsec = 1;
1202                 }
1203         }
1204 }
1205
1206 int
1207 linux_timerfd_gettime(struct thread *td, struct linux_timerfd_gettime_args *args)
1208 {
1209         struct l_itimerspec lots;
1210         struct itimerspec ots;
1211         struct timerfd *tfd;
1212         struct file *fp;
1213         int error;
1214
1215         error = fget(td, args->fd, &cap_read_rights, &fp);
1216         if (error != 0)
1217                 return (error);
1218         tfd = fp->f_data;
1219         if (fp->f_type != DTYPE_LINUXTFD || tfd == NULL) {
1220                 error = EINVAL;
1221                 goto out;
1222         }
1223
1224         mtx_lock(&tfd->tfd_lock);
1225         linux_timerfd_curval(tfd, &ots);
1226         mtx_unlock(&tfd->tfd_lock);
1227
1228         error = native_to_linux_itimerspec(&lots, &ots);
1229         if (error == 0)
1230                 error = copyout(&lots, args->old_value, sizeof(lots));
1231
1232 out:
1233         fdrop(fp, td);
1234         return (error);
1235 }
1236
1237 int
1238 linux_timerfd_settime(struct thread *td, struct linux_timerfd_settime_args *args)
1239 {
1240         struct l_itimerspec lots;
1241         struct itimerspec nts, ots;
1242         struct timespec cts, ts;
1243         struct timerfd *tfd;
1244         struct timeval tv;
1245         struct file *fp;
1246         int error;
1247
1248         if ((args->flags & ~LINUX_TFD_SETTIME_FLAGS) != 0)
1249                 return (EINVAL);
1250
1251         error = copyin(args->new_value, &lots, sizeof(lots));
1252         if (error != 0)
1253                 return (error);
1254         error = linux_to_native_itimerspec(&nts, &lots);
1255         if (error != 0)
1256                 return (error);
1257
1258         error = fget(td, args->fd, &cap_write_rights, &fp);
1259         if (error != 0)
1260                 return (error);
1261         tfd = fp->f_data;
1262         if (fp->f_type != DTYPE_LINUXTFD || tfd == NULL) {
1263                 error = EINVAL;
1264                 goto out;
1265         }
1266
1267         mtx_lock(&tfd->tfd_lock);
1268         if (!timespecisset(&nts.it_value))
1269                 timespecclear(&nts.it_interval);
1270         if (args->old_value != NULL)
1271                 linux_timerfd_curval(tfd, &ots);
1272
1273         tfd->tfd_time = nts;
1274         if (timespecisset(&nts.it_value)) {
1275                 linux_timerfd_clocktime(tfd, &cts);
1276                 ts = nts.it_value;
1277                 if ((args->flags & LINUX_TFD_TIMER_ABSTIME) == 0) {
1278                         timespecadd(&tfd->tfd_time.it_value, &cts,
1279                                 &tfd->tfd_time.it_value);
1280                 } else {
1281                         timespecsub(&ts, &cts, &ts);
1282                 }
1283                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1284                 callout_reset(&tfd->tfd_callout, tvtohz(&tv),
1285                         linux_timerfd_expire, tfd);
1286                 tfd->tfd_canceled = false;
1287         } else {
1288                 tfd->tfd_canceled = true;
1289                 callout_stop(&tfd->tfd_callout);
1290         }
1291         mtx_unlock(&tfd->tfd_lock);
1292
1293         if (args->old_value != NULL) {
1294                 error = native_to_linux_itimerspec(&lots, &ots);
1295                 if (error == 0)
1296                         error = copyout(&lots, args->old_value, sizeof(lots));
1297         }
1298
1299 out:
1300         fdrop(fp, td);
1301         return (error);
1302 }
1303
1304 static void
1305 linux_timerfd_expire(void *arg)
1306 {
1307         struct timespec cts, ts;
1308         struct timeval tv;
1309         struct timerfd *tfd;
1310
1311         tfd = (struct timerfd *)arg;
1312
1313         linux_timerfd_clocktime(tfd, &cts);
1314         if (timespeccmp(&cts, &tfd->tfd_time.it_value, >=)) {
1315                 if (timespecisset(&tfd->tfd_time.it_interval))
1316                         timespecadd(&tfd->tfd_time.it_value,
1317                                     &tfd->tfd_time.it_interval,
1318                                     &tfd->tfd_time.it_value);
1319                 else
1320                         /* single shot timer */
1321                         timespecclear(&tfd->tfd_time.it_value);
1322                 if (timespecisset(&tfd->tfd_time.it_value)) {
1323                         timespecsub(&tfd->tfd_time.it_value, &cts, &ts);
1324                         TIMESPEC_TO_TIMEVAL(&tv, &ts);
1325                         callout_reset(&tfd->tfd_callout, tvtohz(&tv),
1326                                 linux_timerfd_expire, tfd);
1327                 }
1328                 tfd->tfd_count++;
1329                 KNOTE_LOCKED(&tfd->tfd_sel.si_note, 0);
1330                 selwakeup(&tfd->tfd_sel);
1331                 wakeup(&tfd->tfd_count);
1332         } else if (timespecisset(&tfd->tfd_time.it_value)) {
1333                 timespecsub(&tfd->tfd_time.it_value, &cts, &ts);
1334                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1335                 callout_reset(&tfd->tfd_callout, tvtohz(&tv),
1336                     linux_timerfd_expire, tfd);
1337         }
1338 }