time.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  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. #ifdef CONFIG_PPC64
  67. #include <asm/firmware.h>
  68. #endif
  69. #ifdef CONFIG_PPC_ISERIES
  70. #include <asm/iseries/it_lp_queue.h>
  71. #include <asm/iseries/hv_call_xm.h>
  72. #endif
  73. #include <asm/smp.h>
  74. /* keep track of when we need to update the rtc */
  75. time_t last_rtc_update;
  76. #ifdef CONFIG_PPC_ISERIES
  77. static unsigned long __initdata iSeries_recal_titan;
  78. static signed long __initdata iSeries_recal_tb;
  79. #endif
  80. /* The decrementer counts down by 128 every 128ns on a 601. */
  81. #define DECREMENTER_COUNT_601 (1000000000 / HZ)
  82. #define XSEC_PER_SEC (1024*1024)
  83. #ifdef CONFIG_PPC64
  84. #define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
  85. #else
  86. /* compute ((xsec << 12) * max) >> 32 */
  87. #define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
  88. #endif
  89. unsigned long tb_ticks_per_jiffy;
  90. unsigned long tb_ticks_per_usec = 100; /* sane default */
  91. EXPORT_SYMBOL(tb_ticks_per_usec);
  92. unsigned long tb_ticks_per_sec;
  93. EXPORT_SYMBOL(tb_ticks_per_sec); /* for cputime_t conversions */
  94. u64 tb_to_xs;
  95. unsigned tb_to_us;
  96. #define TICKLEN_SCALE TICK_LENGTH_SHIFT
  97. u64 last_tick_len; /* units are ns / 2^TICKLEN_SCALE */
  98. u64 ticklen_to_xs; /* 0.64 fraction */
  99. /* If last_tick_len corresponds to about 1/HZ seconds, then
  100. last_tick_len << TICKLEN_SHIFT will be about 2^63. */
  101. #define TICKLEN_SHIFT (63 - 30 - TICKLEN_SCALE + SHIFT_HZ)
  102. DEFINE_SPINLOCK(rtc_lock);
  103. EXPORT_SYMBOL_GPL(rtc_lock);
  104. static u64 tb_to_ns_scale __read_mostly;
  105. static unsigned tb_to_ns_shift __read_mostly;
  106. static unsigned long boot_tb __read_mostly;
  107. struct gettimeofday_struct do_gtod;
  108. extern struct timezone sys_tz;
  109. static long timezone_offset;
  110. unsigned long ppc_proc_freq;
  111. EXPORT_SYMBOL(ppc_proc_freq);
  112. unsigned long ppc_tb_freq;
  113. static u64 tb_last_jiffy __cacheline_aligned_in_smp;
  114. static DEFINE_PER_CPU(u64, last_jiffy);
  115. #ifdef CONFIG_VIRT_CPU_ACCOUNTING
  116. /*
  117. * Factors for converting from cputime_t (timebase ticks) to
  118. * jiffies, milliseconds, seconds, and clock_t (1/USER_HZ seconds).
  119. * These are all stored as 0.64 fixed-point binary fractions.
  120. */
  121. u64 __cputime_jiffies_factor;
  122. EXPORT_SYMBOL(__cputime_jiffies_factor);
  123. u64 __cputime_msec_factor;
  124. EXPORT_SYMBOL(__cputime_msec_factor);
  125. u64 __cputime_sec_factor;
  126. EXPORT_SYMBOL(__cputime_sec_factor);
  127. u64 __cputime_clockt_factor;
  128. EXPORT_SYMBOL(__cputime_clockt_factor);
  129. static void calc_cputime_factors(void)
  130. {
  131. struct div_result res;
  132. div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
  133. __cputime_jiffies_factor = res.result_low;
  134. div128_by_32(1000, 0, tb_ticks_per_sec, &res);
  135. __cputime_msec_factor = res.result_low;
  136. div128_by_32(1, 0, tb_ticks_per_sec, &res);
  137. __cputime_sec_factor = res.result_low;
  138. div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
  139. __cputime_clockt_factor = res.result_low;
  140. }
  141. /*
  142. * Read the PURR on systems that have it, otherwise the timebase.
  143. */
  144. static u64 read_purr(void)
  145. {
  146. if (cpu_has_feature(CPU_FTR_PURR))
  147. return mfspr(SPRN_PURR);
  148. return mftb();
  149. }
  150. /*
  151. * Account time for a transition between system, hard irq
  152. * or soft irq state.
  153. */
  154. void account_system_vtime(struct task_struct *tsk)
  155. {
  156. u64 now, delta;
  157. unsigned long flags;
  158. local_irq_save(flags);
  159. now = read_purr();
  160. delta = now - get_paca()->startpurr;
  161. get_paca()->startpurr = now;
  162. if (!in_interrupt()) {
  163. delta += get_paca()->system_time;
  164. get_paca()->system_time = 0;
  165. }
  166. account_system_time(tsk, 0, delta);
  167. local_irq_restore(flags);
  168. }
  169. /*
  170. * Transfer the user and system times accumulated in the paca
  171. * by the exception entry and exit code to the generic process
  172. * user and system time records.
  173. * Must be called with interrupts disabled.
  174. */
  175. void account_process_vtime(struct task_struct *tsk)
  176. {
  177. cputime_t utime;
  178. utime = get_paca()->user_time;
  179. get_paca()->user_time = 0;
  180. account_user_time(tsk, utime);
  181. }
  182. static void account_process_time(struct pt_regs *regs)
  183. {
  184. int cpu = smp_processor_id();
  185. account_process_vtime(current);
  186. run_local_timers();
  187. if (rcu_pending(cpu))
  188. rcu_check_callbacks(cpu, user_mode(regs));
  189. scheduler_tick();
  190. run_posix_cpu_timers(current);
  191. }
  192. /*
  193. * Stuff for accounting stolen time.
  194. */
  195. struct cpu_purr_data {
  196. int initialized; /* thread is running */
  197. u64 tb; /* last TB value read */
  198. u64 purr; /* last PURR value read */
  199. };
  200. /*
  201. * Each entry in the cpu_purr_data array is manipulated only by its
  202. * "owner" cpu -- usually in the timer interrupt but also occasionally
  203. * in process context for cpu online. As long as cpus do not touch
  204. * each others' cpu_purr_data, disabling local interrupts is
  205. * sufficient to serialize accesses.
  206. */
  207. static DEFINE_PER_CPU(struct cpu_purr_data, cpu_purr_data);
  208. static void snapshot_tb_and_purr(void *data)
  209. {
  210. unsigned long flags;
  211. struct cpu_purr_data *p = &__get_cpu_var(cpu_purr_data);
  212. local_irq_save(flags);
  213. p->tb = mftb();
  214. p->purr = mfspr(SPRN_PURR);
  215. wmb();
  216. p->initialized = 1;
  217. local_irq_restore(flags);
  218. }
  219. /*
  220. * Called during boot when all cpus have come up.
  221. */
  222. void snapshot_timebases(void)
  223. {
  224. if (!cpu_has_feature(CPU_FTR_PURR))
  225. return;
  226. on_each_cpu(snapshot_tb_and_purr, NULL, 0, 1);
  227. }
  228. /*
  229. * Must be called with interrupts disabled.
  230. */
  231. void calculate_steal_time(void)
  232. {
  233. u64 tb, purr;
  234. s64 stolen;
  235. struct cpu_purr_data *pme;
  236. if (!cpu_has_feature(CPU_FTR_PURR))
  237. return;
  238. pme = &per_cpu(cpu_purr_data, smp_processor_id());
  239. if (!pme->initialized)
  240. return; /* this can happen in early boot */
  241. tb = mftb();
  242. purr = mfspr(SPRN_PURR);
  243. stolen = (tb - pme->tb) - (purr - pme->purr);
  244. if (stolen > 0)
  245. account_steal_time(current, stolen);
  246. pme->tb = tb;
  247. pme->purr = purr;
  248. }
  249. #ifdef CONFIG_PPC_SPLPAR
  250. /*
  251. * Must be called before the cpu is added to the online map when
  252. * a cpu is being brought up at runtime.
  253. */
  254. static void snapshot_purr(void)
  255. {
  256. struct cpu_purr_data *pme;
  257. unsigned long flags;
  258. if (!cpu_has_feature(CPU_FTR_PURR))
  259. return;
  260. local_irq_save(flags);
  261. pme = &per_cpu(cpu_purr_data, smp_processor_id());
  262. pme->tb = mftb();
  263. pme->purr = mfspr(SPRN_PURR);
  264. pme->initialized = 1;
  265. local_irq_restore(flags);
  266. }
  267. #endif /* CONFIG_PPC_SPLPAR */
  268. #else /* ! CONFIG_VIRT_CPU_ACCOUNTING */
  269. #define calc_cputime_factors()
  270. #define account_process_time(regs) update_process_times(user_mode(regs))
  271. #define calculate_steal_time() do { } while (0)
  272. #endif
  273. #if !(defined(CONFIG_VIRT_CPU_ACCOUNTING) && defined(CONFIG_PPC_SPLPAR))
  274. #define snapshot_purr() do { } while (0)
  275. #endif
  276. /*
  277. * Called when a cpu comes up after the system has finished booting,
  278. * i.e. as a result of a hotplug cpu action.
  279. */
  280. void snapshot_timebase(void)
  281. {
  282. __get_cpu_var(last_jiffy) = get_tb();
  283. snapshot_purr();
  284. }
  285. void __delay(unsigned long loops)
  286. {
  287. unsigned long start;
  288. int diff;
  289. if (__USE_RTC()) {
  290. start = get_rtcl();
  291. do {
  292. /* the RTCL register wraps at 1000000000 */
  293. diff = get_rtcl() - start;
  294. if (diff < 0)
  295. diff += 1000000000;
  296. } while (diff < loops);
  297. } else {
  298. start = get_tbl();
  299. while (get_tbl() - start < loops)
  300. HMT_low();
  301. HMT_medium();
  302. }
  303. }
  304. EXPORT_SYMBOL(__delay);
  305. void udelay(unsigned long usecs)
  306. {
  307. __delay(tb_ticks_per_usec * usecs);
  308. }
  309. EXPORT_SYMBOL(udelay);
  310. static __inline__ void timer_check_rtc(void)
  311. {
  312. /*
  313. * update the rtc when needed, this should be performed on the
  314. * right fraction of a second. Half or full second ?
  315. * Full second works on mk48t59 clocks, others need testing.
  316. * Note that this update is basically only used through
  317. * the adjtimex system calls. Setting the HW clock in
  318. * any other way is a /dev/rtc and userland business.
  319. * This is still wrong by -0.5/+1.5 jiffies because of the
  320. * timer interrupt resolution and possible delay, but here we
  321. * hit a quantization limit which can only be solved by higher
  322. * resolution timers and decoupling time management from timer
  323. * interrupts. This is also wrong on the clocks
  324. * which require being written at the half second boundary.
  325. * We should have an rtc call that only sets the minutes and
  326. * seconds like on Intel to avoid problems with non UTC clocks.
  327. */
  328. if (ppc_md.set_rtc_time && ntp_synced() &&
  329. xtime.tv_sec - last_rtc_update >= 659 &&
  330. abs((xtime.tv_nsec/1000) - (1000000-1000000/HZ)) < 500000/HZ) {
  331. struct rtc_time tm;
  332. to_tm(xtime.tv_sec + 1 + timezone_offset, &tm);
  333. tm.tm_year -= 1900;
  334. tm.tm_mon -= 1;
  335. if (ppc_md.set_rtc_time(&tm) == 0)
  336. last_rtc_update = xtime.tv_sec + 1;
  337. else
  338. /* Try again one minute later */
  339. last_rtc_update += 60;
  340. }
  341. }
  342. /*
  343. * This version of gettimeofday has microsecond resolution.
  344. */
  345. static inline void __do_gettimeofday(struct timeval *tv)
  346. {
  347. unsigned long sec, usec;
  348. u64 tb_ticks, xsec;
  349. struct gettimeofday_vars *temp_varp;
  350. u64 temp_tb_to_xs, temp_stamp_xsec;
  351. /*
  352. * These calculations are faster (gets rid of divides)
  353. * if done in units of 1/2^20 rather than microseconds.
  354. * The conversion to microseconds at the end is done
  355. * without a divide (and in fact, without a multiply)
  356. */
  357. temp_varp = do_gtod.varp;
  358. /* Sampling the time base must be done after loading
  359. * do_gtod.varp in order to avoid racing with update_gtod.
  360. */
  361. data_barrier(temp_varp);
  362. tb_ticks = get_tb() - temp_varp->tb_orig_stamp;
  363. temp_tb_to_xs = temp_varp->tb_to_xs;
  364. temp_stamp_xsec = temp_varp->stamp_xsec;
  365. xsec = temp_stamp_xsec + mulhdu(tb_ticks, temp_tb_to_xs);
  366. sec = xsec / XSEC_PER_SEC;
  367. usec = (unsigned long)xsec & (XSEC_PER_SEC - 1);
  368. usec = SCALE_XSEC(usec, 1000000);
  369. tv->tv_sec = sec;
  370. tv->tv_usec = usec;
  371. }
  372. void do_gettimeofday(struct timeval *tv)
  373. {
  374. if (__USE_RTC()) {
  375. /* do this the old way */
  376. unsigned long flags, seq;
  377. unsigned int sec, nsec, usec;
  378. do {
  379. seq = read_seqbegin_irqsave(&xtime_lock, flags);
  380. sec = xtime.tv_sec;
  381. nsec = xtime.tv_nsec + tb_ticks_since(tb_last_jiffy);
  382. } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
  383. usec = nsec / 1000;
  384. while (usec >= 1000000) {
  385. usec -= 1000000;
  386. ++sec;
  387. }
  388. tv->tv_sec = sec;
  389. tv->tv_usec = usec;
  390. return;
  391. }
  392. __do_gettimeofday(tv);
  393. }
  394. EXPORT_SYMBOL(do_gettimeofday);
  395. /*
  396. * There are two copies of tb_to_xs and stamp_xsec so that no
  397. * lock is needed to access and use these values in
  398. * do_gettimeofday. We alternate the copies and as long as a
  399. * reasonable time elapses between changes, there will never
  400. * be inconsistent values. ntpd has a minimum of one minute
  401. * between updates.
  402. */
  403. static inline void update_gtod(u64 new_tb_stamp, u64 new_stamp_xsec,
  404. u64 new_tb_to_xs)
  405. {
  406. unsigned temp_idx;
  407. struct gettimeofday_vars *temp_varp;
  408. temp_idx = (do_gtod.var_idx == 0);
  409. temp_varp = &do_gtod.vars[temp_idx];
  410. temp_varp->tb_to_xs = new_tb_to_xs;
  411. temp_varp->tb_orig_stamp = new_tb_stamp;
  412. temp_varp->stamp_xsec = new_stamp_xsec;
  413. smp_mb();
  414. do_gtod.varp = temp_varp;
  415. do_gtod.var_idx = temp_idx;
  416. /*
  417. * tb_update_count is used to allow the userspace gettimeofday code
  418. * to assure itself that it sees a consistent view of the tb_to_xs and
  419. * stamp_xsec variables. It reads the tb_update_count, then reads
  420. * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
  421. * the two values of tb_update_count match and are even then the
  422. * tb_to_xs and stamp_xsec values are consistent. If not, then it
  423. * loops back and reads them again until this criteria is met.
  424. * We expect the caller to have done the first increment of
  425. * vdso_data->tb_update_count already.
  426. */
  427. vdso_data->tb_orig_stamp = new_tb_stamp;
  428. vdso_data->stamp_xsec = new_stamp_xsec;
  429. vdso_data->tb_to_xs = new_tb_to_xs;
  430. vdso_data->wtom_clock_sec = wall_to_monotonic.tv_sec;
  431. vdso_data->wtom_clock_nsec = wall_to_monotonic.tv_nsec;
  432. smp_wmb();
  433. ++(vdso_data->tb_update_count);
  434. }
  435. /*
  436. * When the timebase - tb_orig_stamp gets too big, we do a manipulation
  437. * between tb_orig_stamp and stamp_xsec. The goal here is to keep the
  438. * difference tb - tb_orig_stamp small enough to always fit inside a
  439. * 32 bits number. This is a requirement of our fast 32 bits userland
  440. * implementation in the vdso. If we "miss" a call to this function
  441. * (interrupt latency, CPU locked in a spinlock, ...) and we end up
  442. * with a too big difference, then the vdso will fallback to calling
  443. * the syscall
  444. */
  445. static __inline__ void timer_recalc_offset(u64 cur_tb)
  446. {
  447. unsigned long offset;
  448. u64 new_stamp_xsec;
  449. u64 tlen, t2x;
  450. u64 tb, xsec_old, xsec_new;
  451. struct gettimeofday_vars *varp;
  452. if (__USE_RTC())
  453. return;
  454. tlen = current_tick_length();
  455. offset = cur_tb - do_gtod.varp->tb_orig_stamp;
  456. if (tlen == last_tick_len && offset < 0x80000000u)
  457. return;
  458. if (tlen != last_tick_len) {
  459. t2x = mulhdu(tlen << TICKLEN_SHIFT, ticklen_to_xs);
  460. last_tick_len = tlen;
  461. } else
  462. t2x = do_gtod.varp->tb_to_xs;
  463. new_stamp_xsec = (u64) xtime.tv_nsec * XSEC_PER_SEC;
  464. do_div(new_stamp_xsec, 1000000000);
  465. new_stamp_xsec += (u64) xtime.tv_sec * XSEC_PER_SEC;
  466. ++vdso_data->tb_update_count;
  467. smp_mb();
  468. /*
  469. * Make sure time doesn't go backwards for userspace gettimeofday.
  470. */
  471. tb = get_tb();
  472. varp = do_gtod.varp;
  473. xsec_old = mulhdu(tb - varp->tb_orig_stamp, varp->tb_to_xs)
  474. + varp->stamp_xsec;
  475. xsec_new = mulhdu(tb - cur_tb, t2x) + new_stamp_xsec;
  476. if (xsec_new < xsec_old)
  477. new_stamp_xsec += xsec_old - xsec_new;
  478. update_gtod(cur_tb, new_stamp_xsec, t2x);
  479. }
  480. #ifdef CONFIG_SMP
  481. unsigned long profile_pc(struct pt_regs *regs)
  482. {
  483. unsigned long pc = instruction_pointer(regs);
  484. if (in_lock_functions(pc))
  485. return regs->link;
  486. return pc;
  487. }
  488. EXPORT_SYMBOL(profile_pc);
  489. #endif
  490. #ifdef CONFIG_PPC_ISERIES
  491. /*
  492. * This function recalibrates the timebase based on the 49-bit time-of-day
  493. * value in the Titan chip. The Titan is much more accurate than the value
  494. * returned by the service processor for the timebase frequency.
  495. */
  496. static int __init iSeries_tb_recal(void)
  497. {
  498. struct div_result divres;
  499. unsigned long titan, tb;
  500. /* Make sure we only run on iSeries */
  501. if (!firmware_has_feature(FW_FEATURE_ISERIES))
  502. return -ENODEV;
  503. tb = get_tb();
  504. titan = HvCallXm_loadTod();
  505. if ( iSeries_recal_titan ) {
  506. unsigned long tb_ticks = tb - iSeries_recal_tb;
  507. unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
  508. unsigned long new_tb_ticks_per_sec = (tb_ticks * USEC_PER_SEC)/titan_usec;
  509. unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
  510. long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
  511. char sign = '+';
  512. /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
  513. new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
  514. if ( tick_diff < 0 ) {
  515. tick_diff = -tick_diff;
  516. sign = '-';
  517. }
  518. if ( tick_diff ) {
  519. if ( tick_diff < tb_ticks_per_jiffy/25 ) {
  520. printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
  521. new_tb_ticks_per_jiffy, sign, tick_diff );
  522. tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
  523. tb_ticks_per_sec = new_tb_ticks_per_sec;
  524. calc_cputime_factors();
  525. div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
  526. do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
  527. tb_to_xs = divres.result_low;
  528. do_gtod.varp->tb_to_xs = tb_to_xs;
  529. vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
  530. vdso_data->tb_to_xs = tb_to_xs;
  531. }
  532. else {
  533. printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
  534. " new tb_ticks_per_jiffy = %lu\n"
  535. " old tb_ticks_per_jiffy = %lu\n",
  536. new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
  537. }
  538. }
  539. }
  540. iSeries_recal_titan = titan;
  541. iSeries_recal_tb = tb;
  542. return 0;
  543. }
  544. late_initcall(iSeries_tb_recal);
  545. /* Called from platform early init */
  546. void __init iSeries_time_init_early(void)
  547. {
  548. iSeries_recal_tb = get_tb();
  549. iSeries_recal_titan = HvCallXm_loadTod();
  550. }
  551. #endif /* CONFIG_PPC_ISERIES */
  552. /*
  553. * For iSeries shared processors, we have to let the hypervisor
  554. * set the hardware decrementer. We set a virtual decrementer
  555. * in the lppaca and call the hypervisor if the virtual
  556. * decrementer is less than the current value in the hardware
  557. * decrementer. (almost always the new decrementer value will
  558. * be greater than the current hardware decementer so the hypervisor
  559. * call will not be needed)
  560. */
  561. /*
  562. * timer_interrupt - gets called when the decrementer overflows,
  563. * with interrupts disabled.
  564. */
  565. void timer_interrupt(struct pt_regs * regs)
  566. {
  567. struct pt_regs *old_regs;
  568. int next_dec;
  569. int cpu = smp_processor_id();
  570. unsigned long ticks;
  571. u64 tb_next_jiffy;
  572. #ifdef CONFIG_PPC32
  573. if (atomic_read(&ppc_n_lost_interrupts) != 0)
  574. do_IRQ(regs);
  575. #endif
  576. old_regs = set_irq_regs(regs);
  577. irq_enter();
  578. profile_tick(CPU_PROFILING);
  579. calculate_steal_time();
  580. #ifdef CONFIG_PPC_ISERIES
  581. if (firmware_has_feature(FW_FEATURE_ISERIES))
  582. get_lppaca()->int_dword.fields.decr_int = 0;
  583. #endif
  584. while ((ticks = tb_ticks_since(per_cpu(last_jiffy, cpu)))
  585. >= tb_ticks_per_jiffy) {
  586. /* Update last_jiffy */
  587. per_cpu(last_jiffy, cpu) += tb_ticks_per_jiffy;
  588. /* Handle RTCL overflow on 601 */
  589. if (__USE_RTC() && per_cpu(last_jiffy, cpu) >= 1000000000)
  590. per_cpu(last_jiffy, cpu) -= 1000000000;
  591. /*
  592. * We cannot disable the decrementer, so in the period
  593. * between this cpu's being marked offline in cpu_online_map
  594. * and calling stop-self, it is taking timer interrupts.
  595. * Avoid calling into the scheduler rebalancing code if this
  596. * is the case.
  597. */
  598. if (!cpu_is_offline(cpu))
  599. account_process_time(regs);
  600. /*
  601. * No need to check whether cpu is offline here; boot_cpuid
  602. * should have been fixed up by now.
  603. */
  604. if (cpu != boot_cpuid)
  605. continue;
  606. write_seqlock(&xtime_lock);
  607. tb_next_jiffy = tb_last_jiffy + tb_ticks_per_jiffy;
  608. if (per_cpu(last_jiffy, cpu) >= tb_next_jiffy) {
  609. tb_last_jiffy = tb_next_jiffy;
  610. do_timer(1);
  611. timer_recalc_offset(tb_last_jiffy);
  612. timer_check_rtc();
  613. }
  614. write_sequnlock(&xtime_lock);
  615. }
  616. next_dec = tb_ticks_per_jiffy - ticks;
  617. set_dec(next_dec);
  618. #ifdef CONFIG_PPC_ISERIES
  619. if (firmware_has_feature(FW_FEATURE_ISERIES) && hvlpevent_is_pending())
  620. process_hvlpevents();
  621. #endif
  622. #ifdef CONFIG_PPC64
  623. /* collect purr register values often, for accurate calculations */
  624. if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
  625. struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
  626. cu->current_tb = mfspr(SPRN_PURR);
  627. }
  628. #endif
  629. irq_exit();
  630. set_irq_regs(old_regs);
  631. }
  632. void wakeup_decrementer(void)
  633. {
  634. unsigned long ticks;
  635. /*
  636. * The timebase gets saved on sleep and restored on wakeup,
  637. * so all we need to do is to reset the decrementer.
  638. */
  639. ticks = tb_ticks_since(__get_cpu_var(last_jiffy));
  640. if (ticks < tb_ticks_per_jiffy)
  641. ticks = tb_ticks_per_jiffy - ticks;
  642. else
  643. ticks = 1;
  644. set_dec(ticks);
  645. }
  646. #ifdef CONFIG_SMP
  647. void __init smp_space_timers(unsigned int max_cpus)
  648. {
  649. int i;
  650. u64 previous_tb = per_cpu(last_jiffy, boot_cpuid);
  651. /* make sure tb > per_cpu(last_jiffy, cpu) for all cpus always */
  652. previous_tb -= tb_ticks_per_jiffy;
  653. for_each_possible_cpu(i) {
  654. if (i == boot_cpuid)
  655. continue;
  656. per_cpu(last_jiffy, i) = previous_tb;
  657. }
  658. }
  659. #endif
  660. /*
  661. * Scheduler clock - returns current time in nanosec units.
  662. *
  663. * Note: mulhdu(a, b) (multiply high double unsigned) returns
  664. * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
  665. * are 64-bit unsigned numbers.
  666. */
  667. unsigned long long sched_clock(void)
  668. {
  669. if (__USE_RTC())
  670. return get_rtc();
  671. return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
  672. }
  673. int do_settimeofday(struct timespec *tv)
  674. {
  675. time_t wtm_sec, new_sec = tv->tv_sec;
  676. long wtm_nsec, new_nsec = tv->tv_nsec;
  677. unsigned long flags;
  678. u64 new_xsec;
  679. unsigned long tb_delta;
  680. if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
  681. return -EINVAL;
  682. write_seqlock_irqsave(&xtime_lock, flags);
  683. /*
  684. * Updating the RTC is not the job of this code. If the time is
  685. * stepped under NTP, the RTC will be updated after STA_UNSYNC
  686. * is cleared. Tools like clock/hwclock either copy the RTC
  687. * to the system time, in which case there is no point in writing
  688. * to the RTC again, or write to the RTC but then they don't call
  689. * settimeofday to perform this operation.
  690. */
  691. /* Make userspace gettimeofday spin until we're done. */
  692. ++vdso_data->tb_update_count;
  693. smp_mb();
  694. /*
  695. * Subtract off the number of nanoseconds since the
  696. * beginning of the last tick.
  697. */
  698. tb_delta = tb_ticks_since(tb_last_jiffy);
  699. tb_delta = mulhdu(tb_delta, do_gtod.varp->tb_to_xs); /* in xsec */
  700. new_nsec -= SCALE_XSEC(tb_delta, 1000000000);
  701. wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
  702. wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
  703. set_normalized_timespec(&xtime, new_sec, new_nsec);
  704. set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
  705. /* In case of a large backwards jump in time with NTP, we want the
  706. * clock to be updated as soon as the PLL is again in lock.
  707. */
  708. last_rtc_update = new_sec - 658;
  709. ntp_clear();
  710. new_xsec = xtime.tv_nsec;
  711. if (new_xsec != 0) {
  712. new_xsec *= XSEC_PER_SEC;
  713. do_div(new_xsec, NSEC_PER_SEC);
  714. }
  715. new_xsec += (u64)xtime.tv_sec * XSEC_PER_SEC;
  716. update_gtod(tb_last_jiffy, new_xsec, do_gtod.varp->tb_to_xs);
  717. vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
  718. vdso_data->tz_dsttime = sys_tz.tz_dsttime;
  719. write_sequnlock_irqrestore(&xtime_lock, flags);
  720. clock_was_set();
  721. return 0;
  722. }
  723. EXPORT_SYMBOL(do_settimeofday);
  724. static int __init get_freq(char *name, int cells, unsigned long *val)
  725. {
  726. struct device_node *cpu;
  727. const unsigned int *fp;
  728. int found = 0;
  729. /* The cpu node should have timebase and clock frequency properties */
  730. cpu = of_find_node_by_type(NULL, "cpu");
  731. if (cpu) {
  732. fp = of_get_property(cpu, name, NULL);
  733. if (fp) {
  734. found = 1;
  735. *val = of_read_ulong(fp, cells);
  736. }
  737. of_node_put(cpu);
  738. }
  739. return found;
  740. }
  741. void __init generic_calibrate_decr(void)
  742. {
  743. ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
  744. if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
  745. !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
  746. printk(KERN_ERR "WARNING: Estimating decrementer frequency "
  747. "(not found)\n");
  748. }
  749. ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
  750. if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
  751. !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
  752. printk(KERN_ERR "WARNING: Estimating processor frequency "
  753. "(not found)\n");
  754. }
  755. #ifdef CONFIG_BOOKE
  756. /* Set the time base to zero */
  757. mtspr(SPRN_TBWL, 0);
  758. mtspr(SPRN_TBWU, 0);
  759. /* Clear any pending timer interrupts */
  760. mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
  761. /* Enable decrementer interrupt */
  762. mtspr(SPRN_TCR, TCR_DIE);
  763. #endif
  764. }
  765. unsigned long get_boot_time(void)
  766. {
  767. struct rtc_time tm;
  768. if (ppc_md.get_boot_time)
  769. return ppc_md.get_boot_time();
  770. if (!ppc_md.get_rtc_time)
  771. return 0;
  772. ppc_md.get_rtc_time(&tm);
  773. return mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
  774. tm.tm_hour, tm.tm_min, tm.tm_sec);
  775. }
  776. /* This function is only called on the boot processor */
  777. void __init time_init(void)
  778. {
  779. unsigned long flags;
  780. unsigned long tm = 0;
  781. struct div_result res;
  782. u64 scale, x;
  783. unsigned shift;
  784. if (ppc_md.time_init != NULL)
  785. timezone_offset = ppc_md.time_init();
  786. if (__USE_RTC()) {
  787. /* 601 processor: dec counts down by 128 every 128ns */
  788. ppc_tb_freq = 1000000000;
  789. tb_last_jiffy = get_rtcl();
  790. } else {
  791. /* Normal PowerPC with timebase register */
  792. ppc_md.calibrate_decr();
  793. printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
  794. ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
  795. printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
  796. ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
  797. tb_last_jiffy = get_tb();
  798. }
  799. tb_ticks_per_jiffy = ppc_tb_freq / HZ;
  800. tb_ticks_per_sec = ppc_tb_freq;
  801. tb_ticks_per_usec = ppc_tb_freq / 1000000;
  802. tb_to_us = mulhwu_scale_factor(ppc_tb_freq, 1000000);
  803. calc_cputime_factors();
  804. /*
  805. * Calculate the length of each tick in ns. It will not be
  806. * exactly 1e9/HZ unless ppc_tb_freq is divisible by HZ.
  807. * We compute 1e9 * tb_ticks_per_jiffy / ppc_tb_freq,
  808. * rounded up.
  809. */
  810. x = (u64) NSEC_PER_SEC * tb_ticks_per_jiffy + ppc_tb_freq - 1;
  811. do_div(x, ppc_tb_freq);
  812. tick_nsec = x;
  813. last_tick_len = x << TICKLEN_SCALE;
  814. /*
  815. * Compute ticklen_to_xs, which is a factor which gets multiplied
  816. * by (last_tick_len << TICKLEN_SHIFT) to get a tb_to_xs value.
  817. * It is computed as:
  818. * ticklen_to_xs = 2^N / (tb_ticks_per_jiffy * 1e9)
  819. * where N = 64 + 20 - TICKLEN_SCALE - TICKLEN_SHIFT
  820. * which turns out to be N = 51 - SHIFT_HZ.
  821. * This gives the result as a 0.64 fixed-point fraction.
  822. * That value is reduced by an offset amounting to 1 xsec per
  823. * 2^31 timebase ticks to avoid problems with time going backwards
  824. * by 1 xsec when we do timer_recalc_offset due to losing the
  825. * fractional xsec. That offset is equal to ppc_tb_freq/2^51
  826. * since there are 2^20 xsec in a second.
  827. */
  828. div128_by_32((1ULL << 51) - ppc_tb_freq, 0,
  829. tb_ticks_per_jiffy << SHIFT_HZ, &res);
  830. div128_by_32(res.result_high, res.result_low, NSEC_PER_SEC, &res);
  831. ticklen_to_xs = res.result_low;
  832. /* Compute tb_to_xs from tick_nsec */
  833. tb_to_xs = mulhdu(last_tick_len << TICKLEN_SHIFT, ticklen_to_xs);
  834. /*
  835. * Compute scale factor for sched_clock.
  836. * The calibrate_decr() function has set tb_ticks_per_sec,
  837. * which is the timebase frequency.
  838. * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
  839. * the 128-bit result as a 64.64 fixed-point number.
  840. * We then shift that number right until it is less than 1.0,
  841. * giving us the scale factor and shift count to use in
  842. * sched_clock().
  843. */
  844. div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
  845. scale = res.result_low;
  846. for (shift = 0; res.result_high != 0; ++shift) {
  847. scale = (scale >> 1) | (res.result_high << 63);
  848. res.result_high >>= 1;
  849. }
  850. tb_to_ns_scale = scale;
  851. tb_to_ns_shift = shift;
  852. /* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
  853. boot_tb = get_tb();
  854. tm = get_boot_time();
  855. write_seqlock_irqsave(&xtime_lock, flags);
  856. /* If platform provided a timezone (pmac), we correct the time */
  857. if (timezone_offset) {
  858. sys_tz.tz_minuteswest = -timezone_offset / 60;
  859. sys_tz.tz_dsttime = 0;
  860. tm -= timezone_offset;
  861. }
  862. xtime.tv_sec = tm;
  863. xtime.tv_nsec = 0;
  864. do_gtod.varp = &do_gtod.vars[0];
  865. do_gtod.var_idx = 0;
  866. do_gtod.varp->tb_orig_stamp = tb_last_jiffy;
  867. __get_cpu_var(last_jiffy) = tb_last_jiffy;
  868. do_gtod.varp->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
  869. do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
  870. do_gtod.varp->tb_to_xs = tb_to_xs;
  871. do_gtod.tb_to_us = tb_to_us;
  872. vdso_data->tb_orig_stamp = tb_last_jiffy;
  873. vdso_data->tb_update_count = 0;
  874. vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
  875. vdso_data->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
  876. vdso_data->tb_to_xs = tb_to_xs;
  877. time_freq = 0;
  878. last_rtc_update = xtime.tv_sec;
  879. set_normalized_timespec(&wall_to_monotonic,
  880. -xtime.tv_sec, -xtime.tv_nsec);
  881. write_sequnlock_irqrestore(&xtime_lock, flags);
  882. /* Not exact, but the timer interrupt takes care of this */
  883. set_dec(tb_ticks_per_jiffy);
  884. }
  885. #define FEBRUARY 2
  886. #define STARTOFTIME 1970
  887. #define SECDAY 86400L
  888. #define SECYR (SECDAY * 365)
  889. #define leapyear(year) ((year) % 4 == 0 && \
  890. ((year) % 100 != 0 || (year) % 400 == 0))
  891. #define days_in_year(a) (leapyear(a) ? 366 : 365)
  892. #define days_in_month(a) (month_days[(a) - 1])
  893. static int month_days[12] = {
  894. 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  895. };
  896. /*
  897. * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
  898. */
  899. void GregorianDay(struct rtc_time * tm)
  900. {
  901. int leapsToDate;
  902. int lastYear;
  903. int day;
  904. int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
  905. lastYear = tm->tm_year - 1;
  906. /*
  907. * Number of leap corrections to apply up to end of last year
  908. */
  909. leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
  910. /*
  911. * This year is a leap year if it is divisible by 4 except when it is
  912. * divisible by 100 unless it is divisible by 400
  913. *
  914. * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
  915. */
  916. day = tm->tm_mon > 2 && leapyear(tm->tm_year);
  917. day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
  918. tm->tm_mday;
  919. tm->tm_wday = day % 7;
  920. }
  921. void to_tm(int tim, struct rtc_time * tm)
  922. {
  923. register int i;
  924. register long hms, day;
  925. day = tim / SECDAY;
  926. hms = tim % SECDAY;
  927. /* Hours, minutes, seconds are easy */
  928. tm->tm_hour = hms / 3600;
  929. tm->tm_min = (hms % 3600) / 60;
  930. tm->tm_sec = (hms % 3600) % 60;
  931. /* Number of years in days */
  932. for (i = STARTOFTIME; day >= days_in_year(i); i++)
  933. day -= days_in_year(i);
  934. tm->tm_year = i;
  935. /* Number of months in days left */
  936. if (leapyear(tm->tm_year))
  937. days_in_month(FEBRUARY) = 29;
  938. for (i = 1; day >= days_in_month(i); i++)
  939. day -= days_in_month(i);
  940. days_in_month(FEBRUARY) = 28;
  941. tm->tm_mon = i;
  942. /* Days are what is left over (+1) from all that. */
  943. tm->tm_mday = day + 1;
  944. /*
  945. * Determine the day of week
  946. */
  947. GregorianDay(tm);
  948. }
  949. /* Auxiliary function to compute scaling factors */
  950. /* Actually the choice of a timebase running at 1/4 the of the bus
  951. * frequency giving resolution of a few tens of nanoseconds is quite nice.
  952. * It makes this computation very precise (27-28 bits typically) which
  953. * is optimistic considering the stability of most processor clock
  954. * oscillators and the precision with which the timebase frequency
  955. * is measured but does not harm.
  956. */
  957. unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale)
  958. {
  959. unsigned mlt=0, tmp, err;
  960. /* No concern for performance, it's done once: use a stupid
  961. * but safe and compact method to find the multiplier.
  962. */
  963. for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
  964. if (mulhwu(inscale, mlt|tmp) < outscale)
  965. mlt |= tmp;
  966. }
  967. /* We might still be off by 1 for the best approximation.
  968. * A side effect of this is that if outscale is too large
  969. * the returned value will be zero.
  970. * Many corner cases have been checked and seem to work,
  971. * some might have been forgotten in the test however.
  972. */
  973. err = inscale * (mlt+1);
  974. if (err <= inscale/2)
  975. mlt++;
  976. return mlt;
  977. }
  978. /*
  979. * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
  980. * result.
  981. */
  982. void div128_by_32(u64 dividend_high, u64 dividend_low,
  983. unsigned divisor, struct div_result *dr)
  984. {
  985. unsigned long a, b, c, d;
  986. unsigned long w, x, y, z;
  987. u64 ra, rb, rc;
  988. a = dividend_high >> 32;
  989. b = dividend_high & 0xffffffff;
  990. c = dividend_low >> 32;
  991. d = dividend_low & 0xffffffff;
  992. w = a / divisor;
  993. ra = ((u64)(a - (w * divisor)) << 32) + b;
  994. rb = ((u64) do_div(ra, divisor) << 32) + c;
  995. x = ra;
  996. rc = ((u64) do_div(rb, divisor) << 32) + d;
  997. y = rb;
  998. do_div(rc, divisor);
  999. z = rc;
  1000. dr->result_high = ((u64)w << 32) + x;
  1001. dr->result_low = ((u64)y << 32) + z;
  1002. }