timer.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  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. typedef struct tvec_s {
  58. struct list_head vec[TVN_SIZE];
  59. } tvec_t;
  60. typedef struct tvec_root_s {
  61. struct list_head vec[TVR_SIZE];
  62. } tvec_root_t;
  63. struct tvec_t_base_s {
  64. spinlock_t lock;
  65. struct timer_list *running_timer;
  66. unsigned long timer_jiffies;
  67. tvec_root_t tv1;
  68. tvec_t tv2;
  69. tvec_t tv3;
  70. tvec_t tv4;
  71. tvec_t tv5;
  72. } ____cacheline_aligned_in_smp;
  73. typedef struct tvec_t_base_s tvec_base_t;
  74. tvec_base_t boot_tvec_bases;
  75. EXPORT_SYMBOL(boot_tvec_bases);
  76. static DEFINE_PER_CPU(tvec_base_t *, tvec_bases) = &boot_tvec_bases;
  77. static inline void set_running_timer(tvec_base_t *base,
  78. struct timer_list *timer)
  79. {
  80. #ifdef CONFIG_SMP
  81. base->running_timer = timer;
  82. #endif
  83. }
  84. static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
  85. {
  86. unsigned long expires = timer->expires;
  87. unsigned long idx = expires - base->timer_jiffies;
  88. struct list_head *vec;
  89. if (idx < TVR_SIZE) {
  90. int i = expires & TVR_MASK;
  91. vec = base->tv1.vec + i;
  92. } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
  93. int i = (expires >> TVR_BITS) & TVN_MASK;
  94. vec = base->tv2.vec + i;
  95. } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
  96. int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
  97. vec = base->tv3.vec + i;
  98. } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
  99. int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
  100. vec = base->tv4.vec + i;
  101. } else if ((signed long) idx < 0) {
  102. /*
  103. * Can happen if you add a timer with expires == jiffies,
  104. * or you set a timer to go off in the past
  105. */
  106. vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
  107. } else {
  108. int i;
  109. /* If the timeout is larger than 0xffffffff on 64-bit
  110. * architectures then we use the maximum timeout:
  111. */
  112. if (idx > 0xffffffffUL) {
  113. idx = 0xffffffffUL;
  114. expires = idx + base->timer_jiffies;
  115. }
  116. i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
  117. vec = base->tv5.vec + i;
  118. }
  119. /*
  120. * Timers are FIFO:
  121. */
  122. list_add_tail(&timer->entry, vec);
  123. }
  124. /**
  125. * init_timer - initialize a timer.
  126. * @timer: the timer to be initialized
  127. *
  128. * init_timer() must be done to a timer prior calling *any* of the
  129. * other timer functions.
  130. */
  131. void fastcall init_timer(struct timer_list *timer)
  132. {
  133. timer->entry.next = NULL;
  134. timer->base = __raw_get_cpu_var(tvec_bases);
  135. }
  136. EXPORT_SYMBOL(init_timer);
  137. static inline void detach_timer(struct timer_list *timer,
  138. int clear_pending)
  139. {
  140. struct list_head *entry = &timer->entry;
  141. __list_del(entry->prev, entry->next);
  142. if (clear_pending)
  143. entry->next = NULL;
  144. entry->prev = LIST_POISON2;
  145. }
  146. /*
  147. * We are using hashed locking: holding per_cpu(tvec_bases).lock
  148. * means that all timers which are tied to this base via timer->base are
  149. * locked, and the base itself is locked too.
  150. *
  151. * So __run_timers/migrate_timers can safely modify all timers which could
  152. * be found on ->tvX lists.
  153. *
  154. * When the timer's base is locked, and the timer removed from list, it is
  155. * possible to set timer->base = NULL and drop the lock: the timer remains
  156. * locked.
  157. */
  158. static tvec_base_t *lock_timer_base(struct timer_list *timer,
  159. unsigned long *flags)
  160. __acquires(timer->base->lock)
  161. {
  162. tvec_base_t *base;
  163. for (;;) {
  164. base = timer->base;
  165. if (likely(base != NULL)) {
  166. spin_lock_irqsave(&base->lock, *flags);
  167. if (likely(base == timer->base))
  168. return base;
  169. /* The timer has migrated to another CPU */
  170. spin_unlock_irqrestore(&base->lock, *flags);
  171. }
  172. cpu_relax();
  173. }
  174. }
  175. int __mod_timer(struct timer_list *timer, unsigned long expires)
  176. {
  177. tvec_base_t *base, *new_base;
  178. unsigned long flags;
  179. int ret = 0;
  180. BUG_ON(!timer->function);
  181. base = lock_timer_base(timer, &flags);
  182. if (timer_pending(timer)) {
  183. detach_timer(timer, 0);
  184. ret = 1;
  185. }
  186. new_base = __get_cpu_var(tvec_bases);
  187. if (base != new_base) {
  188. /*
  189. * We are trying to schedule the timer on the local CPU.
  190. * However we can't change timer's base while it is running,
  191. * otherwise del_timer_sync() can't detect that the timer's
  192. * handler yet has not finished. This also guarantees that
  193. * the timer is serialized wrt itself.
  194. */
  195. if (likely(base->running_timer != timer)) {
  196. /* See the comment in lock_timer_base() */
  197. timer->base = NULL;
  198. spin_unlock(&base->lock);
  199. base = new_base;
  200. spin_lock(&base->lock);
  201. timer->base = base;
  202. }
  203. }
  204. timer->expires = expires;
  205. internal_add_timer(base, timer);
  206. spin_unlock_irqrestore(&base->lock, flags);
  207. return ret;
  208. }
  209. EXPORT_SYMBOL(__mod_timer);
  210. /**
  211. * add_timer_on - start a timer on a particular CPU
  212. * @timer: the timer to be added
  213. * @cpu: the CPU to start it on
  214. *
  215. * This is not very scalable on SMP. Double adds are not possible.
  216. */
  217. void add_timer_on(struct timer_list *timer, int cpu)
  218. {
  219. tvec_base_t *base = per_cpu(tvec_bases, cpu);
  220. unsigned long flags;
  221. BUG_ON(timer_pending(timer) || !timer->function);
  222. spin_lock_irqsave(&base->lock, flags);
  223. timer->base = base;
  224. internal_add_timer(base, timer);
  225. spin_unlock_irqrestore(&base->lock, flags);
  226. }
  227. /**
  228. * mod_timer - modify a timer's timeout
  229. * @timer: the timer to be modified
  230. * @expires: new timeout in jiffies
  231. *
  232. * mod_timer is a more efficient way to update the expire field of an
  233. * active timer (if the timer is inactive it will be activated)
  234. *
  235. * mod_timer(timer, expires) is equivalent to:
  236. *
  237. * del_timer(timer); timer->expires = expires; add_timer(timer);
  238. *
  239. * Note that if there are multiple unserialized concurrent users of the
  240. * same timer, then mod_timer() is the only safe way to modify the timeout,
  241. * since add_timer() cannot modify an already running timer.
  242. *
  243. * The function returns whether it has modified a pending timer or not.
  244. * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
  245. * active timer returns 1.)
  246. */
  247. int mod_timer(struct timer_list *timer, unsigned long expires)
  248. {
  249. BUG_ON(!timer->function);
  250. /*
  251. * This is a common optimization triggered by the
  252. * networking code - if the timer is re-modified
  253. * to be the same thing then just return:
  254. */
  255. if (timer->expires == expires && timer_pending(timer))
  256. return 1;
  257. return __mod_timer(timer, expires);
  258. }
  259. EXPORT_SYMBOL(mod_timer);
  260. /**
  261. * del_timer - deactive a timer.
  262. * @timer: the timer to be deactivated
  263. *
  264. * del_timer() deactivates a timer - this works on both active and inactive
  265. * timers.
  266. *
  267. * The function returns whether it has deactivated a pending timer or not.
  268. * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
  269. * active timer returns 1.)
  270. */
  271. int del_timer(struct timer_list *timer)
  272. {
  273. tvec_base_t *base;
  274. unsigned long flags;
  275. int ret = 0;
  276. if (timer_pending(timer)) {
  277. base = lock_timer_base(timer, &flags);
  278. if (timer_pending(timer)) {
  279. detach_timer(timer, 1);
  280. ret = 1;
  281. }
  282. spin_unlock_irqrestore(&base->lock, flags);
  283. }
  284. return ret;
  285. }
  286. EXPORT_SYMBOL(del_timer);
  287. #ifdef CONFIG_SMP
  288. /**
  289. * try_to_del_timer_sync - Try to deactivate a timer
  290. * @timer: timer do del
  291. *
  292. * This function tries to deactivate a timer. Upon successful (ret >= 0)
  293. * exit the timer is not queued and the handler is not running on any CPU.
  294. *
  295. * It must not be called from interrupt contexts.
  296. */
  297. int try_to_del_timer_sync(struct timer_list *timer)
  298. {
  299. tvec_base_t *base;
  300. unsigned long flags;
  301. int ret = -1;
  302. base = lock_timer_base(timer, &flags);
  303. if (base->running_timer == timer)
  304. goto out;
  305. ret = 0;
  306. if (timer_pending(timer)) {
  307. detach_timer(timer, 1);
  308. ret = 1;
  309. }
  310. out:
  311. spin_unlock_irqrestore(&base->lock, flags);
  312. return ret;
  313. }
  314. /**
  315. * del_timer_sync - deactivate a timer and wait for the handler to finish.
  316. * @timer: the timer to be deactivated
  317. *
  318. * This function only differs from del_timer() on SMP: besides deactivating
  319. * the timer it also makes sure the handler has finished executing on other
  320. * CPUs.
  321. *
  322. * Synchronization rules: callers must prevent restarting of the timer,
  323. * otherwise this function is meaningless. It must not be called from
  324. * interrupt contexts. The caller must not hold locks which would prevent
  325. * completion of the timer's handler. The timer's handler must not call
  326. * add_timer_on(). Upon exit the timer is not queued and the handler is
  327. * not running on any CPU.
  328. *
  329. * The function returns whether it has deactivated a pending timer or not.
  330. */
  331. int del_timer_sync(struct timer_list *timer)
  332. {
  333. for (;;) {
  334. int ret = try_to_del_timer_sync(timer);
  335. if (ret >= 0)
  336. return ret;
  337. cpu_relax();
  338. }
  339. }
  340. EXPORT_SYMBOL(del_timer_sync);
  341. #endif
  342. static int cascade(tvec_base_t *base, tvec_t *tv, int index)
  343. {
  344. /* cascade all the timers from tv up one level */
  345. struct timer_list *timer, *tmp;
  346. struct list_head tv_list;
  347. list_replace_init(tv->vec + index, &tv_list);
  348. /*
  349. * We are removing _all_ timers from the list, so we
  350. * don't have to detach them individually.
  351. */
  352. list_for_each_entry_safe(timer, tmp, &tv_list, entry) {
  353. BUG_ON(timer->base != base);
  354. internal_add_timer(base, timer);
  355. }
  356. return index;
  357. }
  358. #define INDEX(N) ((base->timer_jiffies >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
  359. /**
  360. * __run_timers - run all expired timers (if any) on this CPU.
  361. * @base: the timer vector to be processed.
  362. *
  363. * This function cascades all vectors and executes all expired timer
  364. * vectors.
  365. */
  366. static inline void __run_timers(tvec_base_t *base)
  367. {
  368. struct timer_list *timer;
  369. spin_lock_irq(&base->lock);
  370. while (time_after_eq(jiffies, base->timer_jiffies)) {
  371. struct list_head work_list;
  372. struct list_head *head = &work_list;
  373. int index = base->timer_jiffies & TVR_MASK;
  374. /*
  375. * Cascade timers:
  376. */
  377. if (!index &&
  378. (!cascade(base, &base->tv2, INDEX(0))) &&
  379. (!cascade(base, &base->tv3, INDEX(1))) &&
  380. !cascade(base, &base->tv4, INDEX(2)))
  381. cascade(base, &base->tv5, INDEX(3));
  382. ++base->timer_jiffies;
  383. list_replace_init(base->tv1.vec + index, &work_list);
  384. while (!list_empty(head)) {
  385. void (*fn)(unsigned long);
  386. unsigned long data;
  387. timer = list_entry(head->next,struct timer_list,entry);
  388. fn = timer->function;
  389. data = timer->data;
  390. set_running_timer(base, timer);
  391. detach_timer(timer, 1);
  392. spin_unlock_irq(&base->lock);
  393. {
  394. int preempt_count = preempt_count();
  395. fn(data);
  396. if (preempt_count != preempt_count()) {
  397. printk(KERN_WARNING "huh, entered %p "
  398. "with preempt_count %08x, exited"
  399. " with %08x?\n",
  400. fn, preempt_count,
  401. preempt_count());
  402. BUG();
  403. }
  404. }
  405. spin_lock_irq(&base->lock);
  406. }
  407. }
  408. set_running_timer(base, NULL);
  409. spin_unlock_irq(&base->lock);
  410. }
  411. #ifdef CONFIG_NO_IDLE_HZ
  412. /*
  413. * Find out when the next timer event is due to happen. This
  414. * is used on S/390 to stop all activity when a cpus is idle.
  415. * This functions needs to be called disabled.
  416. */
  417. unsigned long next_timer_interrupt(void)
  418. {
  419. tvec_base_t *base;
  420. struct list_head *list;
  421. struct timer_list *nte;
  422. unsigned long expires;
  423. unsigned long hr_expires = MAX_JIFFY_OFFSET;
  424. ktime_t hr_delta;
  425. tvec_t *varray[4];
  426. int i, j;
  427. hr_delta = hrtimer_get_next_event();
  428. if (hr_delta.tv64 != KTIME_MAX) {
  429. struct timespec tsdelta;
  430. tsdelta = ktime_to_timespec(hr_delta);
  431. hr_expires = timespec_to_jiffies(&tsdelta);
  432. if (hr_expires < 3)
  433. return hr_expires + jiffies;
  434. }
  435. hr_expires += jiffies;
  436. base = __get_cpu_var(tvec_bases);
  437. spin_lock(&base->lock);
  438. expires = base->timer_jiffies + (LONG_MAX >> 1);
  439. list = NULL;
  440. /* Look for timer events in tv1. */
  441. j = base->timer_jiffies & TVR_MASK;
  442. do {
  443. list_for_each_entry(nte, base->tv1.vec + j, entry) {
  444. expires = nte->expires;
  445. if (j < (base->timer_jiffies & TVR_MASK))
  446. list = base->tv2.vec + (INDEX(0));
  447. goto found;
  448. }
  449. j = (j + 1) & TVR_MASK;
  450. } while (j != (base->timer_jiffies & TVR_MASK));
  451. /* Check tv2-tv5. */
  452. varray[0] = &base->tv2;
  453. varray[1] = &base->tv3;
  454. varray[2] = &base->tv4;
  455. varray[3] = &base->tv5;
  456. for (i = 0; i < 4; i++) {
  457. j = INDEX(i);
  458. do {
  459. if (list_empty(varray[i]->vec + j)) {
  460. j = (j + 1) & TVN_MASK;
  461. continue;
  462. }
  463. list_for_each_entry(nte, varray[i]->vec + j, entry)
  464. if (time_before(nte->expires, expires))
  465. expires = nte->expires;
  466. if (j < (INDEX(i)) && i < 3)
  467. list = varray[i + 1]->vec + (INDEX(i + 1));
  468. goto found;
  469. } while (j != (INDEX(i)));
  470. }
  471. found:
  472. if (list) {
  473. /*
  474. * The search wrapped. We need to look at the next list
  475. * from next tv element that would cascade into tv element
  476. * where we found the timer element.
  477. */
  478. list_for_each_entry(nte, list, entry) {
  479. if (time_before(nte->expires, expires))
  480. expires = nte->expires;
  481. }
  482. }
  483. spin_unlock(&base->lock);
  484. /*
  485. * It can happen that other CPUs service timer IRQs and increment
  486. * jiffies, but we have not yet got a local timer tick to process
  487. * the timer wheels. In that case, the expiry time can be before
  488. * jiffies, but since the high-resolution timer here is relative to
  489. * jiffies, the default expression when high-resolution timers are
  490. * not active,
  491. *
  492. * time_before(MAX_JIFFY_OFFSET + jiffies, expires)
  493. *
  494. * would falsely evaluate to true. If that is the case, just
  495. * return jiffies so that we can immediately fire the local timer
  496. */
  497. if (time_before(expires, jiffies))
  498. return jiffies;
  499. if (time_before(hr_expires, expires))
  500. return hr_expires;
  501. return expires;
  502. }
  503. #endif
  504. /******************************************************************/
  505. /*
  506. * Timekeeping variables
  507. */
  508. unsigned long tick_usec = TICK_USEC; /* USER_HZ period (usec) */
  509. unsigned long tick_nsec = TICK_NSEC; /* ACTHZ period (nsec) */
  510. /*
  511. * The current time
  512. * wall_to_monotonic is what we need to add to xtime (or xtime corrected
  513. * for sub jiffie times) to get to monotonic time. Monotonic is pegged
  514. * at zero at system boot time, so wall_to_monotonic will be negative,
  515. * however, we will ALWAYS keep the tv_nsec part positive so we can use
  516. * the usual normalization.
  517. */
  518. struct timespec xtime __attribute__ ((aligned (16)));
  519. struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
  520. EXPORT_SYMBOL(xtime);
  521. /* Don't completely fail for HZ > 500. */
  522. int tickadj = 500/HZ ? : 1; /* microsecs */
  523. /*
  524. * phase-lock loop variables
  525. */
  526. /* TIME_ERROR prevents overwriting the CMOS clock */
  527. int time_state = TIME_OK; /* clock synchronization status */
  528. int time_status = STA_UNSYNC; /* clock status bits */
  529. long time_offset; /* time adjustment (us) */
  530. long time_constant = 2; /* pll time constant */
  531. long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
  532. long time_precision = 1; /* clock precision (us) */
  533. long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
  534. long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
  535. long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
  536. /* frequency offset (scaled ppm)*/
  537. static long time_adj; /* tick adjust (scaled 1 / HZ) */
  538. long time_reftime; /* time at last adjustment (s) */
  539. long time_adjust;
  540. long time_next_adjust;
  541. /*
  542. * this routine handles the overflow of the microsecond field
  543. *
  544. * The tricky bits of code to handle the accurate clock support
  545. * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
  546. * They were originally developed for SUN and DEC kernels.
  547. * All the kudos should go to Dave for this stuff.
  548. *
  549. */
  550. static void second_overflow(void)
  551. {
  552. long ltemp;
  553. /* Bump the maxerror field */
  554. time_maxerror += time_tolerance >> SHIFT_USEC;
  555. if (time_maxerror > NTP_PHASE_LIMIT) {
  556. time_maxerror = NTP_PHASE_LIMIT;
  557. time_status |= STA_UNSYNC;
  558. }
  559. /*
  560. * Leap second processing. If in leap-insert state at the end of the
  561. * day, the system clock is set back one second; if in leap-delete
  562. * state, the system clock is set ahead one second. The microtime()
  563. * routine or external clock driver will insure that reported time is
  564. * always monotonic. The ugly divides should be replaced.
  565. */
  566. switch (time_state) {
  567. case TIME_OK:
  568. if (time_status & STA_INS)
  569. time_state = TIME_INS;
  570. else if (time_status & STA_DEL)
  571. time_state = TIME_DEL;
  572. break;
  573. case TIME_INS:
  574. if (xtime.tv_sec % 86400 == 0) {
  575. xtime.tv_sec--;
  576. wall_to_monotonic.tv_sec++;
  577. /*
  578. * The timer interpolator will make time change
  579. * gradually instead of an immediate jump by one second
  580. */
  581. time_interpolator_update(-NSEC_PER_SEC);
  582. time_state = TIME_OOP;
  583. clock_was_set();
  584. printk(KERN_NOTICE "Clock: inserting leap second "
  585. "23:59:60 UTC\n");
  586. }
  587. break;
  588. case TIME_DEL:
  589. if ((xtime.tv_sec + 1) % 86400 == 0) {
  590. xtime.tv_sec++;
  591. wall_to_monotonic.tv_sec--;
  592. /*
  593. * Use of time interpolator for a gradual change of
  594. * time
  595. */
  596. time_interpolator_update(NSEC_PER_SEC);
  597. time_state = TIME_WAIT;
  598. clock_was_set();
  599. printk(KERN_NOTICE "Clock: deleting leap second "
  600. "23:59:59 UTC\n");
  601. }
  602. break;
  603. case TIME_OOP:
  604. time_state = TIME_WAIT;
  605. break;
  606. case TIME_WAIT:
  607. if (!(time_status & (STA_INS | STA_DEL)))
  608. time_state = TIME_OK;
  609. }
  610. /*
  611. * Compute the phase adjustment for the next second. In PLL mode, the
  612. * offset is reduced by a fixed factor times the time constant. In FLL
  613. * mode the offset is used directly. In either mode, the maximum phase
  614. * adjustment for each second is clamped so as to spread the adjustment
  615. * over not more than the number of seconds between updates.
  616. */
  617. ltemp = time_offset;
  618. if (!(time_status & STA_FLL))
  619. ltemp = shift_right(ltemp, SHIFT_KG + time_constant);
  620. ltemp = min(ltemp, (MAXPHASE / MINSEC) << SHIFT_UPDATE);
  621. ltemp = max(ltemp, -(MAXPHASE / MINSEC) << SHIFT_UPDATE);
  622. time_offset -= ltemp;
  623. time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
  624. /*
  625. * Compute the frequency estimate and additional phase adjustment due
  626. * to frequency error for the next second.
  627. */
  628. ltemp = time_freq;
  629. time_adj += shift_right(ltemp,(SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE));
  630. #if HZ == 100
  631. /*
  632. * Compensate for (HZ==100) != (1 << SHIFT_HZ). Add 25% and 3.125% to
  633. * get 128.125; => only 0.125% error (p. 14)
  634. */
  635. time_adj += shift_right(time_adj, 2) + shift_right(time_adj, 5);
  636. #endif
  637. #if HZ == 250
  638. /*
  639. * Compensate for (HZ==250) != (1 << SHIFT_HZ). Add 1.5625% and
  640. * 0.78125% to get 255.85938; => only 0.05% error (p. 14)
  641. */
  642. time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
  643. #endif
  644. #if HZ == 1000
  645. /*
  646. * Compensate for (HZ==1000) != (1 << SHIFT_HZ). Add 1.5625% and
  647. * 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
  648. */
  649. time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
  650. #endif
  651. }
  652. /*
  653. * Returns how many microseconds we need to add to xtime this tick
  654. * in doing an adjustment requested with adjtime.
  655. */
  656. static long adjtime_adjustment(void)
  657. {
  658. long time_adjust_step;
  659. time_adjust_step = time_adjust;
  660. if (time_adjust_step) {
  661. /*
  662. * We are doing an adjtime thing. Prepare time_adjust_step to
  663. * be within bounds. Note that a positive time_adjust means we
  664. * want the clock to run faster.
  665. *
  666. * Limit the amount of the step to be in the range
  667. * -tickadj .. +tickadj
  668. */
  669. time_adjust_step = min(time_adjust_step, (long)tickadj);
  670. time_adjust_step = max(time_adjust_step, (long)-tickadj);
  671. }
  672. return time_adjust_step;
  673. }
  674. /* in the NTP reference this is called "hardclock()" */
  675. static void update_ntp_one_tick(void)
  676. {
  677. long time_adjust_step;
  678. time_adjust_step = adjtime_adjustment();
  679. if (time_adjust_step)
  680. /* Reduce by this step the amount of time left */
  681. time_adjust -= time_adjust_step;
  682. /* Changes by adjtime() do not take effect till next tick. */
  683. if (time_next_adjust != 0) {
  684. time_adjust = time_next_adjust;
  685. time_next_adjust = 0;
  686. }
  687. }
  688. /*
  689. * Return how long ticks are at the moment, that is, how much time
  690. * update_wall_time_one_tick will add to xtime next time we call it
  691. * (assuming no calls to do_adjtimex in the meantime).
  692. * The return value is in fixed-point nanoseconds shifted by the
  693. * specified number of bits to the right of the binary point.
  694. * This function has no side-effects.
  695. */
  696. u64 current_tick_length(void)
  697. {
  698. long delta_nsec;
  699. u64 ret;
  700. /* calculate the finest interval NTP will allow.
  701. * ie: nanosecond value shifted by (SHIFT_SCALE - 10)
  702. */
  703. delta_nsec = tick_nsec + adjtime_adjustment() * 1000;
  704. ret = (u64)delta_nsec << TICK_LENGTH_SHIFT;
  705. ret += (s64)time_adj << (TICK_LENGTH_SHIFT - (SHIFT_SCALE - 10));
  706. return ret;
  707. }
  708. /* XXX - all of this timekeeping code should be later moved to time.c */
  709. #include <linux/clocksource.h>
  710. static struct clocksource *clock; /* pointer to current clocksource */
  711. #ifdef CONFIG_GENERIC_TIME
  712. /**
  713. * __get_nsec_offset - Returns nanoseconds since last call to periodic_hook
  714. *
  715. * private function, must hold xtime_lock lock when being
  716. * called. Returns the number of nanoseconds since the
  717. * last call to update_wall_time() (adjusted by NTP scaling)
  718. */
  719. static inline s64 __get_nsec_offset(void)
  720. {
  721. cycle_t cycle_now, cycle_delta;
  722. s64 ns_offset;
  723. /* read clocksource: */
  724. cycle_now = clocksource_read(clock);
  725. /* calculate the delta since the last update_wall_time: */
  726. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  727. /* convert to nanoseconds: */
  728. ns_offset = cyc2ns(clock, cycle_delta);
  729. return ns_offset;
  730. }
  731. /**
  732. * __get_realtime_clock_ts - Returns the time of day in a timespec
  733. * @ts: pointer to the timespec to be set
  734. *
  735. * Returns the time of day in a timespec. Used by
  736. * do_gettimeofday() and get_realtime_clock_ts().
  737. */
  738. static inline void __get_realtime_clock_ts(struct timespec *ts)
  739. {
  740. unsigned long seq;
  741. s64 nsecs;
  742. do {
  743. seq = read_seqbegin(&xtime_lock);
  744. *ts = xtime;
  745. nsecs = __get_nsec_offset();
  746. } while (read_seqretry(&xtime_lock, seq));
  747. timespec_add_ns(ts, nsecs);
  748. }
  749. /**
  750. * getnstimeofday - Returns the time of day in a timespec
  751. * @ts: pointer to the timespec to be set
  752. *
  753. * Returns the time of day in a timespec.
  754. */
  755. void getnstimeofday(struct timespec *ts)
  756. {
  757. __get_realtime_clock_ts(ts);
  758. }
  759. EXPORT_SYMBOL(getnstimeofday);
  760. /**
  761. * do_gettimeofday - Returns the time of day in a timeval
  762. * @tv: pointer to the timeval to be set
  763. *
  764. * NOTE: Users should be converted to using get_realtime_clock_ts()
  765. */
  766. void do_gettimeofday(struct timeval *tv)
  767. {
  768. struct timespec now;
  769. __get_realtime_clock_ts(&now);
  770. tv->tv_sec = now.tv_sec;
  771. tv->tv_usec = now.tv_nsec/1000;
  772. }
  773. EXPORT_SYMBOL(do_gettimeofday);
  774. /**
  775. * do_settimeofday - Sets the time of day
  776. * @tv: pointer to the timespec variable containing the new time
  777. *
  778. * Sets the time of day to the new time and update NTP and notify hrtimers
  779. */
  780. int do_settimeofday(struct timespec *tv)
  781. {
  782. unsigned long flags;
  783. time_t wtm_sec, sec = tv->tv_sec;
  784. long wtm_nsec, nsec = tv->tv_nsec;
  785. if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
  786. return -EINVAL;
  787. write_seqlock_irqsave(&xtime_lock, flags);
  788. nsec -= __get_nsec_offset();
  789. wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
  790. wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
  791. set_normalized_timespec(&xtime, sec, nsec);
  792. set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
  793. clock->error = 0;
  794. ntp_clear();
  795. write_sequnlock_irqrestore(&xtime_lock, flags);
  796. /* signal hrtimers about time change */
  797. clock_was_set();
  798. return 0;
  799. }
  800. EXPORT_SYMBOL(do_settimeofday);
  801. /**
  802. * change_clocksource - Swaps clocksources if a new one is available
  803. *
  804. * Accumulates current time interval and initializes new clocksource
  805. */
  806. static int change_clocksource(void)
  807. {
  808. struct clocksource *new;
  809. cycle_t now;
  810. u64 nsec;
  811. new = clocksource_get_next();
  812. if (clock != new) {
  813. now = clocksource_read(new);
  814. nsec = __get_nsec_offset();
  815. timespec_add_ns(&xtime, nsec);
  816. clock = new;
  817. clock->cycle_last = now;
  818. printk(KERN_INFO "Time: %s clocksource has been installed.\n",
  819. clock->name);
  820. return 1;
  821. } else if (clock->update_callback) {
  822. return clock->update_callback();
  823. }
  824. return 0;
  825. }
  826. #else
  827. #define change_clocksource() (0)
  828. #endif
  829. /**
  830. * timeofday_is_continuous - check to see if timekeeping is free running
  831. */
  832. int timekeeping_is_continuous(void)
  833. {
  834. unsigned long seq;
  835. int ret;
  836. do {
  837. seq = read_seqbegin(&xtime_lock);
  838. ret = clock->is_continuous;
  839. } while (read_seqretry(&xtime_lock, seq));
  840. return ret;
  841. }
  842. /*
  843. * timekeeping_init - Initializes the clocksource and common timekeeping values
  844. */
  845. void __init timekeeping_init(void)
  846. {
  847. unsigned long flags;
  848. write_seqlock_irqsave(&xtime_lock, flags);
  849. clock = clocksource_get_next();
  850. clocksource_calculate_interval(clock, tick_nsec);
  851. clock->cycle_last = clocksource_read(clock);
  852. ntp_clear();
  853. write_sequnlock_irqrestore(&xtime_lock, flags);
  854. }
  855. static int timekeeping_suspended;
  856. /**
  857. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  858. * @dev: unused
  859. *
  860. * This is for the generic clocksource timekeeping.
  861. * xtime/wall_to_monotonic/jiffies/wall_jiffies/etc are
  862. * still managed by arch specific suspend/resume code.
  863. */
  864. static int timekeeping_resume(struct sys_device *dev)
  865. {
  866. unsigned long flags;
  867. write_seqlock_irqsave(&xtime_lock, flags);
  868. /* restart the last cycle value */
  869. clock->cycle_last = clocksource_read(clock);
  870. clock->error = 0;
  871. timekeeping_suspended = 0;
  872. write_sequnlock_irqrestore(&xtime_lock, flags);
  873. return 0;
  874. }
  875. static int timekeeping_suspend(struct sys_device *dev, pm_message_t state)
  876. {
  877. unsigned long flags;
  878. write_seqlock_irqsave(&xtime_lock, flags);
  879. timekeeping_suspended = 1;
  880. write_sequnlock_irqrestore(&xtime_lock, flags);
  881. return 0;
  882. }
  883. /* sysfs resume/suspend bits for timekeeping */
  884. static struct sysdev_class timekeeping_sysclass = {
  885. .resume = timekeeping_resume,
  886. .suspend = timekeeping_suspend,
  887. set_kset_name("timekeeping"),
  888. };
  889. static struct sys_device device_timer = {
  890. .id = 0,
  891. .cls = &timekeeping_sysclass,
  892. };
  893. static int __init timekeeping_init_device(void)
  894. {
  895. int error = sysdev_class_register(&timekeeping_sysclass);
  896. if (!error)
  897. error = sysdev_register(&device_timer);
  898. return error;
  899. }
  900. device_initcall(timekeeping_init_device);
  901. /*
  902. * If the error is already larger, we look ahead even further
  903. * to compensate for late or lost adjustments.
  904. */
  905. static __always_inline int clocksource_bigadjust(s64 error, s64 *interval, s64 *offset)
  906. {
  907. s64 tick_error, i;
  908. u32 look_ahead, adj;
  909. s32 error2, mult;
  910. /*
  911. * Use the current error value to determine how much to look ahead.
  912. * The larger the error the slower we adjust for it to avoid problems
  913. * with losing too many ticks, otherwise we would overadjust and
  914. * produce an even larger error. The smaller the adjustment the
  915. * faster we try to adjust for it, as lost ticks can do less harm
  916. * here. This is tuned so that an error of about 1 msec is adusted
  917. * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
  918. */
  919. error2 = clock->error >> (TICK_LENGTH_SHIFT + 22 - 2 * SHIFT_HZ);
  920. error2 = abs(error2);
  921. for (look_ahead = 0; error2 > 0; look_ahead++)
  922. error2 >>= 2;
  923. /*
  924. * Now calculate the error in (1 << look_ahead) ticks, but first
  925. * remove the single look ahead already included in the error.
  926. */
  927. tick_error = current_tick_length() >> (TICK_LENGTH_SHIFT - clock->shift + 1);
  928. tick_error -= clock->xtime_interval >> 1;
  929. error = ((error - tick_error) >> look_ahead) + tick_error;
  930. /* Finally calculate the adjustment shift value. */
  931. i = *interval;
  932. mult = 1;
  933. if (error < 0) {
  934. error = -error;
  935. *interval = -*interval;
  936. *offset = -*offset;
  937. mult = -1;
  938. }
  939. for (adj = 0; error > i; adj++)
  940. error >>= 1;
  941. *interval <<= adj;
  942. *offset <<= adj;
  943. return mult << adj;
  944. }
  945. /*
  946. * Adjust the multiplier to reduce the error value,
  947. * this is optimized for the most common adjustments of -1,0,1,
  948. * for other values we can do a bit more work.
  949. */
  950. static void clocksource_adjust(struct clocksource *clock, s64 offset)
  951. {
  952. s64 error, interval = clock->cycle_interval;
  953. int adj;
  954. error = clock->error >> (TICK_LENGTH_SHIFT - clock->shift - 1);
  955. if (error > interval) {
  956. error >>= 2;
  957. if (likely(error <= interval))
  958. adj = 1;
  959. else
  960. adj = clocksource_bigadjust(error, &interval, &offset);
  961. } else if (error < -interval) {
  962. error >>= 2;
  963. if (likely(error >= -interval)) {
  964. adj = -1;
  965. interval = -interval;
  966. offset = -offset;
  967. } else
  968. adj = clocksource_bigadjust(error, &interval, &offset);
  969. } else
  970. return;
  971. clock->mult += adj;
  972. clock->xtime_interval += interval;
  973. clock->xtime_nsec -= offset;
  974. clock->error -= (interval - offset) << (TICK_LENGTH_SHIFT - clock->shift);
  975. }
  976. /**
  977. * update_wall_time - Uses the current clocksource to increment the wall time
  978. *
  979. * Called from the timer interrupt, must hold a write on xtime_lock.
  980. */
  981. static void update_wall_time(void)
  982. {
  983. cycle_t offset;
  984. /* Make sure we're fully resumed: */
  985. if (unlikely(timekeeping_suspended))
  986. return;
  987. #ifdef CONFIG_GENERIC_TIME
  988. offset = (clocksource_read(clock) - clock->cycle_last) & clock->mask;
  989. #else
  990. offset = clock->cycle_interval;
  991. #endif
  992. clock->xtime_nsec += (s64)xtime.tv_nsec << clock->shift;
  993. /* normally this loop will run just once, however in the
  994. * case of lost or late ticks, it will accumulate correctly.
  995. */
  996. while (offset >= clock->cycle_interval) {
  997. /* accumulate one interval */
  998. clock->xtime_nsec += clock->xtime_interval;
  999. clock->cycle_last += clock->cycle_interval;
  1000. offset -= clock->cycle_interval;
  1001. if (clock->xtime_nsec >= (u64)NSEC_PER_SEC << clock->shift) {
  1002. clock->xtime_nsec -= (u64)NSEC_PER_SEC << clock->shift;
  1003. xtime.tv_sec++;
  1004. second_overflow();
  1005. }
  1006. /* interpolator bits */
  1007. time_interpolator_update(clock->xtime_interval
  1008. >> clock->shift);
  1009. /* increment the NTP state machine */
  1010. update_ntp_one_tick();
  1011. /* accumulate error between NTP and clock interval */
  1012. clock->error += current_tick_length();
  1013. clock->error -= clock->xtime_interval << (TICK_LENGTH_SHIFT - clock->shift);
  1014. }
  1015. /* correct the clock when NTP error is too big */
  1016. clocksource_adjust(clock, offset);
  1017. /* store full nanoseconds into xtime */
  1018. xtime.tv_nsec = (s64)clock->xtime_nsec >> clock->shift;
  1019. clock->xtime_nsec -= (s64)xtime.tv_nsec << clock->shift;
  1020. /* check to see if there is a new clocksource to use */
  1021. if (change_clocksource()) {
  1022. clock->error = 0;
  1023. clock->xtime_nsec = 0;
  1024. clocksource_calculate_interval(clock, tick_nsec);
  1025. }
  1026. }
  1027. /*
  1028. * Called from the timer interrupt handler to charge one tick to the current
  1029. * process. user_tick is 1 if the tick is user time, 0 for system.
  1030. */
  1031. void update_process_times(int user_tick)
  1032. {
  1033. struct task_struct *p = current;
  1034. int cpu = smp_processor_id();
  1035. /* Note: this timer irq context must be accounted for as well. */
  1036. if (user_tick)
  1037. account_user_time(p, jiffies_to_cputime(1));
  1038. else
  1039. account_system_time(p, HARDIRQ_OFFSET, jiffies_to_cputime(1));
  1040. run_local_timers();
  1041. if (rcu_pending(cpu))
  1042. rcu_check_callbacks(cpu, user_tick);
  1043. scheduler_tick();
  1044. run_posix_cpu_timers(p);
  1045. }
  1046. /*
  1047. * Nr of active tasks - counted in fixed-point numbers
  1048. */
  1049. static unsigned long count_active_tasks(void)
  1050. {
  1051. return nr_active() * FIXED_1;
  1052. }
  1053. /*
  1054. * Hmm.. Changed this, as the GNU make sources (load.c) seems to
  1055. * imply that avenrun[] is the standard name for this kind of thing.
  1056. * Nothing else seems to be standardized: the fractional size etc
  1057. * all seem to differ on different machines.
  1058. *
  1059. * Requires xtime_lock to access.
  1060. */
  1061. unsigned long avenrun[3];
  1062. EXPORT_SYMBOL(avenrun);
  1063. /*
  1064. * calc_load - given tick count, update the avenrun load estimates.
  1065. * This is called while holding a write_lock on xtime_lock.
  1066. */
  1067. static inline void calc_load(unsigned long ticks)
  1068. {
  1069. unsigned long active_tasks; /* fixed-point */
  1070. static int count = LOAD_FREQ;
  1071. count -= ticks;
  1072. if (count < 0) {
  1073. count += LOAD_FREQ;
  1074. active_tasks = count_active_tasks();
  1075. CALC_LOAD(avenrun[0], EXP_1, active_tasks);
  1076. CALC_LOAD(avenrun[1], EXP_5, active_tasks);
  1077. CALC_LOAD(avenrun[2], EXP_15, active_tasks);
  1078. }
  1079. }
  1080. /* jiffies at the most recent update of wall time */
  1081. unsigned long wall_jiffies = INITIAL_JIFFIES;
  1082. /*
  1083. * This read-write spinlock protects us from races in SMP while
  1084. * playing with xtime and avenrun.
  1085. */
  1086. #ifndef ARCH_HAVE_XTIME_LOCK
  1087. __cacheline_aligned_in_smp DEFINE_SEQLOCK(xtime_lock);
  1088. EXPORT_SYMBOL(xtime_lock);
  1089. #endif
  1090. /*
  1091. * This function runs timers and the timer-tq in bottom half context.
  1092. */
  1093. static void run_timer_softirq(struct softirq_action *h)
  1094. {
  1095. tvec_base_t *base = __get_cpu_var(tvec_bases);
  1096. hrtimer_run_queues();
  1097. if (time_after_eq(jiffies, base->timer_jiffies))
  1098. __run_timers(base);
  1099. }
  1100. /*
  1101. * Called by the local, per-CPU timer interrupt on SMP.
  1102. */
  1103. void run_local_timers(void)
  1104. {
  1105. raise_softirq(TIMER_SOFTIRQ);
  1106. softlockup_tick();
  1107. }
  1108. /*
  1109. * Called by the timer interrupt. xtime_lock must already be taken
  1110. * by the timer IRQ!
  1111. */
  1112. static inline void update_times(void)
  1113. {
  1114. unsigned long ticks;
  1115. ticks = jiffies - wall_jiffies;
  1116. wall_jiffies += ticks;
  1117. update_wall_time();
  1118. calc_load(ticks);
  1119. }
  1120. /*
  1121. * The 64-bit jiffies value is not atomic - you MUST NOT read it
  1122. * without sampling the sequence number in xtime_lock.
  1123. * jiffies is defined in the linker script...
  1124. */
  1125. void do_timer(struct pt_regs *regs)
  1126. {
  1127. jiffies_64++;
  1128. /* prevent loading jiffies before storing new jiffies_64 value. */
  1129. barrier();
  1130. update_times();
  1131. }
  1132. #ifdef __ARCH_WANT_SYS_ALARM
  1133. /*
  1134. * For backwards compatibility? This can be done in libc so Alpha
  1135. * and all newer ports shouldn't need it.
  1136. */
  1137. asmlinkage unsigned long sys_alarm(unsigned int seconds)
  1138. {
  1139. return alarm_setitimer(seconds);
  1140. }
  1141. #endif
  1142. #ifndef __alpha__
  1143. /*
  1144. * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
  1145. * should be moved into arch/i386 instead?
  1146. */
  1147. /**
  1148. * sys_getpid - return the thread group id of the current process
  1149. *
  1150. * Note, despite the name, this returns the tgid not the pid. The tgid and
  1151. * the pid are identical unless CLONE_THREAD was specified on clone() in
  1152. * which case the tgid is the same in all threads of the same group.
  1153. *
  1154. * This is SMP safe as current->tgid does not change.
  1155. */
  1156. asmlinkage long sys_getpid(void)
  1157. {
  1158. return current->tgid;
  1159. }
  1160. /*
  1161. * Accessing ->real_parent is not SMP-safe, it could
  1162. * change from under us. However, we can use a stale
  1163. * value of ->real_parent under rcu_read_lock(), see
  1164. * release_task()->call_rcu(delayed_put_task_struct).
  1165. */
  1166. asmlinkage long sys_getppid(void)
  1167. {
  1168. int pid;
  1169. rcu_read_lock();
  1170. pid = rcu_dereference(current->real_parent)->tgid;
  1171. rcu_read_unlock();
  1172. return pid;
  1173. }
  1174. asmlinkage long sys_getuid(void)
  1175. {
  1176. /* Only we change this so SMP safe */
  1177. return current->uid;
  1178. }
  1179. asmlinkage long sys_geteuid(void)
  1180. {
  1181. /* Only we change this so SMP safe */
  1182. return current->euid;
  1183. }
  1184. asmlinkage long sys_getgid(void)
  1185. {
  1186. /* Only we change this so SMP safe */
  1187. return current->gid;
  1188. }
  1189. asmlinkage long sys_getegid(void)
  1190. {
  1191. /* Only we change this so SMP safe */
  1192. return current->egid;
  1193. }
  1194. #endif
  1195. static void process_timeout(unsigned long __data)
  1196. {
  1197. wake_up_process((struct task_struct *)__data);
  1198. }
  1199. /**
  1200. * schedule_timeout - sleep until timeout
  1201. * @timeout: timeout value in jiffies
  1202. *
  1203. * Make the current task sleep until @timeout jiffies have
  1204. * elapsed. The routine will return immediately unless
  1205. * the current task state has been set (see set_current_state()).
  1206. *
  1207. * You can set the task state as follows -
  1208. *
  1209. * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
  1210. * pass before the routine returns. The routine will return 0
  1211. *
  1212. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1213. * delivered to the current task. In this case the remaining time
  1214. * in jiffies will be returned, or 0 if the timer expired in time
  1215. *
  1216. * The current task state is guaranteed to be TASK_RUNNING when this
  1217. * routine returns.
  1218. *
  1219. * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
  1220. * the CPU away without a bound on the timeout. In this case the return
  1221. * value will be %MAX_SCHEDULE_TIMEOUT.
  1222. *
  1223. * In all cases the return value is guaranteed to be non-negative.
  1224. */
  1225. fastcall signed long __sched schedule_timeout(signed long timeout)
  1226. {
  1227. struct timer_list timer;
  1228. unsigned long expire;
  1229. switch (timeout)
  1230. {
  1231. case MAX_SCHEDULE_TIMEOUT:
  1232. /*
  1233. * These two special cases are useful to be comfortable
  1234. * in the caller. Nothing more. We could take
  1235. * MAX_SCHEDULE_TIMEOUT from one of the negative value
  1236. * but I' d like to return a valid offset (>=0) to allow
  1237. * the caller to do everything it want with the retval.
  1238. */
  1239. schedule();
  1240. goto out;
  1241. default:
  1242. /*
  1243. * Another bit of PARANOID. Note that the retval will be
  1244. * 0 since no piece of kernel is supposed to do a check
  1245. * for a negative retval of schedule_timeout() (since it
  1246. * should never happens anyway). You just have the printk()
  1247. * that will tell you if something is gone wrong and where.
  1248. */
  1249. if (timeout < 0)
  1250. {
  1251. printk(KERN_ERR "schedule_timeout: wrong timeout "
  1252. "value %lx from %p\n", timeout,
  1253. __builtin_return_address(0));
  1254. current->state = TASK_RUNNING;
  1255. goto out;
  1256. }
  1257. }
  1258. expire = timeout + jiffies;
  1259. setup_timer(&timer, process_timeout, (unsigned long)current);
  1260. __mod_timer(&timer, expire);
  1261. schedule();
  1262. del_singleshot_timer_sync(&timer);
  1263. timeout = expire - jiffies;
  1264. out:
  1265. return timeout < 0 ? 0 : timeout;
  1266. }
  1267. EXPORT_SYMBOL(schedule_timeout);
  1268. /*
  1269. * We can use __set_current_state() here because schedule_timeout() calls
  1270. * schedule() unconditionally.
  1271. */
  1272. signed long __sched schedule_timeout_interruptible(signed long timeout)
  1273. {
  1274. __set_current_state(TASK_INTERRUPTIBLE);
  1275. return schedule_timeout(timeout);
  1276. }
  1277. EXPORT_SYMBOL(schedule_timeout_interruptible);
  1278. signed long __sched schedule_timeout_uninterruptible(signed long timeout)
  1279. {
  1280. __set_current_state(TASK_UNINTERRUPTIBLE);
  1281. return schedule_timeout(timeout);
  1282. }
  1283. EXPORT_SYMBOL(schedule_timeout_uninterruptible);
  1284. /* Thread ID - the internal kernel "pid" */
  1285. asmlinkage long sys_gettid(void)
  1286. {
  1287. return current->pid;
  1288. }
  1289. /**
  1290. * sys_sysinfo - fill in sysinfo struct
  1291. * @info: pointer to buffer to fill
  1292. */
  1293. asmlinkage long sys_sysinfo(struct sysinfo __user *info)
  1294. {
  1295. struct sysinfo val;
  1296. unsigned long mem_total, sav_total;
  1297. unsigned int mem_unit, bitcount;
  1298. unsigned long seq;
  1299. memset((char *)&val, 0, sizeof(struct sysinfo));
  1300. do {
  1301. struct timespec tp;
  1302. seq = read_seqbegin(&xtime_lock);
  1303. /*
  1304. * This is annoying. The below is the same thing
  1305. * posix_get_clock_monotonic() does, but it wants to
  1306. * take the lock which we want to cover the loads stuff
  1307. * too.
  1308. */
  1309. getnstimeofday(&tp);
  1310. tp.tv_sec += wall_to_monotonic.tv_sec;
  1311. tp.tv_nsec += wall_to_monotonic.tv_nsec;
  1312. if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
  1313. tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
  1314. tp.tv_sec++;
  1315. }
  1316. val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
  1317. val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
  1318. val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
  1319. val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
  1320. val.procs = nr_threads;
  1321. } while (read_seqretry(&xtime_lock, seq));
  1322. si_meminfo(&val);
  1323. si_swapinfo(&val);
  1324. /*
  1325. * If the sum of all the available memory (i.e. ram + swap)
  1326. * is less than can be stored in a 32 bit unsigned long then
  1327. * we can be binary compatible with 2.2.x kernels. If not,
  1328. * well, in that case 2.2.x was broken anyways...
  1329. *
  1330. * -Erik Andersen <andersee@debian.org>
  1331. */
  1332. mem_total = val.totalram + val.totalswap;
  1333. if (mem_total < val.totalram || mem_total < val.totalswap)
  1334. goto out;
  1335. bitcount = 0;
  1336. mem_unit = val.mem_unit;
  1337. while (mem_unit > 1) {
  1338. bitcount++;
  1339. mem_unit >>= 1;
  1340. sav_total = mem_total;
  1341. mem_total <<= 1;
  1342. if (mem_total < sav_total)
  1343. goto out;
  1344. }
  1345. /*
  1346. * If mem_total did not overflow, multiply all memory values by
  1347. * val.mem_unit and set it to 1. This leaves things compatible
  1348. * with 2.2.x, and also retains compatibility with earlier 2.4.x
  1349. * kernels...
  1350. */
  1351. val.mem_unit = 1;
  1352. val.totalram <<= bitcount;
  1353. val.freeram <<= bitcount;
  1354. val.sharedram <<= bitcount;
  1355. val.bufferram <<= bitcount;
  1356. val.totalswap <<= bitcount;
  1357. val.freeswap <<= bitcount;
  1358. val.totalhigh <<= bitcount;
  1359. val.freehigh <<= bitcount;
  1360. out:
  1361. if (copy_to_user(info, &val, sizeof(struct sysinfo)))
  1362. return -EFAULT;
  1363. return 0;
  1364. }
  1365. /*
  1366. * lockdep: we want to track each per-CPU base as a separate lock-class,
  1367. * but timer-bases are kmalloc()-ed, so we need to attach separate
  1368. * keys to them:
  1369. */
  1370. static struct lock_class_key base_lock_keys[NR_CPUS];
  1371. static int __devinit init_timers_cpu(int cpu)
  1372. {
  1373. int j;
  1374. tvec_base_t *base;
  1375. static char __devinitdata tvec_base_done[NR_CPUS];
  1376. if (!tvec_base_done[cpu]) {
  1377. static char boot_done;
  1378. if (boot_done) {
  1379. /*
  1380. * The APs use this path later in boot
  1381. */
  1382. base = kmalloc_node(sizeof(*base), GFP_KERNEL,
  1383. cpu_to_node(cpu));
  1384. if (!base)
  1385. return -ENOMEM;
  1386. memset(base, 0, sizeof(*base));
  1387. per_cpu(tvec_bases, cpu) = base;
  1388. } else {
  1389. /*
  1390. * This is for the boot CPU - we use compile-time
  1391. * static initialisation because per-cpu memory isn't
  1392. * ready yet and because the memory allocators are not
  1393. * initialised either.
  1394. */
  1395. boot_done = 1;
  1396. base = &boot_tvec_bases;
  1397. }
  1398. tvec_base_done[cpu] = 1;
  1399. } else {
  1400. base = per_cpu(tvec_bases, cpu);
  1401. }
  1402. spin_lock_init(&base->lock);
  1403. lockdep_set_class(&base->lock, base_lock_keys + cpu);
  1404. for (j = 0; j < TVN_SIZE; j++) {
  1405. INIT_LIST_HEAD(base->tv5.vec + j);
  1406. INIT_LIST_HEAD(base->tv4.vec + j);
  1407. INIT_LIST_HEAD(base->tv3.vec + j);
  1408. INIT_LIST_HEAD(base->tv2.vec + j);
  1409. }
  1410. for (j = 0; j < TVR_SIZE; j++)
  1411. INIT_LIST_HEAD(base->tv1.vec + j);
  1412. base->timer_jiffies = jiffies;
  1413. return 0;
  1414. }
  1415. #ifdef CONFIG_HOTPLUG_CPU
  1416. static void migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
  1417. {
  1418. struct timer_list *timer;
  1419. while (!list_empty(head)) {
  1420. timer = list_entry(head->next, struct timer_list, entry);
  1421. detach_timer(timer, 0);
  1422. timer->base = new_base;
  1423. internal_add_timer(new_base, timer);
  1424. }
  1425. }
  1426. static void __devinit migrate_timers(int cpu)
  1427. {
  1428. tvec_base_t *old_base;
  1429. tvec_base_t *new_base;
  1430. int i;
  1431. BUG_ON(cpu_online(cpu));
  1432. old_base = per_cpu(tvec_bases, cpu);
  1433. new_base = get_cpu_var(tvec_bases);
  1434. local_irq_disable();
  1435. spin_lock(&new_base->lock);
  1436. spin_lock(&old_base->lock);
  1437. BUG_ON(old_base->running_timer);
  1438. for (i = 0; i < TVR_SIZE; i++)
  1439. migrate_timer_list(new_base, old_base->tv1.vec + i);
  1440. for (i = 0; i < TVN_SIZE; i++) {
  1441. migrate_timer_list(new_base, old_base->tv2.vec + i);
  1442. migrate_timer_list(new_base, old_base->tv3.vec + i);
  1443. migrate_timer_list(new_base, old_base->tv4.vec + i);
  1444. migrate_timer_list(new_base, old_base->tv5.vec + i);
  1445. }
  1446. spin_unlock(&old_base->lock);
  1447. spin_unlock(&new_base->lock);
  1448. local_irq_enable();
  1449. put_cpu_var(tvec_bases);
  1450. }
  1451. #endif /* CONFIG_HOTPLUG_CPU */
  1452. static int __cpuinit timer_cpu_notify(struct notifier_block *self,
  1453. unsigned long action, void *hcpu)
  1454. {
  1455. long cpu = (long)hcpu;
  1456. switch(action) {
  1457. case CPU_UP_PREPARE:
  1458. if (init_timers_cpu(cpu) < 0)
  1459. return NOTIFY_BAD;
  1460. break;
  1461. #ifdef CONFIG_HOTPLUG_CPU
  1462. case CPU_DEAD:
  1463. migrate_timers(cpu);
  1464. break;
  1465. #endif
  1466. default:
  1467. break;
  1468. }
  1469. return NOTIFY_OK;
  1470. }
  1471. static struct notifier_block __cpuinitdata timers_nb = {
  1472. .notifier_call = timer_cpu_notify,
  1473. };
  1474. void __init init_timers(void)
  1475. {
  1476. timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
  1477. (void *)(long)smp_processor_id());
  1478. register_cpu_notifier(&timers_nb);
  1479. open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
  1480. }
  1481. #ifdef CONFIG_TIME_INTERPOLATION
  1482. struct time_interpolator *time_interpolator __read_mostly;
  1483. static struct time_interpolator *time_interpolator_list __read_mostly;
  1484. static DEFINE_SPINLOCK(time_interpolator_lock);
  1485. static inline u64 time_interpolator_get_cycles(unsigned int src)
  1486. {
  1487. unsigned long (*x)(void);
  1488. switch (src)
  1489. {
  1490. case TIME_SOURCE_FUNCTION:
  1491. x = time_interpolator->addr;
  1492. return x();
  1493. case TIME_SOURCE_MMIO64 :
  1494. return readq_relaxed((void __iomem *)time_interpolator->addr);
  1495. case TIME_SOURCE_MMIO32 :
  1496. return readl_relaxed((void __iomem *)time_interpolator->addr);
  1497. default: return get_cycles();
  1498. }
  1499. }
  1500. static inline u64 time_interpolator_get_counter(int writelock)
  1501. {
  1502. unsigned int src = time_interpolator->source;
  1503. if (time_interpolator->jitter)
  1504. {
  1505. u64 lcycle;
  1506. u64 now;
  1507. do {
  1508. lcycle = time_interpolator->last_cycle;
  1509. now = time_interpolator_get_cycles(src);
  1510. if (lcycle && time_after(lcycle, now))
  1511. return lcycle;
  1512. /* When holding the xtime write lock, there's no need
  1513. * to add the overhead of the cmpxchg. Readers are
  1514. * force to retry until the write lock is released.
  1515. */
  1516. if (writelock) {
  1517. time_interpolator->last_cycle = now;
  1518. return now;
  1519. }
  1520. /* Keep track of the last timer value returned. The use of cmpxchg here
  1521. * will cause contention in an SMP environment.
  1522. */
  1523. } while (unlikely(cmpxchg(&time_interpolator->last_cycle, lcycle, now) != lcycle));
  1524. return now;
  1525. }
  1526. else
  1527. return time_interpolator_get_cycles(src);
  1528. }
  1529. void time_interpolator_reset(void)
  1530. {
  1531. time_interpolator->offset = 0;
  1532. time_interpolator->last_counter = time_interpolator_get_counter(1);
  1533. }
  1534. #define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
  1535. unsigned long time_interpolator_get_offset(void)
  1536. {
  1537. /* If we do not have a time interpolator set up then just return zero */
  1538. if (!time_interpolator)
  1539. return 0;
  1540. return time_interpolator->offset +
  1541. GET_TI_NSECS(time_interpolator_get_counter(0), time_interpolator);
  1542. }
  1543. #define INTERPOLATOR_ADJUST 65536
  1544. #define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
  1545. static void time_interpolator_update(long delta_nsec)
  1546. {
  1547. u64 counter;
  1548. unsigned long offset;
  1549. /* If there is no time interpolator set up then do nothing */
  1550. if (!time_interpolator)
  1551. return;
  1552. /*
  1553. * The interpolator compensates for late ticks by accumulating the late
  1554. * time in time_interpolator->offset. A tick earlier than expected will
  1555. * lead to a reset of the offset and a corresponding jump of the clock
  1556. * forward. Again this only works if the interpolator clock is running
  1557. * slightly slower than the regular clock and the tuning logic insures
  1558. * that.
  1559. */
  1560. counter = time_interpolator_get_counter(1);
  1561. offset = time_interpolator->offset +
  1562. GET_TI_NSECS(counter, time_interpolator);
  1563. if (delta_nsec < 0 || (unsigned long) delta_nsec < offset)
  1564. time_interpolator->offset = offset - delta_nsec;
  1565. else {
  1566. time_interpolator->skips++;
  1567. time_interpolator->ns_skipped += delta_nsec - offset;
  1568. time_interpolator->offset = 0;
  1569. }
  1570. time_interpolator->last_counter = counter;
  1571. /* Tuning logic for time interpolator invoked every minute or so.
  1572. * Decrease interpolator clock speed if no skips occurred and an offset is carried.
  1573. * Increase interpolator clock speed if we skip too much time.
  1574. */
  1575. if (jiffies % INTERPOLATOR_ADJUST == 0)
  1576. {
  1577. if (time_interpolator->skips == 0 && time_interpolator->offset > tick_nsec)
  1578. time_interpolator->nsec_per_cyc--;
  1579. if (time_interpolator->ns_skipped > INTERPOLATOR_MAX_SKIP && time_interpolator->offset == 0)
  1580. time_interpolator->nsec_per_cyc++;
  1581. time_interpolator->skips = 0;
  1582. time_interpolator->ns_skipped = 0;
  1583. }
  1584. }
  1585. static inline int
  1586. is_better_time_interpolator(struct time_interpolator *new)
  1587. {
  1588. if (!time_interpolator)
  1589. return 1;
  1590. return new->frequency > 2*time_interpolator->frequency ||
  1591. (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
  1592. }
  1593. void
  1594. register_time_interpolator(struct time_interpolator *ti)
  1595. {
  1596. unsigned long flags;
  1597. /* Sanity check */
  1598. BUG_ON(ti->frequency == 0 || ti->mask == 0);
  1599. ti->nsec_per_cyc = ((u64)NSEC_PER_SEC << ti->shift) / ti->frequency;
  1600. spin_lock(&time_interpolator_lock);
  1601. write_seqlock_irqsave(&xtime_lock, flags);
  1602. if (is_better_time_interpolator(ti)) {
  1603. time_interpolator = ti;
  1604. time_interpolator_reset();
  1605. }
  1606. write_sequnlock_irqrestore(&xtime_lock, flags);
  1607. ti->next = time_interpolator_list;
  1608. time_interpolator_list = ti;
  1609. spin_unlock(&time_interpolator_lock);
  1610. }
  1611. void
  1612. unregister_time_interpolator(struct time_interpolator *ti)
  1613. {
  1614. struct time_interpolator *curr, **prev;
  1615. unsigned long flags;
  1616. spin_lock(&time_interpolator_lock);
  1617. prev = &time_interpolator_list;
  1618. for (curr = *prev; curr; curr = curr->next) {
  1619. if (curr == ti) {
  1620. *prev = curr->next;
  1621. break;
  1622. }
  1623. prev = &curr->next;
  1624. }
  1625. write_seqlock_irqsave(&xtime_lock, flags);
  1626. if (ti == time_interpolator) {
  1627. /* we lost the best time-interpolator: */
  1628. time_interpolator = NULL;
  1629. /* find the next-best interpolator */
  1630. for (curr = time_interpolator_list; curr; curr = curr->next)
  1631. if (is_better_time_interpolator(curr))
  1632. time_interpolator = curr;
  1633. time_interpolator_reset();
  1634. }
  1635. write_sequnlock_irqrestore(&xtime_lock, flags);
  1636. spin_unlock(&time_interpolator_lock);
  1637. }
  1638. #endif /* CONFIG_TIME_INTERPOLATION */
  1639. /**
  1640. * msleep - sleep safely even with waitqueue interruptions
  1641. * @msecs: Time in milliseconds to sleep for
  1642. */
  1643. void msleep(unsigned int msecs)
  1644. {
  1645. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1646. while (timeout)
  1647. timeout = schedule_timeout_uninterruptible(timeout);
  1648. }
  1649. EXPORT_SYMBOL(msleep);
  1650. /**
  1651. * msleep_interruptible - sleep waiting for signals
  1652. * @msecs: Time in milliseconds to sleep for
  1653. */
  1654. unsigned long msleep_interruptible(unsigned int msecs)
  1655. {
  1656. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1657. while (timeout && !signal_pending(current))
  1658. timeout = schedule_timeout_interruptible(timeout);
  1659. return jiffies_to_msecs(timeout);
  1660. }
  1661. EXPORT_SYMBOL(msleep_interruptible);