timer.c 43 KB

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