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