~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/kernel/timer.c

Version: ~ [ linux-5.12-rc6 ] ~ [ linux-5.11.13 ] ~ [ linux-5.10.29 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.111 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.186 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.230 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.266 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.266 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  *  linux/kernel/timer.c
  3  *
  4  *  Kernel internal timers, kernel timekeeping, basic process system calls
  5  *
  6  *  Copyright (C) 1991, 1992  Linus Torvalds
  7  *
  8  *  1997-01-28  Modified by Finn Arne Gangstad to make timers scale better.
  9  *
 10  *  1997-09-10  Updated NTP code according to technical memorandum Jan '96
 11  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
 12  *  1998-12-24  Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
 13  *              serialize accesses to xtime/lost_ticks).
 14  *                              Copyright (C) 1998  Andrea Arcangeli
 15  *  1999-03-10  Improved NTP compatibility by Ulrich Windl
 16  *  2002-05-31  Move sys_sysinfo here and make its locking sane, Robert Love
 17  *  2000-10-05  Implemented scalable SMP per-CPU timer handling.
 18  *                              Copyright (C) 2000, 2001, 2002  Ingo Molnar
 19  *              Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar
 20  */
 21 
 22 #include <linux/kernel_stat.h>
 23 #include <linux/module.h>
 24 #include <linux/interrupt.h>
 25 #include <linux/percpu.h>
 26 #include <linux/init.h>
 27 #include <linux/mm.h>
 28 #include <linux/swap.h>
 29 #include <linux/notifier.h>
 30 #include <linux/thread_info.h>
 31 #include <linux/time.h>
 32 #include <linux/jiffies.h>
 33 #include <linux/cpu.h>
 34 
 35 #include <asm/uaccess.h>
 36 #include <asm/div64.h>
 37 #include <asm/timex.h>
 38 
 39 /*
 40  * per-CPU timer vector definitions:
 41  */
 42 #define TVN_BITS 6
 43 #define TVR_BITS 8
 44 #define TVN_SIZE (1 << TVN_BITS)
 45 #define TVR_SIZE (1 << TVR_BITS)
 46 #define TVN_MASK (TVN_SIZE - 1)
 47 #define TVR_MASK (TVR_SIZE - 1)
 48 
 49 typedef struct tvec_s {
 50         struct list_head vec[TVN_SIZE];
 51 } tvec_t;
 52 
 53 typedef struct tvec_root_s {
 54         struct list_head vec[TVR_SIZE];
 55 } tvec_root_t;
 56 
 57 struct tvec_t_base_s {
 58         spinlock_t lock;
 59         unsigned long timer_jiffies;
 60         struct timer_list *running_timer;
 61         tvec_root_t tv1;
 62         tvec_t tv2;
 63         tvec_t tv3;
 64         tvec_t tv4;
 65         tvec_t tv5;
 66 } ____cacheline_aligned_in_smp;
 67 
 68 typedef struct tvec_t_base_s tvec_base_t;
 69 
 70 static inline void set_running_timer(tvec_base_t *base,
 71                                         struct timer_list *timer)
 72 {
 73 #ifdef CONFIG_SMP
 74         base->running_timer = timer;
 75 #endif
 76 }
 77 
 78 /* Fake initialization */
 79 static DEFINE_PER_CPU(tvec_base_t, tvec_bases) = { SPIN_LOCK_UNLOCKED };
 80 
 81 static void check_timer_failed(struct timer_list *timer)
 82 {
 83         static int whine_count;
 84         if (whine_count < 16) {
 85                 whine_count++;
 86                 printk("Uninitialised timer!\n");
 87                 printk("This is just a warning.  Your computer is OK\n");
 88                 printk("function=0x%p, data=0x%lx\n",
 89                         timer->function, timer->data);
 90                 dump_stack();
 91         }
 92         /*
 93          * Now fix it up
 94          */
 95         spin_lock_init(&timer->lock);
 96         timer->magic = TIMER_MAGIC;
 97 }
 98 
 99 static inline void check_timer(struct timer_list *timer)
100 {
101         if (timer->magic != TIMER_MAGIC)
102                 check_timer_failed(timer);
103 }
104 
105 
106 static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
107 {
108         unsigned long expires = timer->expires;
109         unsigned long idx = expires - base->timer_jiffies;
110         struct list_head *vec;
111 
112         if (idx < TVR_SIZE) {
113                 int i = expires & TVR_MASK;
114                 vec = base->tv1.vec + i;
115         } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
116                 int i = (expires >> TVR_BITS) & TVN_MASK;
117                 vec = base->tv2.vec + i;
118         } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
119                 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
120                 vec = base->tv3.vec + i;
121         } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
122                 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
123                 vec = base->tv4.vec + i;
124         } else if ((signed long) idx < 0) {
125                 /*
126                  * Can happen if you add a timer with expires == jiffies,
127                  * or you set a timer to go off in the past
128                  */
129                 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
130         } else {
131                 int i;
132                 /* If the timeout is larger than 0xffffffff on 64-bit
133                  * architectures then we use the maximum timeout:
134                  */
135                 if (idx > 0xffffffffUL) {
136                         idx = 0xffffffffUL;
137                         expires = idx + base->timer_jiffies;
138                 }
139                 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
140                 vec = base->tv5.vec + i;
141         }
142         /*
143          * Timers are FIFO:
144          */
145         list_add_tail(&timer->entry, vec);
146 }
147 
148 int __mod_timer(struct timer_list *timer, unsigned long expires)
149 {
150         tvec_base_t *old_base, *new_base;
151         unsigned long flags;
152         int ret = 0;
153 
154         BUG_ON(!timer->function);
155 
156         check_timer(timer);
157 
158         spin_lock_irqsave(&timer->lock, flags);
159         new_base = &__get_cpu_var(tvec_bases);
160 repeat:
161         old_base = timer->base;
162 
163         /*
164          * Prevent deadlocks via ordering by old_base < new_base.
165          */
166         if (old_base && (new_base != old_base)) {
167                 if (old_base < new_base) {
168                         spin_lock(&new_base->lock);
169                         spin_lock(&old_base->lock);
170                 } else {
171                         spin_lock(&old_base->lock);
172                         spin_lock(&new_base->lock);
173                 }
174                 /*
175                  * The timer base might have been cancelled while we were
176                  * trying to take the lock(s):
177                  */
178                 if (timer->base != old_base) {
179                         spin_unlock(&new_base->lock);
180                         spin_unlock(&old_base->lock);
181                         goto repeat;
182                 }
183         } else {
184                 spin_lock(&new_base->lock);
185                 if (timer->base != old_base) {
186                         spin_unlock(&new_base->lock);
187                         goto repeat;
188                 }
189         }
190 
191         /*
192          * Delete the previous timeout (if there was any), and install
193          * the new one:
194          */
195         if (old_base) {
196                 list_del(&timer->entry);
197                 ret = 1;
198         }
199         timer->expires = expires;
200         internal_add_timer(new_base, timer);
201         timer->base = new_base;
202 
203         if (old_base && (new_base != old_base))
204                 spin_unlock(&old_base->lock);
205         spin_unlock(&new_base->lock);
206         spin_unlock_irqrestore(&timer->lock, flags);
207 
208         return ret;
209 }
210 
211 EXPORT_SYMBOL(__mod_timer);
212 
213 /***
214  * add_timer_on - start a timer on a particular CPU
215  * @timer: the timer to be added
216  * @cpu: the CPU to start it on
217  *
218  * This is not very scalable on SMP. Double adds are not possible.
219  */
220 void add_timer_on(struct timer_list *timer, int cpu)
221 {
222         tvec_base_t *base = &per_cpu(tvec_bases, cpu);
223         unsigned long flags;
224   
225         BUG_ON(timer_pending(timer) || !timer->function);
226 
227         check_timer(timer);
228 
229         spin_lock_irqsave(&base->lock, flags);
230         internal_add_timer(base, timer);
231         timer->base = base;
232         spin_unlock_irqrestore(&base->lock, flags);
233 }
234 
235 /***
236  * mod_timer - modify a timer's timeout
237  * @timer: the timer to be modified
238  *
239  * mod_timer is a more efficient way to update the expire field of an
240  * active timer (if the timer is inactive it will be activated)
241  *
242  * mod_timer(timer, expires) is equivalent to:
243  *
244  *     del_timer(timer); timer->expires = expires; add_timer(timer);
245  *
246  * Note that if there are multiple unserialized concurrent users of the
247  * same timer, then mod_timer() is the only safe way to modify the timeout,
248  * since add_timer() cannot modify an already running timer.
249  *
250  * The function returns whether it has modified a pending timer or not.
251  * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
252  * active timer returns 1.)
253  */
254 int mod_timer(struct timer_list *timer, unsigned long expires)
255 {
256         BUG_ON(!timer->function);
257 
258         check_timer(timer);
259 
260         /*
261          * This is a common optimization triggered by the
262          * networking code - if the timer is re-modified
263          * to be the same thing then just return:
264          */
265         if (timer->expires == expires && timer_pending(timer))
266                 return 1;
267 
268         return __mod_timer(timer, expires);
269 }
270 
271 EXPORT_SYMBOL(mod_timer);
272 
273 /***
274  * del_timer - deactive a timer.
275  * @timer: the timer to be deactivated
276  *
277  * del_timer() deactivates a timer - this works on both active and inactive
278  * timers.
279  *
280  * The function returns whether it has deactivated a pending timer or not.
281  * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
282  * active timer returns 1.)
283  */
284 int del_timer(struct timer_list *timer)
285 {
286         unsigned long flags;
287         tvec_base_t *base;
288 
289         check_timer(timer);
290 
291 repeat:
292         base = timer->base;
293         if (!base)
294                 return 0;
295         spin_lock_irqsave(&base->lock, flags);
296         if (base != timer->base) {
297                 spin_unlock_irqrestore(&base->lock, flags);
298                 goto repeat;
299         }
300         list_del(&timer->entry);
301         timer->base = NULL;
302         spin_unlock_irqrestore(&base->lock, flags);
303 
304         return 1;
305 }
306 
307 EXPORT_SYMBOL(del_timer);
308 
309 #ifdef CONFIG_SMP
310 /***
311  * del_timer_sync - deactivate a timer and wait for the handler to finish.
312  * @timer: the timer to be deactivated
313  *
314  * This function only differs from del_timer() on SMP: besides deactivating
315  * the timer it also makes sure the handler has finished executing on other
316  * CPUs.
317  *
318  * Synchronization rules: callers must prevent restarting of the timer,
319  * otherwise this function is meaningless. It must not be called from
320  * interrupt contexts. Upon exit the timer is not queued and the handler
321  * is not running on any CPU.
322  *
323  * The function returns whether it has deactivated a pending timer or not.
324  */
325 int del_timer_sync(struct timer_list *timer)
326 {
327         tvec_base_t *base;
328         int i, ret = 0;
329 
330         check_timer(timer);
331 
332 del_again:
333         ret += del_timer(timer);
334 
335         for (i = 0; i < NR_CPUS; i++) {
336                 if (!cpu_online(i))
337                         continue;
338 
339                 base = &per_cpu(tvec_bases, i);
340                 if (base->running_timer == timer) {
341                         while (base->running_timer == timer) {
342                                 cpu_relax();
343                                 preempt_check_resched();
344                         }
345                         break;
346                 }
347         }
348         smp_rmb();
349         if (timer_pending(timer))
350                 goto del_again;
351 
352         return ret;
353 }
354 
355 EXPORT_SYMBOL(del_timer_sync);
356 #endif
357 
358 static int cascade(tvec_base_t *base, tvec_t *tv, int index)
359 {
360         /* cascade all the timers from tv up one level */
361         struct list_head *head, *curr;
362 
363         head = tv->vec + index;
364         curr = head->next;
365         /*
366          * We are removing _all_ timers from the list, so we don't  have to
367          * detach them individually, just clear the list afterwards.
368          */
369         while (curr != head) {
370                 struct timer_list *tmp;
371 
372                 tmp = list_entry(curr, struct timer_list, entry);
373                 BUG_ON(tmp->base != base);
374                 curr = curr->next;
375                 internal_add_timer(base, tmp);
376         }
377         INIT_LIST_HEAD(head);
378 
379         return index;
380 }
381 
382 /***
383  * __run_timers - run all expired timers (if any) on this CPU.
384  * @base: the timer vector to be processed.
385  *
386  * This function cascades all vectors and executes all expired timer
387  * vectors.
388  */
389 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
390 
391 static inline void __run_timers(tvec_base_t *base)
392 {
393         struct timer_list *timer;
394 
395         spin_lock_irq(&base->lock);
396         while (time_after_eq(jiffies, base->timer_jiffies)) {
397                 struct list_head work_list = LIST_HEAD_INIT(work_list);
398                 struct list_head *head = &work_list;
399                 int index = base->timer_jiffies & TVR_MASK;
400  
401                 /*
402                  * Cascade timers:
403                  */
404                 if (!index &&
405                         (!cascade(base, &base->tv2, INDEX(0))) &&
406                                 (!cascade(base, &base->tv3, INDEX(1))) &&
407                                         !cascade(base, &base->tv4, INDEX(2)))
408                         cascade(base, &base->tv5, INDEX(3));
409                 ++base->timer_jiffies; 
410                 list_splice_init(base->tv1.vec + index, &work_list);
411 repeat:
412                 if (!list_empty(head)) {
413                         void (*fn)(unsigned long);
414                         unsigned long data;
415 
416                         timer = list_entry(head->next,struct timer_list,entry);
417                         fn = timer->function;
418                         data = timer->data;
419 
420                         list_del(&timer->entry);
421                         set_running_timer(base, timer);
422                         smp_wmb();
423                         timer->base = NULL;
424                         spin_unlock_irq(&base->lock);
425                         fn(data);
426                         spin_lock_irq(&base->lock);
427                         goto repeat;
428                 }
429         }
430         set_running_timer(base, NULL);
431         spin_unlock_irq(&base->lock);
432 }
433 
434 /******************************************************************/
435 
436 /*
437  * Timekeeping variables
438  */
439 unsigned long tick_usec = TICK_USEC;            /* USER_HZ period (usec) */
440 unsigned long tick_nsec = TICK_NSEC;            /* ACTHZ period (nsec) */
441 
442 /* 
443  * The current time 
444  * wall_to_monotonic is what we need to add to xtime (or xtime corrected 
445  * for sub jiffie times) to get to monotonic time.  Monotonic is pegged at zero
446  * at zero at system boot time, so wall_to_monotonic will be negative,
447  * however, we will ALWAYS keep the tv_nsec part positive so we can use
448  * the usual normalization.
449  */
450 struct timespec xtime __attribute__ ((aligned (16)));
451 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
452 
453 EXPORT_SYMBOL(xtime);
454 
455 /* Don't completely fail for HZ > 500.  */
456 int tickadj = 500/HZ ? : 1;             /* microsecs */
457 
458 
459 /*
460  * phase-lock loop variables
461  */
462 /* TIME_ERROR prevents overwriting the CMOS clock */
463 int time_state = TIME_OK;               /* clock synchronization status */
464 int time_status = STA_UNSYNC;           /* clock status bits            */
465 long time_offset;                       /* time adjustment (us)         */
466 long time_constant = 2;                 /* pll time constant            */
467 long time_tolerance = MAXFREQ;          /* frequency tolerance (ppm)    */
468 long time_precision = 1;                /* clock precision (us)         */
469 long time_maxerror = NTP_PHASE_LIMIT;   /* maximum error (us)           */
470 long time_esterror = NTP_PHASE_LIMIT;   /* estimated error (us)         */
471 long time_phase;                        /* phase offset (scaled us)     */
472 long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
473                                         /* frequency offset (scaled ppm)*/
474 long time_adj;                          /* tick adjust (scaled 1 / HZ)  */
475 long time_reftime;                      /* time at last adjustment (s)  */
476 long time_adjust;
477 long time_next_adjust;
478 
479 /*
480  * this routine handles the overflow of the microsecond field
481  *
482  * The tricky bits of code to handle the accurate clock support
483  * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
484  * They were originally developed for SUN and DEC kernels.
485  * All the kudos should go to Dave for this stuff.
486  *
487  */
488 static void second_overflow(void)
489 {
490     long ltemp;
491 
492     /* Bump the maxerror field */
493     time_maxerror += time_tolerance >> SHIFT_USEC;
494     if ( time_maxerror > NTP_PHASE_LIMIT ) {
495         time_maxerror = NTP_PHASE_LIMIT;
496         time_status |= STA_UNSYNC;
497     }
498 
499     /*
500      * Leap second processing. If in leap-insert state at
501      * the end of the day, the system clock is set back one
502      * second; if in leap-delete state, the system clock is
503      * set ahead one second. The microtime() routine or
504      * external clock driver will insure that reported time
505      * is always monotonic. The ugly divides should be
506      * replaced.
507      */
508     switch (time_state) {
509 
510     case TIME_OK:
511         if (time_status & STA_INS)
512             time_state = TIME_INS;
513         else if (time_status & STA_DEL)
514             time_state = TIME_DEL;
515         break;
516 
517     case TIME_INS:
518         if (xtime.tv_sec % 86400 == 0) {
519             xtime.tv_sec--;
520             wall_to_monotonic.tv_sec++;
521             time_interpolator_update(-NSEC_PER_SEC);
522             time_state = TIME_OOP;
523             clock_was_set();
524             printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
525         }
526         break;
527 
528     case TIME_DEL:
529         if ((xtime.tv_sec + 1) % 86400 == 0) {
530             xtime.tv_sec++;
531             wall_to_monotonic.tv_sec--;
532             time_interpolator_update(NSEC_PER_SEC);
533             time_state = TIME_WAIT;
534             clock_was_set();
535             printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
536         }
537         break;
538 
539     case TIME_OOP:
540         time_state = TIME_WAIT;
541         break;
542 
543     case TIME_WAIT:
544         if (!(time_status & (STA_INS | STA_DEL)))
545             time_state = TIME_OK;
546     }
547 
548     /*
549      * Compute the phase adjustment for the next second. In
550      * PLL mode, the offset is reduced by a fixed factor
551      * times the time constant. In FLL mode the offset is
552      * used directly. In either mode, the maximum phase
553      * adjustment for each second is clamped so as to spread
554      * the adjustment over not more than the number of
555      * seconds between updates.
556      */
557     if (time_offset < 0) {
558         ltemp = -time_offset;
559         if (!(time_status & STA_FLL))
560             ltemp >>= SHIFT_KG + time_constant;
561         if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
562             ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
563         time_offset += ltemp;
564         time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
565     } else {
566         ltemp = time_offset;
567         if (!(time_status & STA_FLL))
568             ltemp >>= SHIFT_KG + time_constant;
569         if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
570             ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
571         time_offset -= ltemp;
572         time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
573     }
574 
575     /*
576      * Compute the frequency estimate and additional phase
577      * adjustment due to frequency error for the next
578      * second. When the PPS signal is engaged, gnaw on the
579      * watchdog counter and update the frequency computed by
580      * the pll and the PPS signal.
581      */
582     pps_valid++;
583     if (pps_valid == PPS_VALID) {       /* PPS signal lost */
584         pps_jitter = MAXTIME;
585         pps_stabil = MAXFREQ;
586         time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
587                          STA_PPSWANDER | STA_PPSERROR);
588     }
589     ltemp = time_freq + pps_freq;
590     if (ltemp < 0)
591         time_adj -= -ltemp >>
592             (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
593     else
594         time_adj += ltemp >>
595             (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
596 
597 #if HZ == 100
598     /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
599      * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
600      */
601     if (time_adj < 0)
602         time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
603     else
604         time_adj += (time_adj >> 2) + (time_adj >> 5);
605 #endif
606 #if HZ == 1000
607     /* Compensate for (HZ==1000) != (1 << SHIFT_HZ).
608      * Add 1.5625% and 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
609      */
610     if (time_adj < 0)
611         time_adj -= (-time_adj >> 6) + (-time_adj >> 7);
612     else
613         time_adj += (time_adj >> 6) + (time_adj >> 7);
614 #endif
615 }
616 
617 /* in the NTP reference this is called "hardclock()" */
618 static void update_wall_time_one_tick(void)
619 {
620         long time_adjust_step, delta_nsec;
621 
622         if ( (time_adjust_step = time_adjust) != 0 ) {
623             /* We are doing an adjtime thing. 
624              *
625              * Prepare time_adjust_step to be within bounds.
626              * Note that a positive time_adjust means we want the clock
627              * to run faster.
628              *
629              * Limit the amount of the step to be in the range
630              * -tickadj .. +tickadj
631              */
632              if (time_adjust > tickadj)
633                 time_adjust_step = tickadj;
634              else if (time_adjust < -tickadj)
635                 time_adjust_step = -tickadj;
636 
637             /* Reduce by this step the amount of time left  */
638             time_adjust -= time_adjust_step;
639         }
640         delta_nsec = tick_nsec + time_adjust_step * 1000;
641         /*
642          * Advance the phase, once it gets to one microsecond, then
643          * advance the tick more.
644          */
645         time_phase += time_adj;
646         if (time_phase <= -FINENSEC) {
647                 long ltemp = -time_phase >> (SHIFT_SCALE - 10);
648                 time_phase += ltemp << (SHIFT_SCALE - 10);
649                 delta_nsec -= ltemp;
650         }
651         else if (time_phase >= FINENSEC) {
652                 long ltemp = time_phase >> (SHIFT_SCALE - 10);
653                 time_phase -= ltemp << (SHIFT_SCALE - 10);
654                 delta_nsec += ltemp;
655         }
656         xtime.tv_nsec += delta_nsec;
657         time_interpolator_update(delta_nsec);
658 
659         /* Changes by adjtime() do not take effect till next tick. */
660         if (time_next_adjust != 0) {
661                 time_adjust = time_next_adjust;
662                 time_next_adjust = 0;
663         }
664 }
665 
666 /*
667  * Using a loop looks inefficient, but "ticks" is
668  * usually just one (we shouldn't be losing ticks,
669  * we're doing this this way mainly for interrupt
670  * latency reasons, not because we think we'll
671  * have lots of lost timer ticks
672  */
673 static void update_wall_time(unsigned long ticks)
674 {
675         do {
676                 ticks--;
677                 update_wall_time_one_tick();
678         } while (ticks);
679 
680         if (xtime.tv_nsec >= 1000000000) {
681             xtime.tv_nsec -= 1000000000;
682             xtime.tv_sec++;
683             time_interpolator_update(NSEC_PER_SEC);
684             second_overflow();
685         }
686 }
687 
688 static inline void do_process_times(struct task_struct *p,
689         unsigned long user, unsigned long system)
690 {
691         unsigned long psecs;
692 
693         psecs = (p->utime += user);
694         psecs += (p->stime += system);
695         if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
696                 /* Send SIGXCPU every second.. */
697                 if (!(psecs % HZ))
698                         send_sig(SIGXCPU, p, 1);
699                 /* and SIGKILL when we go over max.. */
700                 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
701                         send_sig(SIGKILL, p, 1);
702         }
703 }
704 
705 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
706 {
707         unsigned long it_virt = p->it_virt_value;
708 
709         if (it_virt) {
710                 it_virt -= ticks;
711                 if (!it_virt) {
712                         it_virt = p->it_virt_incr;
713                         send_sig(SIGVTALRM, p, 1);
714                 }
715                 p->it_virt_value = it_virt;
716         }
717 }
718 
719 static inline void do_it_prof(struct task_struct *p)
720 {
721         unsigned long it_prof = p->it_prof_value;
722 
723         if (it_prof) {
724                 if (--it_prof == 0) {
725                         it_prof = p->it_prof_incr;
726                         send_sig(SIGPROF, p, 1);
727                 }
728                 p->it_prof_value = it_prof;
729         }
730 }
731 
732 void update_one_process(struct task_struct *p, unsigned long user,
733                         unsigned long system, int cpu)
734 {
735         do_process_times(p, user, system);
736         do_it_virt(p, user);
737         do_it_prof(p);
738 }       
739 
740 /*
741  * Called from the timer interrupt handler to charge one tick to the current 
742  * process.  user_tick is 1 if the tick is user time, 0 for system.
743  */
744 void update_process_times(int user_tick)
745 {
746         struct task_struct *p = current;
747         int cpu = smp_processor_id(), system = user_tick ^ 1;
748 
749         update_one_process(p, user_tick, system, cpu);
750         run_local_timers();
751         scheduler_tick(user_tick, system);
752 }
753 
754 /*
755  * Nr of active tasks - counted in fixed-point numbers
756  */
757 static unsigned long count_active_tasks(void)
758 {
759         return (nr_running() + nr_uninterruptible()) * FIXED_1;
760 }
761 
762 /*
763  * Hmm.. Changed this, as the GNU make sources (load.c) seems to
764  * imply that avenrun[] is the standard name for this kind of thing.
765  * Nothing else seems to be standardized: the fractional size etc
766  * all seem to differ on different machines.
767  *
768  * Requires xtime_lock to access.
769  */
770 unsigned long avenrun[3];
771 
772 /*
773  * calc_load - given tick count, update the avenrun load estimates.
774  * This is called while holding a write_lock on xtime_lock.
775  */
776 static inline void calc_load(unsigned long ticks)
777 {
778         unsigned long active_tasks; /* fixed-point */
779         static int count = LOAD_FREQ;
780 
781         count -= ticks;
782         if (count < 0) {
783                 count += LOAD_FREQ;
784                 active_tasks = count_active_tasks();
785                 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
786                 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
787                 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
788         }
789 }
790 
791 /* jiffies at the most recent update of wall time */
792 unsigned long wall_jiffies = INITIAL_JIFFIES;
793 
794 /*
795  * This read-write spinlock protects us from races in SMP while
796  * playing with xtime and avenrun.
797  */
798 #ifndef ARCH_HAVE_XTIME_LOCK
799 seqlock_t xtime_lock __cacheline_aligned_in_smp = SEQLOCK_UNLOCKED;
800 
801 EXPORT_SYMBOL(xtime_lock);
802 #endif
803 
804 /*
805  * This function runs timers and the timer-tq in bottom half context.
806  */
807 static void run_timer_softirq(struct softirq_action *h)
808 {
809         tvec_base_t *base = &__get_cpu_var(tvec_bases);
810 
811         if (time_after_eq(jiffies, base->timer_jiffies))
812                 __run_timers(base);
813 }
814 
815 /*
816  * Called by the local, per-CPU timer interrupt on SMP.
817  */
818 void run_local_timers(void)
819 {
820         raise_softirq(TIMER_SOFTIRQ);
821 }
822 
823 /*
824  * Called by the timer interrupt. xtime_lock must already be taken
825  * by the timer IRQ!
826  */
827 static inline void update_times(void)
828 {
829         unsigned long ticks;
830 
831         ticks = jiffies - wall_jiffies;
832         if (ticks) {
833                 wall_jiffies += ticks;
834                 update_wall_time(ticks);
835         }
836         calc_load(ticks);
837 }
838   
839 /*
840  * The 64-bit jiffies value is not atomic - you MUST NOT read it
841  * without sampling the sequence number in xtime_lock.
842  * jiffies is defined in the linker script...
843  */
844 
845 void do_timer(struct pt_regs *regs)
846 {
847         jiffies_64++;
848 #ifndef CONFIG_SMP
849         /* SMP process accounting uses the local APIC timer */
850 
851         update_process_times(user_mode(regs));
852 #endif
853         update_times();
854 }
855 
856 #if !defined(__alpha__) && !defined(__ia64__)
857 
858 /*
859  * For backwards compatibility?  This can be done in libc so Alpha
860  * and all newer ports shouldn't need it.
861  */
862 asmlinkage unsigned long sys_alarm(unsigned int seconds)
863 {
864         struct itimerval it_new, it_old;
865         unsigned int oldalarm;
866 
867         it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
868         it_new.it_value.tv_sec = seconds;
869         it_new.it_value.tv_usec = 0;
870         do_setitimer(ITIMER_REAL, &it_new, &it_old);
871         oldalarm = it_old.it_value.tv_sec;
872         /* ehhh.. We can't return 0 if we have an alarm pending.. */
873         /* And we'd better return too much than too little anyway */
874         if (it_old.it_value.tv_usec)
875                 oldalarm++;
876         return oldalarm;
877 }
878 
879 #endif
880 
881 #ifndef __alpha__
882 
883 /*
884  * The Alpha uses getxpid, getxuid, and getxgid instead.  Maybe this
885  * should be moved into arch/i386 instead?
886  */
887 
888 /**
889  * sys_getpid - return the thread group id of the current process
890  *
891  * Note, despite the name, this returns the tgid not the pid.  The tgid and
892  * the pid are identical unless CLONE_THREAD was specified on clone() in
893  * which case the tgid is the same in all threads of the same group.
894  *
895  * This is SMP safe as current->tgid does not change.
896  */
897 asmlinkage long sys_getpid(void)
898 {
899         return current->tgid;
900 }
901 
902 /*
903  * Accessing ->group_leader->real_parent is not SMP-safe, it could
904  * change from under us. However, rather than getting any lock
905  * we can use an optimistic algorithm: get the parent
906  * pid, and go back and check that the parent is still
907  * the same. If it has changed (which is extremely unlikely
908  * indeed), we just try again..
909  *
910  * NOTE! This depends on the fact that even if we _do_
911  * get an old value of "parent", we can happily dereference
912  * the pointer (it was and remains a dereferencable kernel pointer
913  * no matter what): we just can't necessarily trust the result
914  * until we know that the parent pointer is valid.
915  *
916  * NOTE2: ->group_leader never changes from under us.
917  */
918 asmlinkage long sys_getppid(void)
919 {
920         int pid;
921         struct task_struct *me = current;
922         struct task_struct *parent;
923 
924         parent = me->group_leader->real_parent;
925         for (;;) {
926                 pid = parent->tgid;
927 #ifdef CONFIG_SMP
928 {
929                 struct task_struct *old = parent;
930 
931                 /*
932                  * Make sure we read the pid before re-reading the
933                  * parent pointer:
934                  */
935                 rmb();
936                 parent = me->group_leader->real_parent;
937                 if (old != parent)
938                         continue;
939 }
940 #endif
941                 break;
942         }
943         return pid;
944 }
945 
946 asmlinkage long sys_getuid(void)
947 {
948         /* Only we change this so SMP safe */
949         return current->uid;
950 }
951 
952 asmlinkage long sys_geteuid(void)
953 {
954         /* Only we change this so SMP safe */
955         return current->euid;
956 }
957 
958 asmlinkage long sys_getgid(void)
959 {
960         /* Only we change this so SMP safe */
961         return current->gid;
962 }
963 
964 asmlinkage long sys_getegid(void)
965 {
966         /* Only we change this so SMP safe */
967         return  current->egid;
968 }
969 
970 #endif
971 
972 static void process_timeout(unsigned long __data)
973 {
974         wake_up_process((task_t *)__data);
975 }
976 
977 /**
978  * schedule_timeout - sleep until timeout
979  * @timeout: timeout value in jiffies
980  *
981  * Make the current task sleep until @timeout jiffies have
982  * elapsed. The routine will return immediately unless
983  * the current task state has been set (see set_current_state()).
984  *
985  * You can set the task state as follows -
986  *
987  * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
988  * pass before the routine returns. The routine will return 0
989  *
990  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
991  * delivered to the current task. In this case the remaining time
992  * in jiffies will be returned, or 0 if the timer expired in time
993  *
994  * The current task state is guaranteed to be TASK_RUNNING when this
995  * routine returns.
996  *
997  * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
998  * the CPU away without a bound on the timeout. In this case the return
999  * value will be %MAX_SCHEDULE_TIMEOUT.
1000  *
1001  * In all cases the return value is guaranteed to be non-negative.
1002  */
1003 signed long schedule_timeout(signed long timeout)
1004 {
1005         struct timer_list timer;
1006         unsigned long expire;
1007 
1008         switch (timeout)
1009         {
1010         case MAX_SCHEDULE_TIMEOUT:
1011                 /*
1012                  * These two special cases are useful to be comfortable
1013                  * in the caller. Nothing more. We could take
1014                  * MAX_SCHEDULE_TIMEOUT from one of the negative value
1015                  * but I' d like to return a valid offset (>=0) to allow
1016                  * the caller to do everything it want with the retval.
1017                  */
1018                 schedule();
1019                 goto out;
1020         default:
1021                 /*
1022                  * Another bit of PARANOID. Note that the retval will be
1023                  * 0 since no piece of kernel is supposed to do a check
1024                  * for a negative retval of schedule_timeout() (since it
1025                  * should never happens anyway). You just have the printk()
1026                  * that will tell you if something is gone wrong and where.
1027                  */
1028                 if (timeout < 0)
1029                 {
1030                         printk(KERN_ERR "schedule_timeout: wrong timeout "
1031                                "value %lx from %p\n", timeout,
1032                                __builtin_return_address(0));
1033                         current->state = TASK_RUNNING;
1034                         goto out;
1035                 }
1036         }
1037 
1038         expire = timeout + jiffies;
1039 
1040         init_timer(&timer);
1041         timer.expires = expire;
1042         timer.data = (unsigned long) current;
1043         timer.function = process_timeout;
1044 
1045         add_timer(&timer);
1046         schedule();
1047         del_timer_sync(&timer);
1048 
1049         timeout = expire - jiffies;
1050 
1051  out:
1052         return timeout < 0 ? 0 : timeout;
1053 }
1054 
1055 EXPORT_SYMBOL(schedule_timeout);
1056 
1057 /* Thread ID - the internal kernel "pid" */
1058 asmlinkage long sys_gettid(void)
1059 {
1060         return current->pid;
1061 }
1062 
1063 static long nanosleep_restart(struct restart_block *restart)
1064 {
1065         unsigned long expire = restart->arg0, now = jiffies;
1066         struct timespec *rmtp = (struct timespec *) restart->arg1;
1067         long ret;
1068 
1069         /* Did it expire while we handled signals? */
1070         if (!time_after(expire, now))
1071                 return 0;
1072 
1073         current->state = TASK_INTERRUPTIBLE;
1074         expire = schedule_timeout(expire - now);
1075 
1076         ret = 0;
1077         if (expire) {
1078                 struct timespec t;
1079                 jiffies_to_timespec(expire, &t);
1080 
1081                 ret = -ERESTART_RESTARTBLOCK;
1082                 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1083                         ret = -EFAULT;
1084                 /* The 'restart' block is already filled in */
1085         }
1086         return ret;
1087 }
1088 
1089 asmlinkage long sys_nanosleep(struct timespec *rqtp, struct timespec *rmtp)
1090 {
1091         struct timespec t;
1092         unsigned long expire;
1093         long ret;
1094 
1095         if (copy_from_user(&t, rqtp, sizeof(t)))
1096                 return -EFAULT;
1097 
1098         if ((t.tv_nsec >= 1000000000L) || (t.tv_nsec < 0) || (t.tv_sec < 0))
1099                 return -EINVAL;
1100 
1101         expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1102         current->state = TASK_INTERRUPTIBLE;
1103         expire = schedule_timeout(expire);
1104 
1105         ret = 0;
1106         if (expire) {
1107                 struct restart_block *restart;
1108                 jiffies_to_timespec(expire, &t);
1109                 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1110                         return -EFAULT;
1111 
1112                 restart = &current_thread_info()->restart_block;
1113                 restart->fn = nanosleep_restart;
1114                 restart->arg0 = jiffies + expire;
1115                 restart->arg1 = (unsigned long) rmtp;
1116                 ret = -ERESTART_RESTARTBLOCK;
1117         }
1118         return ret;
1119 }
1120 
1121 /*
1122  * sys_sysinfo - fill in sysinfo struct
1123  */ 
1124 asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1125 {
1126         struct sysinfo val;
1127         unsigned long mem_total, sav_total;
1128         unsigned int mem_unit, bitcount;
1129         unsigned long seq;
1130 
1131         memset((char *)&val, 0, sizeof(struct sysinfo));
1132 
1133         do {
1134                 struct timespec tp;
1135                 seq = read_seqbegin(&xtime_lock);
1136 
1137                 /*
1138                  * This is annoying.  The below is the same thing
1139                  * posix_get_clock_monotonic() does, but it wants to
1140                  * take the lock which we want to cover the loads stuff
1141                  * too.
1142                  */
1143 
1144                 do_gettimeofday((struct timeval *)&tp);
1145                 tp.tv_nsec *= NSEC_PER_USEC;
1146                 tp.tv_sec += wall_to_monotonic.tv_sec;
1147                 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1148                 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1149                         tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1150                         tp.tv_sec++;
1151                 }
1152                 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1153 
1154                 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1155                 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1156                 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1157 
1158                 val.procs = nr_threads;
1159         } while (read_seqretry(&xtime_lock, seq));
1160 
1161         si_meminfo(&val);
1162         si_swapinfo(&val);
1163 
1164         /*
1165          * If the sum of all the available memory (i.e. ram + swap)
1166          * is less than can be stored in a 32 bit unsigned long then
1167          * we can be binary compatible with 2.2.x kernels.  If not,
1168          * well, in that case 2.2.x was broken anyways...
1169          *
1170          *  -Erik Andersen <andersee@debian.org>
1171          */
1172 
1173         mem_total = val.totalram + val.totalswap;
1174         if (mem_total < val.totalram || mem_total < val.totalswap)
1175                 goto out;
1176         bitcount = 0;
1177         mem_unit = val.mem_unit;
1178         while (mem_unit > 1) {
1179                 bitcount++;
1180                 mem_unit >>= 1;
1181                 sav_total = mem_total;
1182                 mem_total <<= 1;
1183                 if (mem_total < sav_total)
1184                         goto out;
1185         }
1186 
1187         /*
1188          * If mem_total did not overflow, multiply all memory values by
1189          * val.mem_unit and set it to 1.  This leaves things compatible
1190          * with 2.2.x, and also retains compatibility with earlier 2.4.x
1191          * kernels...
1192          */
1193 
1194         val.mem_unit = 1;
1195         val.totalram <<= bitcount;
1196         val.freeram <<= bitcount;
1197         val.sharedram <<= bitcount;
1198         val.bufferram <<= bitcount;
1199         val.totalswap <<= bitcount;
1200         val.freeswap <<= bitcount;
1201         val.totalhigh <<= bitcount;
1202         val.freehigh <<= bitcount;
1203 
1204  out:
1205         if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1206                 return -EFAULT;
1207 
1208         return 0;
1209 }
1210 
1211 static void __devinit init_timers_cpu(int cpu)
1212 {
1213         int j;
1214         tvec_base_t *base;
1215        
1216         base = &per_cpu(tvec_bases, cpu);
1217         spin_lock_init(&base->lock);
1218         for (j = 0; j < TVN_SIZE; j++) {
1219                 INIT_LIST_HEAD(base->tv5.vec + j);
1220                 INIT_LIST_HEAD(base->tv4.vec + j);
1221                 INIT_LIST_HEAD(base->tv3.vec + j);
1222                 INIT_LIST_HEAD(base->tv2.vec + j);
1223         }
1224         for (j = 0; j < TVR_SIZE; j++)
1225                 INIT_LIST_HEAD(base->tv1.vec + j);
1226 
1227         base->timer_jiffies = jiffies;
1228 }
1229         
1230 static int __devinit timer_cpu_notify(struct notifier_block *self, 
1231                                 unsigned long action, void *hcpu)
1232 {
1233         long cpu = (long)hcpu;
1234         switch(action) {
1235         case CPU_UP_PREPARE:
1236                 init_timers_cpu(cpu);
1237                 break;
1238         default:
1239                 break;
1240         }
1241         return NOTIFY_OK;
1242 }
1243 
1244 static struct notifier_block __devinitdata timers_nb = {
1245         .notifier_call  = timer_cpu_notify,
1246 };
1247 
1248 
1249 void __init init_timers(void)
1250 {
1251         timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1252                                 (void *)(long)smp_processor_id());
1253         register_cpu_notifier(&timers_nb);
1254         open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1255 }
1256 
1257 #ifdef CONFIG_TIME_INTERPOLATION
1258 volatile unsigned long last_nsec_offset;
1259 #ifndef __HAVE_ARCH_CMPXCHG
1260 spinlock_t last_nsec_offset_lock = SPIN_LOCK_UNLOCKED;
1261 #endif
1262 
1263 struct time_interpolator *time_interpolator;
1264 static struct time_interpolator *time_interpolator_list;
1265 static spinlock_t time_interpolator_lock = SPIN_LOCK_UNLOCKED;
1266 
1267 static inline int
1268 is_better_time_interpolator(struct time_interpolator *new)
1269 {
1270         if (!time_interpolator)
1271                 return 1;
1272         return new->frequency > 2*time_interpolator->frequency ||
1273             (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1274 }
1275 
1276 void
1277 register_time_interpolator(struct time_interpolator *ti)
1278 {
1279         spin_lock(&time_interpolator_lock);
1280         write_seqlock_irq(&xtime_lock);
1281         if (is_better_time_interpolator(ti))
1282                 time_interpolator = ti;
1283         write_sequnlock_irq(&xtime_lock);
1284 
1285         ti->next = time_interpolator_list;
1286         time_interpolator_list = ti;
1287         spin_unlock(&time_interpolator_lock);
1288 }
1289 
1290 void
1291 unregister_time_interpolator(struct time_interpolator *ti)
1292 {
1293         struct time_interpolator *curr, **prev;
1294 
1295         spin_lock(&time_interpolator_lock);
1296         prev = &time_interpolator_list;
1297         for (curr = *prev; curr; curr = curr->next) {
1298                 if (curr == ti) {
1299                         *prev = curr->next;
1300                         break;
1301                 }
1302                 prev = &curr->next;
1303         }
1304 
1305         write_seqlock_irq(&xtime_lock);
1306         if (ti == time_interpolator) {
1307                 /* we lost the best time-interpolator: */
1308                 time_interpolator = NULL;
1309                 /* find the next-best interpolator */
1310                 for (curr = time_interpolator_list; curr; curr = curr->next)
1311                         if (is_better_time_interpolator(curr))
1312                                 time_interpolator = curr;
1313         }
1314         write_sequnlock_irq(&xtime_lock);
1315         spin_unlock(&time_interpolator_lock);
1316 }
1317 #endif /* CONFIG_TIME_INTERPOLATION */
1318 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp