timer.c 50 KB

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