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.
335 except that it will wait for the callout
337 to complete if it is already in progress.
338 This function MUST NOT be called while holding any
339 locks on which the callout might block, or deadlock will result.
340 Note that if the callout subsystem has already begun processing this
341 callout, then the callout function may be invoked before
344 However, the callout subsystem does guarantee that the callout will be
353 function families schedule a future function invocation for callout
357 already has a pending callout,
358 it is cancelled before the new invocation is scheduled.
359 These functions return a value of one if a pending callout was cancelled
360 and zero if there was no pending callout.
361 If the callout has an associated lock,
362 then that lock must be held when any of these functions are called.
364 The time at which the callout function will be invoked is determined by
376 the callout is scheduled to execute after
379 Non-positive values of
381 are silently converted to the value
389 arguments provide more control over the scheduled time including
390 support for higher resolution times,
391 specifying the precision of the scheduled time,
392 and setting an absolute deadline instead of a relative timeout.
393 The callout is scheduled to execute in a time window which begins at
394 the time specified in
396 and extends for the amount of time specified in
400 specifies a time in the past,
401 the window is adjusted to start at the current time.
404 allows the callout subsystem to coalesce callouts scheduled close to each
405 other into fewer timer interrupts,
406 reducing processing overhead and power consumption.
409 may be specified to adjust the interpretation of
413 .Bl -tag -width ".Dv C_DIRECT_EXEC"
417 argument as an absolute time since boot.
420 is treated as a relative amount of time,
424 Run the handler directly from hardware interrupt context instead of from the
426 This reduces latency and overhead, but puts more constraints on the callout
428 Callout functions run in this context may use only spin mutexes for locking
429 and should be as small as possible because they run with absolute priority.
431 Specifies relative event time precision as binary logarithm of time interval
432 divided by acceptable time deviation: 1 -- 1/2, 2 -- 1/4, etc.
433 Note that the larger of
435 or this value is used as the length of the time window.
437 .Pq which result in larger time intervals
438 allow the callout subsystem to aggregate more events in one timer interrupt.
442 argument specifies the absolute time at which the callout should be run,
445 argument specifies the requested precision, which will not be
446 adjusted during the scheduling process.
451 values should be calculated by an earlier call to
453 which uses the user-supplied
460 Align the timeouts to
469 argument which identifies the function to be called when the time expires.
470 It must be a pointer to a function that takes a single
477 as its only argument.
484 arguments from the previous callout.
487 functions must always be called to initialize
493 functions can be used.
495 The callout subsystem provides a softclock thread for each CPU in the system.
496 Callouts are assigned to a single CPU and are executed by the softclock thread
499 callouts are assigned to CPU 0.
501 .Fn callout_reset_on ,
502 .Fn callout_reset_sbt_on ,
503 .Fn callout_schedule_on
505 .Fn callout_schedule_sbt_on
506 functions assign the callout to CPU
509 .Fn callout_reset_curcpu ,
510 .Fn callout_reset_sbt_curpu ,
511 .Fn callout_schedule_curcpu
513 .Fn callout_schedule_sbt_curcpu
514 functions assign the callout to the current CPU.
517 .Fn callout_reset_sbt ,
520 .Fn callout_schedule_sbt
521 functions schedule the callout to execute in the softclock thread of the CPU
522 to which it is currently assigned.
524 Softclock threads are not pinned to their respective CPUs by default.
525 The softclock thread for CPU 0 can be pinned to CPU 0 by setting the
526 .Va kern.pin_default_swi
527 loader tunable to a non-zero value.
528 Softclock threads for CPUs other than zero can be pinned to their
529 respective CPUs by setting the
530 .Va kern.pin_pcpu_swi
531 loader tunable to a non-zero value.
534 .Fn callout_pending ,
537 .Fn callout_deactivate
538 provide access to the current state of the callout.
541 macro checks whether a callout is
543 a callout is considered
545 when a timeout has been set but the time has not yet arrived.
546 Note that once the timeout time arrives and the callout subsystem
547 starts to process this callout,
551 even though the callout function may not have finished
556 macro checks whether a callout is marked as
559 .Fn callout_deactivate
560 macro clears the callout's
563 The callout subsystem marks a callout as
565 when a timeout is set and it clears the
573 clear it when a callout expires normally via the execution of the
578 function may be used to pre-calculate the absolute time at which the
579 timeout should be run and the precision of the scheduled run time
580 according to the required time
584 and additional adjustments requested by the
587 Flags accepted by the
589 function are the same as flags for the
592 The resulting time is assigned to the variable pointed to by the
594 argument, and the resulting precision is assigned to
596 When passing the results to
602 to avoid incorrect re-adjustment.
603 The function is intended for situations where precise time of the callout
604 run should be known in advance, since
605 trying to read this time from the callout structure itself after a
608 .Ss "Avoiding Race Conditions"
609 The callout subsystem invokes callout functions from its own thread
611 Without some kind of synchronization,
612 it is possible that a callout
613 function will be invoked concurrently with an attempt to stop or reset
614 the callout by another thread.
615 In particular, since callout functions typically acquire a lock as
616 their first action, the callout function may have already been invoked,
617 but is blocked waiting for that lock at the time that another thread
618 tries to reset or stop the callout.
620 There are three main techniques for addressing these
621 synchronization concerns.
622 The first approach is preferred as it is the simplest:
623 .Bl -enum -offset indent
625 Callouts can be associated with a specific lock when they are initialized
627 .Fn callout_init_mtx ,
628 .Fn callout_init_rm ,
630 .Fn callout_init_rw .
631 When a callout is associated with a lock,
632 the callout subsystem acquires the lock before the callout function is
634 This allows the callout subsystem to transparently handle races between
635 callout cancellation,
638 Note that the associated lock must be acquired before calling
644 functions to provide this safety.
646 A callout initialized via
650 set to zero is implicitly associated with the
655 is held when cancelling or rescheduling the callout,
656 then its use will prevent races with the callout function.
658 The return value from
667 indicates whether or not the callout was removed.
668 If it is known that the callout was set and the callout function has
669 not yet executed, then a return value of
671 indicates that the callout function is about to be called.
673 .Bd -literal -offset indent
674 if (sc->sc_flags & SCFLG_CALLOUT_RUNNING) {
675 if (callout_stop(&sc->sc_callout)) {
676 sc->sc_flags &= ~SCFLG_CALLOUT_RUNNING;
677 /* successfully stopped */
680 * callout has expired and callout
681 * function is about to be executed
688 .Fn callout_pending ,
691 .Fn callout_deactivate
692 macros can be used together to work around the race conditions.
693 When a callout's timeout is set, the callout subsystem marks the
698 When the timeout time arrives, the callout subsystem begins processing
699 the callout by first clearing the
702 It then invokes the callout function without changing the
704 flag, and does not clear the
706 flag even after the callout function returns.
707 The mechanism described here requires the callout function itself to
711 .Fn callout_deactivate
717 functions always clear both the
721 flags before returning.
723 The callout function should first check the
725 flag and return without action if
729 This indicates that the callout was rescheduled using
731 just before the callout function was invoked.
736 then the callout function should also return without action.
737 This indicates that the callout has been stopped.
738 Finally, the callout function should call
739 .Fn callout_deactivate
744 .Bd -literal -offset indent
745 mtx_lock(&sc->sc_mtx);
746 if (callout_pending(&sc->sc_callout)) {
747 /* callout was reset */
748 mtx_unlock(&sc->sc_mtx);
751 if (!callout_active(&sc->sc_callout)) {
752 /* callout was stopped */
753 mtx_unlock(&sc->sc_mtx);
756 callout_deactivate(&sc->sc_callout);
757 /* rest of callout function */
760 Together with appropriate synchronization, such as the mutex used above,
761 this approach permits the
765 functions to be used at any time without races.
767 .Bd -literal -offset indent
768 mtx_lock(&sc->sc_mtx);
769 callout_stop(&sc->sc_callout);
770 /* The callout is effectively stopped now. */
773 If the callout is still pending then these functions operate normally,
774 but if processing of the callout has already begun then the tests in
775 the callout function cause it to return without further action.
776 Synchronization between the callout function and other code ensures that
777 stopping or resetting the callout will never be attempted while the
778 callout function is past the
779 .Fn callout_deactivate
782 The above technique additionally ensures that the
784 flag always reflects whether the callout is effectively enabled or
788 returns false, then the callout is effectively disabled, since even if
789 the callout subsystem is actually just about to invoke the callout
790 function, the callout function will return without action.
793 There is one final race condition that must be considered when a
794 callout is being stopped for the last time.
795 In this case it may not be safe to let the callout function itself
796 detect that the callout was stopped, since it may need to access
797 data objects that have already been destroyed or recycled.
798 To ensure that the callout is completely finished, a call to
802 a callout should always be drained prior to destroying its associated lock
803 or releasing the storage for the callout structure.
806 The functions below are a legacy API that will be removed in a future release.
807 New code should not use these routines.
812 schedules a call to the function given by the argument
817 Non-positive values of
819 are silently converted to the value
822 should be a pointer to a function that takes a
829 as its only argument.
830 The return value from
833 .Ft struct callout_handle
834 which can be used in conjunction with the
836 function to request that a scheduled timeout be canceled.
839 .Fn callout_handle_init
840 can be used to initialize a handle to a state which will cause
843 with that handle to return with no side
846 Assigning a callout handle the value of
847 .Fn CALLOUT_HANDLE_INITIALIZER
848 performs the same function as
849 .Fn callout_handle_init
850 and is provided for use on statically declared or global callout handles.
854 cancels the timeout associated with
860 arguments to validate the handle.
861 If the handle does not correspond to a timeout with
868 must be initialized by a previous call to
870 .Fn callout_handle_init ,
871 or assigned the value of
872 .Fn CALLOUT_HANDLE_INITIALIZER "&handle"
873 before being passed to
875 The behavior of calling
877 with an uninitialized handle
880 As handles are recycled by the system, it is possible (although unlikely)
881 that a handle from one invocation of
883 may match the handle of another invocation of
885 if both calls used the same function pointer and argument, and the first
886 timeout is expired or canceled before the second call.
887 The timeout facility offers O(1) running time for
891 Timeouts are executed from
896 Thus they are protected from re-entrancy.
900 macro returns the state of a callout's
906 macro returns the state of a callout's
914 function families return a value of one if the callout was pending before the new
915 function invocation was scheduled.
921 functions return a value of one if the callout was still pending when it was
922 called, a zero if the callout could not be stopped and a negative one is it
923 was either not running or has already completed.
927 .Ft struct callout_handle
928 that can be passed to
931 The current timeout and untimeout routines are based on the work of
934 .An George Varghese ,
935 published in a technical report entitled
936 .%T "Redesigning the BSD Callout and Timer Facilities"
937 and modified slightly for inclusion in
940 .An Justin T. Gibbs .
941 The original work on the data structures used in this implementation
947 .%T "Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility"
949 .%B "Proceedings of the 11th ACM Annual Symposium on Operating Systems Principles" .
950 The current implementation replaces the long standing
953 callout mechanism which offered O(n) insertion and removal running time
954 but did not generate or require handles for untimeout operations.