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