timer.c 42 KB

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