source: rtems-libbsd/freebsd/sys/kern/kern_timeout.c @ a9e26f5

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since a9e26f5 was a9e26f5, checked in by Sebastian Huber <sebastian.huber@…>, on 10/28/13 at 15:42:55

TIMEOUT(9): Use timer server for callout_tick()

  • Property mode set to 100644
File size: 26.5 KB
Line 
1#include <machine/rtems-bsd-config.h>
2
3/*-
4 * Copyright (c) 1982, 1986, 1991, 1993
5 *      The Regents of the University of California.  All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 *      From: @(#)kern_clock.c  8.5 (Berkeley) 1/21/94
37 */
38
39#include <sys/cdefs.h>
40__FBSDID("$FreeBSD$");
41
42#include <rtems/bsd/local/opt_kdtrace.h>
43
44#include <rtems/bsd/sys/param.h>
45#include <sys/systm.h>
46#include <sys/bus.h>
47#include <sys/callout.h>
48#include <sys/condvar.h>
49#include <sys/interrupt.h>
50#include <sys/kernel.h>
51#include <sys/ktr.h>
52#include <rtems/bsd/sys/lock.h>
53#include <sys/malloc.h>
54#include <sys/mutex.h>
55#include <sys/proc.h>
56#include <sys/sdt.h>
57#include <sys/sleepqueue.h>
58#include <sys/sysctl.h>
59#include <sys/smp.h>
60
61#ifdef __rtems__
62int ncallout = 16;
63#endif /* __rtems__ */
64SDT_PROVIDER_DEFINE(callout_execute);
65SDT_PROBE_DEFINE(callout_execute, kernel, , callout_start);
66SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_start, 0,
67    "struct callout *");
68SDT_PROBE_DEFINE(callout_execute, kernel, , callout_end);
69SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_end, 0,
70    "struct callout *");
71
72static int avg_depth;
73SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
74    "Average number of items examined per softclock call. Units = 1/1000");
75static int avg_gcalls;
76SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
77    "Average number of Giant callouts made per softclock call. Units = 1/1000");
78static int avg_lockcalls;
79SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
80    "Average number of lock callouts made per softclock call. Units = 1/1000");
81static int avg_mpcalls;
82SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
83    "Average number of MP callouts made per softclock call. Units = 1/1000");
84/*
85 * TODO:
86 *      allocate more timeout table slots when table overflows.
87 */
88int callwheelsize, callwheelbits, callwheelmask;
89
90/*
91 * There is one struct callout_cpu per cpu, holding all relevant
92 * state for the callout processing thread on the individual CPU.
93 * In particular:
94 *      cc_ticks is incremented once per tick in callout_cpu().
95 *      It tracks the global 'ticks' but in a way that the individual
96 *      threads should not worry about races in the order in which
97 *      hardclock() and hardclock_cpu() run on the various CPUs.
98 *      cc_softclock is advanced in callout_cpu() to point to the
99 *      first entry in cc_callwheel that may need handling. In turn,
100 *      a softclock() is scheduled so it can serve the various entries i
101 *      such that cc_softclock <= i <= cc_ticks .
102 *      XXX maybe cc_softclock and cc_ticks should be volatile ?
103 *
104 *      cc_ticks is also used in callout_reset_cpu() to determine
105 *      when the callout should be served.
106 */
107struct callout_cpu {
108        struct mtx              cc_lock;
109        struct callout          *cc_callout;
110        struct callout_tailq    *cc_callwheel;
111        struct callout_list     cc_callfree;
112        struct callout          *cc_next;
113        struct callout          *cc_curr;
114        void                    *cc_cookie;
115        int                     cc_ticks;
116        int                     cc_softticks;
117        int                     cc_cancel;
118        int                     cc_waiting;
119};
120
121#ifdef SMP
122struct callout_cpu cc_cpu[MAXCPU];
123#define CC_CPU(cpu)     (&cc_cpu[(cpu)])
124#define CC_SELF()       CC_CPU(PCPU_GET(cpuid))
125#else
126struct callout_cpu cc_cpu;
127#define CC_CPU(cpu)     &cc_cpu
128#define CC_SELF()       &cc_cpu
129#endif
130#define CC_LOCK(cc)     mtx_lock_spin(&(cc)->cc_lock)
131#define CC_UNLOCK(cc)   mtx_unlock_spin(&(cc)->cc_lock)
132
133static int timeout_cpu;
134
135MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
136
137/**
138 * Locked by cc_lock:
139 *   cc_curr         - If a callout is in progress, it is curr_callout.
140 *                     If curr_callout is non-NULL, threads waiting in
141 *                     callout_drain() will be woken up as soon as the
142 *                     relevant callout completes.
143 *   cc_cancel       - Changing to 1 with both callout_lock and c_lock held
144 *                     guarantees that the current callout will not run.
145 *                     The softclock() function sets this to 0 before it
146 *                     drops callout_lock to acquire c_lock, and it calls
147 *                     the handler only if curr_cancelled is still 0 after
148 *                     c_lock is successfully acquired.
149 *   cc_waiting      - If a thread is waiting in callout_drain(), then
150 *                     callout_wait is nonzero.  Set only when
151 *                     curr_callout is non-NULL.
152 */
153
154/*
155 * kern_timeout_callwheel_alloc() - kernel low level callwheel initialization
156 *
157 *      This code is called very early in the kernel initialization sequence,
158 *      and may be called more then once.
159 */
160#ifdef __rtems__
161static void rtems_bsd_timeout_init(void *);
162
163static void
164rtems_bsd_callout_timer(rtems_id id, void *arg)
165{
166        rtems_status_code sc;
167
168        (void) arg;
169
170        sc = rtems_timer_reset(id);
171        BSD_ASSERT(sc == RTEMS_SUCCESSFUL);
172
173        callout_tick();
174}
175
176static void callout_cpu_init(struct callout_cpu *);
177
178SYSINIT(rtems_bsd_timeout, SI_SUB_VM, SI_ORDER_FIRST, rtems_bsd_timeout_init,
179    NULL);
180
181static void
182rtems_bsd_timeout_init(void *unused)
183#else /* __rtems__ */
184caddr_t
185kern_timeout_callwheel_alloc(caddr_t v)
186#endif /* __rtems__ */
187{
188        struct callout_cpu *cc;
189#ifdef __rtems__
190        rtems_status_code sc;
191        rtems_id id;
192        caddr_t v;
193
194        (void) unused;
195#endif /* __rtems__ */
196
197        timeout_cpu = PCPU_GET(cpuid);
198        cc = CC_CPU(timeout_cpu);
199        /*
200         * Calculate callout wheel size
201         */
202        for (callwheelsize = 1, callwheelbits = 0;
203             callwheelsize < ncallout;
204             callwheelsize <<= 1, ++callwheelbits)
205                ;
206        callwheelmask = callwheelsize - 1;
207
208#ifdef __rtems__
209        v = malloc(ncallout * sizeof(*cc->cc_callout) + callwheelsize
210            * sizeof(*cc->cc_callwheel), M_CALLOUT, M_ZERO | M_WAITOK);
211#endif /* __rtems__ */
212        cc->cc_callout = (struct callout *)v;
213        v = (caddr_t)(cc->cc_callout + ncallout);
214        cc->cc_callwheel = (struct callout_tailq *)v;
215        v = (caddr_t)(cc->cc_callwheel + callwheelsize);
216#ifndef __rtems__
217        return(v);
218#else /* __rtems__ */
219        callout_cpu_init(cc);
220
221        sc = rtems_timer_create(rtems_build_name('_', 'C', 'L', 'O'), &id);
222        BSD_ASSERT(sc == RTEMS_SUCCESSFUL);
223
224        sc = rtems_timer_server_fire_after(id, 1, rtems_bsd_callout_timer, NULL);
225        BSD_ASSERT(sc == RTEMS_SUCCESSFUL);
226#endif /* __rtems__ */
227}
228
229static void
230callout_cpu_init(struct callout_cpu *cc)
231{
232        struct callout *c;
233        int i;
234
235        mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
236        SLIST_INIT(&cc->cc_callfree);
237        for (i = 0; i < callwheelsize; i++) {
238                TAILQ_INIT(&cc->cc_callwheel[i]);
239        }
240        if (cc->cc_callout == NULL)
241                return;
242        for (i = 0; i < ncallout; i++) {
243                c = &cc->cc_callout[i];
244                callout_init(c, 0);
245                c->c_flags = CALLOUT_LOCAL_ALLOC;
246                SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
247        }
248}
249
250#ifndef __rtems__
251/*
252 * kern_timeout_callwheel_init() - initialize previously reserved callwheel
253 *                                 space.
254 *
255 *      This code is called just once, after the space reserved for the
256 *      callout wheel has been finalized.
257 */
258void
259kern_timeout_callwheel_init(void)
260{
261        callout_cpu_init(CC_CPU(timeout_cpu));
262}
263#endif /* __rtems__ */
264
265/*
266 * Start standard softclock thread.
267 */
268void    *softclock_ih;
269
270static void
271start_softclock(void *dummy)
272{
273        struct callout_cpu *cc;
274#ifdef SMP
275        int cpu;
276#endif
277
278        cc = CC_CPU(timeout_cpu);
279        if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
280            INTR_MPSAFE, &softclock_ih))
281                panic("died while creating standard software ithreads");
282        cc->cc_cookie = softclock_ih;
283#ifdef SMP
284        for (cpu = 0; cpu <= mp_maxid; cpu++) {
285                if (cpu == timeout_cpu)
286                        continue;
287                if (CPU_ABSENT(cpu))
288                        continue;
289                cc = CC_CPU(cpu);
290                if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
291                    INTR_MPSAFE, &cc->cc_cookie))
292                        panic("died while creating standard software ithreads");
293                cc->cc_callout = NULL;  /* Only cpu0 handles timeout(). */
294                cc->cc_callwheel = malloc(
295                    sizeof(struct callout_tailq) * callwheelsize, M_CALLOUT,
296                    M_WAITOK);
297                callout_cpu_init(cc);
298        }
299#endif
300}
301
302SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
303
304void
305callout_tick(void)
306{
307        struct callout_cpu *cc;
308        int need_softclock;
309        int bucket;
310
311        /*
312         * Process callouts at a very low cpu priority, so we don't keep the
313         * relatively high clock interrupt priority any longer than necessary.
314         */
315        need_softclock = 0;
316        cc = CC_SELF();
317        mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
318        cc->cc_ticks++;
319        for (; (cc->cc_softticks - cc->cc_ticks) <= 0; cc->cc_softticks++) {
320                bucket = cc->cc_softticks & callwheelmask;
321                if (!TAILQ_EMPTY(&cc->cc_callwheel[bucket])) {
322                        need_softclock = 1;
323                        break;
324                }
325        }
326        mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
327        /*
328         * swi_sched acquires the thread lock, so we don't want to call it
329         * with cc_lock held; incorrect locking order.
330         */
331        if (need_softclock)
332                swi_sched(cc->cc_cookie, 0);
333}
334
335static struct callout_cpu *
336callout_lock(struct callout *c)
337{
338        struct callout_cpu *cc;
339        int cpu;
340
341        for (;;) {
342                cpu = c->c_cpu;
343                cc = CC_CPU(cpu);
344                CC_LOCK(cc);
345                if (cpu == c->c_cpu)
346                        break;
347                CC_UNLOCK(cc);
348        }
349        return (cc);
350}
351
352/*
353 * The callout mechanism is based on the work of Adam M. Costello and
354 * George Varghese, published in a technical report entitled "Redesigning
355 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
356 * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
357 * used in this implementation was published by G. Varghese and T. Lauck in
358 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
359 * the Efficient Implementation of a Timer Facility" in the Proceedings of
360 * the 11th ACM Annual Symposium on Operating Systems Principles,
361 * Austin, Texas Nov 1987.
362 */
363
364/*
365 * Software (low priority) clock interrupt.
366 * Run periodic events from timeout queue.
367 */
368void
369softclock(void *arg)
370{
371        struct callout_cpu *cc;
372        struct callout *c;
373        struct callout_tailq *bucket;
374        int curticks;
375        int steps;      /* #steps since we last allowed interrupts */
376        int depth;
377        int mpcalls;
378        int lockcalls;
379        int gcalls;
380#ifdef DIAGNOSTIC
381        struct bintime bt1, bt2;
382        struct timespec ts2;
383        static uint64_t maxdt = 36893488147419102LL;    /* 2 msec */
384        static timeout_t *lastfunc;
385#endif
386
387#ifndef MAX_SOFTCLOCK_STEPS
388#define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
389#endif /* MAX_SOFTCLOCK_STEPS */
390
391        mpcalls = 0;
392        lockcalls = 0;
393        gcalls = 0;
394        depth = 0;
395        steps = 0;
396        cc = (struct callout_cpu *)arg;
397        CC_LOCK(cc);
398        while (cc->cc_softticks - 1 != cc->cc_ticks) {
399                /*
400                 * cc_softticks may be modified by hard clock, so cache
401                 * it while we work on a given bucket.
402                 */
403                curticks = cc->cc_softticks;
404                cc->cc_softticks++;
405                bucket = &cc->cc_callwheel[curticks & callwheelmask];
406                c = TAILQ_FIRST(bucket);
407                while (c) {
408                        depth++;
409                        if (c->c_time != curticks) {
410                                c = TAILQ_NEXT(c, c_links.tqe);
411                                ++steps;
412                                if (steps >= MAX_SOFTCLOCK_STEPS) {
413                                        cc->cc_next = c;
414                                        /* Give interrupts a chance. */
415                                        CC_UNLOCK(cc);
416                                        ;       /* nothing */
417                                        CC_LOCK(cc);
418                                        c = cc->cc_next;
419                                        steps = 0;
420                                }
421                        } else {
422                                void (*c_func)(void *);
423                                void *c_arg;
424                                struct lock_class *class;
425                                struct lock_object *c_lock;
426                                int c_flags, sharedlock;
427
428                                cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
429                                TAILQ_REMOVE(bucket, c, c_links.tqe);
430                                class = (c->c_lock != NULL) ?
431                                    LOCK_CLASS(c->c_lock) : NULL;
432                                sharedlock = (c->c_flags & CALLOUT_SHAREDLOCK) ?
433                                    0 : 1;
434                                c_lock = c->c_lock;
435                                c_func = c->c_func;
436                                c_arg = c->c_arg;
437                                c_flags = c->c_flags;
438                                if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
439                                        c->c_flags = CALLOUT_LOCAL_ALLOC;
440                                } else {
441                                        c->c_flags =
442                                            (c->c_flags & ~CALLOUT_PENDING);
443                                }
444                                cc->cc_curr = c;
445                                cc->cc_cancel = 0;
446                                CC_UNLOCK(cc);
447                                if (c_lock != NULL) {
448                                        class->lc_lock(c_lock, sharedlock);
449                                        /*
450                                         * The callout may have been cancelled
451                                         * while we switched locks.
452                                         */
453                                        if (cc->cc_cancel) {
454                                                class->lc_unlock(c_lock);
455                                                goto skip;
456                                        }
457                                        /* The callout cannot be stopped now. */
458                                        cc->cc_cancel = 1;
459
460                                        if (c_lock == &Giant.lock_object) {
461                                                gcalls++;
462                                                CTR3(KTR_CALLOUT,
463                                                    "callout %p func %p arg %p",
464                                                    c, c_func, c_arg);
465                                        } else {
466                                                lockcalls++;
467                                                CTR3(KTR_CALLOUT, "callout lock"
468                                                    " %p func %p arg %p",
469                                                    c, c_func, c_arg);
470                                        }
471                                } else {
472                                        mpcalls++;
473                                        CTR3(KTR_CALLOUT,
474                                            "callout mpsafe %p func %p arg %p",
475                                            c, c_func, c_arg);
476                                }
477#ifdef DIAGNOSTIC
478                                binuptime(&bt1);
479#endif
480#ifndef __rtems__
481                                THREAD_NO_SLEEPING();
482                                SDT_PROBE(callout_execute, kernel, ,
483                                    callout_start, c, 0, 0, 0, 0);
484#endif /* __rtems__ */
485                                c_func(c_arg);
486#ifndef __rtems__
487                                SDT_PROBE(callout_execute, kernel, ,
488                                    callout_end, c, 0, 0, 0, 0);
489                                THREAD_SLEEPING_OK();
490#endif /* __rtems__ */
491#ifdef DIAGNOSTIC
492                                binuptime(&bt2);
493                                bintime_sub(&bt2, &bt1);
494                                if (bt2.frac > maxdt) {
495                                        if (lastfunc != c_func ||
496                                            bt2.frac > maxdt * 2) {
497                                                bintime2timespec(&bt2, &ts2);
498                                                printf(
499                        "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
500                                                    c_func, c_arg,
501                                                    (intmax_t)ts2.tv_sec,
502                                                    ts2.tv_nsec);
503                                        }
504                                        maxdt = bt2.frac;
505                                        lastfunc = c_func;
506                                }
507#endif
508                                CTR1(KTR_CALLOUT, "callout %p finished", c);
509                                if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
510                                        class->lc_unlock(c_lock);
511                        skip:
512                                CC_LOCK(cc);
513                                /*
514                                 * If the current callout is locally
515                                 * allocated (from timeout(9))
516                                 * then put it on the freelist.
517                                 *
518                                 * Note: we need to check the cached
519                                 * copy of c_flags because if it was not
520                                 * local, then it's not safe to deref the
521                                 * callout pointer.
522                                 */
523                                if (c_flags & CALLOUT_LOCAL_ALLOC) {
524                                        KASSERT(c->c_flags ==
525                                            CALLOUT_LOCAL_ALLOC,
526                                            ("corrupted callout"));
527                                        c->c_func = NULL;
528                                        SLIST_INSERT_HEAD(&cc->cc_callfree, c,
529                                            c_links.sle);
530                                }
531                                cc->cc_curr = NULL;
532                                if (cc->cc_waiting) {
533                                        /*
534                                         * There is someone waiting
535                                         * for the callout to complete.
536                                         */
537                                        cc->cc_waiting = 0;
538                                        CC_UNLOCK(cc);
539                                        wakeup(&cc->cc_waiting);
540                                        CC_LOCK(cc);
541                                }
542                                steps = 0;
543                                c = cc->cc_next;
544                        }
545                }
546        }
547        avg_depth += (depth * 1000 - avg_depth) >> 8;
548        avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
549        avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
550        avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
551        cc->cc_next = NULL;
552        CC_UNLOCK(cc);
553}
554
555/*
556 * timeout --
557 *      Execute a function after a specified length of time.
558 *
559 * untimeout --
560 *      Cancel previous timeout function call.
561 *
562 * callout_handle_init --
563 *      Initialize a handle so that using it with untimeout is benign.
564 *
565 *      See AT&T BCI Driver Reference Manual for specification.  This
566 *      implementation differs from that one in that although an
567 *      identification value is returned from timeout, the original
568 *      arguments to timeout as well as the identifier are used to
569 *      identify entries for untimeout.
570 */
571struct callout_handle
572timeout(ftn, arg, to_ticks)
573        timeout_t *ftn;
574        void *arg;
575        int to_ticks;
576{
577        struct callout_cpu *cc;
578        struct callout *new;
579        struct callout_handle handle;
580
581        cc = CC_CPU(timeout_cpu);
582        CC_LOCK(cc);
583        /* Fill in the next free callout structure. */
584        new = SLIST_FIRST(&cc->cc_callfree);
585        if (new == NULL)
586                /* XXX Attempt to malloc first */
587                panic("timeout table full");
588        SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
589        callout_reset(new, to_ticks, ftn, arg);
590        handle.callout = new;
591        CC_UNLOCK(cc);
592
593        return (handle);
594}
595
596void
597untimeout(ftn, arg, handle)
598        timeout_t *ftn;
599        void *arg;
600        struct callout_handle handle;
601{
602        struct callout_cpu *cc;
603
604        /*
605         * Check for a handle that was initialized
606         * by callout_handle_init, but never used
607         * for a real timeout.
608         */
609        if (handle.callout == NULL)
610                return;
611
612        cc = callout_lock(handle.callout);
613        if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
614                callout_stop(handle.callout);
615        CC_UNLOCK(cc);
616}
617
618void
619callout_handle_init(struct callout_handle *handle)
620{
621        handle->callout = NULL;
622}
623
624/*
625 * New interface; clients allocate their own callout structures.
626 *
627 * callout_reset() - establish or change a timeout
628 * callout_stop() - disestablish a timeout
629 * callout_init() - initialize a callout structure so that it can
630 *      safely be passed to callout_reset() and callout_stop()
631 *
632 * <sys/callout.h> defines three convenience macros:
633 *
634 * callout_active() - returns truth if callout has not been stopped,
635 *      drained, or deactivated since the last time the callout was
636 *      reset.
637 * callout_pending() - returns truth if callout is still waiting for timeout
638 * callout_deactivate() - marks the callout as having been serviced
639 */
640int
641callout_reset_on(struct callout *c, int to_ticks, void (*ftn)(void *),
642    void *arg, int cpu)
643{
644        struct callout_cpu *cc;
645        int cancelled = 0;
646
647        /*
648         * Don't allow migration of pre-allocated callouts lest they
649         * become unbalanced.
650         */
651        if (c->c_flags & CALLOUT_LOCAL_ALLOC)
652                cpu = c->c_cpu;
653retry:
654        cc = callout_lock(c);
655        if (cc->cc_curr == c) {
656                /*
657                 * We're being asked to reschedule a callout which is
658                 * currently in progress.  If there is a lock then we
659                 * can cancel the callout if it has not really started.
660                 */
661                if (c->c_lock != NULL && !cc->cc_cancel)
662                        cancelled = cc->cc_cancel = 1;
663                if (cc->cc_waiting) {
664                        /*
665                         * Someone has called callout_drain to kill this
666                         * callout.  Don't reschedule.
667                         */
668                        CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
669                            cancelled ? "cancelled" : "failed to cancel",
670                            c, c->c_func, c->c_arg);
671                        CC_UNLOCK(cc);
672                        return (cancelled);
673                }
674        }
675        if (c->c_flags & CALLOUT_PENDING) {
676                if (cc->cc_next == c) {
677                        cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
678                }
679                TAILQ_REMOVE(&cc->cc_callwheel[c->c_time & callwheelmask], c,
680                    c_links.tqe);
681
682                cancelled = 1;
683                c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
684        }
685        /*
686         * If the lock must migrate we have to check the state again as
687         * we can't hold both the new and old locks simultaneously.
688         */
689        if (c->c_cpu != cpu) {
690                c->c_cpu = cpu;
691                CC_UNLOCK(cc);
692                goto retry;
693        }
694
695        if (to_ticks <= 0)
696                to_ticks = 1;
697
698        c->c_arg = arg;
699        c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
700        c->c_func = ftn;
701        c->c_time = cc->cc_ticks + to_ticks;
702        TAILQ_INSERT_TAIL(&cc->cc_callwheel[c->c_time & callwheelmask],
703                          c, c_links.tqe);
704        CTR5(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d",
705            cancelled ? "re" : "", c, c->c_func, c->c_arg, to_ticks);
706        CC_UNLOCK(cc);
707
708        return (cancelled);
709}
710
711/*
712 * Common idioms that can be optimized in the future.
713 */
714int
715callout_schedule_on(struct callout *c, int to_ticks, int cpu)
716{
717        return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
718}
719
720int
721callout_schedule(struct callout *c, int to_ticks)
722{
723        return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
724}
725
726int
727_callout_stop_safe(c, safe)
728        struct  callout *c;
729        int     safe;
730{
731        struct callout_cpu *cc;
732        struct lock_class *class;
733#ifndef __rtems__
734        int use_lock, sq_locked;
735#else /* __rtems__ */
736        int use_lock;
737#endif /* __rtems__ */
738
739        /*
740         * Some old subsystems don't hold Giant while running a callout_stop(),
741         * so just discard this check for the moment.
742         */
743        if (!safe && c->c_lock != NULL) {
744                if (c->c_lock == &Giant.lock_object)
745                        use_lock = mtx_owned(&Giant);
746                else {
747                        use_lock = 1;
748                        class = LOCK_CLASS(c->c_lock);
749                        class->lc_assert(c->c_lock, LA_XLOCKED);
750                }
751        } else
752                use_lock = 0;
753
754#ifndef __rtems__
755        sq_locked = 0;
756again:
757#endif /* __rtems__ */
758        cc = callout_lock(c);
759        /*
760         * If the callout isn't pending, it's not on the queue, so
761         * don't attempt to remove it from the queue.  We can try to
762         * stop it by other means however.
763         */
764        if (!(c->c_flags & CALLOUT_PENDING)) {
765                c->c_flags &= ~CALLOUT_ACTIVE;
766
767                /*
768                 * If it wasn't on the queue and it isn't the current
769                 * callout, then we can't stop it, so just bail.
770                 */
771                if (cc->cc_curr != c) {
772                        CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
773                            c, c->c_func, c->c_arg);
774                        CC_UNLOCK(cc);
775#ifndef __rtems__
776                        if (sq_locked)
777                                sleepq_release(&cc->cc_waiting);
778#endif /* __rtems__ */
779                        return (0);
780                }
781
782                if (safe) {
783                        /*
784                         * The current callout is running (or just
785                         * about to run) and blocking is allowed, so
786                         * just wait for the current invocation to
787                         * finish.
788                         */
789                        while (cc->cc_curr == c) {
790#ifndef __rtems__
791
792                                /*
793                                 * Use direct calls to sleepqueue interface
794                                 * instead of cv/msleep in order to avoid
795                                 * a LOR between cc_lock and sleepqueue
796                                 * chain spinlocks.  This piece of code
797                                 * emulates a msleep_spin() call actually.
798                                 *
799                                 * If we already have the sleepqueue chain
800                                 * locked, then we can safely block.  If we
801                                 * don't already have it locked, however,
802                                 * we have to drop the cc_lock to lock
803                                 * it.  This opens several races, so we
804                                 * restart at the beginning once we have
805                                 * both locks.  If nothing has changed, then
806                                 * we will end up back here with sq_locked
807                                 * set.
808                                 */
809                                if (!sq_locked) {
810                                        CC_UNLOCK(cc);
811                                        sleepq_lock(&cc->cc_waiting);
812                                        sq_locked = 1;
813                                        goto again;
814                                }
815                                cc->cc_waiting = 1;
816                                DROP_GIANT();
817                                CC_UNLOCK(cc);
818                                sleepq_add(&cc->cc_waiting,
819                                    &cc->cc_lock.lock_object, "codrain",
820                                    SLEEPQ_SLEEP, 0);
821                                sleepq_wait(&cc->cc_waiting, 0);
822                                sq_locked = 0;
823
824                                /* Reacquire locks previously released. */
825                                PICKUP_GIANT();
826                                CC_LOCK(cc);
827#else /* __rtems__ */
828                                BSD_ASSERT(0);
829#endif /* __rtems__ */
830                        }
831                } else if (use_lock && !cc->cc_cancel) {
832                        /*
833                         * The current callout is waiting for its
834                         * lock which we hold.  Cancel the callout
835                         * and return.  After our caller drops the
836                         * lock, the callout will be skipped in
837                         * softclock().
838                         */
839                        cc->cc_cancel = 1;
840                        CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
841                            c, c->c_func, c->c_arg);
842                        CC_UNLOCK(cc);
843                        KASSERT(!sq_locked, ("sleepqueue chain locked"));
844                        return (1);
845                }
846                CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
847                    c, c->c_func, c->c_arg);
848                CC_UNLOCK(cc);
849                KASSERT(!sq_locked, ("sleepqueue chain still locked"));
850                return (0);
851        }
852#ifndef __rtems__
853        if (sq_locked)
854                sleepq_release(&cc->cc_waiting);
855#endif /* __rtems__ */
856
857        c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
858
859        if (cc->cc_next == c) {
860                cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
861        }
862        TAILQ_REMOVE(&cc->cc_callwheel[c->c_time & callwheelmask], c,
863            c_links.tqe);
864
865        CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
866            c, c->c_func, c->c_arg);
867
868        if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
869                c->c_func = NULL;
870                SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
871        }
872        CC_UNLOCK(cc);
873        return (1);
874}
875
876void
877callout_init(c, mpsafe)
878        struct  callout *c;
879        int mpsafe;
880{
881        bzero(c, sizeof *c);
882        if (mpsafe) {
883                c->c_lock = NULL;
884                c->c_flags = CALLOUT_RETURNUNLOCKED;
885        } else {
886                c->c_lock = &Giant.lock_object;
887                c->c_flags = 0;
888        }
889        c->c_cpu = timeout_cpu;
890}
891
892void
893_callout_init_lock(c, lock, flags)
894        struct  callout *c;
895        struct  lock_object *lock;
896        int flags;
897{
898        bzero(c, sizeof *c);
899        c->c_lock = lock;
900        KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
901            ("callout_init_lock: bad flags %d", flags));
902        KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
903            ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
904        KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
905            (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
906            __func__));
907        c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
908        c->c_cpu = timeout_cpu;
909}
910
911#ifdef APM_FIXUP_CALLTODO
912/*
913 * Adjust the kernel calltodo timeout list.  This routine is used after
914 * an APM resume to recalculate the calltodo timer list values with the
915 * number of hz's we have been sleeping.  The next hardclock() will detect
916 * that there are fired timers and run softclock() to execute them.
917 *
918 * Please note, I have not done an exhaustive analysis of what code this
919 * might break.  I am motivated to have my select()'s and alarm()'s that
920 * have expired during suspend firing upon resume so that the applications
921 * which set the timer can do the maintanence the timer was for as close
922 * as possible to the originally intended time.  Testing this code for a
923 * week showed that resuming from a suspend resulted in 22 to 25 timers
924 * firing, which seemed independant on whether the suspend was 2 hours or
925 * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
926 */
927void
928adjust_timeout_calltodo(time_change)
929    struct timeval *time_change;
930{
931        register struct callout *p;
932        unsigned long delta_ticks;
933
934        /*
935         * How many ticks were we asleep?
936         * (stolen from tvtohz()).
937         */
938
939        /* Don't do anything */
940        if (time_change->tv_sec < 0)
941                return;
942        else if (time_change->tv_sec <= LONG_MAX / 1000000)
943                delta_ticks = (time_change->tv_sec * 1000000 +
944                               time_change->tv_usec + (tick - 1)) / tick + 1;
945        else if (time_change->tv_sec <= LONG_MAX / hz)
946                delta_ticks = time_change->tv_sec * hz +
947                              (time_change->tv_usec + (tick - 1)) / tick + 1;
948        else
949                delta_ticks = LONG_MAX;
950
951        if (delta_ticks > INT_MAX)
952                delta_ticks = INT_MAX;
953
954        /*
955         * Now rip through the timer calltodo list looking for timers
956         * to expire.
957         */
958
959        /* don't collide with softclock() */
960        CC_LOCK(cc);
961        for (p = calltodo.c_next; p != NULL; p = p->c_next) {
962                p->c_time -= delta_ticks;
963
964                /* Break if the timer had more time on it than delta_ticks */
965                if (p->c_time > 0)
966                        break;
967
968                /* take back the ticks the timer didn't use (p->c_time <= 0) */
969                delta_ticks = -p->c_time;
970        }
971        CC_UNLOCK(cc);
972
973        return;
974}
975#endif /* APM_FIXUP_CALLTODO */
Note: See TracBrowser for help on using the repository browser.