time.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. /*
  2. * Common time routines among all ppc machines.
  3. *
  4. * Written by Cort Dougan (cort@cs.nmt.edu) to merge
  5. * Paul Mackerras' version and mine for PReP and Pmac.
  6. * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
  7. * Converted for 64-bit by Mike Corrigan (mikejc@us.ibm.com)
  8. *
  9. * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
  10. * to make clock more stable (2.4.0-test5). The only thing
  11. * that this code assumes is that the timebases have been synchronized
  12. * by firmware on SMP and are never stopped (never do sleep
  13. * on SMP then, nap and doze are OK).
  14. *
  15. * Speeded up do_gettimeofday by getting rid of references to
  16. * xtime (which required locks for consistency). (mikejc@us.ibm.com)
  17. *
  18. * TODO (not necessarily in this file):
  19. * - improve precision and reproducibility of timebase frequency
  20. * measurement at boot time. (for iSeries, we calibrate the timebase
  21. * against the Titan chip's clock.)
  22. * - for astronomical applications: add a new function to get
  23. * non ambiguous timestamps even around leap seconds. This needs
  24. * a new timestamp format and a good name.
  25. *
  26. * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
  27. * "A Kernel Model for Precision Timekeeping" by Dave Mills
  28. *
  29. * This program is free software; you can redistribute it and/or
  30. * modify it under the terms of the GNU General Public License
  31. * as published by the Free Software Foundation; either version
  32. * 2 of the License, or (at your option) any later version.
  33. */
  34. #include <linux/errno.h>
  35. #include <linux/module.h>
  36. #include <linux/sched.h>
  37. #include <linux/kernel.h>
  38. #include <linux/param.h>
  39. #include <linux/string.h>
  40. #include <linux/mm.h>
  41. #include <linux/interrupt.h>
  42. #include <linux/timex.h>
  43. #include <linux/kernel_stat.h>
  44. #include <linux/time.h>
  45. #include <linux/init.h>
  46. #include <linux/profile.h>
  47. #include <linux/cpu.h>
  48. #include <linux/security.h>
  49. #include <linux/percpu.h>
  50. #include <linux/rtc.h>
  51. #include <linux/jiffies.h>
  52. #include <linux/posix-timers.h>
  53. #include <linux/irq.h>
  54. #include <asm/io.h>
  55. #include <asm/processor.h>
  56. #include <asm/nvram.h>
  57. #include <asm/cache.h>
  58. #include <asm/machdep.h>
  59. #include <asm/uaccess.h>
  60. #include <asm/time.h>
  61. #include <asm/prom.h>
  62. #include <asm/irq.h>
  63. #include <asm/div64.h>
  64. #include <asm/smp.h>
  65. #include <asm/vdso_datapage.h>
  66. #include <asm/firmware.h>
  67. #ifdef CONFIG_PPC_ISERIES
  68. #include <asm/iseries/it_lp_queue.h>
  69. #include <asm/iseries/hv_call_xm.h>
  70. #endif
  71. /* powerpc clocksource/clockevent code */
  72. #include <linux/clockchips.h>
  73. #include <linux/clocksource.h>
  74. static cycle_t rtc_read(void);
  75. static struct clocksource clocksource_rtc = {
  76. .name = "rtc",
  77. .rating = 400,
  78. .flags = CLOCK_SOURCE_IS_CONTINUOUS,
  79. .mask = CLOCKSOURCE_MASK(64),
  80. .shift = 22,
  81. .mult = 0, /* To be filled in */
  82. .read = rtc_read,
  83. };
  84. static cycle_t timebase_read(void);
  85. static struct clocksource clocksource_timebase = {
  86. .name = "timebase",
  87. .rating = 400,
  88. .flags = CLOCK_SOURCE_IS_CONTINUOUS,
  89. .mask = CLOCKSOURCE_MASK(64),
  90. .shift = 22,
  91. .mult = 0, /* To be filled in */
  92. .read = timebase_read,
  93. };
  94. #define DECREMENTER_MAX 0x7fffffff
  95. static int decrementer_set_next_event(unsigned long evt,
  96. struct clock_event_device *dev);
  97. static void decrementer_set_mode(enum clock_event_mode mode,
  98. struct clock_event_device *dev);
  99. static struct clock_event_device decrementer_clockevent = {
  100. .name = "decrementer",
  101. .rating = 200,
  102. .shift = 16,
  103. .mult = 0, /* To be filled in */
  104. .irq = 0,
  105. .set_next_event = decrementer_set_next_event,
  106. .set_mode = decrementer_set_mode,
  107. .features = CLOCK_EVT_FEAT_ONESHOT,
  108. };
  109. static DEFINE_PER_CPU(struct clock_event_device, decrementers);
  110. void init_decrementer_clockevent(void);
  111. static DEFINE_PER_CPU(u64, decrementer_next_tb);
  112. #ifdef CONFIG_PPC_ISERIES
  113. static unsigned long __initdata iSeries_recal_titan;
  114. static signed long __initdata iSeries_recal_tb;
  115. /* Forward declaration is only needed for iSereis compiles */
  116. void __init clocksource_init(void);
  117. #endif
  118. #define XSEC_PER_SEC (1024*1024)
  119. #ifdef CONFIG_PPC64
  120. #define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
  121. #else
  122. /* compute ((xsec << 12) * max) >> 32 */
  123. #define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
  124. #endif
  125. unsigned long tb_ticks_per_jiffy;
  126. unsigned long tb_ticks_per_usec = 100; /* sane default */
  127. EXPORT_SYMBOL(tb_ticks_per_usec);
  128. unsigned long tb_ticks_per_sec;
  129. EXPORT_SYMBOL(tb_ticks_per_sec); /* for cputime_t conversions */
  130. u64 tb_to_xs;
  131. unsigned tb_to_us;
  132. #define TICKLEN_SCALE TICK_LENGTH_SHIFT
  133. u64 last_tick_len; /* units are ns / 2^TICKLEN_SCALE */
  134. u64 ticklen_to_xs; /* 0.64 fraction */
  135. /* If last_tick_len corresponds to about 1/HZ seconds, then
  136. last_tick_len << TICKLEN_SHIFT will be about 2^63. */
  137. #define TICKLEN_SHIFT (63 - 30 - TICKLEN_SCALE + SHIFT_HZ)
  138. DEFINE_SPINLOCK(rtc_lock);
  139. EXPORT_SYMBOL_GPL(rtc_lock);
  140. static u64 tb_to_ns_scale __read_mostly;
  141. static unsigned tb_to_ns_shift __read_mostly;
  142. static unsigned long boot_tb __read_mostly;
  143. struct gettimeofday_struct do_gtod;
  144. extern struct timezone sys_tz;
  145. static long timezone_offset;
  146. unsigned long ppc_proc_freq;
  147. EXPORT_SYMBOL(ppc_proc_freq);
  148. unsigned long ppc_tb_freq;
  149. static u64 tb_last_jiffy __cacheline_aligned_in_smp;
  150. static DEFINE_PER_CPU(u64, last_jiffy);
  151. #ifdef CONFIG_VIRT_CPU_ACCOUNTING
  152. /*
  153. * Factors for converting from cputime_t (timebase ticks) to
  154. * jiffies, milliseconds, seconds, and clock_t (1/USER_HZ seconds).
  155. * These are all stored as 0.64 fixed-point binary fractions.
  156. */
  157. u64 __cputime_jiffies_factor;
  158. EXPORT_SYMBOL(__cputime_jiffies_factor);
  159. u64 __cputime_msec_factor;
  160. EXPORT_SYMBOL(__cputime_msec_factor);
  161. u64 __cputime_sec_factor;
  162. EXPORT_SYMBOL(__cputime_sec_factor);
  163. u64 __cputime_clockt_factor;
  164. EXPORT_SYMBOL(__cputime_clockt_factor);
  165. static void calc_cputime_factors(void)
  166. {
  167. struct div_result res;
  168. div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
  169. __cputime_jiffies_factor = res.result_low;
  170. div128_by_32(1000, 0, tb_ticks_per_sec, &res);
  171. __cputime_msec_factor = res.result_low;
  172. div128_by_32(1, 0, tb_ticks_per_sec, &res);
  173. __cputime_sec_factor = res.result_low;
  174. div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
  175. __cputime_clockt_factor = res.result_low;
  176. }
  177. /*
  178. * Read the PURR on systems that have it, otherwise the timebase.
  179. */
  180. static u64 read_purr(void)
  181. {
  182. if (cpu_has_feature(CPU_FTR_PURR))
  183. return mfspr(SPRN_PURR);
  184. return mftb();
  185. }
  186. /*
  187. * Read the SPURR on systems that have it, otherwise the purr
  188. */
  189. static u64 read_spurr(u64 purr)
  190. {
  191. if (cpu_has_feature(CPU_FTR_SPURR))
  192. return mfspr(SPRN_SPURR);
  193. return purr;
  194. }
  195. /*
  196. * Account time for a transition between system, hard irq
  197. * or soft irq state.
  198. */
  199. void account_system_vtime(struct task_struct *tsk)
  200. {
  201. u64 now, nowscaled, delta, deltascaled;
  202. unsigned long flags;
  203. local_irq_save(flags);
  204. now = read_purr();
  205. delta = now - get_paca()->startpurr;
  206. get_paca()->startpurr = now;
  207. nowscaled = read_spurr(now);
  208. deltascaled = nowscaled - get_paca()->startspurr;
  209. get_paca()->startspurr = nowscaled;
  210. if (!in_interrupt()) {
  211. /* deltascaled includes both user and system time.
  212. * Hence scale it based on the purr ratio to estimate
  213. * the system time */
  214. if (get_paca()->user_time)
  215. deltascaled = deltascaled * get_paca()->system_time /
  216. (get_paca()->system_time + get_paca()->user_time);
  217. delta += get_paca()->system_time;
  218. get_paca()->system_time = 0;
  219. }
  220. account_system_time(tsk, 0, delta);
  221. get_paca()->purrdelta = delta;
  222. account_system_time_scaled(tsk, deltascaled);
  223. get_paca()->spurrdelta = deltascaled;
  224. local_irq_restore(flags);
  225. }
  226. /*
  227. * Transfer the user and system times accumulated in the paca
  228. * by the exception entry and exit code to the generic process
  229. * user and system time records.
  230. * Must be called with interrupts disabled.
  231. */
  232. void account_process_tick(struct task_struct *tsk, int user_tick)
  233. {
  234. cputime_t utime, utimescaled;
  235. utime = get_paca()->user_time;
  236. get_paca()->user_time = 0;
  237. account_user_time(tsk, utime);
  238. /* Estimate the scaled utime by scaling the real utime based
  239. * on the last spurr to purr ratio */
  240. utimescaled = utime * get_paca()->spurrdelta / get_paca()->purrdelta;
  241. get_paca()->spurrdelta = get_paca()->purrdelta = 0;
  242. account_user_time_scaled(tsk, utimescaled);
  243. }
  244. /*
  245. * Stuff for accounting stolen time.
  246. */
  247. struct cpu_purr_data {
  248. int initialized; /* thread is running */
  249. u64 tb; /* last TB value read */
  250. u64 purr; /* last PURR value read */
  251. u64 spurr; /* last SPURR value read */
  252. };
  253. /*
  254. * Each entry in the cpu_purr_data array is manipulated only by its
  255. * "owner" cpu -- usually in the timer interrupt but also occasionally
  256. * in process context for cpu online. As long as cpus do not touch
  257. * each others' cpu_purr_data, disabling local interrupts is
  258. * sufficient to serialize accesses.
  259. */
  260. static DEFINE_PER_CPU(struct cpu_purr_data, cpu_purr_data);
  261. static void snapshot_tb_and_purr(void *data)
  262. {
  263. unsigned long flags;
  264. struct cpu_purr_data *p = &__get_cpu_var(cpu_purr_data);
  265. local_irq_save(flags);
  266. p->tb = get_tb_or_rtc();
  267. p->purr = mfspr(SPRN_PURR);
  268. wmb();
  269. p->initialized = 1;
  270. local_irq_restore(flags);
  271. }
  272. /*
  273. * Called during boot when all cpus have come up.
  274. */
  275. void snapshot_timebases(void)
  276. {
  277. if (!cpu_has_feature(CPU_FTR_PURR))
  278. return;
  279. on_each_cpu(snapshot_tb_and_purr, NULL, 0, 1);
  280. }
  281. /*
  282. * Must be called with interrupts disabled.
  283. */
  284. void calculate_steal_time(void)
  285. {
  286. u64 tb, purr;
  287. s64 stolen;
  288. struct cpu_purr_data *pme;
  289. if (!cpu_has_feature(CPU_FTR_PURR))
  290. return;
  291. pme = &per_cpu(cpu_purr_data, smp_processor_id());
  292. if (!pme->initialized)
  293. return; /* this can happen in early boot */
  294. tb = mftb();
  295. purr = mfspr(SPRN_PURR);
  296. stolen = (tb - pme->tb) - (purr - pme->purr);
  297. if (stolen > 0)
  298. account_steal_time(current, stolen);
  299. pme->tb = tb;
  300. pme->purr = purr;
  301. }
  302. #ifdef CONFIG_PPC_SPLPAR
  303. /*
  304. * Must be called before the cpu is added to the online map when
  305. * a cpu is being brought up at runtime.
  306. */
  307. static void snapshot_purr(void)
  308. {
  309. struct cpu_purr_data *pme;
  310. unsigned long flags;
  311. if (!cpu_has_feature(CPU_FTR_PURR))
  312. return;
  313. local_irq_save(flags);
  314. pme = &per_cpu(cpu_purr_data, smp_processor_id());
  315. pme->tb = mftb();
  316. pme->purr = mfspr(SPRN_PURR);
  317. pme->initialized = 1;
  318. local_irq_restore(flags);
  319. }
  320. #endif /* CONFIG_PPC_SPLPAR */
  321. #else /* ! CONFIG_VIRT_CPU_ACCOUNTING */
  322. #define calc_cputime_factors()
  323. #define calculate_steal_time() do { } while (0)
  324. #endif
  325. #if !(defined(CONFIG_VIRT_CPU_ACCOUNTING) && defined(CONFIG_PPC_SPLPAR))
  326. #define snapshot_purr() do { } while (0)
  327. #endif
  328. /*
  329. * Called when a cpu comes up after the system has finished booting,
  330. * i.e. as a result of a hotplug cpu action.
  331. */
  332. void snapshot_timebase(void)
  333. {
  334. __get_cpu_var(last_jiffy) = get_tb_or_rtc();
  335. snapshot_purr();
  336. }
  337. void __delay(unsigned long loops)
  338. {
  339. unsigned long start;
  340. int diff;
  341. if (__USE_RTC()) {
  342. start = get_rtcl();
  343. do {
  344. /* the RTCL register wraps at 1000000000 */
  345. diff = get_rtcl() - start;
  346. if (diff < 0)
  347. diff += 1000000000;
  348. } while (diff < loops);
  349. } else {
  350. start = get_tbl();
  351. while (get_tbl() - start < loops)
  352. HMT_low();
  353. HMT_medium();
  354. }
  355. }
  356. EXPORT_SYMBOL(__delay);
  357. void udelay(unsigned long usecs)
  358. {
  359. __delay(tb_ticks_per_usec * usecs);
  360. }
  361. EXPORT_SYMBOL(udelay);
  362. /*
  363. * There are two copies of tb_to_xs and stamp_xsec so that no
  364. * lock is needed to access and use these values in
  365. * do_gettimeofday. We alternate the copies and as long as a
  366. * reasonable time elapses between changes, there will never
  367. * be inconsistent values. ntpd has a minimum of one minute
  368. * between updates.
  369. */
  370. static inline void update_gtod(u64 new_tb_stamp, u64 new_stamp_xsec,
  371. u64 new_tb_to_xs)
  372. {
  373. unsigned temp_idx;
  374. struct gettimeofday_vars *temp_varp;
  375. temp_idx = (do_gtod.var_idx == 0);
  376. temp_varp = &do_gtod.vars[temp_idx];
  377. temp_varp->tb_to_xs = new_tb_to_xs;
  378. temp_varp->tb_orig_stamp = new_tb_stamp;
  379. temp_varp->stamp_xsec = new_stamp_xsec;
  380. smp_mb();
  381. do_gtod.varp = temp_varp;
  382. do_gtod.var_idx = temp_idx;
  383. /*
  384. * tb_update_count is used to allow the userspace gettimeofday code
  385. * to assure itself that it sees a consistent view of the tb_to_xs and
  386. * stamp_xsec variables. It reads the tb_update_count, then reads
  387. * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
  388. * the two values of tb_update_count match and are even then the
  389. * tb_to_xs and stamp_xsec values are consistent. If not, then it
  390. * loops back and reads them again until this criteria is met.
  391. * We expect the caller to have done the first increment of
  392. * vdso_data->tb_update_count already.
  393. */
  394. vdso_data->tb_orig_stamp = new_tb_stamp;
  395. vdso_data->stamp_xsec = new_stamp_xsec;
  396. vdso_data->tb_to_xs = new_tb_to_xs;
  397. vdso_data->wtom_clock_sec = wall_to_monotonic.tv_sec;
  398. vdso_data->wtom_clock_nsec = wall_to_monotonic.tv_nsec;
  399. smp_wmb();
  400. ++(vdso_data->tb_update_count);
  401. }
  402. #ifdef CONFIG_SMP
  403. unsigned long profile_pc(struct pt_regs *regs)
  404. {
  405. unsigned long pc = instruction_pointer(regs);
  406. if (in_lock_functions(pc))
  407. return regs->link;
  408. return pc;
  409. }
  410. EXPORT_SYMBOL(profile_pc);
  411. #endif
  412. #ifdef CONFIG_PPC_ISERIES
  413. /*
  414. * This function recalibrates the timebase based on the 49-bit time-of-day
  415. * value in the Titan chip. The Titan is much more accurate than the value
  416. * returned by the service processor for the timebase frequency.
  417. */
  418. static int __init iSeries_tb_recal(void)
  419. {
  420. struct div_result divres;
  421. unsigned long titan, tb;
  422. /* Make sure we only run on iSeries */
  423. if (!firmware_has_feature(FW_FEATURE_ISERIES))
  424. return -ENODEV;
  425. tb = get_tb();
  426. titan = HvCallXm_loadTod();
  427. if ( iSeries_recal_titan ) {
  428. unsigned long tb_ticks = tb - iSeries_recal_tb;
  429. unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
  430. unsigned long new_tb_ticks_per_sec = (tb_ticks * USEC_PER_SEC)/titan_usec;
  431. unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
  432. long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
  433. char sign = '+';
  434. /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
  435. new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
  436. if ( tick_diff < 0 ) {
  437. tick_diff = -tick_diff;
  438. sign = '-';
  439. }
  440. if ( tick_diff ) {
  441. if ( tick_diff < tb_ticks_per_jiffy/25 ) {
  442. printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
  443. new_tb_ticks_per_jiffy, sign, tick_diff );
  444. tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
  445. tb_ticks_per_sec = new_tb_ticks_per_sec;
  446. calc_cputime_factors();
  447. div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
  448. do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
  449. tb_to_xs = divres.result_low;
  450. do_gtod.varp->tb_to_xs = tb_to_xs;
  451. vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
  452. vdso_data->tb_to_xs = tb_to_xs;
  453. }
  454. else {
  455. printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
  456. " new tb_ticks_per_jiffy = %lu\n"
  457. " old tb_ticks_per_jiffy = %lu\n",
  458. new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
  459. }
  460. }
  461. }
  462. iSeries_recal_titan = titan;
  463. iSeries_recal_tb = tb;
  464. /* Called here as now we know accurate values for the timebase */
  465. clocksource_init();
  466. return 0;
  467. }
  468. late_initcall(iSeries_tb_recal);
  469. /* Called from platform early init */
  470. void __init iSeries_time_init_early(void)
  471. {
  472. iSeries_recal_tb = get_tb();
  473. iSeries_recal_titan = HvCallXm_loadTod();
  474. }
  475. #endif /* CONFIG_PPC_ISERIES */
  476. /*
  477. * For iSeries shared processors, we have to let the hypervisor
  478. * set the hardware decrementer. We set a virtual decrementer
  479. * in the lppaca and call the hypervisor if the virtual
  480. * decrementer is less than the current value in the hardware
  481. * decrementer. (almost always the new decrementer value will
  482. * be greater than the current hardware decementer so the hypervisor
  483. * call will not be needed)
  484. */
  485. /*
  486. * timer_interrupt - gets called when the decrementer overflows,
  487. * with interrupts disabled.
  488. */
  489. void timer_interrupt(struct pt_regs * regs)
  490. {
  491. struct pt_regs *old_regs;
  492. int cpu = smp_processor_id();
  493. struct clock_event_device *evt = &per_cpu(decrementers, cpu);
  494. u64 now;
  495. /* Ensure a positive value is written to the decrementer, or else
  496. * some CPUs will continuue to take decrementer exceptions */
  497. set_dec(DECREMENTER_MAX);
  498. #ifdef CONFIG_PPC32
  499. if (atomic_read(&ppc_n_lost_interrupts) != 0)
  500. do_IRQ(regs);
  501. #endif
  502. now = get_tb_or_rtc();
  503. if (now < per_cpu(decrementer_next_tb, cpu)) {
  504. /* not time for this event yet */
  505. now = per_cpu(decrementer_next_tb, cpu) - now;
  506. if (now <= DECREMENTER_MAX)
  507. set_dec((int)now);
  508. return;
  509. }
  510. old_regs = set_irq_regs(regs);
  511. irq_enter();
  512. calculate_steal_time();
  513. #ifdef CONFIG_PPC_ISERIES
  514. if (firmware_has_feature(FW_FEATURE_ISERIES))
  515. get_lppaca()->int_dword.fields.decr_int = 0;
  516. #endif
  517. if (evt->event_handler)
  518. evt->event_handler(evt);
  519. #ifdef CONFIG_PPC_ISERIES
  520. if (firmware_has_feature(FW_FEATURE_ISERIES) && hvlpevent_is_pending())
  521. process_hvlpevents();
  522. #endif
  523. #ifdef CONFIG_PPC64
  524. /* collect purr register values often, for accurate calculations */
  525. if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
  526. struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
  527. cu->current_tb = mfspr(SPRN_PURR);
  528. }
  529. #endif
  530. irq_exit();
  531. set_irq_regs(old_regs);
  532. }
  533. void wakeup_decrementer(void)
  534. {
  535. unsigned long ticks;
  536. /*
  537. * The timebase gets saved on sleep and restored on wakeup,
  538. * so all we need to do is to reset the decrementer.
  539. */
  540. ticks = tb_ticks_since(__get_cpu_var(last_jiffy));
  541. if (ticks < tb_ticks_per_jiffy)
  542. ticks = tb_ticks_per_jiffy - ticks;
  543. else
  544. ticks = 1;
  545. set_dec(ticks);
  546. }
  547. #ifdef CONFIG_SMP
  548. void __init smp_space_timers(unsigned int max_cpus)
  549. {
  550. int i;
  551. u64 previous_tb = per_cpu(last_jiffy, boot_cpuid);
  552. /* make sure tb > per_cpu(last_jiffy, cpu) for all cpus always */
  553. previous_tb -= tb_ticks_per_jiffy;
  554. for_each_possible_cpu(i) {
  555. if (i == boot_cpuid)
  556. continue;
  557. per_cpu(last_jiffy, i) = previous_tb;
  558. }
  559. }
  560. #endif
  561. /*
  562. * Scheduler clock - returns current time in nanosec units.
  563. *
  564. * Note: mulhdu(a, b) (multiply high double unsigned) returns
  565. * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
  566. * are 64-bit unsigned numbers.
  567. */
  568. unsigned long long sched_clock(void)
  569. {
  570. if (__USE_RTC())
  571. return get_rtc();
  572. return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
  573. }
  574. static int __init get_freq(char *name, int cells, unsigned long *val)
  575. {
  576. struct device_node *cpu;
  577. const unsigned int *fp;
  578. int found = 0;
  579. /* The cpu node should have timebase and clock frequency properties */
  580. cpu = of_find_node_by_type(NULL, "cpu");
  581. if (cpu) {
  582. fp = of_get_property(cpu, name, NULL);
  583. if (fp) {
  584. found = 1;
  585. *val = of_read_ulong(fp, cells);
  586. }
  587. of_node_put(cpu);
  588. }
  589. return found;
  590. }
  591. void __init generic_calibrate_decr(void)
  592. {
  593. ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
  594. if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
  595. !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
  596. printk(KERN_ERR "WARNING: Estimating decrementer frequency "
  597. "(not found)\n");
  598. }
  599. ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
  600. if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
  601. !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
  602. printk(KERN_ERR "WARNING: Estimating processor frequency "
  603. "(not found)\n");
  604. }
  605. #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
  606. /* Set the time base to zero */
  607. mtspr(SPRN_TBWL, 0);
  608. mtspr(SPRN_TBWU, 0);
  609. /* Clear any pending timer interrupts */
  610. mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
  611. /* Enable decrementer interrupt */
  612. mtspr(SPRN_TCR, TCR_DIE);
  613. #endif
  614. }
  615. int update_persistent_clock(struct timespec now)
  616. {
  617. struct rtc_time tm;
  618. if (!ppc_md.set_rtc_time)
  619. return 0;
  620. to_tm(now.tv_sec + 1 + timezone_offset, &tm);
  621. tm.tm_year -= 1900;
  622. tm.tm_mon -= 1;
  623. return ppc_md.set_rtc_time(&tm);
  624. }
  625. unsigned long read_persistent_clock(void)
  626. {
  627. struct rtc_time tm;
  628. static int first = 1;
  629. /* XXX this is a litle fragile but will work okay in the short term */
  630. if (first) {
  631. first = 0;
  632. if (ppc_md.time_init)
  633. timezone_offset = ppc_md.time_init();
  634. /* get_boot_time() isn't guaranteed to be safe to call late */
  635. if (ppc_md.get_boot_time)
  636. return ppc_md.get_boot_time() -timezone_offset;
  637. }
  638. if (!ppc_md.get_rtc_time)
  639. return 0;
  640. ppc_md.get_rtc_time(&tm);
  641. return mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
  642. tm.tm_hour, tm.tm_min, tm.tm_sec);
  643. }
  644. /* clocksource code */
  645. static cycle_t rtc_read(void)
  646. {
  647. return (cycle_t)get_rtc();
  648. }
  649. static cycle_t timebase_read(void)
  650. {
  651. return (cycle_t)get_tb();
  652. }
  653. void update_vsyscall(struct timespec *wall_time, struct clocksource *clock)
  654. {
  655. u64 t2x, stamp_xsec;
  656. if (clock != &clocksource_timebase)
  657. return;
  658. /* Make userspace gettimeofday spin until we're done. */
  659. ++vdso_data->tb_update_count;
  660. smp_mb();
  661. /* XXX this assumes clock->shift == 22 */
  662. /* 4611686018 ~= 2^(20+64-22) / 1e9 */
  663. t2x = (u64) clock->mult * 4611686018ULL;
  664. stamp_xsec = (u64) xtime.tv_nsec * XSEC_PER_SEC;
  665. do_div(stamp_xsec, 1000000000);
  666. stamp_xsec += (u64) xtime.tv_sec * XSEC_PER_SEC;
  667. update_gtod(clock->cycle_last, stamp_xsec, t2x);
  668. }
  669. void update_vsyscall_tz(void)
  670. {
  671. /* Make userspace gettimeofday spin until we're done. */
  672. ++vdso_data->tb_update_count;
  673. smp_mb();
  674. vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
  675. vdso_data->tz_dsttime = sys_tz.tz_dsttime;
  676. smp_mb();
  677. ++vdso_data->tb_update_count;
  678. }
  679. void __init clocksource_init(void)
  680. {
  681. struct clocksource *clock;
  682. if (__USE_RTC())
  683. clock = &clocksource_rtc;
  684. else
  685. clock = &clocksource_timebase;
  686. clock->mult = clocksource_hz2mult(tb_ticks_per_sec, clock->shift);
  687. if (clocksource_register(clock)) {
  688. printk(KERN_ERR "clocksource: %s is already registered\n",
  689. clock->name);
  690. return;
  691. }
  692. printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
  693. clock->name, clock->mult, clock->shift);
  694. }
  695. static int decrementer_set_next_event(unsigned long evt,
  696. struct clock_event_device *dev)
  697. {
  698. __get_cpu_var(decrementer_next_tb) = get_tb_or_rtc() + evt;
  699. set_dec(evt);
  700. return 0;
  701. }
  702. static void decrementer_set_mode(enum clock_event_mode mode,
  703. struct clock_event_device *dev)
  704. {
  705. if (mode != CLOCK_EVT_MODE_ONESHOT)
  706. decrementer_set_next_event(DECREMENTER_MAX, dev);
  707. }
  708. static void register_decrementer_clockevent(int cpu)
  709. {
  710. struct clock_event_device *dec = &per_cpu(decrementers, cpu);
  711. *dec = decrementer_clockevent;
  712. dec->cpumask = cpumask_of_cpu(cpu);
  713. printk(KERN_DEBUG "clockevent: %s mult[%lx] shift[%d] cpu[%d]\n",
  714. dec->name, dec->mult, dec->shift, cpu);
  715. clockevents_register_device(dec);
  716. }
  717. void init_decrementer_clockevent(void)
  718. {
  719. int cpu = smp_processor_id();
  720. decrementer_clockevent.mult = div_sc(ppc_tb_freq, NSEC_PER_SEC,
  721. decrementer_clockevent.shift);
  722. decrementer_clockevent.max_delta_ns =
  723. clockevent_delta2ns(DECREMENTER_MAX, &decrementer_clockevent);
  724. decrementer_clockevent.min_delta_ns =
  725. clockevent_delta2ns(2, &decrementer_clockevent);
  726. register_decrementer_clockevent(cpu);
  727. }
  728. void secondary_cpu_time_init(void)
  729. {
  730. /* FIME: Should make unrelatred change to move snapshot_timebase
  731. * call here ! */
  732. register_decrementer_clockevent(smp_processor_id());
  733. }
  734. /* This function is only called on the boot processor */
  735. void __init time_init(void)
  736. {
  737. unsigned long flags;
  738. struct div_result res;
  739. u64 scale, x;
  740. unsigned shift;
  741. if (__USE_RTC()) {
  742. /* 601 processor: dec counts down by 128 every 128ns */
  743. ppc_tb_freq = 1000000000;
  744. tb_last_jiffy = get_rtcl();
  745. } else {
  746. /* Normal PowerPC with timebase register */
  747. ppc_md.calibrate_decr();
  748. printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
  749. ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
  750. printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
  751. ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
  752. tb_last_jiffy = get_tb();
  753. }
  754. tb_ticks_per_jiffy = ppc_tb_freq / HZ;
  755. tb_ticks_per_sec = ppc_tb_freq;
  756. tb_ticks_per_usec = ppc_tb_freq / 1000000;
  757. tb_to_us = mulhwu_scale_factor(ppc_tb_freq, 1000000);
  758. calc_cputime_factors();
  759. /*
  760. * Calculate the length of each tick in ns. It will not be
  761. * exactly 1e9/HZ unless ppc_tb_freq is divisible by HZ.
  762. * We compute 1e9 * tb_ticks_per_jiffy / ppc_tb_freq,
  763. * rounded up.
  764. */
  765. x = (u64) NSEC_PER_SEC * tb_ticks_per_jiffy + ppc_tb_freq - 1;
  766. do_div(x, ppc_tb_freq);
  767. tick_nsec = x;
  768. last_tick_len = x << TICKLEN_SCALE;
  769. /*
  770. * Compute ticklen_to_xs, which is a factor which gets multiplied
  771. * by (last_tick_len << TICKLEN_SHIFT) to get a tb_to_xs value.
  772. * It is computed as:
  773. * ticklen_to_xs = 2^N / (tb_ticks_per_jiffy * 1e9)
  774. * where N = 64 + 20 - TICKLEN_SCALE - TICKLEN_SHIFT
  775. * which turns out to be N = 51 - SHIFT_HZ.
  776. * This gives the result as a 0.64 fixed-point fraction.
  777. * That value is reduced by an offset amounting to 1 xsec per
  778. * 2^31 timebase ticks to avoid problems with time going backwards
  779. * by 1 xsec when we do timer_recalc_offset due to losing the
  780. * fractional xsec. That offset is equal to ppc_tb_freq/2^51
  781. * since there are 2^20 xsec in a second.
  782. */
  783. div128_by_32((1ULL << 51) - ppc_tb_freq, 0,
  784. tb_ticks_per_jiffy << SHIFT_HZ, &res);
  785. div128_by_32(res.result_high, res.result_low, NSEC_PER_SEC, &res);
  786. ticklen_to_xs = res.result_low;
  787. /* Compute tb_to_xs from tick_nsec */
  788. tb_to_xs = mulhdu(last_tick_len << TICKLEN_SHIFT, ticklen_to_xs);
  789. /*
  790. * Compute scale factor for sched_clock.
  791. * The calibrate_decr() function has set tb_ticks_per_sec,
  792. * which is the timebase frequency.
  793. * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
  794. * the 128-bit result as a 64.64 fixed-point number.
  795. * We then shift that number right until it is less than 1.0,
  796. * giving us the scale factor and shift count to use in
  797. * sched_clock().
  798. */
  799. div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
  800. scale = res.result_low;
  801. for (shift = 0; res.result_high != 0; ++shift) {
  802. scale = (scale >> 1) | (res.result_high << 63);
  803. res.result_high >>= 1;
  804. }
  805. tb_to_ns_scale = scale;
  806. tb_to_ns_shift = shift;
  807. /* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
  808. boot_tb = get_tb_or_rtc();
  809. write_seqlock_irqsave(&xtime_lock, flags);
  810. /* If platform provided a timezone (pmac), we correct the time */
  811. if (timezone_offset) {
  812. sys_tz.tz_minuteswest = -timezone_offset / 60;
  813. sys_tz.tz_dsttime = 0;
  814. }
  815. do_gtod.varp = &do_gtod.vars[0];
  816. do_gtod.var_idx = 0;
  817. do_gtod.varp->tb_orig_stamp = tb_last_jiffy;
  818. __get_cpu_var(last_jiffy) = tb_last_jiffy;
  819. do_gtod.varp->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
  820. do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
  821. do_gtod.varp->tb_to_xs = tb_to_xs;
  822. do_gtod.tb_to_us = tb_to_us;
  823. vdso_data->tb_orig_stamp = tb_last_jiffy;
  824. vdso_data->tb_update_count = 0;
  825. vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
  826. vdso_data->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
  827. vdso_data->tb_to_xs = tb_to_xs;
  828. time_freq = 0;
  829. write_sequnlock_irqrestore(&xtime_lock, flags);
  830. /* Register the clocksource, if we're not running on iSeries */
  831. if (!firmware_has_feature(FW_FEATURE_ISERIES))
  832. clocksource_init();
  833. init_decrementer_clockevent();
  834. }
  835. #define FEBRUARY 2
  836. #define STARTOFTIME 1970
  837. #define SECDAY 86400L
  838. #define SECYR (SECDAY * 365)
  839. #define leapyear(year) ((year) % 4 == 0 && \
  840. ((year) % 100 != 0 || (year) % 400 == 0))
  841. #define days_in_year(a) (leapyear(a) ? 366 : 365)
  842. #define days_in_month(a) (month_days[(a) - 1])
  843. static int month_days[12] = {
  844. 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  845. };
  846. /*
  847. * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
  848. */
  849. void GregorianDay(struct rtc_time * tm)
  850. {
  851. int leapsToDate;
  852. int lastYear;
  853. int day;
  854. int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
  855. lastYear = tm->tm_year - 1;
  856. /*
  857. * Number of leap corrections to apply up to end of last year
  858. */
  859. leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
  860. /*
  861. * This year is a leap year if it is divisible by 4 except when it is
  862. * divisible by 100 unless it is divisible by 400
  863. *
  864. * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
  865. */
  866. day = tm->tm_mon > 2 && leapyear(tm->tm_year);
  867. day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
  868. tm->tm_mday;
  869. tm->tm_wday = day % 7;
  870. }
  871. void to_tm(int tim, struct rtc_time * tm)
  872. {
  873. register int i;
  874. register long hms, day;
  875. day = tim / SECDAY;
  876. hms = tim % SECDAY;
  877. /* Hours, minutes, seconds are easy */
  878. tm->tm_hour = hms / 3600;
  879. tm->tm_min = (hms % 3600) / 60;
  880. tm->tm_sec = (hms % 3600) % 60;
  881. /* Number of years in days */
  882. for (i = STARTOFTIME; day >= days_in_year(i); i++)
  883. day -= days_in_year(i);
  884. tm->tm_year = i;
  885. /* Number of months in days left */
  886. if (leapyear(tm->tm_year))
  887. days_in_month(FEBRUARY) = 29;
  888. for (i = 1; day >= days_in_month(i); i++)
  889. day -= days_in_month(i);
  890. days_in_month(FEBRUARY) = 28;
  891. tm->tm_mon = i;
  892. /* Days are what is left over (+1) from all that. */
  893. tm->tm_mday = day + 1;
  894. /*
  895. * Determine the day of week
  896. */
  897. GregorianDay(tm);
  898. }
  899. /* Auxiliary function to compute scaling factors */
  900. /* Actually the choice of a timebase running at 1/4 the of the bus
  901. * frequency giving resolution of a few tens of nanoseconds is quite nice.
  902. * It makes this computation very precise (27-28 bits typically) which
  903. * is optimistic considering the stability of most processor clock
  904. * oscillators and the precision with which the timebase frequency
  905. * is measured but does not harm.
  906. */
  907. unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale)
  908. {
  909. unsigned mlt=0, tmp, err;
  910. /* No concern for performance, it's done once: use a stupid
  911. * but safe and compact method to find the multiplier.
  912. */
  913. for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
  914. if (mulhwu(inscale, mlt|tmp) < outscale)
  915. mlt |= tmp;
  916. }
  917. /* We might still be off by 1 for the best approximation.
  918. * A side effect of this is that if outscale is too large
  919. * the returned value will be zero.
  920. * Many corner cases have been checked and seem to work,
  921. * some might have been forgotten in the test however.
  922. */
  923. err = inscale * (mlt+1);
  924. if (err <= inscale/2)
  925. mlt++;
  926. return mlt;
  927. }
  928. /*
  929. * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
  930. * result.
  931. */
  932. void div128_by_32(u64 dividend_high, u64 dividend_low,
  933. unsigned divisor, struct div_result *dr)
  934. {
  935. unsigned long a, b, c, d;
  936. unsigned long w, x, y, z;
  937. u64 ra, rb, rc;
  938. a = dividend_high >> 32;
  939. b = dividend_high & 0xffffffff;
  940. c = dividend_low >> 32;
  941. d = dividend_low & 0xffffffff;
  942. w = a / divisor;
  943. ra = ((u64)(a - (w * divisor)) << 32) + b;
  944. rb = ((u64) do_div(ra, divisor) << 32) + c;
  945. x = ra;
  946. rc = ((u64) do_div(rb, divisor) << 32) + d;
  947. y = rb;
  948. do_div(rc, divisor);
  949. z = rc;
  950. dr->result_high = ((u64)w << 32) + x;
  951. dr->result_low = ((u64)y << 32) + z;
  952. }