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