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