timer.c 50 KB

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