time.c 16 KB

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