1.\"	$NetBSD: timeout.9,v 1.2 1996/06/23 22:32:34 pk Exp $
2.\"
3.\" Copyright (c) 1996 The NetBSD Foundation, Inc.
4.\" All rights reserved.
5.\"
6.\" This code is derived from software contributed to The NetBSD Foundation
7.\" by Paul Kranenburg.
8.\"
9.\" Redistribution and use in source and binary forms, with or without
10.\" modification, are permitted provided that the following conditions
11.\" are met:
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.
17.\"
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.
29.\"
30.\" $FreeBSD: stable/9/share/man/man9/timeout.9 237216 2012-06-18 04:55:07Z eadler $
31.\"
32.Dd August 2, 2008
33.Dt TIMEOUT 9
34.Os
35.Sh NAME
36.Nm timeout ,
37.Nm untimeout ,
38.Nm callout_handle_init ,
39.Nm callout_init ,
40.Nm callout_init_mtx ,
41.Nm callout_init_rw ,
42.Nm callout_stop ,
43.Nm callout_drain ,
44.Nm callout_reset ,
45.Nm callout_schedule ,
46.Nm callout_pending ,
47.Nm callout_active ,
48.Nm callout_deactivate
49.Nd execute a function after a specified length of time
50.Sh SYNOPSIS
51.In sys/types.h
52.In sys/systm.h
53.Bd -literal
54typedef void timeout_t (void *);
55.Ed
56.Ft struct callout_handle
57.Fn timeout "timeout_t *func" "void *arg" "int ticks"
58.Ft void
59.Fn callout_handle_init "struct callout_handle *handle"
60.Bd -literal
61struct callout_handle handle = CALLOUT_HANDLE_INITIALIZER(&handle)
62.Ed
63.Ft void
64.Fn untimeout "timeout_t *func" "void *arg" "struct callout_handle handle"
65.Ft void
66.Fn callout_init "struct callout *c" "int mpsafe"
67.Ft void
68.Fn callout_init_mtx "struct callout *c" "struct mtx *mtx" "int flags"
69.Ft void
70.Fn callout_init_rw "struct callout *c" "struct rwlock *rw" "int flags"
71.Ft int
72.Fn callout_stop "struct callout *c"
73.Ft int
74.Fn callout_drain "struct callout *c"
75.Ft int
76.Fn callout_reset "struct callout *c" "int ticks" "timeout_t *func" "void *arg"
77.Ft int
78.Fn callout_schedule "struct callout *c" "int ticks"
79.Ft int
80.Fn callout_pending "struct callout *c"
81.Ft int
82.Fn callout_active "struct callout *c"
83.Fn callout_deactivate "struct callout *c"
84.Sh DESCRIPTION
85The function
86.Fn timeout
87schedules a call to the function given by the argument
88.Fa func
89to take place after
90.Fa ticks Ns No /hz
91seconds.
92Non-positive values of
93.Fa ticks
94are silently converted to the value
95.Sq 1 .
96.Fa func
97should be a pointer to a function that takes a
98.Fa void *
99argument.
100Upon invocation,
101.Fa func
102will receive
103.Fa arg
104as its only argument.
105The return value from
106.Fn timeout
107is a
108.Ft struct callout_handle
109which can be used in conjunction with the
110.Fn untimeout
111function to request that a scheduled timeout be canceled.
112The
113.Fn timeout
114call is the old style and new code should use the
115.Fn callout_*
116functions.
117.Pp
118The function
119.Fn callout_handle_init
120can be used to initialize a handle to a state which will cause
121any calls to
122.Fn untimeout
123with that handle to return with no side
124effects.
125.Pp
126Assigning a callout handle the value of
127.Fn CALLOUT_HANDLE_INITIALIZER
128performs the same function as
129.Fn callout_handle_init
130and is provided for use on statically declared or global callout handles.
131.Pp
132The function
133.Fn untimeout
134cancels the timeout associated with
135.Fa handle
136using the
137.Fa func
138and
139.Fa arg
140arguments to validate the handle.
141If the handle does not correspond to a timeout with
142the function
143.Fa func
144taking the argument
145.Fa arg
146no action is taken.
147.Fa handle
148must be initialized by a previous call to
149.Fn timeout ,
150.Fn callout_handle_init ,
151or assigned the value of
152.Fn CALLOUT_HANDLE_INITIALIZER "&handle"
153before being passed to
154.Fn untimeout .
155The behavior of calling
156.Fn untimeout
157with an uninitialized handle
158is undefined.
159The
160.Fn untimeout
161call is the old style and new code should use the
162.Fn callout_*
163functions.
164.Pp
165As handles are recycled by the system, it is possible (although unlikely)
166that a handle from one invocation of
167.Fn timeout
168may match the handle of another invocation of
169.Fn timeout
170if both calls used the same function pointer and argument, and the first
171timeout is expired or canceled before the second call.
172The timeout facility offers O(1) running time for
173.Fn timeout
174and
175.Fn untimeout .
176Timeouts are executed from
177.Fn softclock
178with the
179.Va Giant
180lock held.
181Thus they are protected from re-entrancy.
182.Pp
183The functions
184.Fn callout_init ,
185.Fn callout_init_mtx ,
186.Fn callout_init_rw ,
187.Fn callout_stop ,
188.Fn callout_drain ,
189.Fn callout_reset
190and
191.Fn callout_schedule
192are low-level routines for clients who wish to allocate their own
193callout structures.
194.Pp
195The function
196.Fn callout_init
197initializes a callout so it can be passed to
198.Fn callout_stop ,
199.Fn callout_drain ,
200.Fn callout_reset
201or
202.Fn callout_schedule
203without any side effects.
204If the
205.Fa mpsafe
206argument is zero,
207the callout structure is not considered to be
208.Dq multi-processor safe ;
209that is,
210the Giant lock will be acquired before calling the callout function,
211and released when the callout function returns.
212.Pp
213The
214.Fn callout_init_mtx
215function may be used as an alternative to
216.Fn callout_init .
217The parameter
218.Fa mtx
219specifies a mutex that is to be acquired by the callout subsystem
220before calling the callout function, and released when the callout
221function returns.
222The following
223.Fa flags
224may be specified:
225.Bl -tag -width ".Dv CALLOUT_RETURNUNLOCKED"
226.It Dv CALLOUT_RETURNUNLOCKED
227The callout function will release
228.Fa mtx
229itself, so the callout subsystem should not attempt to unlock it
230after the callout function returns.
231.El
232.Pp
233The
234.Fn callout_init_rw
235function serves the need of using rwlocks in conjunction with callouts.
236The function does basically the same as
237.Fn callout_init_mtx
238with the possibility of specifying an extra
239.Fa rw
240argument.
241The usable lock classes are currently limited to mutexes and rwlocks,
242because callout handlers run in softclock swi, so they cannot sleep nor
243acquire sleepable locks like sx or lockmgr.
244The following
245.Fa flags
246may be specified:
247.Bl -tag -width ".Dv CALLOUT_SHAREDLOCK"
248.It Dv CALLOUT_SHAREDLOCK
249The lock is only acquired in read mode when running the callout handler.
250It has no effects when used in conjunction with
251.Fa mtx .
252.El
253.Pp
254The function
255.Fn callout_stop
256cancels a callout if it is currently pending.
257If the callout is pending, then
258.Fn callout_stop
259will return a non-zero value.
260If the callout is not set, has already been serviced or is currently
261being serviced, then zero will be returned.
262If the callout has an associated mutex, then that mutex must be
263held when this function is called.
264.Pp
265The function
266.Fn callout_drain
267is identical to
268.Fn callout_stop
269except that it will wait for the callout to be completed if it is
270already in progress.
271This function MUST NOT be called while holding any
272locks on which the callout might block, or deadlock will result.
273Note that if the callout subsystem has already begun processing this
274callout, then the callout function may be invoked during the execution of
275.Fn callout_drain .
276However, the callout subsystem does guarantee that the callout will be
277fully stopped before
278.Fn callout_drain
279returns.
280.Pp
281The function
282.Fn callout_reset
283first performs the equivalent of
284.Fn callout_stop
285to disestablish the callout, and then establishes a new callout in the
286same manner as
287.Fn timeout .
288If there was already a pending callout and it was rescheduled, then
289.Fn callout_reset
290will return a non-zero value.
291If the callout has an associated mutex, then that mutex must be
292held when this function is called.
293The function
294.Fn callout_schedule
295(re)schedules an existing callout for a new period of time;
296it is equivalent to calling
297.Fn callout_reset
298with the
299.Fa func
300and
301.Fa arg
302parameters extracted from the callout structure (though possibly with
303lower overhead).
304.Pp
305The macros
306.Fn callout_pending ,
307.Fn callout_active
308and
309.Fn callout_deactivate
310provide access to the current state of the callout.
311Careful use of these macros can avoid many of the race conditions
312that are inherent in asynchronous timer facilities; see
313.Sx "Avoiding Race Conditions"
314below for further details.
315The
316.Fn callout_pending
317macro checks whether a callout is
318.Em pending ;
319a callout is considered
320.Em pending
321when a timeout has been set but the time has not yet arrived.
322Note that once the timeout time arrives and the callout subsystem
323starts to process this callout,
324.Fn callout_pending
325will return
326.Dv FALSE
327even though the callout function may not have finished (or even begun)
328executing.
329The
330.Fn callout_active
331macro checks whether a callout is marked as
332.Em active ,
333and the
334.Fn callout_deactivate
335macro clears the callout's
336.Em active
337flag.
338The callout subsystem marks a callout as
339.Em active
340when a timeout is set and it clears the
341.Em active
342flag in
343.Fn callout_stop
344and
345.Fn callout_drain ,
346but it
347.Em does not
348clear it when a callout expires normally via the execution of the
349callout function.
350.Ss "Avoiding Race Conditions"
351The callout subsystem invokes callout functions from its own timer
352context.
353Without some kind of synchronization it is possible that a callout
354function will be invoked concurrently with an attempt to stop or reset
355the callout by another thread.
356In particular, since callout functions typically acquire a mutex as
357their first action, the callout function may have already been invoked,
358but be blocked waiting for that mutex at the time that another thread
359tries to reset or stop the callout.
360.Pp
361The callout subsystem provides a number of mechanisms to address these
362synchronization concerns:
363.Bl -enum -offset indent
364.It
365If the callout has an associated mutex that was specified using the
366.Fn callout_init_mtx
367function (or implicitly specified as the
368.Va Giant
369mutex using
370.Fn callout_init
371with
372.Fa mpsafe
373set to
374.Dv FALSE ) ,
375then this mutex is used to avoid the race conditions.
376The associated mutex must be acquired by the caller before calling
377.Fn callout_stop
378or
379.Fn callout_reset
380and it is guaranteed that the callout will be correctly stopped
381or reset as expected.
382Note that it is still necessary to use
383.Fn callout_drain
384before destroying the callout or its associated mutex.
385.It
386The return value from
387.Fn callout_stop
388and
389.Fn callout_reset
390indicates whether or not the callout was removed.
391If it is known that the callout was set and the callout function has
392not yet executed, then a return value of
393.Dv FALSE
394indicates that the callout function is about to be called.
395For example:
396.Bd -literal -offset indent
397if (sc->sc_flags & SCFLG_CALLOUT_RUNNING) {
398	if (callout_stop(&sc->sc_callout)) {
399		sc->sc_flags &= ~SCFLG_CALLOUT_RUNNING;
400		/* successfully stopped */
401	} else {
402		/*
403		 * callout has expired and callout
404		 * function is about to be executed
405		 */
406	}
407}
408.Ed
409.It
410The
411.Fn callout_pending ,
412.Fn callout_active
413and
414.Fn callout_deactivate
415macros can be used together to work around the race conditions.
416When a callout's timeout is set, the callout subsystem marks the
417callout as both
418.Em active
419and
420.Em pending .
421When the timeout time arrives, the callout subsystem begins processing
422the callout by first clearing the
423.Em pending
424flag.
425It then invokes the callout function without changing the
426.Em active
427flag, and does not clear the
428.Em active
429flag even after the callout function returns.
430The mechanism described here requires the callout function itself to
431clear the
432.Em active
433flag using the
434.Fn callout_deactivate
435macro.
436The
437.Fn callout_stop
438and
439.Fn callout_drain
440functions always clear both the
441.Em active
442and
443.Em pending
444flags before returning.
445.Pp
446The callout function should first check the
447.Em pending
448flag and return without action if
449.Fn callout_pending
450returns
451.Dv TRUE .
452This indicates that the callout was rescheduled using
453.Fn callout_reset
454just before the callout function was invoked.
455If
456.Fn callout_active
457returns
458.Dv FALSE
459then the callout function should also return without action.
460This indicates that the callout has been stopped.
461Finally, the callout function should call
462.Fn callout_deactivate
463to clear the
464.Em active
465flag.
466For example:
467.Bd -literal -offset indent
468mtx_lock(&sc->sc_mtx);
469if (callout_pending(&sc->sc_callout)) {
470	/* callout was reset */
471	mtx_unlock(&sc->sc_mtx);
472	return;
473}
474if (!callout_active(&sc->sc_callout)) {
475	/* callout was stopped */
476	mtx_unlock(&sc->sc_mtx);
477	return;
478}
479callout_deactivate(&sc->sc_callout);
480/* rest of callout function */
481.Ed
482.Pp
483Together with appropriate synchronization, such as the mutex used above,
484this approach permits the
485.Fn callout_stop
486and
487.Fn callout_reset
488functions to be used at any time without races.
489For example:
490.Bd -literal -offset indent
491mtx_lock(&sc->sc_mtx);
492callout_stop(&sc->sc_callout);
493/* The callout is effectively stopped now. */
494.Ed
495.Pp
496If the callout is still pending then these functions operate normally,
497but if processing of the callout has already begun then the tests in
498the callout function cause it to return without further action.
499Synchronization between the callout function and other code ensures that
500stopping or resetting the callout will never be attempted while the
501callout function is past the
502.Fn callout_deactivate
503call.
504.Pp
505The above technique additionally ensures that the
506.Em active
507flag always reflects whether the callout is effectively enabled or
508disabled.
509If
510.Fn callout_active
511returns false, then the callout is effectively disabled, since even if
512the callout subsystem is actually just about to invoke the callout
513function, the callout function will return without action.
514.El
515.Pp
516There is one final race condition that must be considered when a
517callout is being stopped for the last time.
518In this case it may not be safe to let the callout function itself
519detect that the callout was stopped, since it may need to access
520data objects that have already been destroyed or recycled.
521To ensure that the callout is completely finished, a call to
522.Fn callout_drain
523should be used.
524.Sh RETURN VALUES
525The
526.Fn timeout
527function returns a
528.Ft struct callout_handle
529that can be passed to
530.Fn untimeout .
531The
532.Fn callout_stop
533and
534.Fn callout_drain
535functions return non-zero if the callout was still pending when it was
536called or zero otherwise.
537.Sh HISTORY
538The current timeout and untimeout routines are based on the work of
539.An Adam M. Costello
540and
541.An George Varghese ,
542published in a technical report entitled
543.%T "Redesigning the BSD Callout and Timer Facilities"
544and modified slightly for inclusion in
545.Fx
546by
547.An Justin T. Gibbs .
548The original work on the data structures used in this implementation
549was published by
550.An G. Varghese
551and
552.An A. Lauck
553in the paper
554.%T "Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility"
555in the
556.%B "Proceedings of the 11th ACM Annual Symposium on Operating Systems Principles" .
557The current implementation replaces the long standing
558.Bx
559linked list
560callout mechanism which offered O(n) insertion and removal running time
561but did not generate or require handles for untimeout operations.
562