timer.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  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. /**
  453. * del_timer_sync - deactivate a timer and wait for the handler to finish.
  454. * @timer: the timer to be deactivated
  455. *
  456. * This function only differs from del_timer() on SMP: besides deactivating
  457. * the timer it also makes sure the handler has finished executing on other
  458. * CPUs.
  459. *
  460. * Synchronization rules: Callers must prevent restarting of the timer,
  461. * otherwise this function is meaningless. It must not be called from
  462. * interrupt contexts. The caller must not hold locks which would prevent
  463. * completion of the timer's handler. The timer's handler must not call
  464. * add_timer_on(). Upon exit the timer is not queued and the handler is
  465. * not running on any CPU.
  466. *
  467. * The function returns whether it has deactivated a pending timer or not.
  468. */
  469. int del_timer_sync(struct timer_list *timer)
  470. {
  471. for (;;) {
  472. int ret = try_to_del_timer_sync(timer);
  473. if (ret >= 0)
  474. return ret;
  475. cpu_relax();
  476. }
  477. }
  478. EXPORT_SYMBOL(del_timer_sync);
  479. #endif
  480. static int cascade(tvec_base_t *base, tvec_t *tv, int index)
  481. {
  482. /* cascade all the timers from tv up one level */
  483. struct timer_list *timer, *tmp;
  484. struct list_head tv_list;
  485. list_replace_init(tv->vec + index, &tv_list);
  486. /*
  487. * We are removing _all_ timers from the list, so we
  488. * don't have to detach them individually.
  489. */
  490. list_for_each_entry_safe(timer, tmp, &tv_list, entry) {
  491. BUG_ON(timer->base != base);
  492. internal_add_timer(base, timer);
  493. }
  494. return index;
  495. }
  496. #define INDEX(N) ((base->timer_jiffies >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
  497. /**
  498. * __run_timers - run all expired timers (if any) on this CPU.
  499. * @base: the timer vector to be processed.
  500. *
  501. * This function cascades all vectors and executes all expired timer
  502. * vectors.
  503. */
  504. static inline void __run_timers(tvec_base_t *base)
  505. {
  506. struct timer_list *timer;
  507. spin_lock_irq(&base->lock);
  508. while (time_after_eq(jiffies, base->timer_jiffies)) {
  509. struct list_head work_list;
  510. struct list_head *head = &work_list;
  511. int index = base->timer_jiffies & TVR_MASK;
  512. /*
  513. * Cascade timers:
  514. */
  515. if (!index &&
  516. (!cascade(base, &base->tv2, INDEX(0))) &&
  517. (!cascade(base, &base->tv3, INDEX(1))) &&
  518. !cascade(base, &base->tv4, INDEX(2)))
  519. cascade(base, &base->tv5, INDEX(3));
  520. ++base->timer_jiffies;
  521. list_replace_init(base->tv1.vec + index, &work_list);
  522. while (!list_empty(head)) {
  523. void (*fn)(unsigned long);
  524. unsigned long data;
  525. timer = list_entry(head->next,struct timer_list,entry);
  526. fn = timer->function;
  527. data = timer->data;
  528. timer_stats_account_timer(timer);
  529. set_running_timer(base, timer);
  530. detach_timer(timer, 1);
  531. spin_unlock_irq(&base->lock);
  532. {
  533. int preempt_count = preempt_count();
  534. fn(data);
  535. if (preempt_count != preempt_count()) {
  536. printk(KERN_WARNING "huh, entered %p "
  537. "with preempt_count %08x, exited"
  538. " with %08x?\n",
  539. fn, preempt_count,
  540. preempt_count());
  541. BUG();
  542. }
  543. }
  544. spin_lock_irq(&base->lock);
  545. }
  546. }
  547. set_running_timer(base, NULL);
  548. spin_unlock_irq(&base->lock);
  549. }
  550. #if defined(CONFIG_NO_IDLE_HZ) || defined(CONFIG_NO_HZ)
  551. /*
  552. * Find out when the next timer event is due to happen. This
  553. * is used on S/390 to stop all activity when a cpus is idle.
  554. * This functions needs to be called disabled.
  555. */
  556. static unsigned long __next_timer_interrupt(tvec_base_t *base)
  557. {
  558. unsigned long timer_jiffies = base->timer_jiffies;
  559. unsigned long expires = timer_jiffies + (LONG_MAX >> 1);
  560. int index, slot, array, found = 0;
  561. struct timer_list *nte;
  562. tvec_t *varray[4];
  563. /* Look for timer events in tv1. */
  564. index = slot = timer_jiffies & TVR_MASK;
  565. do {
  566. list_for_each_entry(nte, base->tv1.vec + slot, entry) {
  567. found = 1;
  568. expires = nte->expires;
  569. /* Look at the cascade bucket(s)? */
  570. if (!index || slot < index)
  571. goto cascade;
  572. return expires;
  573. }
  574. slot = (slot + 1) & TVR_MASK;
  575. } while (slot != index);
  576. cascade:
  577. /* Calculate the next cascade event */
  578. if (index)
  579. timer_jiffies += TVR_SIZE - index;
  580. timer_jiffies >>= TVR_BITS;
  581. /* Check tv2-tv5. */
  582. varray[0] = &base->tv2;
  583. varray[1] = &base->tv3;
  584. varray[2] = &base->tv4;
  585. varray[3] = &base->tv5;
  586. for (array = 0; array < 4; array++) {
  587. tvec_t *varp = varray[array];
  588. index = slot = timer_jiffies & TVN_MASK;
  589. do {
  590. list_for_each_entry(nte, varp->vec + slot, entry) {
  591. found = 1;
  592. if (time_before(nte->expires, expires))
  593. expires = nte->expires;
  594. }
  595. /*
  596. * Do we still search for the first timer or are
  597. * we looking up the cascade buckets ?
  598. */
  599. if (found) {
  600. /* Look at the cascade bucket(s)? */
  601. if (!index || slot < index)
  602. break;
  603. return expires;
  604. }
  605. slot = (slot + 1) & TVN_MASK;
  606. } while (slot != index);
  607. if (index)
  608. timer_jiffies += TVN_SIZE - index;
  609. timer_jiffies >>= TVN_BITS;
  610. }
  611. return expires;
  612. }
  613. /*
  614. * Check, if the next hrtimer event is before the next timer wheel
  615. * event:
  616. */
  617. static unsigned long cmp_next_hrtimer_event(unsigned long now,
  618. unsigned long expires)
  619. {
  620. ktime_t hr_delta = hrtimer_get_next_event();
  621. struct timespec tsdelta;
  622. if (hr_delta.tv64 == KTIME_MAX)
  623. return expires;
  624. if (hr_delta.tv64 <= TICK_NSEC)
  625. return now;
  626. tsdelta = ktime_to_timespec(hr_delta);
  627. now += timespec_to_jiffies(&tsdelta);
  628. if (time_before(now, expires))
  629. return now;
  630. return expires;
  631. }
  632. /**
  633. * next_timer_interrupt - return the jiffy of the next pending timer
  634. * @now: current time (in jiffies)
  635. */
  636. unsigned long get_next_timer_interrupt(unsigned long now)
  637. {
  638. tvec_base_t *base = __get_cpu_var(tvec_bases);
  639. unsigned long expires;
  640. spin_lock(&base->lock);
  641. expires = __next_timer_interrupt(base);
  642. spin_unlock(&base->lock);
  643. if (time_before_eq(expires, now))
  644. return now;
  645. return cmp_next_hrtimer_event(now, expires);
  646. }
  647. #ifdef CONFIG_NO_IDLE_HZ
  648. unsigned long next_timer_interrupt(void)
  649. {
  650. return get_next_timer_interrupt(jiffies);
  651. }
  652. #endif
  653. #endif
  654. /******************************************************************/
  655. /*
  656. * The current time
  657. * wall_to_monotonic is what we need to add to xtime (or xtime corrected
  658. * for sub jiffie times) to get to monotonic time. Monotonic is pegged
  659. * at zero at system boot time, so wall_to_monotonic will be negative,
  660. * however, we will ALWAYS keep the tv_nsec part positive so we can use
  661. * the usual normalization.
  662. */
  663. struct timespec xtime __attribute__ ((aligned (16)));
  664. struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
  665. EXPORT_SYMBOL(xtime);
  666. /* XXX - all of this timekeeping code should be later moved to time.c */
  667. #include <linux/clocksource.h>
  668. static struct clocksource *clock; /* pointer to current clocksource */
  669. #ifdef CONFIG_GENERIC_TIME
  670. /**
  671. * __get_nsec_offset - Returns nanoseconds since last call to periodic_hook
  672. *
  673. * private function, must hold xtime_lock lock when being
  674. * called. Returns the number of nanoseconds since the
  675. * last call to update_wall_time() (adjusted by NTP scaling)
  676. */
  677. static inline s64 __get_nsec_offset(void)
  678. {
  679. cycle_t cycle_now, cycle_delta;
  680. s64 ns_offset;
  681. /* read clocksource: */
  682. cycle_now = clocksource_read(clock);
  683. /* calculate the delta since the last update_wall_time: */
  684. cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
  685. /* convert to nanoseconds: */
  686. ns_offset = cyc2ns(clock, cycle_delta);
  687. return ns_offset;
  688. }
  689. /**
  690. * __get_realtime_clock_ts - Returns the time of day in a timespec
  691. * @ts: pointer to the timespec to be set
  692. *
  693. * Returns the time of day in a timespec. Used by
  694. * do_gettimeofday() and get_realtime_clock_ts().
  695. */
  696. static inline void __get_realtime_clock_ts(struct timespec *ts)
  697. {
  698. unsigned long seq;
  699. s64 nsecs;
  700. do {
  701. seq = read_seqbegin(&xtime_lock);
  702. *ts = xtime;
  703. nsecs = __get_nsec_offset();
  704. } while (read_seqretry(&xtime_lock, seq));
  705. timespec_add_ns(ts, nsecs);
  706. }
  707. /**
  708. * getnstimeofday - Returns the time of day in a timespec
  709. * @ts: pointer to the timespec to be set
  710. *
  711. * Returns the time of day in a timespec.
  712. */
  713. void getnstimeofday(struct timespec *ts)
  714. {
  715. __get_realtime_clock_ts(ts);
  716. }
  717. EXPORT_SYMBOL(getnstimeofday);
  718. /**
  719. * do_gettimeofday - Returns the time of day in a timeval
  720. * @tv: pointer to the timeval to be set
  721. *
  722. * NOTE: Users should be converted to using get_realtime_clock_ts()
  723. */
  724. void do_gettimeofday(struct timeval *tv)
  725. {
  726. struct timespec now;
  727. __get_realtime_clock_ts(&now);
  728. tv->tv_sec = now.tv_sec;
  729. tv->tv_usec = now.tv_nsec/1000;
  730. }
  731. EXPORT_SYMBOL(do_gettimeofday);
  732. /**
  733. * do_settimeofday - Sets the time of day
  734. * @tv: pointer to the timespec variable containing the new time
  735. *
  736. * Sets the time of day to the new time and update NTP and notify hrtimers
  737. */
  738. int do_settimeofday(struct timespec *tv)
  739. {
  740. unsigned long flags;
  741. time_t wtm_sec, sec = tv->tv_sec;
  742. long wtm_nsec, nsec = tv->tv_nsec;
  743. if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
  744. return -EINVAL;
  745. write_seqlock_irqsave(&xtime_lock, flags);
  746. nsec -= __get_nsec_offset();
  747. wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
  748. wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
  749. set_normalized_timespec(&xtime, sec, nsec);
  750. set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
  751. clock->error = 0;
  752. ntp_clear();
  753. write_sequnlock_irqrestore(&xtime_lock, flags);
  754. /* signal hrtimers about time change */
  755. clock_was_set();
  756. return 0;
  757. }
  758. EXPORT_SYMBOL(do_settimeofday);
  759. /**
  760. * change_clocksource - Swaps clocksources if a new one is available
  761. *
  762. * Accumulates current time interval and initializes new clocksource
  763. */
  764. static void change_clocksource(void)
  765. {
  766. struct clocksource *new;
  767. cycle_t now;
  768. u64 nsec;
  769. new = clocksource_get_next();
  770. if (clock == new)
  771. return;
  772. now = clocksource_read(new);
  773. nsec = __get_nsec_offset();
  774. timespec_add_ns(&xtime, nsec);
  775. clock = new;
  776. clock->cycle_last = now;
  777. clock->error = 0;
  778. clock->xtime_nsec = 0;
  779. clocksource_calculate_interval(clock, NTP_INTERVAL_LENGTH);
  780. tick_clock_notify();
  781. printk(KERN_INFO "Time: %s clocksource has been installed.\n",
  782. clock->name);
  783. }
  784. #else
  785. static inline void change_clocksource(void) { }
  786. #endif
  787. /**
  788. * timekeeping_is_continuous - check to see if timekeeping is free running
  789. */
  790. int timekeeping_is_continuous(void)
  791. {
  792. unsigned long seq;
  793. int ret;
  794. do {
  795. seq = read_seqbegin(&xtime_lock);
  796. ret = clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
  797. } while (read_seqretry(&xtime_lock, seq));
  798. return ret;
  799. }
  800. /**
  801. * read_persistent_clock - Return time in seconds from the persistent clock.
  802. *
  803. * Weak dummy function for arches that do not yet support it.
  804. * Returns seconds from epoch using the battery backed persistent clock.
  805. * Returns zero if unsupported.
  806. *
  807. * XXX - Do be sure to remove it once all arches implement it.
  808. */
  809. unsigned long __attribute__((weak)) read_persistent_clock(void)
  810. {
  811. return 0;
  812. }
  813. /*
  814. * timekeeping_init - Initializes the clocksource and common timekeeping values
  815. */
  816. void __init timekeeping_init(void)
  817. {
  818. unsigned long flags;
  819. unsigned long sec = read_persistent_clock();
  820. write_seqlock_irqsave(&xtime_lock, flags);
  821. ntp_clear();
  822. clock = clocksource_get_next();
  823. clocksource_calculate_interval(clock, NTP_INTERVAL_LENGTH);
  824. clock->cycle_last = clocksource_read(clock);
  825. xtime.tv_sec = sec;
  826. xtime.tv_nsec = 0;
  827. set_normalized_timespec(&wall_to_monotonic,
  828. -xtime.tv_sec, -xtime.tv_nsec);
  829. write_sequnlock_irqrestore(&xtime_lock, flags);
  830. }
  831. /* flag for if timekeeping is suspended */
  832. static int timekeeping_suspended;
  833. /* time in seconds when suspend began */
  834. static unsigned long timekeeping_suspend_time;
  835. /**
  836. * timekeeping_resume - Resumes the generic timekeeping subsystem.
  837. * @dev: unused
  838. *
  839. * This is for the generic clocksource timekeeping.
  840. * xtime/wall_to_monotonic/jiffies/etc are
  841. * still managed by arch specific suspend/resume code.
  842. */
  843. static int timekeeping_resume(struct sys_device *dev)
  844. {
  845. unsigned long flags;
  846. unsigned long now = read_persistent_clock();
  847. write_seqlock_irqsave(&xtime_lock, flags);
  848. if (now && (now > timekeeping_suspend_time)) {
  849. unsigned long sleep_length = now - timekeeping_suspend_time;
  850. xtime.tv_sec += sleep_length;
  851. wall_to_monotonic.tv_sec -= sleep_length;
  852. }
  853. /* re-base the last cycle value */
  854. clock->cycle_last = clocksource_read(clock);
  855. clock->error = 0;
  856. timekeeping_suspended = 0;
  857. write_sequnlock_irqrestore(&xtime_lock, flags);
  858. touch_softlockup_watchdog();
  859. /* Resume hrtimers */
  860. clock_was_set();
  861. return 0;
  862. }
  863. static int timekeeping_suspend(struct sys_device *dev, pm_message_t state)
  864. {
  865. unsigned long flags;
  866. write_seqlock_irqsave(&xtime_lock, flags);
  867. timekeeping_suspended = 1;
  868. timekeeping_suspend_time = read_persistent_clock();
  869. write_sequnlock_irqrestore(&xtime_lock, flags);
  870. return 0;
  871. }
  872. /* sysfs resume/suspend bits for timekeeping */
  873. static struct sysdev_class timekeeping_sysclass = {
  874. .resume = timekeeping_resume,
  875. .suspend = timekeeping_suspend,
  876. set_kset_name("timekeeping"),
  877. };
  878. static struct sys_device device_timer = {
  879. .id = 0,
  880. .cls = &timekeeping_sysclass,
  881. };
  882. static int __init timekeeping_init_device(void)
  883. {
  884. int error = sysdev_class_register(&timekeeping_sysclass);
  885. if (!error)
  886. error = sysdev_register(&device_timer);
  887. return error;
  888. }
  889. device_initcall(timekeeping_init_device);
  890. /*
  891. * If the error is already larger, we look ahead even further
  892. * to compensate for late or lost adjustments.
  893. */
  894. static __always_inline int clocksource_bigadjust(s64 error, s64 *interval,
  895. s64 *offset)
  896. {
  897. s64 tick_error, i;
  898. u32 look_ahead, adj;
  899. s32 error2, mult;
  900. /*
  901. * Use the current error value to determine how much to look ahead.
  902. * The larger the error the slower we adjust for it to avoid problems
  903. * with losing too many ticks, otherwise we would overadjust and
  904. * produce an even larger error. The smaller the adjustment the
  905. * faster we try to adjust for it, as lost ticks can do less harm
  906. * here. This is tuned so that an error of about 1 msec is adusted
  907. * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
  908. */
  909. error2 = clock->error >> (TICK_LENGTH_SHIFT + 22 - 2 * SHIFT_HZ);
  910. error2 = abs(error2);
  911. for (look_ahead = 0; error2 > 0; look_ahead++)
  912. error2 >>= 2;
  913. /*
  914. * Now calculate the error in (1 << look_ahead) ticks, but first
  915. * remove the single look ahead already included in the error.
  916. */
  917. tick_error = current_tick_length() >>
  918. (TICK_LENGTH_SHIFT - clock->shift + 1);
  919. tick_error -= clock->xtime_interval >> 1;
  920. error = ((error - tick_error) >> look_ahead) + tick_error;
  921. /* Finally calculate the adjustment shift value. */
  922. i = *interval;
  923. mult = 1;
  924. if (error < 0) {
  925. error = -error;
  926. *interval = -*interval;
  927. *offset = -*offset;
  928. mult = -1;
  929. }
  930. for (adj = 0; error > i; adj++)
  931. error >>= 1;
  932. *interval <<= adj;
  933. *offset <<= adj;
  934. return mult << adj;
  935. }
  936. /*
  937. * Adjust the multiplier to reduce the error value,
  938. * this is optimized for the most common adjustments of -1,0,1,
  939. * for other values we can do a bit more work.
  940. */
  941. static void clocksource_adjust(struct clocksource *clock, s64 offset)
  942. {
  943. s64 error, interval = clock->cycle_interval;
  944. int adj;
  945. error = clock->error >> (TICK_LENGTH_SHIFT - clock->shift - 1);
  946. if (error > interval) {
  947. error >>= 2;
  948. if (likely(error <= interval))
  949. adj = 1;
  950. else
  951. adj = clocksource_bigadjust(error, &interval, &offset);
  952. } else if (error < -interval) {
  953. error >>= 2;
  954. if (likely(error >= -interval)) {
  955. adj = -1;
  956. interval = -interval;
  957. offset = -offset;
  958. } else
  959. adj = clocksource_bigadjust(error, &interval, &offset);
  960. } else
  961. return;
  962. clock->mult += adj;
  963. clock->xtime_interval += interval;
  964. clock->xtime_nsec -= offset;
  965. clock->error -= (interval - offset) <<
  966. (TICK_LENGTH_SHIFT - clock->shift);
  967. }
  968. /**
  969. * update_wall_time - Uses the current clocksource to increment the wall time
  970. *
  971. * Called from the timer interrupt, must hold a write on xtime_lock.
  972. */
  973. static void update_wall_time(void)
  974. {
  975. cycle_t offset;
  976. /* Make sure we're fully resumed: */
  977. if (unlikely(timekeeping_suspended))
  978. return;
  979. #ifdef CONFIG_GENERIC_TIME
  980. offset = (clocksource_read(clock) - clock->cycle_last) & clock->mask;
  981. #else
  982. offset = clock->cycle_interval;
  983. #endif
  984. clock->xtime_nsec += (s64)xtime.tv_nsec << clock->shift;
  985. /* normally this loop will run just once, however in the
  986. * case of lost or late ticks, it will accumulate correctly.
  987. */
  988. while (offset >= clock->cycle_interval) {
  989. /* accumulate one interval */
  990. clock->xtime_nsec += clock->xtime_interval;
  991. clock->cycle_last += clock->cycle_interval;
  992. offset -= clock->cycle_interval;
  993. if (clock->xtime_nsec >= (u64)NSEC_PER_SEC << clock->shift) {
  994. clock->xtime_nsec -= (u64)NSEC_PER_SEC << clock->shift;
  995. xtime.tv_sec++;
  996. second_overflow();
  997. }
  998. /* interpolator bits */
  999. time_interpolator_update(clock->xtime_interval
  1000. >> clock->shift);
  1001. /* accumulate error between NTP and clock interval */
  1002. clock->error += current_tick_length();
  1003. clock->error -= clock->xtime_interval << (TICK_LENGTH_SHIFT - clock->shift);
  1004. }
  1005. /* correct the clock when NTP error is too big */
  1006. clocksource_adjust(clock, offset);
  1007. /* store full nanoseconds into xtime */
  1008. xtime.tv_nsec = (s64)clock->xtime_nsec >> clock->shift;
  1009. clock->xtime_nsec -= (s64)xtime.tv_nsec << clock->shift;
  1010. /* check to see if there is a new clocksource to use */
  1011. change_clocksource();
  1012. update_vsyscall(&xtime, clock);
  1013. }
  1014. /*
  1015. * Called from the timer interrupt handler to charge one tick to the current
  1016. * process. user_tick is 1 if the tick is user time, 0 for system.
  1017. */
  1018. void update_process_times(int user_tick)
  1019. {
  1020. struct task_struct *p = current;
  1021. int cpu = smp_processor_id();
  1022. /* Note: this timer irq context must be accounted for as well. */
  1023. if (user_tick)
  1024. account_user_time(p, jiffies_to_cputime(1));
  1025. else
  1026. account_system_time(p, HARDIRQ_OFFSET, jiffies_to_cputime(1));
  1027. run_local_timers();
  1028. if (rcu_pending(cpu))
  1029. rcu_check_callbacks(cpu, user_tick);
  1030. scheduler_tick();
  1031. run_posix_cpu_timers(p);
  1032. }
  1033. /*
  1034. * Nr of active tasks - counted in fixed-point numbers
  1035. */
  1036. static unsigned long count_active_tasks(void)
  1037. {
  1038. return nr_active() * FIXED_1;
  1039. }
  1040. /*
  1041. * Hmm.. Changed this, as the GNU make sources (load.c) seems to
  1042. * imply that avenrun[] is the standard name for this kind of thing.
  1043. * Nothing else seems to be standardized: the fractional size etc
  1044. * all seem to differ on different machines.
  1045. *
  1046. * Requires xtime_lock to access.
  1047. */
  1048. unsigned long avenrun[3];
  1049. EXPORT_SYMBOL(avenrun);
  1050. /*
  1051. * calc_load - given tick count, update the avenrun load estimates.
  1052. * This is called while holding a write_lock on xtime_lock.
  1053. */
  1054. static inline void calc_load(unsigned long ticks)
  1055. {
  1056. unsigned long active_tasks; /* fixed-point */
  1057. static int count = LOAD_FREQ;
  1058. count -= ticks;
  1059. if (unlikely(count < 0)) {
  1060. active_tasks = count_active_tasks();
  1061. do {
  1062. CALC_LOAD(avenrun[0], EXP_1, active_tasks);
  1063. CALC_LOAD(avenrun[1], EXP_5, active_tasks);
  1064. CALC_LOAD(avenrun[2], EXP_15, active_tasks);
  1065. count += LOAD_FREQ;
  1066. } while (count < 0);
  1067. }
  1068. }
  1069. /*
  1070. * This read-write spinlock protects us from races in SMP while
  1071. * playing with xtime and avenrun.
  1072. */
  1073. __attribute__((weak)) __cacheline_aligned_in_smp DEFINE_SEQLOCK(xtime_lock);
  1074. EXPORT_SYMBOL(xtime_lock);
  1075. /*
  1076. * This function runs timers and the timer-tq in bottom half context.
  1077. */
  1078. static void run_timer_softirq(struct softirq_action *h)
  1079. {
  1080. tvec_base_t *base = __get_cpu_var(tvec_bases);
  1081. hrtimer_run_queues();
  1082. if (time_after_eq(jiffies, base->timer_jiffies))
  1083. __run_timers(base);
  1084. }
  1085. /*
  1086. * Called by the local, per-CPU timer interrupt on SMP.
  1087. */
  1088. void run_local_timers(void)
  1089. {
  1090. raise_softirq(TIMER_SOFTIRQ);
  1091. softlockup_tick();
  1092. }
  1093. /*
  1094. * Called by the timer interrupt. xtime_lock must already be taken
  1095. * by the timer IRQ!
  1096. */
  1097. static inline void update_times(unsigned long ticks)
  1098. {
  1099. update_wall_time();
  1100. calc_load(ticks);
  1101. }
  1102. /*
  1103. * The 64-bit jiffies value is not atomic - you MUST NOT read it
  1104. * without sampling the sequence number in xtime_lock.
  1105. * jiffies is defined in the linker script...
  1106. */
  1107. void do_timer(unsigned long ticks)
  1108. {
  1109. jiffies_64 += ticks;
  1110. update_times(ticks);
  1111. }
  1112. #ifdef __ARCH_WANT_SYS_ALARM
  1113. /*
  1114. * For backwards compatibility? This can be done in libc so Alpha
  1115. * and all newer ports shouldn't need it.
  1116. */
  1117. asmlinkage unsigned long sys_alarm(unsigned int seconds)
  1118. {
  1119. return alarm_setitimer(seconds);
  1120. }
  1121. #endif
  1122. #ifndef __alpha__
  1123. /*
  1124. * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
  1125. * should be moved into arch/i386 instead?
  1126. */
  1127. /**
  1128. * sys_getpid - return the thread group id of the current process
  1129. *
  1130. * Note, despite the name, this returns the tgid not the pid. The tgid and
  1131. * the pid are identical unless CLONE_THREAD was specified on clone() in
  1132. * which case the tgid is the same in all threads of the same group.
  1133. *
  1134. * This is SMP safe as current->tgid does not change.
  1135. */
  1136. asmlinkage long sys_getpid(void)
  1137. {
  1138. return current->tgid;
  1139. }
  1140. /*
  1141. * Accessing ->real_parent is not SMP-safe, it could
  1142. * change from under us. However, we can use a stale
  1143. * value of ->real_parent under rcu_read_lock(), see
  1144. * release_task()->call_rcu(delayed_put_task_struct).
  1145. */
  1146. asmlinkage long sys_getppid(void)
  1147. {
  1148. int pid;
  1149. rcu_read_lock();
  1150. pid = rcu_dereference(current->real_parent)->tgid;
  1151. rcu_read_unlock();
  1152. return pid;
  1153. }
  1154. asmlinkage long sys_getuid(void)
  1155. {
  1156. /* Only we change this so SMP safe */
  1157. return current->uid;
  1158. }
  1159. asmlinkage long sys_geteuid(void)
  1160. {
  1161. /* Only we change this so SMP safe */
  1162. return current->euid;
  1163. }
  1164. asmlinkage long sys_getgid(void)
  1165. {
  1166. /* Only we change this so SMP safe */
  1167. return current->gid;
  1168. }
  1169. asmlinkage long sys_getegid(void)
  1170. {
  1171. /* Only we change this so SMP safe */
  1172. return current->egid;
  1173. }
  1174. #endif
  1175. static void process_timeout(unsigned long __data)
  1176. {
  1177. wake_up_process((struct task_struct *)__data);
  1178. }
  1179. /**
  1180. * schedule_timeout - sleep until timeout
  1181. * @timeout: timeout value in jiffies
  1182. *
  1183. * Make the current task sleep until @timeout jiffies have
  1184. * elapsed. The routine will return immediately unless
  1185. * the current task state has been set (see set_current_state()).
  1186. *
  1187. * You can set the task state as follows -
  1188. *
  1189. * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
  1190. * pass before the routine returns. The routine will return 0
  1191. *
  1192. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1193. * delivered to the current task. In this case the remaining time
  1194. * in jiffies will be returned, or 0 if the timer expired in time
  1195. *
  1196. * The current task state is guaranteed to be TASK_RUNNING when this
  1197. * routine returns.
  1198. *
  1199. * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
  1200. * the CPU away without a bound on the timeout. In this case the return
  1201. * value will be %MAX_SCHEDULE_TIMEOUT.
  1202. *
  1203. * In all cases the return value is guaranteed to be non-negative.
  1204. */
  1205. fastcall signed long __sched schedule_timeout(signed long timeout)
  1206. {
  1207. struct timer_list timer;
  1208. unsigned long expire;
  1209. switch (timeout)
  1210. {
  1211. case MAX_SCHEDULE_TIMEOUT:
  1212. /*
  1213. * These two special cases are useful to be comfortable
  1214. * in the caller. Nothing more. We could take
  1215. * MAX_SCHEDULE_TIMEOUT from one of the negative value
  1216. * but I' d like to return a valid offset (>=0) to allow
  1217. * the caller to do everything it want with the retval.
  1218. */
  1219. schedule();
  1220. goto out;
  1221. default:
  1222. /*
  1223. * Another bit of PARANOID. Note that the retval will be
  1224. * 0 since no piece of kernel is supposed to do a check
  1225. * for a negative retval of schedule_timeout() (since it
  1226. * should never happens anyway). You just have the printk()
  1227. * that will tell you if something is gone wrong and where.
  1228. */
  1229. if (timeout < 0) {
  1230. printk(KERN_ERR "schedule_timeout: wrong timeout "
  1231. "value %lx\n", timeout);
  1232. dump_stack();
  1233. current->state = TASK_RUNNING;
  1234. goto out;
  1235. }
  1236. }
  1237. expire = timeout + jiffies;
  1238. setup_timer(&timer, process_timeout, (unsigned long)current);
  1239. __mod_timer(&timer, expire);
  1240. schedule();
  1241. del_singleshot_timer_sync(&timer);
  1242. timeout = expire - jiffies;
  1243. out:
  1244. return timeout < 0 ? 0 : timeout;
  1245. }
  1246. EXPORT_SYMBOL(schedule_timeout);
  1247. /*
  1248. * We can use __set_current_state() here because schedule_timeout() calls
  1249. * schedule() unconditionally.
  1250. */
  1251. signed long __sched schedule_timeout_interruptible(signed long timeout)
  1252. {
  1253. __set_current_state(TASK_INTERRUPTIBLE);
  1254. return schedule_timeout(timeout);
  1255. }
  1256. EXPORT_SYMBOL(schedule_timeout_interruptible);
  1257. signed long __sched schedule_timeout_uninterruptible(signed long timeout)
  1258. {
  1259. __set_current_state(TASK_UNINTERRUPTIBLE);
  1260. return schedule_timeout(timeout);
  1261. }
  1262. EXPORT_SYMBOL(schedule_timeout_uninterruptible);
  1263. /* Thread ID - the internal kernel "pid" */
  1264. asmlinkage long sys_gettid(void)
  1265. {
  1266. return current->pid;
  1267. }
  1268. /**
  1269. * do_sysinfo - fill in sysinfo struct
  1270. * @info: pointer to buffer to fill
  1271. */
  1272. int do_sysinfo(struct sysinfo *info)
  1273. {
  1274. unsigned long mem_total, sav_total;
  1275. unsigned int mem_unit, bitcount;
  1276. unsigned long seq;
  1277. memset(info, 0, sizeof(struct sysinfo));
  1278. do {
  1279. struct timespec tp;
  1280. seq = read_seqbegin(&xtime_lock);
  1281. /*
  1282. * This is annoying. The below is the same thing
  1283. * posix_get_clock_monotonic() does, but it wants to
  1284. * take the lock which we want to cover the loads stuff
  1285. * too.
  1286. */
  1287. getnstimeofday(&tp);
  1288. tp.tv_sec += wall_to_monotonic.tv_sec;
  1289. tp.tv_nsec += wall_to_monotonic.tv_nsec;
  1290. if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
  1291. tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
  1292. tp.tv_sec++;
  1293. }
  1294. info->uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
  1295. info->loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
  1296. info->loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
  1297. info->loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
  1298. info->procs = nr_threads;
  1299. } while (read_seqretry(&xtime_lock, seq));
  1300. si_meminfo(info);
  1301. si_swapinfo(info);
  1302. /*
  1303. * If the sum of all the available memory (i.e. ram + swap)
  1304. * is less than can be stored in a 32 bit unsigned long then
  1305. * we can be binary compatible with 2.2.x kernels. If not,
  1306. * well, in that case 2.2.x was broken anyways...
  1307. *
  1308. * -Erik Andersen <andersee@debian.org>
  1309. */
  1310. mem_total = info->totalram + info->totalswap;
  1311. if (mem_total < info->totalram || mem_total < info->totalswap)
  1312. goto out;
  1313. bitcount = 0;
  1314. mem_unit = info->mem_unit;
  1315. while (mem_unit > 1) {
  1316. bitcount++;
  1317. mem_unit >>= 1;
  1318. sav_total = mem_total;
  1319. mem_total <<= 1;
  1320. if (mem_total < sav_total)
  1321. goto out;
  1322. }
  1323. /*
  1324. * If mem_total did not overflow, multiply all memory values by
  1325. * info->mem_unit and set it to 1. This leaves things compatible
  1326. * with 2.2.x, and also retains compatibility with earlier 2.4.x
  1327. * kernels...
  1328. */
  1329. info->mem_unit = 1;
  1330. info->totalram <<= bitcount;
  1331. info->freeram <<= bitcount;
  1332. info->sharedram <<= bitcount;
  1333. info->bufferram <<= bitcount;
  1334. info->totalswap <<= bitcount;
  1335. info->freeswap <<= bitcount;
  1336. info->totalhigh <<= bitcount;
  1337. info->freehigh <<= bitcount;
  1338. out:
  1339. return 0;
  1340. }
  1341. asmlinkage long sys_sysinfo(struct sysinfo __user *info)
  1342. {
  1343. struct sysinfo val;
  1344. do_sysinfo(&val);
  1345. if (copy_to_user(info, &val, sizeof(struct sysinfo)))
  1346. return -EFAULT;
  1347. return 0;
  1348. }
  1349. /*
  1350. * lockdep: we want to track each per-CPU base as a separate lock-class,
  1351. * but timer-bases are kmalloc()-ed, so we need to attach separate
  1352. * keys to them:
  1353. */
  1354. static struct lock_class_key base_lock_keys[NR_CPUS];
  1355. static int __devinit init_timers_cpu(int cpu)
  1356. {
  1357. int j;
  1358. tvec_base_t *base;
  1359. static char __devinitdata tvec_base_done[NR_CPUS];
  1360. if (!tvec_base_done[cpu]) {
  1361. static char boot_done;
  1362. if (boot_done) {
  1363. /*
  1364. * The APs use this path later in boot
  1365. */
  1366. base = kmalloc_node(sizeof(*base), GFP_KERNEL,
  1367. cpu_to_node(cpu));
  1368. if (!base)
  1369. return -ENOMEM;
  1370. memset(base, 0, sizeof(*base));
  1371. per_cpu(tvec_bases, cpu) = base;
  1372. } else {
  1373. /*
  1374. * This is for the boot CPU - we use compile-time
  1375. * static initialisation because per-cpu memory isn't
  1376. * ready yet and because the memory allocators are not
  1377. * initialised either.
  1378. */
  1379. boot_done = 1;
  1380. base = &boot_tvec_bases;
  1381. }
  1382. tvec_base_done[cpu] = 1;
  1383. } else {
  1384. base = per_cpu(tvec_bases, cpu);
  1385. }
  1386. spin_lock_init(&base->lock);
  1387. lockdep_set_class(&base->lock, base_lock_keys + cpu);
  1388. for (j = 0; j < TVN_SIZE; j++) {
  1389. INIT_LIST_HEAD(base->tv5.vec + j);
  1390. INIT_LIST_HEAD(base->tv4.vec + j);
  1391. INIT_LIST_HEAD(base->tv3.vec + j);
  1392. INIT_LIST_HEAD(base->tv2.vec + j);
  1393. }
  1394. for (j = 0; j < TVR_SIZE; j++)
  1395. INIT_LIST_HEAD(base->tv1.vec + j);
  1396. base->timer_jiffies = jiffies;
  1397. return 0;
  1398. }
  1399. #ifdef CONFIG_HOTPLUG_CPU
  1400. static void migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
  1401. {
  1402. struct timer_list *timer;
  1403. while (!list_empty(head)) {
  1404. timer = list_entry(head->next, struct timer_list, entry);
  1405. detach_timer(timer, 0);
  1406. timer->base = new_base;
  1407. internal_add_timer(new_base, timer);
  1408. }
  1409. }
  1410. static void __devinit migrate_timers(int cpu)
  1411. {
  1412. tvec_base_t *old_base;
  1413. tvec_base_t *new_base;
  1414. int i;
  1415. BUG_ON(cpu_online(cpu));
  1416. old_base = per_cpu(tvec_bases, cpu);
  1417. new_base = get_cpu_var(tvec_bases);
  1418. local_irq_disable();
  1419. spin_lock(&new_base->lock);
  1420. spin_lock(&old_base->lock);
  1421. BUG_ON(old_base->running_timer);
  1422. for (i = 0; i < TVR_SIZE; i++)
  1423. migrate_timer_list(new_base, old_base->tv1.vec + i);
  1424. for (i = 0; i < TVN_SIZE; i++) {
  1425. migrate_timer_list(new_base, old_base->tv2.vec + i);
  1426. migrate_timer_list(new_base, old_base->tv3.vec + i);
  1427. migrate_timer_list(new_base, old_base->tv4.vec + i);
  1428. migrate_timer_list(new_base, old_base->tv5.vec + i);
  1429. }
  1430. spin_unlock(&old_base->lock);
  1431. spin_unlock(&new_base->lock);
  1432. local_irq_enable();
  1433. put_cpu_var(tvec_bases);
  1434. }
  1435. #endif /* CONFIG_HOTPLUG_CPU */
  1436. static int __cpuinit timer_cpu_notify(struct notifier_block *self,
  1437. unsigned long action, void *hcpu)
  1438. {
  1439. long cpu = (long)hcpu;
  1440. switch(action) {
  1441. case CPU_UP_PREPARE:
  1442. if (init_timers_cpu(cpu) < 0)
  1443. return NOTIFY_BAD;
  1444. break;
  1445. #ifdef CONFIG_HOTPLUG_CPU
  1446. case CPU_DEAD:
  1447. migrate_timers(cpu);
  1448. break;
  1449. #endif
  1450. default:
  1451. break;
  1452. }
  1453. return NOTIFY_OK;
  1454. }
  1455. static struct notifier_block __cpuinitdata timers_nb = {
  1456. .notifier_call = timer_cpu_notify,
  1457. };
  1458. void __init init_timers(void)
  1459. {
  1460. int err = timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
  1461. (void *)(long)smp_processor_id());
  1462. init_timer_stats();
  1463. BUG_ON(err == NOTIFY_BAD);
  1464. register_cpu_notifier(&timers_nb);
  1465. open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
  1466. }
  1467. #ifdef CONFIG_TIME_INTERPOLATION
  1468. struct time_interpolator *time_interpolator __read_mostly;
  1469. static struct time_interpolator *time_interpolator_list __read_mostly;
  1470. static DEFINE_SPINLOCK(time_interpolator_lock);
  1471. static inline cycles_t time_interpolator_get_cycles(unsigned int src)
  1472. {
  1473. unsigned long (*x)(void);
  1474. switch (src)
  1475. {
  1476. case TIME_SOURCE_FUNCTION:
  1477. x = time_interpolator->addr;
  1478. return x();
  1479. case TIME_SOURCE_MMIO64 :
  1480. return readq_relaxed((void __iomem *)time_interpolator->addr);
  1481. case TIME_SOURCE_MMIO32 :
  1482. return readl_relaxed((void __iomem *)time_interpolator->addr);
  1483. default: return get_cycles();
  1484. }
  1485. }
  1486. static inline u64 time_interpolator_get_counter(int writelock)
  1487. {
  1488. unsigned int src = time_interpolator->source;
  1489. if (time_interpolator->jitter)
  1490. {
  1491. cycles_t lcycle;
  1492. cycles_t now;
  1493. do {
  1494. lcycle = time_interpolator->last_cycle;
  1495. now = time_interpolator_get_cycles(src);
  1496. if (lcycle && time_after(lcycle, now))
  1497. return lcycle;
  1498. /* When holding the xtime write lock, there's no need
  1499. * to add the overhead of the cmpxchg. Readers are
  1500. * force to retry until the write lock is released.
  1501. */
  1502. if (writelock) {
  1503. time_interpolator->last_cycle = now;
  1504. return now;
  1505. }
  1506. /* Keep track of the last timer value returned. The use of cmpxchg here
  1507. * will cause contention in an SMP environment.
  1508. */
  1509. } while (unlikely(cmpxchg(&time_interpolator->last_cycle, lcycle, now) != lcycle));
  1510. return now;
  1511. }
  1512. else
  1513. return time_interpolator_get_cycles(src);
  1514. }
  1515. void time_interpolator_reset(void)
  1516. {
  1517. time_interpolator->offset = 0;
  1518. time_interpolator->last_counter = time_interpolator_get_counter(1);
  1519. }
  1520. #define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
  1521. unsigned long time_interpolator_get_offset(void)
  1522. {
  1523. /* If we do not have a time interpolator set up then just return zero */
  1524. if (!time_interpolator)
  1525. return 0;
  1526. return time_interpolator->offset +
  1527. GET_TI_NSECS(time_interpolator_get_counter(0), time_interpolator);
  1528. }
  1529. #define INTERPOLATOR_ADJUST 65536
  1530. #define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
  1531. void time_interpolator_update(long delta_nsec)
  1532. {
  1533. u64 counter;
  1534. unsigned long offset;
  1535. /* If there is no time interpolator set up then do nothing */
  1536. if (!time_interpolator)
  1537. return;
  1538. /*
  1539. * The interpolator compensates for late ticks by accumulating the late
  1540. * time in time_interpolator->offset. A tick earlier than expected will
  1541. * lead to a reset of the offset and a corresponding jump of the clock
  1542. * forward. Again this only works if the interpolator clock is running
  1543. * slightly slower than the regular clock and the tuning logic insures
  1544. * that.
  1545. */
  1546. counter = time_interpolator_get_counter(1);
  1547. offset = time_interpolator->offset +
  1548. GET_TI_NSECS(counter, time_interpolator);
  1549. if (delta_nsec < 0 || (unsigned long) delta_nsec < offset)
  1550. time_interpolator->offset = offset - delta_nsec;
  1551. else {
  1552. time_interpolator->skips++;
  1553. time_interpolator->ns_skipped += delta_nsec - offset;
  1554. time_interpolator->offset = 0;
  1555. }
  1556. time_interpolator->last_counter = counter;
  1557. /* Tuning logic for time interpolator invoked every minute or so.
  1558. * Decrease interpolator clock speed if no skips occurred and an offset is carried.
  1559. * Increase interpolator clock speed if we skip too much time.
  1560. */
  1561. if (jiffies % INTERPOLATOR_ADJUST == 0)
  1562. {
  1563. if (time_interpolator->skips == 0 && time_interpolator->offset > tick_nsec)
  1564. time_interpolator->nsec_per_cyc--;
  1565. if (time_interpolator->ns_skipped > INTERPOLATOR_MAX_SKIP && time_interpolator->offset == 0)
  1566. time_interpolator->nsec_per_cyc++;
  1567. time_interpolator->skips = 0;
  1568. time_interpolator->ns_skipped = 0;
  1569. }
  1570. }
  1571. static inline int
  1572. is_better_time_interpolator(struct time_interpolator *new)
  1573. {
  1574. if (!time_interpolator)
  1575. return 1;
  1576. return new->frequency > 2*time_interpolator->frequency ||
  1577. (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
  1578. }
  1579. void
  1580. register_time_interpolator(struct time_interpolator *ti)
  1581. {
  1582. unsigned long flags;
  1583. /* Sanity check */
  1584. BUG_ON(ti->frequency == 0 || ti->mask == 0);
  1585. ti->nsec_per_cyc = ((u64)NSEC_PER_SEC << ti->shift) / ti->frequency;
  1586. spin_lock(&time_interpolator_lock);
  1587. write_seqlock_irqsave(&xtime_lock, flags);
  1588. if (is_better_time_interpolator(ti)) {
  1589. time_interpolator = ti;
  1590. time_interpolator_reset();
  1591. }
  1592. write_sequnlock_irqrestore(&xtime_lock, flags);
  1593. ti->next = time_interpolator_list;
  1594. time_interpolator_list = ti;
  1595. spin_unlock(&time_interpolator_lock);
  1596. }
  1597. void
  1598. unregister_time_interpolator(struct time_interpolator *ti)
  1599. {
  1600. struct time_interpolator *curr, **prev;
  1601. unsigned long flags;
  1602. spin_lock(&time_interpolator_lock);
  1603. prev = &time_interpolator_list;
  1604. for (curr = *prev; curr; curr = curr->next) {
  1605. if (curr == ti) {
  1606. *prev = curr->next;
  1607. break;
  1608. }
  1609. prev = &curr->next;
  1610. }
  1611. write_seqlock_irqsave(&xtime_lock, flags);
  1612. if (ti == time_interpolator) {
  1613. /* we lost the best time-interpolator: */
  1614. time_interpolator = NULL;
  1615. /* find the next-best interpolator */
  1616. for (curr = time_interpolator_list; curr; curr = curr->next)
  1617. if (is_better_time_interpolator(curr))
  1618. time_interpolator = curr;
  1619. time_interpolator_reset();
  1620. }
  1621. write_sequnlock_irqrestore(&xtime_lock, flags);
  1622. spin_unlock(&time_interpolator_lock);
  1623. }
  1624. #endif /* CONFIG_TIME_INTERPOLATION */
  1625. /**
  1626. * msleep - sleep safely even with waitqueue interruptions
  1627. * @msecs: Time in milliseconds to sleep for
  1628. */
  1629. void msleep(unsigned int msecs)
  1630. {
  1631. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1632. while (timeout)
  1633. timeout = schedule_timeout_uninterruptible(timeout);
  1634. }
  1635. EXPORT_SYMBOL(msleep);
  1636. /**
  1637. * msleep_interruptible - sleep waiting for signals
  1638. * @msecs: Time in milliseconds to sleep for
  1639. */
  1640. unsigned long msleep_interruptible(unsigned int msecs)
  1641. {
  1642. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1643. while (timeout && !signal_pending(current))
  1644. timeout = schedule_timeout_interruptible(timeout);
  1645. return jiffies_to_msecs(timeout);
  1646. }
  1647. EXPORT_SYMBOL(msleep_interruptible);