sys_timerfd.c revision 1.7 1 /* $NetBSD: sys_timerfd.c,v 1.7 2021/11/24 16:35:33 thorpej Exp $ */
2
3 /*-
4 * Copyright (c) 2020 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: sys_timerfd.c,v 1.7 2021/11/24 16:35:33 thorpej Exp $");
34
35 /*
36 * timerfd
37 *
38 * Timerfd objects are similar to POSIX timers, except they are associated
39 * with a file descriptor rather than a process. Timerfd objects are
40 * created with the timerfd_create(2) system call, similar to timer_create(2).
41 * The timerfd analogues for timer_gettime(2) and timer_settime(2) are
42 * timerfd_gettime(2) and timerfd_settime(2), respectively.
43 *
44 * When a timerfd object's timer fires, an internal counter is incremented.
45 * When this counter is non-zero, the descriptor associated with the timerfd
46 * object is "readable". Note that this is slightly different than the
47 * POSIX timer "overrun" counter, which only increments if the timer fires
48 * again while the notification signal is already pending. Thus, we are
49 * responsible for incrementing the "overrun" counter each time the timerfd
50 * timer fires.
51 *
52 * This implementation is API compatible with the Linux timerfd interface.
53 */
54
55 #include <sys/param.h>
56 #include <sys/types.h>
57 #include <sys/condvar.h>
58 #include <sys/file.h>
59 #include <sys/filedesc.h>
60 #include <sys/kauth.h>
61 #include <sys/mutex.h>
62 #include <sys/poll.h>
63 #include <sys/proc.h>
64 #include <sys/select.h>
65 #include <sys/stat.h>
66 #include <sys/syscallargs.h>
67 #include <sys/timerfd.h>
68 #include <sys/uio.h>
69
70 /* N.B. all timerfd state is protected by itimer_lock() */
71 struct timerfd {
72 struct itimer tfd_itimer;
73 kcondvar_t tfd_read_wait;
74 struct selinfo tfd_read_sel;
75 int64_t tfd_nwaiters;
76 bool tfd_cancel_on_set;
77 bool tfd_cancelled;
78 bool tfd_restarting;
79
80 /*
81 * Information kept for stat(2).
82 */
83 struct timespec tfd_btime; /* time created */
84 struct timespec tfd_mtime; /* last timerfd_settime() */
85 struct timespec tfd_atime; /* last read */
86 };
87
88 static void timerfd_wake(struct timerfd *);
89
90 static inline uint64_t
91 timerfd_fire_count(const struct timerfd * const tfd)
92 {
93 return (unsigned int)tfd->tfd_itimer.it_overruns;
94 }
95
96 static inline bool
97 timerfd_is_readable(const struct timerfd * const tfd)
98 {
99 return tfd->tfd_itimer.it_overruns != 0 || tfd->tfd_cancelled;
100 }
101
102 /*
103 * timerfd_fire:
104 *
105 * Called when the timerfd's timer fires.
106 *
107 * Called from a callout with itimer lock held.
108 */
109 static void
110 timerfd_fire(struct itimer * const it)
111 {
112 struct timerfd * const tfd =
113 container_of(it, struct timerfd, tfd_itimer);
114
115 it->it_overruns++;
116 timerfd_wake(tfd);
117 }
118
119 /*
120 * timerfd_realtime_changed:
121 *
122 * Called when CLOCK_REALTIME is changed with clock_settime()
123 * or settimeofday().
124 *
125 * Called with itimer lock held.
126 */
127 static void
128 timerfd_realtime_changed(struct itimer * const it)
129 {
130 struct timerfd * const tfd =
131 container_of(it, struct timerfd, tfd_itimer);
132
133 /* Should only be called when timer is armed. */
134 KASSERT(timespecisset(&it->it_time.it_value));
135
136 if (tfd->tfd_cancel_on_set) {
137 tfd->tfd_cancelled = true;
138 timerfd_wake(tfd);
139 }
140 }
141
142 static const struct itimer_ops timerfd_itimer_monotonic_ops = {
143 .ito_fire = timerfd_fire,
144 };
145
146 static const struct itimer_ops timerfd_itimer_realtime_ops = {
147 .ito_fire = timerfd_fire,
148 .ito_realtime_changed = timerfd_realtime_changed,
149 };
150
151 /*
152 * timerfd_create:
153 *
154 * Create a timerfd object.
155 */
156 static struct timerfd *
157 timerfd_create(clockid_t const clock_id, int const flags)
158 {
159 struct timerfd * const tfd = kmem_zalloc(sizeof(*tfd), KM_SLEEP);
160
161 KASSERT(clock_id == CLOCK_REALTIME || clock_id == CLOCK_MONOTONIC);
162
163 cv_init(&tfd->tfd_read_wait, "tfdread");
164 selinit(&tfd->tfd_read_sel);
165 getnanotime(&tfd->tfd_btime);
166
167 /* Caller deals with TFD_CLOEXEC and TFD_NONBLOCK. */
168
169 itimer_lock();
170 itimer_init(&tfd->tfd_itimer,
171 clock_id == CLOCK_REALTIME ? &timerfd_itimer_realtime_ops
172 : &timerfd_itimer_monotonic_ops,
173 clock_id, NULL);
174 itimer_unlock();
175
176 return tfd;
177 }
178
179 /*
180 * timerfd_destroy:
181 *
182 * Destroy a timerfd object.
183 */
184 static void
185 timerfd_destroy(struct timerfd * const tfd)
186 {
187
188 KASSERT(tfd->tfd_nwaiters == 0);
189
190 itimer_lock();
191 itimer_poison(&tfd->tfd_itimer);
192 itimer_fini(&tfd->tfd_itimer); /* drops itimer lock */
193
194 cv_destroy(&tfd->tfd_read_wait);
195
196 seldestroy(&tfd->tfd_read_sel);
197
198 kmem_free(tfd, sizeof(*tfd));
199 }
200
201 /*
202 * timerfd_wait:
203 *
204 * Block on a timerfd. Handles non-blocking, as well as
205 * the restart cases.
206 */
207 static int
208 timerfd_wait(struct timerfd * const tfd, int const fflag)
209 {
210 extern kmutex_t itimer_mutex; /* XXX */
211 int error;
212
213 if (fflag & FNONBLOCK) {
214 return EAGAIN;
215 }
216
217 /*
218 * We're going to block. Check if we need to return ERESTART.
219 */
220 if (tfd->tfd_restarting) {
221 return ERESTART;
222 }
223
224 tfd->tfd_nwaiters++;
225 KASSERT(tfd->tfd_nwaiters > 0);
226 error = cv_wait_sig(&tfd->tfd_read_wait, &itimer_mutex);
227 tfd->tfd_nwaiters--;
228 KASSERT(tfd->tfd_nwaiters >= 0);
229
230 /*
231 * If a restart was triggered while we were asleep, we need
232 * to return ERESTART if no other error was returned.
233 */
234 if (tfd->tfd_restarting) {
235 if (error == 0) {
236 error = ERESTART;
237 }
238 }
239
240 return error;
241 }
242
243 /*
244 * timerfd_wake:
245 *
246 * Wake LWPs blocked on a timerfd.
247 */
248 static void
249 timerfd_wake(struct timerfd * const tfd)
250 {
251
252 if (tfd->tfd_nwaiters) {
253 cv_broadcast(&tfd->tfd_read_wait);
254 }
255 selnotify(&tfd->tfd_read_sel, POLLIN | POLLRDNORM, NOTE_SUBMIT);
256 }
257
258 /*
259 * timerfd file operations
260 */
261
262 static int
263 timerfd_fop_read(file_t * const fp, off_t * const offset,
264 struct uio * const uio, kauth_cred_t const cred, int const flags)
265 {
266 struct timerfd * const tfd = fp->f_timerfd;
267 struct itimer * const it = &tfd->tfd_itimer;
268 int const fflag = fp->f_flag;
269 uint64_t return_value;
270 int error;
271
272 if (uio->uio_resid < sizeof(uint64_t)) {
273 return EINVAL;
274 }
275
276 itimer_lock();
277
278 while (!timerfd_is_readable(tfd)) {
279 if ((error = timerfd_wait(tfd, fflag)) != 0) {
280 itimer_unlock();
281 return error;
282 }
283 }
284
285 if (tfd->tfd_cancelled) {
286 itimer_unlock();
287 return ECANCELED;
288 }
289
290 return_value = timerfd_fire_count(tfd);
291 it->it_overruns = 0;
292
293 getnanotime(&tfd->tfd_atime);
294
295 itimer_unlock();
296
297 error = uiomove(&return_value, sizeof(return_value), uio);
298
299 return error;
300 }
301
302 static int
303 timerfd_fop_ioctl(file_t * const fp, unsigned long const cmd, void * const data)
304 {
305 struct timerfd * const tfd = fp->f_timerfd;
306 int error = 0;
307
308 switch (cmd) {
309 case TFD_IOC_SET_TICKS: {
310 const uint64_t * const new_ticksp = data;
311 if (*new_ticksp > INT_MAX) {
312 return EINVAL;
313 }
314 itimer_lock();
315 tfd->tfd_itimer.it_overruns = (int)*new_ticksp;
316 itimer_unlock();
317 break;
318 }
319
320 default:
321 error = EPASSTHROUGH;
322 }
323
324 return error;
325 }
326
327 static int
328 timerfd_fop_poll(file_t * const fp, int const events)
329 {
330 struct timerfd * const tfd = fp->f_timerfd;
331 int revents = events & (POLLOUT | POLLWRNORM);
332
333 if (events & (POLLIN | POLLRDNORM)) {
334 itimer_lock();
335 if (timerfd_is_readable(tfd)) {
336 revents |= events & (POLLIN | POLLRDNORM);
337 } else {
338 selrecord(curlwp, &tfd->tfd_read_sel);
339 }
340 itimer_unlock();
341 }
342
343 return revents;
344 }
345
346 static int
347 timerfd_fop_stat(file_t * const fp, struct stat * const st)
348 {
349 struct timerfd * const tfd = fp->f_timerfd;
350
351 memset(st, 0, sizeof(*st));
352
353 itimer_lock();
354 st->st_size = (off_t)timerfd_fire_count(tfd);
355 st->st_atimespec = tfd->tfd_atime;
356 st->st_mtimespec = tfd->tfd_mtime;
357 itimer_unlock();
358
359 st->st_blksize = sizeof(uint64_t);
360 st->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
361 st->st_blocks = 1;
362 st->st_birthtimespec = tfd->tfd_btime;
363 st->st_ctimespec = st->st_mtimespec;
364 st->st_uid = kauth_cred_geteuid(fp->f_cred);
365 st->st_gid = kauth_cred_getegid(fp->f_cred);
366
367 return 0;
368 }
369
370 static int
371 timerfd_fop_close(file_t * const fp)
372 {
373 struct timerfd * const tfd = fp->f_timerfd;
374
375 fp->f_timerfd = NULL;
376 timerfd_destroy(tfd);
377
378 return 0;
379 }
380
381 static void
382 timerfd_filt_read_detach(struct knote * const kn)
383 {
384 struct timerfd * const tfd = ((file_t *)kn->kn_obj)->f_timerfd;
385
386 itimer_lock();
387 KASSERT(kn->kn_hook == tfd);
388 selremove_knote(&tfd->tfd_read_sel, kn);
389 itimer_unlock();
390 }
391
392 static int
393 timerfd_filt_read(struct knote * const kn, long const hint)
394 {
395 struct timerfd * const tfd = ((file_t *)kn->kn_obj)->f_timerfd;
396 int rv;
397
398 if (hint & NOTE_SUBMIT) {
399 KASSERT(itimer_lock_held());
400 } else {
401 itimer_lock();
402 }
403
404 kn->kn_data = (int64_t)timerfd_fire_count(tfd);
405 rv = kn->kn_data != 0;
406
407 if ((hint & NOTE_SUBMIT) == 0) {
408 itimer_unlock();
409 }
410
411 return rv;
412 }
413
414 static const struct filterops timerfd_read_filterops = {
415 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
416 .f_detach = timerfd_filt_read_detach,
417 .f_event = timerfd_filt_read,
418 };
419
420 static int
421 timerfd_fop_kqfilter(file_t * const fp, struct knote * const kn)
422 {
423 struct timerfd * const tfd = ((file_t *)kn->kn_obj)->f_timerfd;
424 struct selinfo *sel;
425
426 switch (kn->kn_filter) {
427 case EVFILT_READ:
428 sel = &tfd->tfd_read_sel;
429 kn->kn_fop = &timerfd_read_filterops;
430 break;
431
432 default:
433 return EINVAL;
434 }
435
436 kn->kn_hook = tfd;
437
438 itimer_lock();
439 selrecord_knote(sel, kn);
440 itimer_unlock();
441
442 return 0;
443 }
444
445 static void
446 timerfd_fop_restart(file_t * const fp)
447 {
448 struct timerfd * const tfd = fp->f_timerfd;
449
450 /*
451 * Unblock blocked reads in order to allow close() to complete.
452 * System calls return ERESTART so that the fd is revalidated.
453 */
454
455 itimer_lock();
456
457 if (tfd->tfd_nwaiters != 0) {
458 tfd->tfd_restarting = true;
459 cv_broadcast(&tfd->tfd_read_wait);
460 }
461
462 itimer_unlock();
463 }
464
465 static const struct fileops timerfd_fileops = {
466 .fo_name = "timerfd",
467 .fo_read = timerfd_fop_read,
468 .fo_write = fbadop_write,
469 .fo_ioctl = timerfd_fop_ioctl,
470 .fo_fcntl = fnullop_fcntl,
471 .fo_poll = timerfd_fop_poll,
472 .fo_stat = timerfd_fop_stat,
473 .fo_close = timerfd_fop_close,
474 .fo_kqfilter = timerfd_fop_kqfilter,
475 .fo_restart = timerfd_fop_restart,
476 };
477
478 /*
479 * timerfd_create(2) system call
480 */
481 int
482 do_timerfd_create(struct lwp * const l, clockid_t const clock_id,
483 int const flags, register_t *retval)
484 {
485 file_t *fp;
486 int fd, error;
487
488 if (flags & ~(TFD_CLOEXEC | TFD_NONBLOCK)) {
489 return EINVAL;
490 }
491
492 switch (clock_id) {
493 case CLOCK_REALTIME:
494 case CLOCK_MONOTONIC:
495 /* allowed */
496 break;
497
498 default:
499 return EINVAL;
500 }
501
502 if ((error = fd_allocfile(&fp, &fd)) != 0) {
503 return error;
504 }
505
506 fp->f_flag = FREAD;
507 if (flags & TFD_NONBLOCK) {
508 fp->f_flag |= FNONBLOCK;
509 }
510 fp->f_type = DTYPE_TIMERFD;
511 fp->f_ops = &timerfd_fileops;
512 fp->f_timerfd = timerfd_create(clock_id, flags);
513 fd_set_exclose(l, fd, !!(flags & TFD_CLOEXEC));
514 fd_affix(curproc, fp, fd);
515
516 *retval = fd;
517 return 0;
518 }
519
520 int
521 sys_timerfd_create(struct lwp *l, const struct sys_timerfd_create_args *uap,
522 register_t *retval)
523 {
524 /* {
525 syscallarg(clockid_t) clock_id;
526 syscallarg(int) flags;
527 } */
528
529 return do_timerfd_create(l, SCARG(uap, clock_id), SCARG(uap, flags),
530 retval);
531 }
532
533 /*
534 * timerfd_gettime(2) system call.
535 */
536 int
537 do_timerfd_gettime(struct lwp *l, int fd, struct itimerspec *curr_value,
538 register_t *retval)
539 {
540 file_t *fp;
541
542 if ((fp = fd_getfile(fd)) == NULL) {
543 return EBADF;
544 }
545
546 if (fp->f_ops != &timerfd_fileops) {
547 fd_putfile(fd);
548 return EINVAL;
549 }
550
551 struct timerfd * const tfd = fp->f_timerfd;
552 itimer_lock();
553 itimer_gettime(&tfd->tfd_itimer, curr_value);
554 itimer_unlock();
555
556 fd_putfile(fd);
557 return 0;
558 }
559
560 int
561 sys_timerfd_gettime(struct lwp *l, const struct sys_timerfd_gettime_args *uap,
562 register_t *retval)
563 {
564 /* {
565 syscallarg(int) fd;
566 syscallarg(struct itimerspec *) curr_value;
567 } */
568
569 struct itimerspec oits;
570 int error;
571
572 error = do_timerfd_gettime(l, SCARG(uap, fd), &oits, retval);
573 if (error == 0) {
574 error = copyout(&oits, SCARG(uap, curr_value), sizeof(oits));
575 }
576 return error;
577 }
578
579 /*
580 * timerfd_settime(2) system call.
581 */
582 int
583 do_timerfd_settime(struct lwp *l, int fd, int flags,
584 const struct itimerspec *new_value, struct itimerspec *old_value,
585 register_t *retval)
586 {
587 file_t *fp;
588 int error;
589
590 if (flags & ~(TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET)) {
591 return EINVAL;
592 }
593
594 if ((fp = fd_getfile(fd)) == NULL) {
595 return EBADF;
596 }
597
598 if (fp->f_ops != &timerfd_fileops) {
599 fd_putfile(fd);
600 return EINVAL;
601 }
602
603 struct timerfd * const tfd = fp->f_timerfd;
604 struct itimer * const it = &tfd->tfd_itimer;
605
606 itimer_lock();
607
608 restart:
609 if (old_value != NULL) {
610 *old_value = it->it_time;
611 }
612 it->it_time = *new_value;
613
614 /*
615 * If we've been passed a relative value, convert it to an
616 * absolute, as that's what the itimer facility expects for
617 * non-virtual timers. Also ensure that this doesn't set it
618 * to zero or lets it go negative.
619 * XXXJRT re-factor.
620 */
621 if (timespecisset(&it->it_time.it_value) &&
622 (flags & TFD_TIMER_ABSTIME) == 0) {
623 struct timespec now;
624 if (it->it_clockid == CLOCK_REALTIME) {
625 getnanotime(&now);
626 } else { /* CLOCK_MONOTONIC */
627 getnanouptime(&now);
628 }
629 timespecadd(&it->it_time.it_value, &now,
630 &it->it_time.it_value);
631 }
632
633 error = itimer_settime(it);
634 if (error == ERESTART) {
635 goto restart;
636 }
637 KASSERT(error == 0);
638
639 /* Reset the expirations counter. */
640 it->it_overruns = 0;
641
642 if (it->it_clockid == CLOCK_REALTIME) {
643 tfd->tfd_cancelled = false;
644 tfd->tfd_cancel_on_set = !!(flags & TFD_TIMER_CANCEL_ON_SET);
645 }
646
647 getnanotime(&tfd->tfd_mtime);
648 itimer_unlock();
649
650 fd_putfile(fd);
651 return error;
652 }
653
654 int
655 sys_timerfd_settime(struct lwp *l, const struct sys_timerfd_settime_args *uap,
656 register_t *retval)
657 {
658 /* {
659 syscallarg(int) fd;
660 syscallarg(int) flags;
661 syscallarg(const struct itimerspec *) new_value;
662 syscallarg(struct itimerspec *) old_value;
663 } */
664
665 struct itimerspec nits, oits, *oitsp = NULL;
666 int error;
667
668 error = copyin(SCARG(uap, new_value), &nits, sizeof(nits));
669 if (error) {
670 return error;
671 }
672
673 if (SCARG(uap, old_value) != NULL) {
674 oitsp = &oits;
675 }
676
677 error = do_timerfd_settime(l, SCARG(uap, fd), SCARG(uap, flags),
678 &nits, oitsp, retval);
679 if (error == 0 && oitsp != NULL) {
680 error = copyout(oitsp, SCARG(uap, old_value), sizeof(*oitsp));
681 }
682 return error;
683 }
684