]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/iicbus/nxprtc.c
Handle the PCF2127 RTC chip the same as PCF2129 when init'ing the chip.
[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
64 #include <dev/iicbus/iicbus.h>
65 #include <dev/iicbus/iiconf.h>
66 #ifdef FDT
67 #include <dev/ofw/openfirm.h>
68 #include <dev/ofw/ofw_bus.h>
69 #include <dev/ofw/ofw_bus_subr.h>
70 #endif
71
72 #include "clock_if.h"
73 #include "iicbus_if.h"
74
75 /*
76  * I2C address 1010 001x : PCA2129 PCF2127 PCF2129 PCF8563 PCF8565
77  * I2C address 1101 000x : PCF8523
78  */
79 #define PCF8563_ADDR            0xa2
80 #define PCF8523_ADDR            0xd0
81
82 /*
83  * Registers, bits within them, and masks that are common to all chip types.
84  */
85 #define PCF85xx_R_CS1           0x00    /* CS1 and CS2 control regs are in */
86 #define PCF85xx_R_CS2           0x01    /* the same location on all chips. */
87
88 #define PCF85xx_B_CS1_STOP      0x20    /* Stop time incrementing bit */
89 #define PCF85xx_B_SECOND_OS     0x80    /* Oscillator Stopped bit */
90
91 #define PCF85xx_M_SECOND        0x7f    /* Masks for all BCD time regs... */
92 #define PCF85xx_M_MINUTE        0x7f
93 #define PCF85xx_M_12HOUR        0x1f
94 #define PCF85xx_M_24HOUR        0x3f
95 #define PCF85xx_M_DAY           0x3f
96 #define PCF85xx_M_MONTH         0x1f
97 #define PCF85xx_M_YEAR          0xff
98
99 /*
100  * PCF2127-specific registers, bits, and masks.
101  */
102 #define PCF2127_R_TMR_CTL       0x10    /* Timer/watchdog control */
103
104 #define PCF2127_M_TMR_CTRL      0xe3    /* Mask off undef bits */
105
106 #define PCF2127_B_TMR_CD        0x40    /* Run in countdown mode */
107 #define PCF2127_B_TMR_64HZ      0x01    /* Timer frequency 64Hz */
108
109 /*
110  * PCA/PCF2129-specific registers, bits, and masks.
111  */
112 #define PCF2129_B_CS1_12HR      0x04    /* Use 12-hour (AM/PM) mode bit */
113 #define PCF2129_B_CLKOUT_OTPR   0x20    /* OTP refresh command */
114 #define PCF2129_B_CLKOUT_HIGHZ  0x07    /* Clock Out Freq = disable */
115
116 /*
117  * PCF8523-specific registers, bits, and masks.
118  */
119 #define PCF8523_R_CS3           0x02    /* Control and status reg 3 */
120 #define PCF8523_R_SECOND        0x03    /* Seconds */
121 #define PCF8523_R_TMR_CLKOUT    0x0F    /* Timer and clockout control */
122 #define PCF8523_R_TMR_A_FREQ    0x10    /* Timer A frequency control */
123 #define PCF8523_R_TMR_A_COUNT   0x11    /* Timer A count */
124
125 #define PCF8523_M_TMR_A_FREQ    0x07    /* Mask off undef bits */
126
127 #define PCF8523_B_HOUR_PM       0x20    /* PM bit */
128 #define PCF8523_B_CS1_SOFTRESET 0x58    /* Initiate Soft Reset bits */
129 #define PCF8523_B_CS1_12HR      0x08    /* Use 12-hour (AM/PM) mode bit */
130 #define PCF8523_B_CLKOUT_TACD   0x02    /* TimerA runs in CountDown mode */
131 #define PCF8523_B_CLKOUT_HIGHZ  0x38    /* Clock Out Freq = disable */
132 #define PCF8523_B_TMR_A_64HZ    0x01    /* Timer A freq 64Hz */
133
134 #define PCF8523_M_CS3_PM        0xE0    /* Power mode mask */
135 #define PCF8523_B_CS3_PM_NOBAT  0xE0    /* PM bits: no battery usage */
136 #define PCF8523_B_CS3_PM_STD    0x00    /* PM bits: standard */
137 #define PCF8523_B_CS3_BLF       0x04    /* Battery Low Flag bit */
138
139 /*
140  * PCF8563-specific registers, bits, and masks.
141  */
142 #define PCF8563_R_SECOND        0x02    /* Seconds */
143 #define PCF8563_R_TMR_CTRL      0x0e    /* Timer control */
144 #define PCF8563_R_TMR_COUNT     0x0f    /* Timer count */
145
146 #define PCF8563_M_TMR_CTRL      0x93    /* Mask off undef bits */
147
148 #define PCF8563_B_TMR_ENABLE    0x80    /* Enable countdown timer */
149 #define PCF8563_B_TMR_64HZ      0x01    /* Timer frequency 64Hz */
150
151 #define PCF8563_B_MONTH_C       0x80    /* Century bit */
152
153 /*
154  * We use the countdown timer for fractional seconds.  We program it for 64 Hz,
155  * the fastest available rate that doesn't roll over in less than a second.
156  */
157 #define TMR_TICKS_SEC           64
158 #define TMR_TICKS_HALFSEC       32
159
160 /*
161  * The chip types we support.
162  */
163 enum {
164         TYPE_NONE,
165         TYPE_PCA2129,
166         TYPE_PCA8565,
167         TYPE_PCF2127,
168         TYPE_PCF2129,
169         TYPE_PCF8523,
170         TYPE_PCF8563,
171
172         TYPE_COUNT
173 };
174 static const char *desc_strings[] = {
175         "",
176         "NXP PCA2129 RTC",
177         "NXP PCA8565 RTC",
178         "NXP PCF2127 RTC",
179         "NXP PCF2129 RTC",
180         "NXP PCF8523 RTC",
181         "NXP PCF8563 RTC",
182 };
183 CTASSERT(nitems(desc_strings) == TYPE_COUNT);
184
185 /*
186  * The time registers in the order they are laid out in hardware.
187  */
188 struct time_regs {
189         uint8_t sec, min, hour, day, wday, month, year;
190 };
191
192 struct nxprtc_softc {
193         device_t        dev;
194         device_t        busdev;
195         struct intr_config_hook
196                         config_hook;
197         u_int           flags;          /* SC_F_* flags */
198         u_int           chiptype;       /* Type of PCF85xx chip */
199         uint8_t         secaddr;        /* Address of seconds register */
200         uint8_t         tmcaddr;        /* Address of timer count register */
201         bool            use_timer;      /* Use timer for fractional sec */
202         bool            use_ampm;       /* Chip is set to use am/pm mode */
203 };
204
205 #define SC_F_CPOL       (1 << 0)        /* Century bit means 19xx */
206
207 /*
208  * When doing i2c IO, indicate that we need to wait for exclusive bus ownership,
209  * but that we should not wait if we already own the bus.  This lets us put
210  * iicbus_acquire_bus() calls with a non-recursive wait at the entry of our API
211  * functions to ensure that only one client at a time accesses the hardware for
212  * the entire series of operations it takes to read or write the clock.
213  */
214 #define WAITFLAGS       (IIC_WAIT | IIC_RECURSIVE)
215
216 /*
217  * We use the compat_data table to look up hint strings in the non-FDT case, so
218  * define the struct locally when we don't get it from ofw_bus_subr.h.
219  */
220 #ifdef FDT
221 typedef struct ofw_compat_data nxprtc_compat_data;
222 #else
223 typedef struct {
224         const char *ocd_str;
225         uintptr_t  ocd_data;
226 } nxprtc_compat_data;
227 #endif
228
229 static nxprtc_compat_data compat_data[] = {
230         {"nxp,pca2129",     TYPE_PCA2129},
231         {"nxp,pca8565",     TYPE_PCA8565},
232         {"nxp,pcf2127",     TYPE_PCF2127},
233         {"nxp,pcf2129",     TYPE_PCF2129},
234         {"nxp,pcf8523",     TYPE_PCF8523},
235         {"nxp,pcf8563",     TYPE_PCF8563},
236
237         /* Undocumented compat strings known to exist in the wild... */
238         {"pcf8563",         TYPE_PCF8563},
239         {"phg,pcf8563",     TYPE_PCF8563},
240         {"philips,pcf8563", TYPE_PCF8563},
241
242         {NULL,              TYPE_NONE},
243 };
244
245 static int
246 nxprtc_readfrom(device_t slavedev, uint8_t regaddr, void *buffer,
247     uint16_t buflen, int waithow)
248 {
249         struct iic_msg msg;
250         int err;
251         uint8_t slaveaddr;
252
253         /*
254          * Two transfers back to back with a stop and start between them; first we
255          * write the address-within-device, then we read from the device.  This
256          * is used instead of the standard iicdev_readfrom() because some of the
257          * chips we service don't support i2c repeat-start operations (grrrrr)
258          * so we do two completely separate transfers with a full stop between.
259          */
260         slaveaddr = iicbus_get_addr(slavedev);
261
262         msg.slave = slaveaddr;
263         msg.flags = IIC_M_WR;
264         msg.len   = 1;
265         msg.buf   = &regaddr;
266
267         if ((err = iicbus_transfer_excl(slavedev, &msg, 1, waithow)) != 0)
268                 return (err);
269
270         msg.slave = slaveaddr;
271         msg.flags = IIC_M_RD;
272         msg.len   = buflen;
273         msg.buf   = buffer;
274
275         return (iicbus_transfer_excl(slavedev, &msg, 1, waithow));
276 }
277
278 static int
279 read_reg(struct nxprtc_softc *sc, uint8_t reg, uint8_t *val)
280 {
281
282         return (nxprtc_readfrom(sc->dev, reg, val, sizeof(*val), WAITFLAGS));
283 }
284
285 static int
286 write_reg(struct nxprtc_softc *sc, uint8_t reg, uint8_t val)
287 {
288
289         return (iicdev_writeto(sc->dev, reg, &val, sizeof(val), WAITFLAGS));
290 }
291
292 static int
293 read_timeregs(struct nxprtc_softc *sc, struct time_regs *tregs, uint8_t *tmr)
294 {
295         int err;
296         uint8_t sec, tmr1, tmr2;
297
298         /*
299          * The datasheet says loop to read the same timer value twice because it
300          * does not freeze while reading.  To that we add our own logic that
301          * the seconds register must be the same before and after reading the
302          * timer, ensuring the fractional part is from the same second as tregs.
303          */
304         do {
305                 if (sc->use_timer) {
306                         if ((err = read_reg(sc, sc->secaddr, &sec)) != 0)
307                                 break;
308                         if ((err = read_reg(sc, sc->tmcaddr, &tmr1)) != 0)
309                                 break;
310                         if ((err = read_reg(sc, sc->tmcaddr, &tmr2)) != 0)
311                                 break;
312                         if (tmr1 != tmr2)
313                                 continue;
314                 }
315                 if ((err = nxprtc_readfrom(sc->dev, sc->secaddr, tregs,
316                     sizeof(*tregs), WAITFLAGS)) != 0)
317                         break;
318         } while (sc->use_timer && tregs->sec != sec);
319
320         /*
321          * If the timer value is greater than our hz rate (or is zero),
322          * something is wrong.  Maybe some other OS used the timer differently?
323          * Just set it to zero.  Likewise if we're not using the timer.  After
324          * the offset calc below, the zero turns into 32, the mid-second point,
325          * which in effect performs 4/5 rounding, which is just the right thing
326          * to do if we don't have fine-grained time.
327          */
328         if (!sc->use_timer || tmr1 > TMR_TICKS_SEC)
329                 tmr1 = 0;
330
331         /*
332          * Turn the downcounter into an upcounter.  The timer starts counting at
333          * and rolls over at mid-second, so add half a second worth of ticks to
334          * get its zero point back in sync with the tregs.sec rollover.
335          */
336         *tmr = (TMR_TICKS_SEC - tmr1 + TMR_TICKS_HALFSEC) % TMR_TICKS_SEC;
337
338         return (err);
339 }
340
341 static int
342 write_timeregs(struct nxprtc_softc *sc, struct time_regs *tregs)
343 {
344
345         return (iicdev_writeto(sc->dev, sc->secaddr, tregs,
346             sizeof(*tregs), WAITFLAGS));
347 }
348
349 static int
350 pcf8523_start(struct nxprtc_softc *sc)
351 {
352         int err;
353         uint8_t cs1, cs3, clkout;
354         bool is212x;
355
356         switch (sc->chiptype) {
357         case TYPE_PCF2127:
358         case TYPE_PCA2129:
359         case TYPE_PCF2129:
360                 is212x = true;
361                 break;
362         default:
363                 is212x = true;
364                 break;
365         }
366
367         /* Read and sanity-check the control registers. */
368         if ((err = read_reg(sc, PCF85xx_R_CS1, &cs1)) != 0) {
369                 device_printf(sc->dev, "cannot read RTC CS1 control\n");
370                 return (err);
371         }
372         if ((err = read_reg(sc, PCF8523_R_CS3, &cs3)) != 0) {
373                 device_printf(sc->dev, "cannot read RTC CS3 control\n");
374                 return (err);
375         }
376
377         /*
378          * Do a full init (soft-reset) if...
379          *  - The chip is in battery-disable mode (fresh from the factory).
380          *  - The clock-increment STOP flag is set (this is just insane).
381          * After reset, battery disable mode has to be overridden to "standard"
382          * mode.  Also, turn off clock output to save battery power.
383          */
384         if ((cs3 & PCF8523_M_CS3_PM) == PCF8523_B_CS3_PM_NOBAT ||
385             (cs1 & PCF85xx_B_CS1_STOP)) {
386                 cs1 = PCF8523_B_CS1_SOFTRESET;
387                 if ((err = write_reg(sc, PCF85xx_R_CS1, cs1)) != 0) {
388                         device_printf(sc->dev, "cannot write CS1 control\n");
389                         return (err);
390                 }
391                 cs3 = PCF8523_B_CS3_PM_STD;
392                 if ((err = write_reg(sc, PCF8523_R_CS3, cs3)) != 0) {
393                         device_printf(sc->dev, "cannot write CS3 control\n");
394                         return (err);
395                 }
396                 /*
397                  * For 2129 series, trigger OTP refresh by forcing the OTPR bit
398                  * to zero then back to 1, then wait 100ms for the refresh, and
399                  * finally set the bit back to zero with the COF_HIGHZ write.
400                  */
401                 if (is212x) {
402                         clkout = PCF2129_B_CLKOUT_HIGHZ;
403                         if ((err = write_reg(sc, PCF8523_R_TMR_CLKOUT,
404                             clkout)) != 0) {
405                                 device_printf(sc->dev,
406                                     "cannot write CLKOUT control\n");
407                                 return (err);
408                         }
409                         if ((err = write_reg(sc, PCF8523_R_TMR_CLKOUT,
410                             clkout | PCF2129_B_CLKOUT_OTPR)) != 0) {
411                                 device_printf(sc->dev,
412                                     "cannot write CLKOUT control\n");
413                                 return (err);
414                         }
415                         pause_sbt("nxpotp", mstosbt(100), mstosbt(10), 0);
416                 } else
417                         clkout = PCF8523_B_CLKOUT_HIGHZ;
418                 if ((err = write_reg(sc, PCF8523_R_TMR_CLKOUT, clkout)) != 0) {
419                         device_printf(sc->dev, "cannot write CLKOUT control\n");
420                         return (err);
421                 }
422                 device_printf(sc->dev,
423                     "first time startup, enabled RTC battery operation\n");
424
425                 /*
426                  * Sleep briefly so the battery monitor can make a measurement,
427                  * then re-read CS3 so battery-low status can be reported below.
428                  */
429                 pause_sbt("nxpbat", mstosbt(100), 0, 0);
430                 if ((err = read_reg(sc, PCF8523_R_CS3, &cs3)) != 0) {
431                         device_printf(sc->dev, "cannot read RTC CS3 control\n");
432                         return (err);
433                 }
434         }
435
436         /* Let someone know if the battery is weak. */
437         if (cs3 & PCF8523_B_CS3_BLF)
438                 device_printf(sc->dev, "WARNING: RTC battery is low\n");
439
440         /* Remember whether we're running in AM/PM mode. */
441         if (is212x) {
442                 if (cs1 & PCF2129_B_CS1_12HR)
443                         sc->use_ampm = true;
444         } else {
445                 if (cs1 & PCF8523_B_CS1_12HR)
446                         sc->use_ampm = true;
447         }
448
449         return (0);
450 }
451
452 static int
453 pcf8523_start_timer(struct nxprtc_softc *sc)
454 {
455         int err;
456         uint8_t clkout, stdclk, stdfreq, tmrfreq;
457
458         /*
459          * Read the timer control and frequency regs.  If they don't have the
460          * values we normally program into them then the timer count doesn't
461          * contain a valid fractional second, so zero it to prevent using a bad
462          * value.  Then program the normal timer values so that on the first
463          * settime call we'll begin to use fractional time.
464          */
465         if ((err = read_reg(sc, PCF8523_R_TMR_A_FREQ, &tmrfreq)) != 0)
466                 return (err);
467         if ((err = read_reg(sc, PCF8523_R_TMR_CLKOUT, &clkout)) != 0)
468                 return (err);
469
470         stdfreq = PCF8523_B_TMR_A_64HZ;
471         stdclk = PCF8523_B_CLKOUT_TACD | PCF8523_B_CLKOUT_HIGHZ;
472
473         if (clkout != stdclk || (tmrfreq & PCF8523_M_TMR_A_FREQ) != stdfreq) {
474                 if ((err = write_reg(sc, sc->tmcaddr, 0)) != 0)
475                         return (err);
476                 if ((err = write_reg(sc, PCF8523_R_TMR_A_FREQ, stdfreq)) != 0)
477                         return (err);
478                 if ((err = write_reg(sc, PCF8523_R_TMR_CLKOUT, stdclk)) != 0)
479                         return (err);
480         }
481         return (0);
482 }
483
484 static int
485 pcf2127_start_timer(struct nxprtc_softc *sc)
486 {
487         int err;
488         uint8_t stdctl, tmrctl;
489
490         /*
491          * Set up timer if it's not already in the mode we normally run it.  See
492          * the comment in pcf8523_start_timer() for more details.
493          *
494          * Note that the PCF2129 datasheet says it has no countdown timer, but
495          * empirical testing shows that it works just fine for our purposes.
496          */
497         if ((err = read_reg(sc, PCF2127_R_TMR_CTL, &tmrctl)) != 0)
498                 return (err);
499
500         stdctl = PCF2127_B_TMR_CD | PCF8523_B_TMR_A_64HZ;
501
502         if ((tmrctl & PCF2127_M_TMR_CTRL) != stdctl) {
503                 if ((err = write_reg(sc, sc->tmcaddr, 0)) != 0)
504                         return (err);
505                 if ((err = write_reg(sc, PCF2127_R_TMR_CTL, stdctl)) != 0)
506                         return (err);
507         }
508         return (0);
509 }
510
511 static int
512 pcf8563_start_timer(struct nxprtc_softc *sc)
513 {
514         int err;
515         uint8_t stdctl, tmrctl;
516
517         /* See comment in pcf8523_start_timer().  */
518         if ((err = read_reg(sc, PCF8563_R_TMR_CTRL, &tmrctl)) != 0)
519                 return (err);
520
521         stdctl = PCF8563_B_TMR_ENABLE | PCF8563_B_TMR_64HZ;
522
523         if ((tmrctl & PCF8563_M_TMR_CTRL) != stdctl) {
524                 if ((err = write_reg(sc, sc->tmcaddr, 0)) != 0)
525                         return (err);
526                 if ((err = write_reg(sc, PCF8563_R_TMR_CTRL, stdctl)) != 0)
527                         return (err);
528         }
529         return (0);
530 }
531
532 static void
533 nxprtc_start(void *dev)
534 {
535         struct nxprtc_softc *sc;
536         int clockflags, resolution;
537         uint8_t sec;
538
539         sc = device_get_softc((device_t)dev);
540         config_intrhook_disestablish(&sc->config_hook);
541
542         /* First do chip-specific inits. */
543         switch (sc->chiptype) {
544         case TYPE_PCA2129:
545         case TYPE_PCF2129:
546         case TYPE_PCF2127:
547                 if (pcf8523_start(sc) != 0)
548                         return;
549                 if (pcf2127_start_timer(sc) != 0) {
550                         device_printf(sc->dev, "cannot set up timer\n");
551                         return;
552                 }
553                 break;
554         case TYPE_PCF8523:
555                 if (pcf8523_start(sc) != 0)
556                         return;
557                 if (pcf8523_start_timer(sc) != 0) {
558                         device_printf(sc->dev, "cannot set up timer\n");
559                         return;
560                 }
561                 break;
562         case TYPE_PCA8565:
563         case TYPE_PCF8563:
564                 if (pcf8563_start_timer(sc) != 0) {
565                         device_printf(sc->dev, "cannot set up timer\n");
566                         return;
567                 }
568                 break;
569         default:
570                 device_printf(sc->dev, "missing init code for this chiptype\n");
571                 return;
572         }
573
574         /*
575          * Common init.  Read the seconds register so we can check the
576          * oscillator-stopped status bit in it.
577          */
578         if (read_reg(sc, sc->secaddr, &sec) != 0) {
579                 device_printf(sc->dev, "cannot read RTC seconds\n");
580                 return;
581         }
582         if ((sec & PCF85xx_B_SECOND_OS) != 0) {
583                 device_printf(sc->dev, 
584                     "WARNING: RTC battery failed; time is invalid\n");
585         }
586
587         /*
588          * Everything looks good if we make it to here; register as an RTC.  If
589          * we're using the timer to count fractional seconds, our resolution is
590          * 1e6/64, about 15.6ms.  Without the timer we still align the RTC clock
591          * when setting it so our error is an average .5s when reading it.
592          * Schedule our clock_settime() method to be called at a .495ms offset
593          * into the second, because the clock hardware resets the divider chain
594          * to the mid-second point when you set the time and it takes about 5ms
595          * of i2c bus activity to set the clock.
596          */
597         resolution = sc->use_timer ? 1000000 / TMR_TICKS_SEC : 1000000 / 2;
598         clockflags = CLOCKF_GETTIME_NO_ADJ | CLOCKF_SETTIME_NO_TS;
599         clock_register_flags(sc->dev, resolution, clockflags);
600         clock_schedule(sc->dev, 495000000);
601 }
602
603 static int
604 nxprtc_gettime(device_t dev, struct timespec *ts)
605 {
606         struct bcd_clocktime bct;
607         struct time_regs tregs;
608         struct nxprtc_softc *sc;
609         int err;
610         uint8_t cs1, hourmask, tmrcount;
611
612         sc = device_get_softc(dev);
613
614         /*
615          * Read the time, but before using it, validate that the oscillator-
616          * stopped/power-fail bit is not set, and that the time-increment STOP
617          * bit is not set in the control reg.  The latter can happen if there
618          * was an error when setting the time.
619          */
620         if ((err = iicbus_request_bus(sc->busdev, sc->dev, IIC_WAIT)) == 0) {
621                 if ((err = read_timeregs(sc, &tregs, &tmrcount)) == 0) {
622                         err = read_reg(sc, PCF85xx_R_CS1, &cs1);
623                 }
624                 iicbus_release_bus(sc->busdev, sc->dev);
625         }
626         if (err != 0)
627                 return (err);
628
629         if ((tregs.sec & PCF85xx_B_SECOND_OS) || (cs1 & PCF85xx_B_CS1_STOP)) {
630                 device_printf(dev, "RTC clock not running\n");
631                 return (EINVAL); /* hardware is good, time is not. */
632         }
633
634         if (sc->use_ampm)
635                 hourmask = PCF85xx_M_12HOUR;
636         else
637                 hourmask = PCF85xx_M_24HOUR;
638
639         bct.nsec = ((uint64_t)tmrcount * 1000000000) / TMR_TICKS_SEC;
640         bct.ispm = (tregs.hour & PCF8523_B_HOUR_PM) != 0;
641         bct.sec  = tregs.sec   & PCF85xx_M_SECOND;
642         bct.min  = tregs.min   & PCF85xx_M_MINUTE;
643         bct.hour = tregs.hour  & hourmask;
644         bct.day  = tregs.day   & PCF85xx_M_DAY;
645         bct.mon  = tregs.month & PCF85xx_M_MONTH;
646         bct.year = tregs.year  & PCF85xx_M_YEAR;
647
648         /*
649          * Old PCF8563 datasheets recommended that the C bit be 1 for 19xx and 0
650          * for 20xx; newer datasheets don't recommend that.  We don't care,
651          * but we may co-exist with other OSes sharing the hardware. Determine
652          * existing polarity on a read so that we can preserve it on a write.
653          */
654         if (sc->chiptype == TYPE_PCF8563) {
655                 if (tregs.month & PCF8563_B_MONTH_C) {
656                         if (bct.year < 0x70)
657                                 sc->flags |= SC_F_CPOL;
658                 } else if (bct.year >= 0x70)
659                                 sc->flags |= SC_F_CPOL;
660         }
661
662         clock_dbgprint_bcd(sc->dev, CLOCK_DBG_READ, &bct); 
663         err = clock_bcd_to_ts(&bct, ts, sc->use_ampm);
664         ts->tv_sec += utc_offset();
665
666         return (err);
667 }
668
669 static int
670 nxprtc_settime(device_t dev, struct timespec *ts)
671 {
672         struct bcd_clocktime bct;
673         struct time_regs tregs;
674         struct nxprtc_softc *sc;
675         int err;
676         uint8_t cflag, cs1;
677
678         sc = device_get_softc(dev);
679
680         /*
681          * We stop the clock, set the time, then restart the clock.  Half a
682          * second after restarting the clock it ticks over to the next second.
683          * So to align the RTC, we schedule this function to be called when
684          * system time is roughly halfway (.495) through the current second.
685          *
686          * Reserve use of the i2c bus and stop the RTC clock.  Note that if
687          * anything goes wrong from this point on, we leave the clock stopped,
688          * because we don't really know what state it's in.
689          */
690         if ((err = iicbus_request_bus(sc->busdev, sc->dev, IIC_WAIT)) != 0)
691                 return (err);
692         if ((err = read_reg(sc, PCF85xx_R_CS1, &cs1)) != 0)
693                 goto errout;
694         cs1 |= PCF85xx_B_CS1_STOP;
695         if ((err = write_reg(sc, PCF85xx_R_CS1, cs1)) != 0)
696                 goto errout;
697
698         /* Grab a fresh post-sleep idea of what time it is. */
699         getnanotime(ts);
700         ts->tv_sec -= utc_offset();
701         ts->tv_nsec = 0;
702         clock_ts_to_bcd(ts, &bct, sc->use_ampm);
703         clock_dbgprint_bcd(sc->dev, CLOCK_DBG_WRITE, &bct);
704
705         /* On 8563 set the century based on the polarity seen when reading. */
706         cflag = 0;
707         if (sc->chiptype == TYPE_PCF8563) {
708                 if ((sc->flags & SC_F_CPOL) != 0) {
709                         if (bct.year >= 0x2000)
710                                 cflag = PCF8563_B_MONTH_C;
711                 } else if (bct.year < 0x2000)
712                                 cflag = PCF8563_B_MONTH_C;
713         }
714
715         tregs.sec   = bct.sec;
716         tregs.min   = bct.min;
717         tregs.hour  = bct.hour | (bct.ispm ? PCF8523_B_HOUR_PM : 0);
718         tregs.day   = bct.day;
719         tregs.month = bct.mon;
720         tregs.year  = (bct.year & 0xff) | cflag;
721         tregs.wday  = bct.dow;
722
723         /*
724          * Set the time, reset the timer count register, then start the clocks.
725          */
726         if ((err = write_timeregs(sc, &tregs)) != 0)
727                 goto errout;
728
729         if ((err = write_reg(sc, sc->tmcaddr, TMR_TICKS_SEC)) != 0)
730                 return (err);
731
732         cs1 &= ~PCF85xx_B_CS1_STOP;
733         err = write_reg(sc, PCF85xx_R_CS1, cs1);
734
735 errout:
736
737         iicbus_release_bus(sc->busdev, sc->dev);
738
739         if (err != 0)
740                 device_printf(dev, "cannot write RTC time\n");
741
742         return (err);
743 }
744
745 static int
746 nxprtc_get_chiptype(device_t dev)
747 {
748 #ifdef FDT
749
750         return (ofw_bus_search_compatible(dev, compat_data)->ocd_data);
751 #else
752         nxprtc_compat_data *cdata;
753         const char *htype;
754         int chiptype;
755
756         /*
757          * If given a chiptype hint string, loop through the ofw compat data
758          * comparing the hinted chip type to the compat strings.  The table end
759          * marker ocd_data is TYPE_NONE.
760          */
761         if (resource_string_value(device_get_name(dev), 
762             device_get_unit(dev), "compatible", &htype) == 0) {
763                 for (cdata = compat_data; cdata->ocd_str != NULL; ++cdata) {
764                         if (strcmp(htype, cdata->ocd_str) == 0)
765                                 break;
766                 }
767                 chiptype = cdata->ocd_data;
768         } else
769                 chiptype = TYPE_NONE;
770
771         /*
772          * On non-FDT systems the historical behavior of this driver was to
773          * assume a PCF8563; keep doing that for compatibility.
774          */
775         if (chiptype == TYPE_NONE)
776                 return (TYPE_PCF8563);
777         else
778                 return (chiptype);
779 #endif
780 }
781
782 static int
783 nxprtc_probe(device_t dev)
784 {
785         int chiptype, rv;
786
787 #ifdef FDT
788         if (!ofw_bus_status_okay(dev))
789                 return (ENXIO);
790         rv = BUS_PROBE_GENERIC;
791 #else
792         rv = BUS_PROBE_NOWILDCARD;
793 #endif
794         if ((chiptype = nxprtc_get_chiptype(dev)) == TYPE_NONE)
795                 return (ENXIO);
796
797         device_set_desc(dev, desc_strings[chiptype]);
798         return (rv);
799 }
800
801 static int
802 nxprtc_attach(device_t dev)
803 {
804         struct nxprtc_softc *sc;
805
806         sc = device_get_softc(dev);
807         sc->dev = dev;
808         sc->busdev = device_get_parent(dev);
809
810         /* We need to know what kind of chip we're driving. */
811         sc->chiptype = nxprtc_get_chiptype(dev);
812
813         /* The features and some register addresses vary by chip type. */
814         switch (sc->chiptype) {
815         case TYPE_PCA2129:
816         case TYPE_PCF2129:
817         case TYPE_PCF2127:
818         case TYPE_PCF8523:
819                 sc->secaddr = PCF8523_R_SECOND;
820                 sc->tmcaddr = PCF8523_R_TMR_A_COUNT;
821                 sc->use_timer = true;
822                 break;
823         case TYPE_PCA8565:
824         case TYPE_PCF8563:
825                 sc->secaddr = PCF8563_R_SECOND;
826                 sc->tmcaddr = PCF8563_R_TMR_COUNT;
827                 sc->use_timer = true;
828                 break;
829         default:
830                 device_printf(dev, "impossible: cannot determine chip type\n");
831                 return (ENXIO);
832         }
833
834         /*
835          * We have to wait until interrupts are enabled.  Sometimes I2C read
836          * and write only works when the interrupts are available.
837          */
838         sc->config_hook.ich_func = nxprtc_start;
839         sc->config_hook.ich_arg = dev;
840         if (config_intrhook_establish(&sc->config_hook) != 0)
841                 return (ENOMEM);
842
843         return (0);
844 }
845
846 static int
847 nxprtc_detach(device_t dev)
848 {
849
850         clock_unregister(dev);
851         return (0);
852 }
853
854 static device_method_t nxprtc_methods[] = {
855         DEVMETHOD(device_probe,         nxprtc_probe),
856         DEVMETHOD(device_attach,        nxprtc_attach),
857         DEVMETHOD(device_detach,        nxprtc_detach),
858
859         DEVMETHOD(clock_gettime,        nxprtc_gettime),
860         DEVMETHOD(clock_settime,        nxprtc_settime),
861
862         DEVMETHOD_END
863 };
864
865 static driver_t nxprtc_driver = {
866         "nxprtc",
867         nxprtc_methods,
868         sizeof(struct nxprtc_softc),
869 };
870
871 static devclass_t nxprtc_devclass;
872
873 DRIVER_MODULE(nxprtc, iicbus, nxprtc_driver, nxprtc_devclass, NULL, NULL);
874 MODULE_VERSION(nxprtc, 1);
875 MODULE_DEPEND(nxprtc, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
876 IICBUS_FDT_PNP_INFO(compat_data);