timer.c 49 KB

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