]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/iicbus/nxprtc.c
bhnd(9): Fix a few mandoc related issues
[FreeBSD/FreeBSD.git] / sys / dev / iicbus / nxprtc.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2017 Ian Lepore <ian@freebsd.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 /*
32  * Driver for NXP real-time clock/calendar chips:
33  *  - PCF8563 = low power, countdown timer
34  *  - PCA8565 = like PCF8563, automotive temperature range
35  *  - PCF8523 = low power, countdown timer, oscillator freq tuning, 2 timers
36  *  - PCF2127 = like PCF8523, industrial, tcxo, tamper/ts, i2c & spi, 512B ram
37  *  - PCA2129 = like PCF8523, automotive, tcxo, tamper/ts, i2c & spi, (note 1)
38  *  - PCF2129 = like PCF8523, industrial, tcxo, tamper/ts, i2c & spi, (note 1)
39  *
40  *  Most chips have a countdown timer, ostensibly intended to generate periodic
41  *  interrupt signals on an output pin.  The timer is driven from the same
42  *  divider chain that clocks the time of day registers, and they start counting
43  *  in sync when the STOP bit is cleared after the time and timer registers are
44  *  set.  The timer register can also be read on the fly, so we use it to count
45  *  fractional seconds and get a resolution of ~15ms.
46  *
47  *  [1] Note that the datasheets for the PCx2129 chips state that they have only
48  *  a watchdog timer, not a countdown timer.  Empirical testing shows that the
49  *  countdown timer is actually there and it works fine, except that it can't
50  *  trigger an interrupt or toggle an output pin like it can on other chips.  We
51  *  don't care about interrupts and output pins, we just read the timer register
52  *  to get better resolution.
53  */
54
55 #include "opt_platform.h"
56
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/bus.h>
60 #include <sys/clock.h>
61 #include <sys/kernel.h>
62 #include <sys/libkern.h>
63 #include <sys/module.h>
64 #include <sys/sysctl.h>
65
66 #include <dev/iicbus/iicbus.h>
67 #include <dev/iicbus/iiconf.h>
68 #ifdef FDT
69 #include <dev/ofw/openfirm.h>
70 #include <dev/ofw/ofw_bus.h>
71 #include <dev/ofw/ofw_bus_subr.h>
72 #endif
73
74 #include "clock_if.h"
75 #include "iicbus_if.h"
76
77 /*
78  * I2C address 1010 001x : PCA2129 PCF2127 PCF2129 PCF8563 PCF8565
79  * I2C address 1101 000x : PCF8523
80  */
81 #define PCF8563_ADDR            0xa2
82 #define PCF8523_ADDR            0xd0
83
84 /*
85  * Registers, bits within them, and masks that are common to all chip types.
86  */
87 #define PCF85xx_R_CS1           0x00    /* CS1 and CS2 control regs are in */
88 #define PCF85xx_R_CS2           0x01    /* the same location on all chips. */
89
90 #define PCF85xx_B_CS1_STOP      0x20    /* Stop time incrementing bit */
91 #define PCF85xx_B_SECOND_OS     0x80    /* Oscillator Stopped bit */
92
93 #define PCF85xx_M_SECOND        0x7f    /* Masks for all BCD time regs... */
94 #define PCF85xx_M_MINUTE        0x7f
95 #define PCF85xx_M_12HOUR        0x1f
96 #define PCF85xx_M_24HOUR        0x3f
97 #define PCF85xx_M_DAY           0x3f
98 #define PCF85xx_M_MONTH         0x1f
99 #define PCF85xx_M_YEAR          0xff
100
101 /*
102  * PCF2127-specific registers, bits, and masks.
103  */
104 #define PCF2127_R_TMR_CTL       0x10    /* Timer/watchdog control */
105
106 #define PCF2127_M_TMR_CTRL      0xe3    /* Mask off undef bits */
107
108 #define PCF2127_B_TMR_CD        0x40    /* Run in countdown mode */
109 #define PCF2127_B_TMR_64HZ      0x01    /* Timer frequency 64Hz */
110
111 #define PCF2127_R_TS_CTL        0x12    /* Timestamp control */
112 #define PCF2127_B_TSOFF         0x40    /* Turn off timestamp function */
113
114 #define PCF2127_R_AGING_OFFSET  0x19    /* Frequency aging offset in PPM */
115
116 /*
117  * PCA/PCF2129-specific registers, bits, and masks.
118  */
119 #define PCF2129_B_CS1_12HR      0x04    /* Use 12-hour (AM/PM) mode bit */
120 #define PCF2129_B_CLKOUT_OTPR   0x20    /* OTP refresh command */
121 #define PCF2129_B_CLKOUT_HIGHZ  0x07    /* Clock Out Freq = disable */
122
123 /*
124  * PCF8523-specific registers, bits, and masks.
125  */
126 #define PCF8523_R_CS3           0x02    /* Control and status reg 3 */
127 #define PCF8523_R_SECOND        0x03    /* Seconds */
128 #define PCF8523_R_TMR_CLKOUT    0x0F    /* Timer and clockout control */
129 #define PCF8523_R_TMR_A_FREQ    0x10    /* Timer A frequency control */
130 #define PCF8523_R_TMR_A_COUNT   0x11    /* Timer A count */
131
132 #define PCF8523_M_TMR_A_FREQ    0x07    /* Mask off undef bits */
133
134 #define PCF8523_B_HOUR_PM       0x20    /* PM bit */
135 #define PCF8523_B_CS1_SOFTRESET 0x58    /* Initiate Soft Reset bits */
136 #define PCF8523_B_CS1_12HR      0x08    /* Use 12-hour (AM/PM) mode bit */
137 #define PCF8523_B_CLKOUT_TACD   0x02    /* TimerA runs in CountDown mode */
138 #define PCF8523_B_CLKOUT_HIGHZ  0x38    /* Clock Out Freq = disable */
139 #define PCF8523_B_TMR_A_64HZ    0x01    /* Timer A freq 64Hz */
140
141 #define PCF8523_M_CS3_PM        0xE0    /* Power mode mask */
142 #define PCF8523_B_CS3_PM_NOBAT  0xE0    /* PM bits: no battery usage */
143 #define PCF8523_B_CS3_PM_STD    0x00    /* PM bits: standard */
144 #define PCF8523_B_CS3_PM_DSNBM  0xa0    /* PM bits: direct switch, no bat mon */
145 #define PCF8523_B_CS3_BLF       0x04    /* Battery Low Flag bit */
146
147 /*
148  * PCF8563-specific registers, bits, and masks.
149  */
150 #define PCF8563_R_SECOND        0x02    /* Seconds */
151
152 #define PCF8563_R_CLKOUT        0x0d    /* Clock output control */
153
154 #define PCF8563_R_TMR_CTRL      0x0e    /* Timer control */
155 #define PCF8563_R_TMR_COUNT     0x0f    /* Timer count */
156
157 #define PCF8563_M_TMR_CTRL      0x93    /* Mask off undef bits */
158
159 #define PCF8563_B_TMR_ENABLE    0x80    /* Enable countdown timer */
160 #define PCF8563_B_TMR_64HZ      0x01    /* Timer frequency 64Hz */
161
162 #define PCF8563_B_MONTH_C       0x80    /* Century bit */
163
164 /*
165  * We use the countdown timer for fractional seconds.  We program it for 64 Hz,
166  * the fastest available rate that doesn't roll over in less than a second.
167  */
168 #define TMR_TICKS_SEC           64
169 #define TMR_TICKS_HALFSEC       32
170
171 /*
172  * The chip types we support.
173  */
174 enum {
175         TYPE_NONE,
176         TYPE_PCA2129,
177         TYPE_PCA8565,
178         TYPE_PCF2127,
179         TYPE_PCF2129,
180         TYPE_PCF8523,
181         TYPE_PCF8563,
182
183         TYPE_COUNT
184 };
185 static const char *desc_strings[] = {
186         "",
187         "NXP PCA2129 RTC",
188         "NXP PCA8565 RTC",
189         "NXP PCF2127 RTC",
190         "NXP PCF2129 RTC",
191         "NXP PCF8523 RTC",
192         "NXP PCF8563 RTC",
193 };
194 CTASSERT(nitems(desc_strings) == TYPE_COUNT);
195
196 /*
197  * The time registers in the order they are laid out in hardware.
198  */
199 struct time_regs {
200         uint8_t sec, min, hour, day, wday, month, year;
201 };
202
203 struct nxprtc_softc {
204         device_t        dev;
205         device_t        busdev;
206         struct intr_config_hook
207                         config_hook;
208         u_int           flags;          /* SC_F_* flags */
209         u_int           chiptype;       /* Type of PCF85xx chip */
210         time_t          bat_time;       /* Next time to check battery */
211         int             freqadj;        /* Current freq adj in PPM */
212         uint8_t         secaddr;        /* Address of seconds register */
213         uint8_t         tmcaddr;        /* Address of timer count register */
214         bool            use_timer;      /* Use timer for fractional sec */
215         bool            use_ampm;       /* Chip is set to use am/pm mode */
216         bool            is212x;         /* Chip type is 2127 or 2129 */
217 };
218
219 #define SC_F_CPOL       (1 << 0)        /* Century bit means 19xx */
220
221 /*
222  * When doing i2c IO, indicate that we need to wait for exclusive bus ownership,
223  * but that we should not wait if we already own the bus.  This lets us put
224  * iicbus_acquire_bus() calls with a non-recursive wait at the entry of our API
225  * functions to ensure that only one client at a time accesses the hardware for
226  * the entire series of operations it takes to read or write the clock.
227  */
228 #define WAITFLAGS       (IIC_WAIT | IIC_RECURSIVE)
229
230 /*
231  * We use the compat_data table to look up hint strings in the non-FDT case, so
232  * define the struct locally when we don't get it from ofw_bus_subr.h.
233  */
234 #ifdef FDT
235 typedef struct ofw_compat_data nxprtc_compat_data;
236 #else
237 typedef struct {
238         const char *ocd_str;
239         uintptr_t  ocd_data;
240 } nxprtc_compat_data;
241 #endif
242
243 static nxprtc_compat_data compat_data[] = {
244         {"nxp,pca2129",     TYPE_PCA2129},
245         {"nxp,pca8565",     TYPE_PCA8565},
246         {"nxp,pcf2127",     TYPE_PCF2127},
247         {"nxp,pcf2129",     TYPE_PCF2129},
248         {"nxp,pcf8523",     TYPE_PCF8523},
249         {"nxp,pcf8563",     TYPE_PCF8563},
250
251         /* Undocumented compat strings known to exist in the wild... */
252         {"pcf8563",         TYPE_PCF8563},
253         {"phg,pcf8563",     TYPE_PCF8563},
254         {"philips,pcf8563", TYPE_PCF8563},
255
256         {NULL,              TYPE_NONE},
257 };
258
259 static int
260 nxprtc_readfrom(device_t slavedev, uint8_t regaddr, void *buffer,
261     uint16_t buflen, int waithow)
262 {
263         struct iic_msg msg;
264         int err;
265         uint8_t slaveaddr;
266
267         /*
268          * Two transfers back to back with a stop and start between them; first we
269          * write the address-within-device, then we read from the device.  This
270          * is used instead of the standard iicdev_readfrom() because some of the
271          * chips we service don't support i2c repeat-start operations (grrrrr)
272          * so we do two completely separate transfers with a full stop between.
273          */
274         slaveaddr = iicbus_get_addr(slavedev);
275
276         msg.slave = slaveaddr;
277         msg.flags = IIC_M_WR;
278         msg.len   = 1;
279         msg.buf   = &regaddr;
280
281         if ((err = iicbus_transfer_excl(slavedev, &msg, 1, waithow)) != 0)
282                 return (err);
283
284         msg.slave = slaveaddr;
285         msg.flags = IIC_M_RD;
286         msg.len   = buflen;
287         msg.buf   = buffer;
288
289         return (iicbus_transfer_excl(slavedev, &msg, 1, waithow));
290 }
291
292 static int
293 read_reg(struct nxprtc_softc *sc, uint8_t reg, uint8_t *val)
294 {
295
296         return (nxprtc_readfrom(sc->dev, reg, val, sizeof(*val), WAITFLAGS));
297 }
298
299 static int
300 write_reg(struct nxprtc_softc *sc, uint8_t reg, uint8_t val)
301 {
302
303         return (iicdev_writeto(sc->dev, reg, &val, sizeof(val), WAITFLAGS));
304 }
305
306 static int
307 read_timeregs(struct nxprtc_softc *sc, struct time_regs *tregs, uint8_t *tmr)
308 {
309         int err;
310         uint8_t sec, tmr1, tmr2;
311
312         /*
313          * The datasheet says loop to read the same timer value twice because it
314          * does not freeze while reading.  To that we add our own logic that
315          * the seconds register must be the same before and after reading the
316          * timer, ensuring the fractional part is from the same second as tregs.
317          */
318         do {
319                 if (sc->use_timer) {
320                         if ((err = read_reg(sc, sc->secaddr, &sec)) != 0)
321                                 break;
322                         if ((err = read_reg(sc, sc->tmcaddr, &tmr1)) != 0)
323                                 break;
324                         if ((err = read_reg(sc, sc->tmcaddr, &tmr2)) != 0)
325                                 break;
326                         if (tmr1 != tmr2)
327                                 continue;
328                 }
329                 if ((err = nxprtc_readfrom(sc->dev, sc->secaddr, tregs,
330                     sizeof(*tregs), WAITFLAGS)) != 0)
331                         break;
332         } while (sc->use_timer && tregs->sec != sec);
333
334         /*
335          * If the timer value is greater than our hz rate (or is zero),
336          * something is wrong.  Maybe some other OS used the timer differently?
337          * Just set it to zero.  Likewise if we're not using the timer.  After
338          * the offset calc below, the zero turns into 32, the mid-second point,
339          * which in effect performs 4/5 rounding, which is just the right thing
340          * to do if we don't have fine-grained time.
341          */
342         if (!sc->use_timer || tmr1 > TMR_TICKS_SEC)
343                 tmr1 = 0;
344
345         /*
346          * Turn the downcounter into an upcounter.  The timer starts counting at
347          * and rolls over at mid-second, so add half a second worth of ticks to
348          * get its zero point back in sync with the tregs.sec rollover.
349          */
350         *tmr = (TMR_TICKS_SEC - tmr1 + TMR_TICKS_HALFSEC) % TMR_TICKS_SEC;
351
352         return (err);
353 }
354
355 static int
356 write_timeregs(struct nxprtc_softc *sc, struct time_regs *tregs)
357 {
358
359         return (iicdev_writeto(sc->dev, sc->secaddr, tregs,
360             sizeof(*tregs), WAITFLAGS));
361 }
362
363 static int
364 freqadj_sysctl(SYSCTL_HANDLER_ARGS)
365 {
366         struct nxprtc_softc *sc;
367         int err, freqppm, newppm;
368
369         sc = arg1;
370
371         /* PPM range [-7,8] maps to reg value range [0,15] */
372         freqppm = newppm = 8 - sc->freqadj;
373
374         err = sysctl_handle_int(oidp, &newppm, 0, req);
375         if (err != 0 || req->newptr == NULL)
376                 return (err);
377         if (freqppm != newppm) {
378                 if (newppm < -7 || newppm > 8)
379                         return (EINVAL);
380                 sc->freqadj = 8 - newppm;
381                 err = write_reg(sc, PCF2127_R_AGING_OFFSET, sc->freqadj);
382         }
383
384         return (err);
385 }
386
387 static int
388 pcf8523_battery_check(struct nxprtc_softc *sc)
389 {
390         struct timespec ts;
391         int err;
392         uint8_t cs3;
393
394         /* We check the battery when starting up, and then only once a day. */
395         getnanouptime(&ts);
396         if (ts.tv_sec < sc->bat_time)
397                 return (0);
398         sc->bat_time = ts.tv_sec + (60 * 60 * 24);
399
400         /*
401          * The 8523, 2127, and 2129 chips have a "power manager" which includes
402          * an optional battery voltage monitor and several choices for power
403          * switching modes.  The battery monitor uses a lot of current and it
404          * remains active when running from battery, making it the "drain my
405          * battery twice as fast" mode.  So, we run the chip in direct-switching
406          * mode with the battery monitor disabled, reducing the current draw
407          * when running on battery from 1930nA to 880nA.  While it's not clear
408          * from the datasheets, empirical testing shows that both disabling the
409          * battery monitor and using direct-switch mode are required to get the
410          * full power savings.
411          *
412          * There isn't any need to continuously monitor the battery voltage, so
413          * this function is used to periodically enable the monitor, check the
414          * voltage, then return to the low-power monitor-disabled mode.
415          */
416         err = write_reg(sc, PCF8523_R_CS3, PCF8523_B_CS3_PM_STD);
417         if (err != 0) {
418                 device_printf(sc->dev, "cannot write CS3 reg\n");
419                 return (err);
420         }
421         pause_sbt("nxpbat", mstosbt(10), 0, 0);
422         if ((err = read_reg(sc, PCF8523_R_CS3, &cs3)) != 0) {
423                 device_printf(sc->dev, "cannot read CS3 reg\n");
424                 return (err);
425         }
426         err = write_reg(sc, PCF8523_R_CS3, PCF8523_B_CS3_PM_DSNBM);
427         if (err != 0) {
428                 device_printf(sc->dev, "cannot write CS3 reg\n");
429                 return (err);
430         }
431
432         if (cs3 & PCF8523_B_CS3_BLF)
433                 device_printf(sc->dev, "WARNING: RTC battery is low\n");
434
435         return (0);
436 }
437
438 static int
439 pcf8523_start(struct nxprtc_softc *sc)
440 {
441         struct sysctl_ctx_list *ctx;
442         struct sysctl_oid_list *tree;
443         struct csr {
444                 uint8_t cs1;
445                 uint8_t cs2;
446                 uint8_t cs3;
447                 uint8_t sec;
448         } csr;
449         int err;
450         uint8_t clkout, freqadj;
451
452         /* Read the control and status registers. */
453         if ((err = nxprtc_readfrom(sc->dev, PCF85xx_R_CS1, &csr,
454             sizeof(csr), WAITFLAGS)) != 0){
455                 device_printf(sc->dev, "cannot read RTC control regs\n");
456                 return (err);
457         }
458
459         /*
460          * Do a full init if...
461          *  - The chip power manager is in battery-disable mode.
462          *  - The OS (oscillator stopped) bit is set (all power was lost).
463          *  - The clock-increment STOP flag is set (this is just insane).
464          */
465         if ((csr.cs3 & PCF8523_M_CS3_PM) == PCF8523_B_CS3_PM_NOBAT ||
466             (csr.cs1 & PCF85xx_B_CS1_STOP) || (csr.sec & PCF85xx_B_SECOND_OS)) {
467                 device_printf(sc->dev, 
468                     "WARNING: RTC battery failed; time is invalid\n");
469
470                 /*
471                  * For 212x series...
472                  * - Turn off the POR-Override bit (used for mfg test only), 
473                  *   by writing zero to cs 1 (all other bits power on as zero). 
474                  * - Turn off the timestamp option to save the power used to
475                  *   monitor that input pin.
476                  * - Trigger OTP refresh by forcing the OTPR bit to zero then
477                  *   back to 1, then wait 100ms for the refresh.
478                  */
479                 if (sc->is212x) {
480                         err = write_reg(sc, PCF85xx_R_CS1, 0);
481                         if (err != 0) {
482                                 device_printf(sc->dev,
483                                     "cannot write CS1 reg\n");
484                                 return (err);
485                         }
486
487                         err = write_reg(sc, PCF2127_R_TS_CTL, PCF2127_B_TSOFF);
488                         if (err != 0) {
489                                 device_printf(sc->dev,
490                                     "cannot write timestamp control\n");
491                                 return (err);
492                         }
493
494                         clkout = PCF2129_B_CLKOUT_HIGHZ;
495                         err = write_reg(sc, PCF8523_R_TMR_CLKOUT, clkout);
496                         if (err == 0)
497                                 err = write_reg(sc, PCF8523_R_TMR_CLKOUT,
498                                     clkout | PCF2129_B_CLKOUT_OTPR);
499                         if (err != 0) {
500                                 device_printf(sc->dev,
501                                     "cannot write CLKOUT control\n");
502                                 return (err);
503                         }
504                         pause_sbt("nxpotp", mstosbt(100), mstosbt(10), 0);
505                 } else
506                         clkout = PCF8523_B_CLKOUT_HIGHZ;
507
508                 /* All chips: set clock output pin to high-z to save power */
509                 if ((err = write_reg(sc, PCF8523_R_TMR_CLKOUT, clkout)) != 0) {
510                         device_printf(sc->dev, "cannot write CLKOUT control\n");
511                         return (err);
512                 }
513         }
514
515         /*
516          * Check the battery voltage and report if it's low.  This also has the
517          * side effect of (re-)initializing the power manager to low-power mode
518          * when we come up after a power fail.
519          */
520         pcf8523_battery_check(sc);
521
522         /*
523          * Remember whether we're running in AM/PM mode.  The chip default is
524          * 24-hour mode, but if we're co-existing with some other OS that
525          * prefers AM/PM we can run that way too.
526          *
527          * Also, for 212x chips, retrieve the current frequency aging offset,
528          * and set up the sysctl handler for reading/setting it.
529          */
530         if (sc->is212x) {
531                 if (csr.cs1 & PCF2129_B_CS1_12HR)
532                         sc->use_ampm = true;
533
534                 err = read_reg(sc, PCF2127_R_AGING_OFFSET, &freqadj);
535                 if (err != 0) {
536                         device_printf(sc->dev,
537                             "cannot read AGINGOFFSET register\n");
538                         return (err);
539                 }
540                 sc->freqadj = (int8_t)freqadj;
541
542                 ctx = device_get_sysctl_ctx(sc->dev);
543                 tree = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
544
545                 SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "freqadj",
546                     CTLFLAG_RWTUN | CTLTYPE_INT | CTLFLAG_MPSAFE, sc, 0,
547                     freqadj_sysctl, "I", "Frequency adjust in PPM, range [-7,+8]");
548         } else {
549                 if (csr.cs1 & PCF8523_B_CS1_12HR)
550                         sc->use_ampm = true;
551         }
552
553         return (0);
554 }
555 static int
556 pcf8523_start_timer(struct nxprtc_softc *sc)
557 {
558         int err;
559         uint8_t clkout, stdclk, stdfreq, tmrfreq;
560
561         /*
562          * Read the timer control and frequency regs.  If they don't have the
563          * values we normally program into them then the timer count doesn't
564          * contain a valid fractional second, so zero it to prevent using a bad
565          * value.  Then program the normal timer values so that on the first
566          * settime call we'll begin to use fractional time.
567          */
568         if ((err = read_reg(sc, PCF8523_R_TMR_A_FREQ, &tmrfreq)) != 0)
569                 return (err);
570         if ((err = read_reg(sc, PCF8523_R_TMR_CLKOUT, &clkout)) != 0)
571                 return (err);
572
573         stdfreq = PCF8523_B_TMR_A_64HZ;
574         stdclk = PCF8523_B_CLKOUT_TACD | PCF8523_B_CLKOUT_HIGHZ;
575
576         if (clkout != stdclk || (tmrfreq & PCF8523_M_TMR_A_FREQ) != stdfreq) {
577                 if ((err = write_reg(sc, sc->tmcaddr, 0)) != 0)
578                         return (err);
579                 if ((err = write_reg(sc, PCF8523_R_TMR_A_FREQ, stdfreq)) != 0)
580                         return (err);
581                 if ((err = write_reg(sc, PCF8523_R_TMR_CLKOUT, stdclk)) != 0)
582                         return (err);
583         }
584         return (0);
585 }
586
587 static int
588 pcf2127_start_timer(struct nxprtc_softc *sc)
589 {
590         int err;
591         uint8_t stdctl, tmrctl;
592
593         /*
594          * Set up timer if it's not already in the mode we normally run it.  See
595          * the comment in pcf8523_start_timer() for more details.
596          *
597          * Note that the PCF2129 datasheet says it has no countdown timer, but
598          * empirical testing shows that it works just fine for our purposes.
599          */
600         if ((err = read_reg(sc, PCF2127_R_TMR_CTL, &tmrctl)) != 0)
601                 return (err);
602
603         stdctl = PCF2127_B_TMR_CD | PCF8523_B_TMR_A_64HZ;
604
605         if ((tmrctl & PCF2127_M_TMR_CTRL) != stdctl) {
606                 if ((err = write_reg(sc, sc->tmcaddr, 0)) != 0)
607                         return (err);
608                 if ((err = write_reg(sc, PCF2127_R_TMR_CTL, stdctl)) != 0)
609                         return (err);
610         }
611         return (0);
612 }
613
614 static int
615 pcf8563_start(struct nxprtc_softc *sc)
616 {
617         struct csr {
618                 uint8_t cs1;
619                 uint8_t cs2;
620                 uint8_t sec;
621         } csr;
622         int err;
623
624         /* Read the control and status registers. */
625         if ((err = nxprtc_readfrom(sc->dev, PCF85xx_R_CS1, &csr,
626             sizeof(csr), WAITFLAGS)) != 0){
627                 device_printf(sc->dev, "cannot read RTC control regs\n");
628                 return (err);
629         }
630
631         /*
632          * Do a full init if...
633          *  - The OS (oscillator stopped) bit is set (all power was lost).  This
634          *    bit is called VL (Voltage Low) in the 8563 datasheet.
635          *  - The clock-increment STOP flag is set (this is just insane).
636          */
637         if ((csr.cs1 & PCF85xx_B_CS1_STOP) || (csr.sec & PCF85xx_B_SECOND_OS)) {
638                 device_printf(sc->dev, 
639                     "WARNING: RTC battery failed; time is invalid\n");
640                 /*
641                  * - Turn off the POR-Override bit (used for mfg test only), by
642                  *   writing zero to cs 1 (all other bits power on as zero).
643                  * - Turn off the clock output pin (to save battery power), by
644                  *   writing zero to the clkout control reg.
645                  */
646                 if ((err = write_reg(sc, PCF85xx_R_CS1, 0)) != 0) {
647                         device_printf(sc->dev, "cannot write CS1 reg\n");
648                         return (err);
649                 }
650
651                 if ((err = write_reg(sc, PCF8563_R_CLKOUT, 0)) != 0) {
652                         device_printf(sc->dev, "cannot write CS1 reg\n");
653                         return (err);
654                 }
655         }
656
657         return (0);
658 }
659
660 static int
661 pcf8563_start_timer(struct nxprtc_softc *sc)
662 {
663         int err;
664         uint8_t stdctl, tmrctl;
665
666         /* See comment in pcf8523_start_timer().  */
667         if ((err = read_reg(sc, PCF8563_R_TMR_CTRL, &tmrctl)) != 0)
668                 return (err);
669
670         stdctl = PCF8563_B_TMR_ENABLE | PCF8563_B_TMR_64HZ;
671
672         if ((tmrctl & PCF8563_M_TMR_CTRL) != stdctl) {
673                 if ((err = write_reg(sc, sc->tmcaddr, 0)) != 0)
674                         return (err);
675                 if ((err = write_reg(sc, PCF8563_R_TMR_CTRL, stdctl)) != 0)
676                         return (err);
677         }
678         return (0);
679 }
680
681 static void
682 nxprtc_start(void *dev)
683 {
684         struct nxprtc_softc *sc;
685         int clockflags, resolution;
686
687         sc = device_get_softc((device_t)dev);
688         config_intrhook_disestablish(&sc->config_hook);
689
690         /* First do chip-specific inits. */
691         switch (sc->chiptype) {
692         case TYPE_PCA2129:
693         case TYPE_PCF2129:
694         case TYPE_PCF2127:
695                 sc->is212x = true;
696                 if (pcf8523_start(sc) != 0)
697                         return;
698                 if (pcf2127_start_timer(sc) != 0) {
699                         device_printf(sc->dev, "cannot set up timer\n");
700                         return;
701                 }
702                 break;
703         case TYPE_PCF8523:
704                 if (pcf8523_start(sc) != 0)
705                         return;
706                 if (pcf8523_start_timer(sc) != 0) {
707                         device_printf(sc->dev, "cannot set up timer\n");
708                         return;
709                 }
710                 break;
711         case TYPE_PCA8565:
712         case TYPE_PCF8563:
713                 if (pcf8563_start(sc) != 0)
714                         return;
715                 if (pcf8563_start_timer(sc) != 0) {
716                         device_printf(sc->dev, "cannot set up timer\n");
717                         return;
718                 }
719                 break;
720         default:
721                 device_printf(sc->dev, "missing init code for this chiptype\n");
722                 return;
723         }
724
725         /*
726          * Everything looks good if we make it to here; register as an RTC.  If
727          * we're using the timer to count fractional seconds, our resolution is
728          * 1e6/64, about 15.6ms.  Without the timer we still align the RTC clock
729          * when setting it so our error is an average .5s when reading it.
730          * Schedule our clock_settime() method to be called at a .495ms offset
731          * into the second, because the clock hardware resets the divider chain
732          * to the mid-second point when you set the time and it takes about 5ms
733          * of i2c bus activity to set the clock.
734          */
735         resolution = sc->use_timer ? 1000000 / TMR_TICKS_SEC : 1000000 / 2;
736         clockflags = CLOCKF_GETTIME_NO_ADJ | CLOCKF_SETTIME_NO_TS;
737         clock_register_flags(sc->dev, resolution, clockflags);
738         clock_schedule(sc->dev, 495000000);
739 }
740
741 static int
742 nxprtc_gettime(device_t dev, struct timespec *ts)
743 {
744         struct bcd_clocktime bct;
745         struct time_regs tregs;
746         struct nxprtc_softc *sc;
747         int err;
748         uint8_t cs1, hourmask, tmrcount;
749
750         sc = device_get_softc(dev);
751
752         /*
753          * Read the time, but before using it, validate that the oscillator-
754          * stopped/power-fail bit is not set, and that the time-increment STOP
755          * bit is not set in the control reg.  The latter can happen if there
756          * was an error when setting the time.
757          */
758         if ((err = iicbus_request_bus(sc->busdev, sc->dev, IIC_WAIT)) == 0) {
759                 if ((err = read_timeregs(sc, &tregs, &tmrcount)) == 0) {
760                         err = read_reg(sc, PCF85xx_R_CS1, &cs1);
761                 }
762                 iicbus_release_bus(sc->busdev, sc->dev);
763         }
764         if (err != 0)
765                 return (err);
766
767         if ((tregs.sec & PCF85xx_B_SECOND_OS) || (cs1 & PCF85xx_B_CS1_STOP)) {
768                 device_printf(dev, "RTC clock not running\n");
769                 return (EINVAL); /* hardware is good, time is not. */
770         }
771
772         if (sc->use_ampm)
773                 hourmask = PCF85xx_M_12HOUR;
774         else
775                 hourmask = PCF85xx_M_24HOUR;
776
777         bct.nsec = ((uint64_t)tmrcount * 1000000000) / TMR_TICKS_SEC;
778         bct.ispm = (tregs.hour & PCF8523_B_HOUR_PM) != 0;
779         bct.sec  = tregs.sec   & PCF85xx_M_SECOND;
780         bct.min  = tregs.min   & PCF85xx_M_MINUTE;
781         bct.hour = tregs.hour  & hourmask;
782         bct.day  = tregs.day   & PCF85xx_M_DAY;
783         bct.mon  = tregs.month & PCF85xx_M_MONTH;
784         bct.year = tregs.year  & PCF85xx_M_YEAR;
785
786         /*
787          * Old PCF8563 datasheets recommended that the C bit be 1 for 19xx and 0
788          * for 20xx; newer datasheets don't recommend that.  We don't care,
789          * but we may co-exist with other OSes sharing the hardware. Determine
790          * existing polarity on a read so that we can preserve it on a write.
791          */
792         if (sc->chiptype == TYPE_PCF8563) {
793                 if (tregs.month & PCF8563_B_MONTH_C) {
794                         if (bct.year < 0x70)
795                                 sc->flags |= SC_F_CPOL;
796                 } else if (bct.year >= 0x70)
797                                 sc->flags |= SC_F_CPOL;
798         }
799
800         clock_dbgprint_bcd(sc->dev, CLOCK_DBG_READ, &bct); 
801         err = clock_bcd_to_ts(&bct, ts, sc->use_ampm);
802         ts->tv_sec += utc_offset();
803
804         return (err);
805 }
806
807 static int
808 nxprtc_settime(device_t dev, struct timespec *ts)
809 {
810         struct bcd_clocktime bct;
811         struct time_regs tregs;
812         struct nxprtc_softc *sc;
813         int err;
814         uint8_t cflag, cs1;
815
816         sc = device_get_softc(dev);
817
818         /*
819          * We stop the clock, set the time, then restart the clock.  Half a
820          * second after restarting the clock it ticks over to the next second.
821          * So to align the RTC, we schedule this function to be called when
822          * system time is roughly halfway (.495) through the current second.
823          *
824          * Reserve use of the i2c bus and stop the RTC clock.  Note that if
825          * anything goes wrong from this point on, we leave the clock stopped,
826          * because we don't really know what state it's in.
827          */
828         if ((err = iicbus_request_bus(sc->busdev, sc->dev, IIC_WAIT)) != 0)
829                 return (err);
830         if ((err = read_reg(sc, PCF85xx_R_CS1, &cs1)) != 0)
831                 goto errout;
832         cs1 |= PCF85xx_B_CS1_STOP;
833         if ((err = write_reg(sc, PCF85xx_R_CS1, cs1)) != 0)
834                 goto errout;
835
836         /* Grab a fresh post-sleep idea of what time it is. */
837         getnanotime(ts);
838         ts->tv_sec -= utc_offset();
839         ts->tv_nsec = 0;
840         clock_ts_to_bcd(ts, &bct, sc->use_ampm);
841         clock_dbgprint_bcd(sc->dev, CLOCK_DBG_WRITE, &bct);
842
843         /* On 8563 set the century based on the polarity seen when reading. */
844         cflag = 0;
845         if (sc->chiptype == TYPE_PCF8563) {
846                 if ((sc->flags & SC_F_CPOL) != 0) {
847                         if (bct.year >= 0x2000)
848                                 cflag = PCF8563_B_MONTH_C;
849                 } else if (bct.year < 0x2000)
850                                 cflag = PCF8563_B_MONTH_C;
851         }
852
853         tregs.sec   = bct.sec;
854         tregs.min   = bct.min;
855         tregs.hour  = bct.hour | (bct.ispm ? PCF8523_B_HOUR_PM : 0);
856         tregs.day   = bct.day;
857         tregs.month = bct.mon;
858         tregs.year  = (bct.year & 0xff) | cflag;
859         tregs.wday  = bct.dow;
860
861         /*
862          * Set the time, reset the timer count register, then start the clocks.
863          */
864         if ((err = write_timeregs(sc, &tregs)) != 0)
865                 goto errout;
866
867         if ((err = write_reg(sc, sc->tmcaddr, TMR_TICKS_SEC)) != 0)
868                 return (err);
869
870         cs1 &= ~PCF85xx_B_CS1_STOP;
871         err = write_reg(sc, PCF85xx_R_CS1, cs1);
872
873         /*
874          * Check for battery-low.  The actual check is throttled to only occur
875          * once a day, mostly to avoid spamming the user with frequent warnings.
876          */
877         pcf8523_battery_check(sc);
878
879 errout:
880
881         iicbus_release_bus(sc->busdev, sc->dev);
882
883         if (err != 0)
884                 device_printf(dev, "cannot write RTC time\n");
885
886         return (err);
887 }
888
889 static int
890 nxprtc_get_chiptype(device_t dev)
891 {
892 #ifdef FDT
893
894         return (ofw_bus_search_compatible(dev, compat_data)->ocd_data);
895 #else
896         nxprtc_compat_data *cdata;
897         const char *htype;
898         int chiptype;
899
900         /*
901          * If given a chiptype hint string, loop through the ofw compat data
902          * comparing the hinted chip type to the compat strings.  The table end
903          * marker ocd_data is TYPE_NONE.
904          */
905         if (resource_string_value(device_get_name(dev), 
906             device_get_unit(dev), "compatible", &htype) == 0) {
907                 for (cdata = compat_data; cdata->ocd_str != NULL; ++cdata) {
908                         if (strcmp(htype, cdata->ocd_str) == 0)
909                                 break;
910                 }
911                 chiptype = cdata->ocd_data;
912         } else
913                 chiptype = TYPE_NONE;
914
915         /*
916          * On non-FDT systems the historical behavior of this driver was to
917          * assume a PCF8563; keep doing that for compatibility.
918          */
919         if (chiptype == TYPE_NONE)
920                 return (TYPE_PCF8563);
921         else
922                 return (chiptype);
923 #endif
924 }
925
926 static int
927 nxprtc_probe(device_t dev)
928 {
929         int chiptype, rv;
930
931 #ifdef FDT
932         if (!ofw_bus_status_okay(dev))
933                 return (ENXIO);
934         rv = BUS_PROBE_GENERIC;
935 #else
936         rv = BUS_PROBE_NOWILDCARD;
937 #endif
938         if ((chiptype = nxprtc_get_chiptype(dev)) == TYPE_NONE)
939                 return (ENXIO);
940
941         device_set_desc(dev, desc_strings[chiptype]);
942         return (rv);
943 }
944
945 static int
946 nxprtc_attach(device_t dev)
947 {
948         struct nxprtc_softc *sc;
949
950         sc = device_get_softc(dev);
951         sc->dev = dev;
952         sc->busdev = device_get_parent(dev);
953
954         /* We need to know what kind of chip we're driving. */
955         sc->chiptype = nxprtc_get_chiptype(dev);
956
957         /* The features and some register addresses vary by chip type. */
958         switch (sc->chiptype) {
959         case TYPE_PCA2129:
960         case TYPE_PCF2129:
961         case TYPE_PCF2127:
962         case TYPE_PCF8523:
963                 sc->secaddr = PCF8523_R_SECOND;
964                 sc->tmcaddr = PCF8523_R_TMR_A_COUNT;
965                 sc->use_timer = true;
966                 break;
967         case TYPE_PCA8565:
968         case TYPE_PCF8563:
969                 sc->secaddr = PCF8563_R_SECOND;
970                 sc->tmcaddr = PCF8563_R_TMR_COUNT;
971                 sc->use_timer = true;
972                 break;
973         default:
974                 device_printf(dev, "impossible: cannot determine chip type\n");
975                 return (ENXIO);
976         }
977
978         /*
979          * We have to wait until interrupts are enabled.  Sometimes I2C read
980          * and write only works when the interrupts are available.
981          */
982         sc->config_hook.ich_func = nxprtc_start;
983         sc->config_hook.ich_arg = dev;
984         if (config_intrhook_establish(&sc->config_hook) != 0)
985                 return (ENOMEM);
986
987         return (0);
988 }
989
990 static int
991 nxprtc_detach(device_t dev)
992 {
993
994         clock_unregister(dev);
995         return (0);
996 }
997
998 static device_method_t nxprtc_methods[] = {
999         DEVMETHOD(device_probe,         nxprtc_probe),
1000         DEVMETHOD(device_attach,        nxprtc_attach),
1001         DEVMETHOD(device_detach,        nxprtc_detach),
1002
1003         DEVMETHOD(clock_gettime,        nxprtc_gettime),
1004         DEVMETHOD(clock_settime,        nxprtc_settime),
1005
1006         DEVMETHOD_END
1007 };
1008
1009 static driver_t nxprtc_driver = {
1010         "nxprtc",
1011         nxprtc_methods,
1012         sizeof(struct nxprtc_softc),
1013 };
1014
1015 static devclass_t nxprtc_devclass;
1016
1017 DRIVER_MODULE(nxprtc, iicbus, nxprtc_driver, nxprtc_devclass, NULL, NULL);
1018 MODULE_VERSION(nxprtc, 1);
1019 MODULE_DEPEND(nxprtc, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
1020 IICBUS_FDT_PNP_INFO(compat_data);