timer.c 49 KB

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