time.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /*
  2. * linux/arch/alpha/kernel/time.c
  3. *
  4. * Copyright (C) 1991, 1992, 1995, 1999, 2000 Linus Torvalds
  5. *
  6. * This file contains the PC-specific time handling details:
  7. * reading the RTC at bootup, etc..
  8. * 1994-07-02 Alan Modra
  9. * fixed set_rtc_mmss, fixed time.year for >= 2000, new mktime
  10. * 1995-03-26 Markus Kuhn
  11. * fixed 500 ms bug at call to set_rtc_mmss, fixed DS12887
  12. * precision CMOS clock update
  13. * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
  14. * "A Kernel Model for Precision Timekeeping" by Dave Mills
  15. * 1997-01-09 Adrian Sun
  16. * use interval timer if CONFIG_RTC=y
  17. * 1997-10-29 John Bowman (bowman@math.ualberta.ca)
  18. * fixed tick loss calculation in timer_interrupt
  19. * (round system clock to nearest tick instead of truncating)
  20. * fixed algorithm in time_init for getting time from CMOS clock
  21. * 1999-04-16 Thorsten Kranzkowski (dl8bcu@gmx.net)
  22. * fixed algorithm in do_gettimeofday() for calculating the precise time
  23. * from processor cycle counter (now taking lost_ticks into account)
  24. * 2000-08-13 Jan-Benedict Glaw <jbglaw@lug-owl.de>
  25. * Fixed time_init to be aware of epoches != 1900. This prevents
  26. * booting up in 2048 for me;) Code is stolen from rtc.c.
  27. * 2003-06-03 R. Scott Bailey <scott.bailey@eds.com>
  28. * Tighten sanity in time_init from 1% (10,000 PPM) to 250 PPM
  29. */
  30. #include <linux/config.h>
  31. #include <linux/errno.h>
  32. #include <linux/module.h>
  33. #include <linux/sched.h>
  34. #include <linux/kernel.h>
  35. #include <linux/param.h>
  36. #include <linux/string.h>
  37. #include <linux/mm.h>
  38. #include <linux/delay.h>
  39. #include <linux/ioport.h>
  40. #include <linux/irq.h>
  41. #include <linux/interrupt.h>
  42. #include <linux/init.h>
  43. #include <linux/bcd.h>
  44. #include <linux/profile.h>
  45. #include <asm/uaccess.h>
  46. #include <asm/io.h>
  47. #include <asm/hwrpb.h>
  48. #include <asm/8253pit.h>
  49. #include <linux/mc146818rtc.h>
  50. #include <linux/time.h>
  51. #include <linux/timex.h>
  52. #include "proto.h"
  53. #include "irq_impl.h"
  54. u64 jiffies_64 = INITIAL_JIFFIES;
  55. EXPORT_SYMBOL(jiffies_64);
  56. extern unsigned long wall_jiffies; /* kernel/timer.c */
  57. static int set_rtc_mmss(unsigned long);
  58. DEFINE_SPINLOCK(rtc_lock);
  59. #define TICK_SIZE (tick_nsec / 1000)
  60. /*
  61. * Shift amount by which scaled_ticks_per_cycle is scaled. Shifting
  62. * by 48 gives us 16 bits for HZ while keeping the accuracy good even
  63. * for large CPU clock rates.
  64. */
  65. #define FIX_SHIFT 48
  66. /* lump static variables together for more efficient access: */
  67. static struct {
  68. /* cycle counter last time it got invoked */
  69. __u32 last_time;
  70. /* ticks/cycle * 2^48 */
  71. unsigned long scaled_ticks_per_cycle;
  72. /* last time the CMOS clock got updated */
  73. time_t last_rtc_update;
  74. /* partial unused tick */
  75. unsigned long partial_tick;
  76. } state;
  77. unsigned long est_cycle_freq;
  78. static inline __u32 rpcc(void)
  79. {
  80. __u32 result;
  81. asm volatile ("rpcc %0" : "=r"(result));
  82. return result;
  83. }
  84. /*
  85. * Scheduler clock - returns current time in nanosec units.
  86. *
  87. * Copied from ARM code for expediency... ;-}
  88. */
  89. unsigned long long sched_clock(void)
  90. {
  91. return (unsigned long long)jiffies * (1000000000 / HZ);
  92. }
  93. /*
  94. * timer_interrupt() needs to keep up the real-time clock,
  95. * as well as call the "do_timer()" routine every clocktick
  96. */
  97. irqreturn_t timer_interrupt(int irq, void *dev, struct pt_regs * regs)
  98. {
  99. unsigned long delta;
  100. __u32 now;
  101. long nticks;
  102. #ifndef CONFIG_SMP
  103. /* Not SMP, do kernel PC profiling here. */
  104. profile_tick(CPU_PROFILING, regs);
  105. #endif
  106. write_seqlock(&xtime_lock);
  107. /*
  108. * Calculate how many ticks have passed since the last update,
  109. * including any previous partial leftover. Save any resulting
  110. * fraction for the next pass.
  111. */
  112. now = rpcc();
  113. delta = now - state.last_time;
  114. state.last_time = now;
  115. delta = delta * state.scaled_ticks_per_cycle + state.partial_tick;
  116. state.partial_tick = delta & ((1UL << FIX_SHIFT) - 1);
  117. nticks = delta >> FIX_SHIFT;
  118. while (nticks > 0) {
  119. do_timer(regs);
  120. #ifndef CONFIG_SMP
  121. update_process_times(user_mode(regs));
  122. #endif
  123. nticks--;
  124. }
  125. /*
  126. * If we have an externally synchronized Linux clock, then update
  127. * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
  128. * called as close as possible to 500 ms before the new second starts.
  129. */
  130. if (ntp_synced()
  131. && xtime.tv_sec > state.last_rtc_update + 660
  132. && xtime.tv_nsec >= 500000 - ((unsigned) TICK_SIZE) / 2
  133. && xtime.tv_nsec <= 500000 + ((unsigned) TICK_SIZE) / 2) {
  134. int tmp = set_rtc_mmss(xtime.tv_sec);
  135. state.last_rtc_update = xtime.tv_sec - (tmp ? 600 : 0);
  136. }
  137. write_sequnlock(&xtime_lock);
  138. return IRQ_HANDLED;
  139. }
  140. void
  141. common_init_rtc(void)
  142. {
  143. unsigned char x;
  144. /* Reset periodic interrupt frequency. */
  145. x = CMOS_READ(RTC_FREQ_SELECT) & 0x3f;
  146. /* Test includes known working values on various platforms
  147. where 0x26 is wrong; we refuse to change those. */
  148. if (x != 0x26 && x != 0x25 && x != 0x19 && x != 0x06) {
  149. printk("Setting RTC_FREQ to 1024 Hz (%x)\n", x);
  150. CMOS_WRITE(0x26, RTC_FREQ_SELECT);
  151. }
  152. /* Turn on periodic interrupts. */
  153. x = CMOS_READ(RTC_CONTROL);
  154. if (!(x & RTC_PIE)) {
  155. printk("Turning on RTC interrupts.\n");
  156. x |= RTC_PIE;
  157. x &= ~(RTC_AIE | RTC_UIE);
  158. CMOS_WRITE(x, RTC_CONTROL);
  159. }
  160. (void) CMOS_READ(RTC_INTR_FLAGS);
  161. outb(0x36, 0x43); /* pit counter 0: system timer */
  162. outb(0x00, 0x40);
  163. outb(0x00, 0x40);
  164. outb(0xb6, 0x43); /* pit counter 2: speaker */
  165. outb(0x31, 0x42);
  166. outb(0x13, 0x42);
  167. init_rtc_irq();
  168. }
  169. /* Validate a computed cycle counter result against the known bounds for
  170. the given processor core. There's too much brokenness in the way of
  171. timing hardware for any one method to work everywhere. :-(
  172. Return 0 if the result cannot be trusted, otherwise return the argument. */
  173. static unsigned long __init
  174. validate_cc_value(unsigned long cc)
  175. {
  176. static struct bounds {
  177. unsigned int min, max;
  178. } cpu_hz[] __initdata = {
  179. [EV3_CPU] = { 50000000, 200000000 }, /* guess */
  180. [EV4_CPU] = { 100000000, 300000000 },
  181. [LCA4_CPU] = { 100000000, 300000000 }, /* guess */
  182. [EV45_CPU] = { 200000000, 300000000 },
  183. [EV5_CPU] = { 250000000, 433000000 },
  184. [EV56_CPU] = { 333000000, 667000000 },
  185. [PCA56_CPU] = { 400000000, 600000000 }, /* guess */
  186. [PCA57_CPU] = { 500000000, 600000000 }, /* guess */
  187. [EV6_CPU] = { 466000000, 600000000 },
  188. [EV67_CPU] = { 600000000, 750000000 },
  189. [EV68AL_CPU] = { 750000000, 940000000 },
  190. [EV68CB_CPU] = { 1000000000, 1333333333 },
  191. /* None of the following are shipping as of 2001-11-01. */
  192. [EV68CX_CPU] = { 1000000000, 1700000000 }, /* guess */
  193. [EV69_CPU] = { 1000000000, 1700000000 }, /* guess */
  194. [EV7_CPU] = { 800000000, 1400000000 }, /* guess */
  195. [EV79_CPU] = { 1000000000, 2000000000 }, /* guess */
  196. };
  197. /* Allow for some drift in the crystal. 10MHz is more than enough. */
  198. const unsigned int deviation = 10000000;
  199. struct percpu_struct *cpu;
  200. unsigned int index;
  201. cpu = (struct percpu_struct *)((char*)hwrpb + hwrpb->processor_offset);
  202. index = cpu->type & 0xffffffff;
  203. /* If index out of bounds, no way to validate. */
  204. if (index >= sizeof(cpu_hz)/sizeof(cpu_hz[0]))
  205. return cc;
  206. /* If index contains no data, no way to validate. */
  207. if (cpu_hz[index].max == 0)
  208. return cc;
  209. if (cc < cpu_hz[index].min - deviation
  210. || cc > cpu_hz[index].max + deviation)
  211. return 0;
  212. return cc;
  213. }
  214. /*
  215. * Calibrate CPU clock using legacy 8254 timer/counter. Stolen from
  216. * arch/i386/time.c.
  217. */
  218. #define CALIBRATE_LATCH 0xffff
  219. #define TIMEOUT_COUNT 0x100000
  220. static unsigned long __init
  221. calibrate_cc_with_pit(void)
  222. {
  223. int cc, count = 0;
  224. /* Set the Gate high, disable speaker */
  225. outb((inb(0x61) & ~0x02) | 0x01, 0x61);
  226. /*
  227. * Now let's take care of CTC channel 2
  228. *
  229. * Set the Gate high, program CTC channel 2 for mode 0,
  230. * (interrupt on terminal count mode), binary count,
  231. * load 5 * LATCH count, (LSB and MSB) to begin countdown.
  232. */
  233. outb(0xb0, 0x43); /* binary, mode 0, LSB/MSB, Ch 2 */
  234. outb(CALIBRATE_LATCH & 0xff, 0x42); /* LSB of count */
  235. outb(CALIBRATE_LATCH >> 8, 0x42); /* MSB of count */
  236. cc = rpcc();
  237. do {
  238. count++;
  239. } while ((inb(0x61) & 0x20) == 0 && count < TIMEOUT_COUNT);
  240. cc = rpcc() - cc;
  241. /* Error: ECTCNEVERSET or ECPUTOOFAST. */
  242. if (count <= 1 || count == TIMEOUT_COUNT)
  243. return 0;
  244. return ((long)cc * PIT_TICK_RATE) / (CALIBRATE_LATCH + 1);
  245. }
  246. /* The Linux interpretation of the CMOS clock register contents:
  247. When the Update-In-Progress (UIP) flag goes from 1 to 0, the
  248. RTC registers show the second which has precisely just started.
  249. Let's hope other operating systems interpret the RTC the same way. */
  250. static unsigned long __init
  251. rpcc_after_update_in_progress(void)
  252. {
  253. do { } while (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP));
  254. do { } while (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
  255. return rpcc();
  256. }
  257. void __init
  258. time_init(void)
  259. {
  260. unsigned int year, mon, day, hour, min, sec, cc1, cc2, epoch;
  261. unsigned long cycle_freq, tolerance;
  262. long diff;
  263. /* Calibrate CPU clock -- attempt #1. */
  264. if (!est_cycle_freq)
  265. est_cycle_freq = validate_cc_value(calibrate_cc_with_pit());
  266. cc1 = rpcc_after_update_in_progress();
  267. /* Calibrate CPU clock -- attempt #2. */
  268. if (!est_cycle_freq) {
  269. cc2 = rpcc_after_update_in_progress();
  270. est_cycle_freq = validate_cc_value(cc2 - cc1);
  271. cc1 = cc2;
  272. }
  273. cycle_freq = hwrpb->cycle_freq;
  274. if (est_cycle_freq) {
  275. /* If the given value is within 250 PPM of what we calculated,
  276. accept it. Otherwise, use what we found. */
  277. tolerance = cycle_freq / 4000;
  278. diff = cycle_freq - est_cycle_freq;
  279. if (diff < 0)
  280. diff = -diff;
  281. if ((unsigned long)diff > tolerance) {
  282. cycle_freq = est_cycle_freq;
  283. printk("HWRPB cycle frequency bogus. "
  284. "Estimated %lu Hz\n", cycle_freq);
  285. } else {
  286. est_cycle_freq = 0;
  287. }
  288. } else if (! validate_cc_value (cycle_freq)) {
  289. printk("HWRPB cycle frequency bogus, "
  290. "and unable to estimate a proper value!\n");
  291. }
  292. /* From John Bowman <bowman@math.ualberta.ca>: allow the values
  293. to settle, as the Update-In-Progress bit going low isn't good
  294. enough on some hardware. 2ms is our guess; we haven't found
  295. bogomips yet, but this is close on a 500Mhz box. */
  296. __delay(1000000);
  297. sec = CMOS_READ(RTC_SECONDS);
  298. min = CMOS_READ(RTC_MINUTES);
  299. hour = CMOS_READ(RTC_HOURS);
  300. day = CMOS_READ(RTC_DAY_OF_MONTH);
  301. mon = CMOS_READ(RTC_MONTH);
  302. year = CMOS_READ(RTC_YEAR);
  303. if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
  304. BCD_TO_BIN(sec);
  305. BCD_TO_BIN(min);
  306. BCD_TO_BIN(hour);
  307. BCD_TO_BIN(day);
  308. BCD_TO_BIN(mon);
  309. BCD_TO_BIN(year);
  310. }
  311. /* PC-like is standard; used for year >= 70 */
  312. epoch = 1900;
  313. if (year < 20)
  314. epoch = 2000;
  315. else if (year >= 20 && year < 48)
  316. /* NT epoch */
  317. epoch = 1980;
  318. else if (year >= 48 && year < 70)
  319. /* Digital UNIX epoch */
  320. epoch = 1952;
  321. printk(KERN_INFO "Using epoch = %d\n", epoch);
  322. if ((year += epoch) < 1970)
  323. year += 100;
  324. xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
  325. xtime.tv_nsec = 0;
  326. wall_to_monotonic.tv_sec -= xtime.tv_sec;
  327. wall_to_monotonic.tv_nsec = 0;
  328. if (HZ > (1<<16)) {
  329. extern void __you_loose (void);
  330. __you_loose();
  331. }
  332. state.last_time = cc1;
  333. state.scaled_ticks_per_cycle
  334. = ((unsigned long) HZ << FIX_SHIFT) / cycle_freq;
  335. state.last_rtc_update = 0;
  336. state.partial_tick = 0L;
  337. /* Startup the timer source. */
  338. alpha_mv.init_rtc();
  339. }
  340. /*
  341. * Use the cycle counter to estimate an displacement from the last time
  342. * tick. Unfortunately the Alpha designers made only the low 32-bits of
  343. * the cycle counter active, so we overflow on 8.2 seconds on a 500MHz
  344. * part. So we can't do the "find absolute time in terms of cycles" thing
  345. * that the other ports do.
  346. */
  347. void
  348. do_gettimeofday(struct timeval *tv)
  349. {
  350. unsigned long flags;
  351. unsigned long sec, usec, lost, seq;
  352. unsigned long delta_cycles, delta_usec, partial_tick;
  353. do {
  354. seq = read_seqbegin_irqsave(&xtime_lock, flags);
  355. delta_cycles = rpcc() - state.last_time;
  356. sec = xtime.tv_sec;
  357. usec = (xtime.tv_nsec / 1000);
  358. partial_tick = state.partial_tick;
  359. lost = jiffies - wall_jiffies;
  360. } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
  361. #ifdef CONFIG_SMP
  362. /* Until and unless we figure out how to get cpu cycle counters
  363. in sync and keep them there, we can't use the rpcc tricks. */
  364. delta_usec = lost * (1000000 / HZ);
  365. #else
  366. /*
  367. * usec = cycles * ticks_per_cycle * 2**48 * 1e6 / (2**48 * ticks)
  368. * = cycles * (s_t_p_c) * 1e6 / (2**48 * ticks)
  369. * = cycles * (s_t_p_c) * 15625 / (2**42 * ticks)
  370. *
  371. * which, given a 600MHz cycle and a 1024Hz tick, has a
  372. * dynamic range of about 1.7e17, which is less than the
  373. * 1.8e19 in an unsigned long, so we are safe from overflow.
  374. *
  375. * Round, but with .5 up always, since .5 to even is harder
  376. * with no clear gain.
  377. */
  378. delta_usec = (delta_cycles * state.scaled_ticks_per_cycle
  379. + partial_tick
  380. + (lost << FIX_SHIFT)) * 15625;
  381. delta_usec = ((delta_usec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
  382. #endif
  383. usec += delta_usec;
  384. if (usec >= 1000000) {
  385. sec += 1;
  386. usec -= 1000000;
  387. }
  388. tv->tv_sec = sec;
  389. tv->tv_usec = usec;
  390. }
  391. EXPORT_SYMBOL(do_gettimeofday);
  392. int
  393. do_settimeofday(struct timespec *tv)
  394. {
  395. time_t wtm_sec, sec = tv->tv_sec;
  396. long wtm_nsec, nsec = tv->tv_nsec;
  397. unsigned long delta_nsec;
  398. if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
  399. return -EINVAL;
  400. write_seqlock_irq(&xtime_lock);
  401. /* The offset that is added into time in do_gettimeofday above
  402. must be subtracted out here to keep a coherent view of the
  403. time. Without this, a full-tick error is possible. */
  404. #ifdef CONFIG_SMP
  405. delta_nsec = (jiffies - wall_jiffies) * (NSEC_PER_SEC / HZ);
  406. #else
  407. delta_nsec = rpcc() - state.last_time;
  408. delta_nsec = (delta_nsec * state.scaled_ticks_per_cycle
  409. + state.partial_tick
  410. + ((jiffies - wall_jiffies) << FIX_SHIFT)) * 15625;
  411. delta_nsec = ((delta_nsec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
  412. delta_nsec *= 1000;
  413. #endif
  414. nsec -= delta_nsec;
  415. wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
  416. wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
  417. set_normalized_timespec(&xtime, sec, nsec);
  418. set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
  419. ntp_clear();
  420. write_sequnlock_irq(&xtime_lock);
  421. clock_was_set();
  422. return 0;
  423. }
  424. EXPORT_SYMBOL(do_settimeofday);
  425. /*
  426. * In order to set the CMOS clock precisely, set_rtc_mmss has to be
  427. * called 500 ms after the second nowtime has started, because when
  428. * nowtime is written into the registers of the CMOS clock, it will
  429. * jump to the next second precisely 500 ms later. Check the Motorola
  430. * MC146818A or Dallas DS12887 data sheet for details.
  431. *
  432. * BUG: This routine does not handle hour overflow properly; it just
  433. * sets the minutes. Usually you won't notice until after reboot!
  434. */
  435. static int
  436. set_rtc_mmss(unsigned long nowtime)
  437. {
  438. int retval = 0;
  439. int real_seconds, real_minutes, cmos_minutes;
  440. unsigned char save_control, save_freq_select;
  441. /* irq are locally disabled here */
  442. spin_lock(&rtc_lock);
  443. /* Tell the clock it's being set */
  444. save_control = CMOS_READ(RTC_CONTROL);
  445. CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
  446. /* Stop and reset prescaler */
  447. save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
  448. CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
  449. cmos_minutes = CMOS_READ(RTC_MINUTES);
  450. if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
  451. BCD_TO_BIN(cmos_minutes);
  452. /*
  453. * since we're only adjusting minutes and seconds,
  454. * don't interfere with hour overflow. This avoids
  455. * messing with unknown time zones but requires your
  456. * RTC not to be off by more than 15 minutes
  457. */
  458. real_seconds = nowtime % 60;
  459. real_minutes = nowtime / 60;
  460. if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) {
  461. /* correct for half hour time zone */
  462. real_minutes += 30;
  463. }
  464. real_minutes %= 60;
  465. if (abs(real_minutes - cmos_minutes) < 30) {
  466. if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
  467. BIN_TO_BCD(real_seconds);
  468. BIN_TO_BCD(real_minutes);
  469. }
  470. CMOS_WRITE(real_seconds,RTC_SECONDS);
  471. CMOS_WRITE(real_minutes,RTC_MINUTES);
  472. } else {
  473. printk(KERN_WARNING
  474. "set_rtc_mmss: can't update from %d to %d\n",
  475. cmos_minutes, real_minutes);
  476. retval = -1;
  477. }
  478. /* The following flags have to be released exactly in this order,
  479. * otherwise the DS12887 (popular MC146818A clone with integrated
  480. * battery and quartz) will not reset the oscillator and will not
  481. * update precisely 500 ms later. You won't find this mentioned in
  482. * the Dallas Semiconductor data sheets, but who believes data
  483. * sheets anyway ... -- Markus Kuhn
  484. */
  485. CMOS_WRITE(save_control, RTC_CONTROL);
  486. CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
  487. spin_unlock(&rtc_lock);
  488. return retval;
  489. }