time.c 32 KB

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