1 .\" $NetBSD: timeout.9,v 1.2 1996/06/23 22:32:34 pk Exp $
3 .\" Copyright (c) 1996 The NetBSD Foundation, Inc.
4 .\" All rights reserved.
6 .\" This code is derived from software contributed to The NetBSD Foundation
7 .\" by Paul Kranenburg.
9 .\" Redistribution and use in source and binary forms, with or without
10 .\" modification, are permitted provided that the following conditions
12 .\" 1. Redistributions of source code must retain the above copyright
13 .\" notice, this list of conditions and the following disclaimer.
14 .\" 2. Redistributions in binary form must reproduce the above copyright
15 .\" notice, this list of conditions and the following disclaimer in the
16 .\" documentation and/or other materials provided with the distribution.
18 .\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
19 .\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20 .\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 .\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
22 .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 .\" POSSIBILITY OF SUCH DAMAGE.
37 .Nm callout_deactivate ,
38 .Nm callout_async_drain ,
40 .Nm callout_handle_init ,
42 .Nm callout_init_mtx ,
47 .Nm callout_reset_curcpu ,
48 .Nm callout_reset_on ,
49 .Nm callout_reset_sbt ,
50 .Nm callout_reset_sbt_curcpu ,
51 .Nm callout_reset_sbt_on ,
52 .Nm callout_schedule ,
53 .Nm callout_schedule_curcpu ,
54 .Nm callout_schedule_on ,
55 .Nm callout_schedule_sbt ,
56 .Nm callout_schedule_sbt_curcpu ,
57 .Nm callout_schedule_sbt_on ,
62 .Nd execute a function after a specified length of time
67 typedef void timeout_t (void *);
70 .Fn callout_active "struct callout *c"
72 .Fn callout_deactivate "struct callout *c"
74 .Fn callout_async_drain "struct callout *c" "timeout_t *drain"
76 .Fn callout_drain "struct callout *c"
78 .Fn callout_handle_init "struct callout_handle *handle"
80 struct callout_handle handle = CALLOUT_HANDLE_INITIALIZER(&handle);
83 .Fn callout_init "struct callout *c" "int mpsafe"
85 .Fn callout_init_mtx "struct callout *c" "struct mtx *mtx" "int flags"
87 .Fn callout_init_rm "struct callout *c" "struct rmlock *rm" "int flags"
89 .Fn callout_init_rw "struct callout *c" "struct rwlock *rw" "int flags"
91 .Fn callout_pending "struct callout *c"
93 .Fn callout_reset "struct callout *c" "int ticks" "timeout_t *func" "void *arg"
95 .Fo callout_reset_curcpu
96 .Fa "struct callout *c"
103 .Fa "struct callout *c"
105 .Fa "timeout_t *func"
110 .Fo callout_reset_sbt
111 .Fa "struct callout *c"
114 .Fa "timeout_t *func"
119 .Fo callout_reset_sbt_curcpu
120 .Fa "struct callout *c"
123 .Fa "timeout_t *func"
128 .Fo callout_reset_sbt_on
129 .Fa "struct callout *c"
132 .Fa "timeout_t *func"
138 .Fn callout_schedule "struct callout *c" "int ticks"
140 .Fn callout_schedule_curcpu "struct callout *c" "int ticks"
142 .Fn callout_schedule_on "struct callout *c" "int ticks" "int cpu"
144 .Fo callout_schedule_sbt
145 .Fa "struct callout *c"
151 .Fo callout_schedule_sbt_curcpu
152 .Fa "struct callout *c"
158 .Fo callout_schedule_sbt_on
159 .Fa "struct callout *c"
166 .Fn callout_stop "struct callout *c"
170 .Fa "sbintime_t precision"
172 .Fa "sbintime_t *sbt_res"
173 .Fa "sbintime_t *precision_res"
175 .Ft struct callout_handle
176 .Fn timeout "timeout_t *func" "void *arg" "int ticks"
178 .Fn untimeout "timeout_t *func" "void *arg" "struct callout_handle handle"
182 API is used to schedule a call to an arbitrary function at a specific
184 Consumers of this API are required to allocate a callout structure
186 for each pending function invocation.
187 This structure stores state about the pending function invocation including
188 the function to be called and the time at which the function should be invoked.
189 Pending function calls can be cancelled or rescheduled to a different time.
191 a callout structure may be reused to schedule a new function call after a
192 scheduled call is completed.
194 Callouts only provide a single-shot mode.
195 If a consumer requires a periodic timer,
196 it must explicitly reschedule each function call.
197 This is normally done by rescheduling the subsequent call within the called
200 Callout functions must not sleep.
201 They may not acquire sleepable locks,
202 wait on condition variables,
203 perform blocking allocation requests,
204 or invoke any other action that might sleep.
206 Each callout structure must be initialized by
208 .Fn callout_init_mtx ,
209 .Fn callout_init_rm ,
212 before it is passed to any of the other callout functions.
215 function initializes a callout structure in
217 that is not associated with a specific lock.
221 the callout structure is not considered to be
222 .Dq multi-processor safe ;
223 and the Giant lock will be acquired before calling the callout function
224 and released when the callout function returns.
227 .Fn callout_init_mtx ,
228 .Fn callout_init_rm ,
231 functions initialize a callout structure in
233 that is associated with a specific lock.
234 The lock is specified by the
240 The associated lock must be held while stopping or rescheduling the
242 The callout subsystem acquires the associated lock before calling the
243 callout function and releases it after the function returns.
244 If the callout was cancelled while the callout subsystem waited for the
246 the callout function is not called,
247 and the associated lock is released.
248 This ensures that stopping or rescheduling the callout will abort any
249 previously scheduled invocation.
251 Only regular mutexes may be used with
252 .Fn callout_init_mtx ;
253 spin mutexes are not supported.
254 A sleepable read-mostly lock
256 one initialized with the
261 .Fn callout_init_rm .
262 Similarly, other sleepable lock types such as
266 cannot be used with callouts because sleeping is not permitted in
267 the callout subsystem.
272 .Fn callout_init_mtx ,
273 .Fn callout_init_rm ,
275 .Fn callout_init_rw :
276 .Bl -tag -width ".Dv CALLOUT_RETURNUNLOCKED"
277 .It Dv CALLOUT_RETURNUNLOCKED
278 The callout function will release the associated lock itself,
279 so the callout subsystem should not attempt to unlock it
280 after the callout function returns.
281 .It Dv CALLOUT_SHAREDLOCK
282 The lock is only acquired in read mode when running the callout handler.
283 This flag is ignored by
284 .Fn callout_init_mtx .
291 if it is currently pending.
292 If the callout is pending and successfully stopped, then
294 returns a value of one.
295 If the callout is not set, or
296 has already been serviced, then
297 negative one is returned.
298 If the callout is currently being serviced and cannot be stopped,
299 then zero will be returned.
300 If the callout is currently being serviced and cannot be stopped, and at the
301 same time a next invocation of the same callout is also scheduled, then
303 unschedules the next run and returns zero.
304 If the callout has an associated lock,
305 then that lock must be held when this function is called.
308 .Fn callout_async_drain
313 .Fn callout_async_drain
314 returns zero it will arrange for the function
316 to be called using the same argument given to the
319 .Fn callout_async_drain
320 If the callout has an associated lock,
321 then that lock must be held when this function is called.
322 Note that when stopping multiple callouts that use the same lock it is possible
323 to get multiple return's of zero and multiple calls to the
325 function, depending upon which CPU's the callouts are running.
328 function itself is called from the context of the completing callout
329 i.e. softclock or hardclock, just like a callout itself.
336 except that it will wait for the callout
338 to complete if it is already in progress.
339 This function MUST NOT be called while holding any
340 locks on which the callout might block, or deadlock will result.
341 Note that if the callout subsystem has already begun processing this
342 callout, then the callout function may be invoked before
345 However, the callout subsystem does guarantee that the callout will be
354 function families schedule a future function invocation for callout
358 already has a pending callout,
359 it is cancelled before the new invocation is scheduled.
360 These functions return a value of one if a pending callout was cancelled
361 and zero if there was no pending callout.
362 If the callout has an associated lock,
363 then that lock must be held when any of these functions are called.
365 The time at which the callout function will be invoked is determined by
377 the callout is scheduled to execute after
380 Non-positive values of
382 are silently converted to the value
390 arguments provide more control over the scheduled time including
391 support for higher resolution times,
392 specifying the precision of the scheduled time,
393 and setting an absolute deadline instead of a relative timeout.
394 The callout is scheduled to execute in a time window which begins at
395 the time specified in
397 and extends for the amount of time specified in
401 specifies a time in the past,
402 the window is adjusted to start at the current time.
405 allows the callout subsystem to coalesce callouts scheduled close to each
406 other into fewer timer interrupts,
407 reducing processing overhead and power consumption.
410 may be specified to adjust the interpretation of
414 .Bl -tag -width ".Dv C_DIRECT_EXEC"
418 argument as an absolute time since boot.
421 is treated as a relative amount of time,
425 Run the handler directly from hardware interrupt context instead of from the
427 This reduces latency and overhead, but puts more constraints on the callout
429 Callout functions run in this context may use only spin mutexes for locking
430 and should be as small as possible because they run with absolute priority.
432 Specifies relative event time precision as binary logarithm of time interval
433 divided by acceptable time deviation: 1 -- 1/2, 2 -- 1/4, etc.
434 Note that the larger of
436 or this value is used as the length of the time window.
438 .Pq which result in larger time intervals
439 allow the callout subsystem to aggregate more events in one timer interrupt.
443 argument specifies the absolute time at which the callout should be run,
446 argument specifies the requested precision, which will not be
447 adjusted during the scheduling process.
452 values should be calculated by an earlier call to
454 which uses the user-supplied
461 Align the timeouts to
470 argument which identifies the function to be called when the time expires.
471 It must be a pointer to a function that takes a single
478 as its only argument.
485 arguments from the previous callout.
488 functions must always be called to initialize
494 functions can be used.
496 The callout subsystem provides a softclock thread for each CPU in the system.
497 Callouts are assigned to a single CPU and are executed by the softclock thread
500 callouts are assigned to CPU 0.
502 .Fn callout_reset_on ,
503 .Fn callout_reset_sbt_on ,
504 .Fn callout_schedule_on
506 .Fn callout_schedule_sbt_on
507 functions assign the callout to CPU
510 .Fn callout_reset_curcpu ,
511 .Fn callout_reset_sbt_curpu ,
512 .Fn callout_schedule_curcpu
514 .Fn callout_schedule_sbt_curcpu
515 functions assign the callout to the current CPU.
518 .Fn callout_reset_sbt ,
521 .Fn callout_schedule_sbt
522 functions schedule the callout to execute in the softclock thread of the CPU
523 to which it is currently assigned.
525 Softclock threads are not pinned to their respective CPUs by default.
526 The softclock thread for CPU 0 can be pinned to CPU 0 by setting the
527 .Va kern.pin_default_swi
528 loader tunable to a non-zero value.
529 Softclock threads for CPUs other than zero can be pinned to their
530 respective CPUs by setting the
531 .Va kern.pin_pcpu_swi
532 loader tunable to a non-zero value.
535 .Fn callout_pending ,
538 .Fn callout_deactivate
539 provide access to the current state of the callout.
542 macro checks whether a callout is
544 a callout is considered
546 when a timeout has been set but the time has not yet arrived.
547 Note that once the timeout time arrives and the callout subsystem
548 starts to process this callout,
552 even though the callout function may not have finished
557 macro checks whether a callout is marked as
560 .Fn callout_deactivate
561 macro clears the callout's
564 The callout subsystem marks a callout as
566 when a timeout is set and it clears the
574 clear it when a callout expires normally via the execution of the
579 function may be used to pre-calculate the absolute time at which the
580 timeout should be run and the precision of the scheduled run time
581 according to the required time
585 and additional adjustments requested by the
588 Flags accepted by the
590 function are the same as flags for the
593 The resulting time is assigned to the variable pointed to by the
595 argument, and the resulting precision is assigned to
597 When passing the results to
603 to avoid incorrect re-adjustment.
604 The function is intended for situations where precise time of the callout
605 run should be known in advance, since
606 trying to read this time from the callout structure itself after a
609 .Ss "Avoiding Race Conditions"
610 The callout subsystem invokes callout functions from its own thread
612 Without some kind of synchronization,
613 it is possible that a callout
614 function will be invoked concurrently with an attempt to stop or reset
615 the callout by another thread.
616 In particular, since callout functions typically acquire a lock as
617 their first action, the callout function may have already been invoked,
618 but is blocked waiting for that lock at the time that another thread
619 tries to reset or stop the callout.
621 There are three main techniques for addressing these
622 synchronization concerns.
623 The first approach is preferred as it is the simplest:
624 .Bl -enum -offset indent
626 Callouts can be associated with a specific lock when they are initialized
628 .Fn callout_init_mtx ,
629 .Fn callout_init_rm ,
631 .Fn callout_init_rw .
632 When a callout is associated with a lock,
633 the callout subsystem acquires the lock before the callout function is
635 This allows the callout subsystem to transparently handle races between
636 callout cancellation,
639 Note that the associated lock must be acquired before calling
645 functions to provide this safety.
647 A callout initialized via
651 set to zero is implicitly associated with the
656 is held when cancelling or rescheduling the callout,
657 then its use will prevent races with the callout function.
659 The return value from
668 indicates whether or not the callout was removed.
669 If it is known that the callout was set and the callout function has
670 not yet executed, then a return value of
672 indicates that the callout function is about to be called.
674 .Bd -literal -offset indent
675 if (sc->sc_flags & SCFLG_CALLOUT_RUNNING) {
676 if (callout_stop(&sc->sc_callout)) {
677 sc->sc_flags &= ~SCFLG_CALLOUT_RUNNING;
678 /* successfully stopped */
681 * callout has expired and callout
682 * function is about to be executed
689 .Fn callout_pending ,
692 .Fn callout_deactivate
693 macros can be used together to work around the race conditions.
694 When a callout's timeout is set, the callout subsystem marks the
699 When the timeout time arrives, the callout subsystem begins processing
700 the callout by first clearing the
703 It then invokes the callout function without changing the
705 flag, and does not clear the
707 flag even after the callout function returns.
708 The mechanism described here requires the callout function itself to
712 .Fn callout_deactivate
718 functions always clear both the
722 flags before returning.
724 The callout function should first check the
726 flag and return without action if
730 This indicates that the callout was rescheduled using
732 just before the callout function was invoked.
737 then the callout function should also return without action.
738 This indicates that the callout has been stopped.
739 Finally, the callout function should call
740 .Fn callout_deactivate
745 .Bd -literal -offset indent
746 mtx_lock(&sc->sc_mtx);
747 if (callout_pending(&sc->sc_callout)) {
748 /* callout was reset */
749 mtx_unlock(&sc->sc_mtx);
752 if (!callout_active(&sc->sc_callout)) {
753 /* callout was stopped */
754 mtx_unlock(&sc->sc_mtx);
757 callout_deactivate(&sc->sc_callout);
758 /* rest of callout function */
761 Together with appropriate synchronization, such as the mutex used above,
762 this approach permits the
766 functions to be used at any time without races.
768 .Bd -literal -offset indent
769 mtx_lock(&sc->sc_mtx);
770 callout_stop(&sc->sc_callout);
771 /* The callout is effectively stopped now. */
774 If the callout is still pending then these functions operate normally,
775 but if processing of the callout has already begun then the tests in
776 the callout function cause it to return without further action.
777 Synchronization between the callout function and other code ensures that
778 stopping or resetting the callout will never be attempted while the
779 callout function is past the
780 .Fn callout_deactivate
783 The above technique additionally ensures that the
785 flag always reflects whether the callout is effectively enabled or
789 returns false, then the callout is effectively disabled, since even if
790 the callout subsystem is actually just about to invoke the callout
791 function, the callout function will return without action.
794 There is one final race condition that must be considered when a
795 callout is being stopped for the last time.
796 In this case it may not be safe to let the callout function itself
797 detect that the callout was stopped, since it may need to access
798 data objects that have already been destroyed or recycled.
799 To ensure that the callout is completely finished, a call to
803 a callout should always be drained prior to destroying its associated lock
804 or releasing the storage for the callout structure.
807 The functions below are a legacy API that will be removed in a future release.
808 New code should not use these routines.
813 schedules a call to the function given by the argument
818 Non-positive values of
820 are silently converted to the value
823 should be a pointer to a function that takes a
830 as its only argument.
831 The return value from
834 .Ft struct callout_handle
835 which can be used in conjunction with the
837 function to request that a scheduled timeout be canceled.
840 .Fn callout_handle_init
841 can be used to initialize a handle to a state which will cause
844 with that handle to return with no side
847 Assigning a callout handle the value of
848 .Fn CALLOUT_HANDLE_INITIALIZER
849 performs the same function as
850 .Fn callout_handle_init
851 and is provided for use on statically declared or global callout handles.
855 cancels the timeout associated with
861 arguments to validate the handle.
862 If the handle does not correspond to a timeout with
869 must be initialized by a previous call to
871 .Fn callout_handle_init ,
872 or assigned the value of
873 .Fn CALLOUT_HANDLE_INITIALIZER "&handle"
874 before being passed to
876 The behavior of calling
878 with an uninitialized handle
881 As handles are recycled by the system, it is possible (although unlikely)
882 that a handle from one invocation of
884 may match the handle of another invocation of
886 if both calls used the same function pointer and argument, and the first
887 timeout is expired or canceled before the second call.
888 The timeout facility offers O(1) running time for
892 Timeouts are executed from
897 Thus they are protected from re-entrancy.
901 macro returns the state of a callout's
907 macro returns the state of a callout's
915 function families return a value of one if the callout was pending before the new
916 function invocation was scheduled.
922 functions return a value of one if the callout was still pending when it was
923 called, a zero if the callout could not be stopped and a negative one is it
924 was either not running or has already completed.
928 .Ft struct callout_handle
929 that can be passed to
932 The current timeout and untimeout routines are based on the work of
935 .An George Varghese ,
936 published in a technical report entitled
937 .%T "Redesigning the BSD Callout and Timer Facilities"
938 and modified slightly for inclusion in
941 .An Justin T. Gibbs .
942 The original work on the data structures used in this implementation
948 .%T "Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility"
950 .%B "Proceedings of the 11th ACM Annual Symposium on Operating Systems Principles" .
951 The current implementation replaces the long standing
954 callout mechanism which offered O(n) insertion and removal running time
955 but did not generate or require handles for untimeout operations.