time.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. *
  8. * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
  9. * to make clock more stable (2.4.0-test5). The only thing
  10. * that this code assumes is that the timebases have been synchronized
  11. * by firmware on SMP and are never stopped (never do sleep
  12. * on SMP then, nap and doze are OK).
  13. *
  14. * TODO (not necessarily in this file):
  15. * - improve precision and reproducibility of timebase frequency
  16. * measurement at boot time.
  17. * - get rid of xtime_lock for gettimeofday (generic kernel problem
  18. * to be implemented on all architectures for SMP scalability and
  19. * eventually implementing gettimeofday without entering the kernel).
  20. * - put all time/clock related variables in a single structure
  21. * to minimize number of cache lines touched by gettimeofday()
  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. *
  27. * The following comment is partially obsolete (at least the long wait
  28. * is no more a valid reason):
  29. * Since the MPC8xx has a programmable interrupt timer, I decided to
  30. * use that rather than the decrementer. Two reasons: 1.) the clock
  31. * frequency is low, causing 2.) a long wait in the timer interrupt
  32. * while ((d = get_dec()) == dval)
  33. * loop. The MPC8xx can be driven from a variety of input clocks,
  34. * so a number of assumptions have been made here because the kernel
  35. * parameter HZ is a constant. We assume (correctly, today :-) that
  36. * the MPC8xx on the MBX board is driven from a 32.768 kHz crystal.
  37. * This is then divided by 4, providing a 8192 Hz clock into the PIT.
  38. * Since it is not possible to get a nice 100 Hz clock out of this, without
  39. * creating a software PLL, I have set HZ to 128. -- Dan
  40. *
  41. * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
  42. * "A Kernel Model for Precision Timekeeping" by Dave Mills
  43. */
  44. #include <linux/config.h>
  45. #include <linux/errno.h>
  46. #include <linux/sched.h>
  47. #include <linux/kernel.h>
  48. #include <linux/param.h>
  49. #include <linux/string.h>
  50. #include <linux/mm.h>
  51. #include <linux/module.h>
  52. #include <linux/interrupt.h>
  53. #include <linux/timex.h>
  54. #include <linux/kernel_stat.h>
  55. #include <linux/mc146818rtc.h>
  56. #include <linux/time.h>
  57. #include <linux/init.h>
  58. #include <linux/profile.h>
  59. #include <asm/io.h>
  60. #include <asm/nvram.h>
  61. #include <asm/cache.h>
  62. #include <asm/8xx_immap.h>
  63. #include <asm/machdep.h>
  64. #include <asm/time.h>
  65. /* XXX false sharing with below? */
  66. u64 jiffies_64 = INITIAL_JIFFIES;
  67. EXPORT_SYMBOL(jiffies_64);
  68. unsigned long disarm_decr[NR_CPUS];
  69. extern struct timezone sys_tz;
  70. /* keep track of when we need to update the rtc */
  71. time_t last_rtc_update;
  72. /* The decrementer counts down by 128 every 128ns on a 601. */
  73. #define DECREMENTER_COUNT_601 (1000000000 / HZ)
  74. unsigned tb_ticks_per_jiffy;
  75. unsigned tb_to_us;
  76. unsigned tb_last_stamp;
  77. unsigned long tb_to_ns_scale;
  78. extern unsigned long wall_jiffies;
  79. /* used for timezone offset */
  80. static long timezone_offset;
  81. DEFINE_SPINLOCK(rtc_lock);
  82. EXPORT_SYMBOL(rtc_lock);
  83. /* Timer interrupt helper function */
  84. static inline int tb_delta(unsigned *jiffy_stamp) {
  85. int delta;
  86. if (__USE_RTC()) {
  87. delta = get_rtcl();
  88. if (delta < *jiffy_stamp) *jiffy_stamp -= 1000000000;
  89. delta -= *jiffy_stamp;
  90. } else {
  91. delta = get_tbl() - *jiffy_stamp;
  92. }
  93. return delta;
  94. }
  95. #ifdef CONFIG_SMP
  96. unsigned long profile_pc(struct pt_regs *regs)
  97. {
  98. unsigned long pc = instruction_pointer(regs);
  99. if (in_lock_functions(pc))
  100. return regs->link;
  101. return pc;
  102. }
  103. EXPORT_SYMBOL(profile_pc);
  104. #endif
  105. /*
  106. * timer_interrupt - gets called when the decrementer overflows,
  107. * with interrupts disabled.
  108. * We set it up to overflow again in 1/HZ seconds.
  109. */
  110. void timer_interrupt(struct pt_regs * regs)
  111. {
  112. int next_dec;
  113. unsigned long cpu = smp_processor_id();
  114. unsigned jiffy_stamp = last_jiffy_stamp(cpu);
  115. extern void do_IRQ(struct pt_regs *);
  116. if (atomic_read(&ppc_n_lost_interrupts) != 0)
  117. do_IRQ(regs);
  118. irq_enter();
  119. while ((next_dec = tb_ticks_per_jiffy - tb_delta(&jiffy_stamp)) <= 0) {
  120. jiffy_stamp += tb_ticks_per_jiffy;
  121. profile_tick(CPU_PROFILING, regs);
  122. update_process_times(user_mode(regs));
  123. if (smp_processor_id())
  124. continue;
  125. /* We are in an interrupt, no need to save/restore flags */
  126. write_seqlock(&xtime_lock);
  127. tb_last_stamp = jiffy_stamp;
  128. do_timer(regs);
  129. /*
  130. * update the rtc when needed, this should be performed on the
  131. * right fraction of a second. Half or full second ?
  132. * Full second works on mk48t59 clocks, others need testing.
  133. * Note that this update is basically only used through
  134. * the adjtimex system calls. Setting the HW clock in
  135. * any other way is a /dev/rtc and userland business.
  136. * This is still wrong by -0.5/+1.5 jiffies because of the
  137. * timer interrupt resolution and possible delay, but here we
  138. * hit a quantization limit which can only be solved by higher
  139. * resolution timers and decoupling time management from timer
  140. * interrupts. This is also wrong on the clocks
  141. * which require being written at the half second boundary.
  142. * We should have an rtc call that only sets the minutes and
  143. * seconds like on Intel to avoid problems with non UTC clocks.
  144. */
  145. if ( ppc_md.set_rtc_time && ntp_synced() &&
  146. xtime.tv_sec - last_rtc_update >= 659 &&
  147. abs((xtime.tv_nsec / 1000) - (1000000-1000000/HZ)) < 500000/HZ &&
  148. jiffies - wall_jiffies == 1) {
  149. if (ppc_md.set_rtc_time(xtime.tv_sec+1 + timezone_offset) == 0)
  150. last_rtc_update = xtime.tv_sec+1;
  151. else
  152. /* Try again one minute later */
  153. last_rtc_update += 60;
  154. }
  155. write_sequnlock(&xtime_lock);
  156. }
  157. if ( !disarm_decr[smp_processor_id()] )
  158. set_dec(next_dec);
  159. last_jiffy_stamp(cpu) = jiffy_stamp;
  160. if (ppc_md.heartbeat && !ppc_md.heartbeat_count--)
  161. ppc_md.heartbeat();
  162. irq_exit();
  163. }
  164. /*
  165. * This version of gettimeofday has microsecond resolution.
  166. */
  167. void do_gettimeofday(struct timeval *tv)
  168. {
  169. unsigned long flags;
  170. unsigned long seq;
  171. unsigned delta, lost_ticks, usec, sec;
  172. do {
  173. seq = read_seqbegin_irqsave(&xtime_lock, flags);
  174. sec = xtime.tv_sec;
  175. usec = (xtime.tv_nsec / 1000);
  176. delta = tb_ticks_since(tb_last_stamp);
  177. #ifdef CONFIG_SMP
  178. /* As long as timebases are not in sync, gettimeofday can only
  179. * have jiffy resolution on SMP.
  180. */
  181. if (!smp_tb_synchronized)
  182. delta = 0;
  183. #endif /* CONFIG_SMP */
  184. lost_ticks = jiffies - wall_jiffies;
  185. } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
  186. usec += mulhwu(tb_to_us, tb_ticks_per_jiffy * lost_ticks + delta);
  187. while (usec >= 1000000) {
  188. sec++;
  189. usec -= 1000000;
  190. }
  191. tv->tv_sec = sec;
  192. tv->tv_usec = usec;
  193. }
  194. EXPORT_SYMBOL(do_gettimeofday);
  195. int do_settimeofday(struct timespec *tv)
  196. {
  197. time_t wtm_sec, new_sec = tv->tv_sec;
  198. long wtm_nsec, new_nsec = tv->tv_nsec;
  199. unsigned long flags;
  200. int tb_delta;
  201. if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
  202. return -EINVAL;
  203. write_seqlock_irqsave(&xtime_lock, flags);
  204. /* Updating the RTC is not the job of this code. If the time is
  205. * stepped under NTP, the RTC will be update after STA_UNSYNC
  206. * is cleared. Tool like clock/hwclock either copy the RTC
  207. * to the system time, in which case there is no point in writing
  208. * to the RTC again, or write to the RTC but then they don't call
  209. * settimeofday to perform this operation. Note also that
  210. * we don't touch the decrementer since:
  211. * a) it would lose timer interrupt synchronization on SMP
  212. * (if it is working one day)
  213. * b) it could make one jiffy spuriously shorter or longer
  214. * which would introduce another source of uncertainty potentially
  215. * harmful to relatively short timers.
  216. */
  217. /* This works perfectly on SMP only if the tb are in sync but
  218. * guarantees an error < 1 jiffy even if they are off by eons,
  219. * still reasonable when gettimeofday resolution is 1 jiffy.
  220. */
  221. tb_delta = tb_ticks_since(last_jiffy_stamp(smp_processor_id()));
  222. tb_delta += (jiffies - wall_jiffies) * tb_ticks_per_jiffy;
  223. new_nsec -= 1000 * mulhwu(tb_to_us, tb_delta);
  224. wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
  225. wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
  226. set_normalized_timespec(&xtime, new_sec, new_nsec);
  227. set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
  228. /* In case of a large backwards jump in time with NTP, we want the
  229. * clock to be updated as soon as the PLL is again in lock.
  230. */
  231. last_rtc_update = new_sec - 658;
  232. ntp_clear();
  233. write_sequnlock_irqrestore(&xtime_lock, flags);
  234. clock_was_set();
  235. return 0;
  236. }
  237. EXPORT_SYMBOL(do_settimeofday);
  238. /* This function is only called on the boot processor */
  239. void __init time_init(void)
  240. {
  241. time_t sec, old_sec;
  242. unsigned old_stamp, stamp, elapsed;
  243. if (ppc_md.time_init != NULL)
  244. timezone_offset = ppc_md.time_init();
  245. if (__USE_RTC()) {
  246. /* 601 processor: dec counts down by 128 every 128ns */
  247. tb_ticks_per_jiffy = DECREMENTER_COUNT_601;
  248. /* mulhwu_scale_factor(1000000000, 1000000) is 0x418937 */
  249. tb_to_us = 0x418937;
  250. } else {
  251. ppc_md.calibrate_decr();
  252. tb_to_ns_scale = mulhwu(tb_to_us, 1000 << 10);
  253. }
  254. /* Now that the decrementer is calibrated, it can be used in case the
  255. * clock is stuck, but the fact that we have to handle the 601
  256. * makes things more complex. Repeatedly read the RTC until the
  257. * next second boundary to try to achieve some precision. If there
  258. * is no RTC, we still need to set tb_last_stamp and
  259. * last_jiffy_stamp(cpu 0) to the current stamp.
  260. */
  261. stamp = get_native_tbl();
  262. if (ppc_md.get_rtc_time) {
  263. sec = ppc_md.get_rtc_time();
  264. elapsed = 0;
  265. do {
  266. old_stamp = stamp;
  267. old_sec = sec;
  268. stamp = get_native_tbl();
  269. if (__USE_RTC() && stamp < old_stamp)
  270. old_stamp -= 1000000000;
  271. elapsed += stamp - old_stamp;
  272. sec = ppc_md.get_rtc_time();
  273. } while ( sec == old_sec && elapsed < 2*HZ*tb_ticks_per_jiffy);
  274. if (sec==old_sec)
  275. printk("Warning: real time clock seems stuck!\n");
  276. xtime.tv_sec = sec;
  277. xtime.tv_nsec = 0;
  278. /* No update now, we just read the time from the RTC ! */
  279. last_rtc_update = xtime.tv_sec;
  280. }
  281. last_jiffy_stamp(0) = tb_last_stamp = stamp;
  282. /* Not exact, but the timer interrupt takes care of this */
  283. set_dec(tb_ticks_per_jiffy);
  284. /* If platform provided a timezone (pmac), we correct the time */
  285. if (timezone_offset) {
  286. sys_tz.tz_minuteswest = -timezone_offset / 60;
  287. sys_tz.tz_dsttime = 0;
  288. xtime.tv_sec -= timezone_offset;
  289. }
  290. set_normalized_timespec(&wall_to_monotonic,
  291. -xtime.tv_sec, -xtime.tv_nsec);
  292. }
  293. #define FEBRUARY 2
  294. #define STARTOFTIME 1970
  295. #define SECDAY 86400L
  296. #define SECYR (SECDAY * 365)
  297. /*
  298. * Note: this is wrong for 2100, but our signed 32-bit time_t will
  299. * have overflowed long before that, so who cares. -- paulus
  300. */
  301. #define leapyear(year) ((year) % 4 == 0)
  302. #define days_in_year(a) (leapyear(a) ? 366 : 365)
  303. #define days_in_month(a) (month_days[(a) - 1])
  304. static int month_days[12] = {
  305. 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  306. };
  307. void to_tm(int tim, struct rtc_time * tm)
  308. {
  309. register int i;
  310. register long hms, day, gday;
  311. gday = day = tim / SECDAY;
  312. hms = tim % SECDAY;
  313. /* Hours, minutes, seconds are easy */
  314. tm->tm_hour = hms / 3600;
  315. tm->tm_min = (hms % 3600) / 60;
  316. tm->tm_sec = (hms % 3600) % 60;
  317. /* Number of years in days */
  318. for (i = STARTOFTIME; day >= days_in_year(i); i++)
  319. day -= days_in_year(i);
  320. tm->tm_year = i;
  321. /* Number of months in days left */
  322. if (leapyear(tm->tm_year))
  323. days_in_month(FEBRUARY) = 29;
  324. for (i = 1; day >= days_in_month(i); i++)
  325. day -= days_in_month(i);
  326. days_in_month(FEBRUARY) = 28;
  327. tm->tm_mon = i;
  328. /* Days are what is left over (+1) from all that. */
  329. tm->tm_mday = day + 1;
  330. /*
  331. * Determine the day of week. Jan. 1, 1970 was a Thursday.
  332. */
  333. tm->tm_wday = (gday + 4) % 7;
  334. }
  335. /* Auxiliary function to compute scaling factors */
  336. /* Actually the choice of a timebase running at 1/4 the of the bus
  337. * frequency giving resolution of a few tens of nanoseconds is quite nice.
  338. * It makes this computation very precise (27-28 bits typically) which
  339. * is optimistic considering the stability of most processor clock
  340. * oscillators and the precision with which the timebase frequency
  341. * is measured but does not harm.
  342. */
  343. unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale) {
  344. unsigned mlt=0, tmp, err;
  345. /* No concern for performance, it's done once: use a stupid
  346. * but safe and compact method to find the multiplier.
  347. */
  348. for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
  349. if (mulhwu(inscale, mlt|tmp) < outscale) mlt|=tmp;
  350. }
  351. /* We might still be off by 1 for the best approximation.
  352. * A side effect of this is that if outscale is too large
  353. * the returned value will be zero.
  354. * Many corner cases have been checked and seem to work,
  355. * some might have been forgotten in the test however.
  356. */
  357. err = inscale*(mlt+1);
  358. if (err <= inscale/2) mlt++;
  359. return mlt;
  360. }
  361. unsigned long long sched_clock(void)
  362. {
  363. unsigned long lo, hi, hi2;
  364. unsigned long long tb;
  365. if (!__USE_RTC()) {
  366. do {
  367. hi = get_tbu();
  368. lo = get_tbl();
  369. hi2 = get_tbu();
  370. } while (hi2 != hi);
  371. tb = ((unsigned long long) hi << 32) | lo;
  372. tb = (tb * tb_to_ns_scale) >> 10;
  373. } else {
  374. do {
  375. hi = get_rtcu();
  376. lo = get_rtcl();
  377. hi2 = get_rtcu();
  378. } while (hi2 != hi);
  379. tb = ((unsigned long long) hi) * 1000000000 + lo;
  380. }
  381. return tb;
  382. }