timer.c 43 KB

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