1/*-
2 * Copyright (c) 2014-2015 Luiz Otavio O Souza <loos@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/*
29 * Driver for Maxim DS3231[N] real-time clock/calendar.
30 */
31
32#include "opt_platform.h"
33
34#include <sys/param.h>
35#include <sys/systm.h>
36#include <sys/bus.h>
37#include <sys/clock.h>
38#include <sys/kernel.h>
39#include <sys/module.h>
40#include <sys/sysctl.h>
41
42#include <dev/iicbus/iicbus.h>
43#include <dev/iicbus/iiconf.h>
44#ifdef FDT
45#include <dev/ofw/openfirm.h>
46#include <dev/ofw/ofw_bus.h>
47#include <dev/ofw/ofw_bus_subr.h>
48#endif
49
50#include <dev/iicbus/rtc/ds3231reg.h>
51
52#include "clock_if.h"
53#include "iicbus_if.h"
54
55struct ds3231_softc {
56	device_t	sc_dev;
57	int		sc_last_c;
58	int		sc_year0;
59	struct intr_config_hook	enum_hook;
60	uint16_t	sc_addr;	/* DS3231 slave address. */
61	uint8_t		sc_ctrl;
62	uint8_t		sc_status;
63	bool		sc_use_ampm;
64};
65
66static void ds3231_start(void *);
67
68static int
69ds3231_read1(device_t dev, uint8_t reg, uint8_t *data)
70{
71
72	return (iicdev_readfrom(dev, reg, data, 1, IIC_INTRWAIT));
73}
74
75static int
76ds3231_write1(device_t dev, uint8_t reg, uint8_t data)
77{
78
79	return (iicdev_writeto(dev, reg, &data, 1, IIC_INTRWAIT));
80}
81
82static int
83ds3231_ctrl_read(struct ds3231_softc *sc)
84{
85	int error;
86
87	error = ds3231_read1(sc->sc_dev, DS3231_CONTROL, &sc->sc_ctrl);
88	if (error) {
89		device_printf(sc->sc_dev, "cannot read from RTC.\n");
90		return (error);
91	}
92	return (0);
93}
94
95static int
96ds3231_ctrl_write(struct ds3231_softc *sc)
97{
98	int error;
99	uint8_t data;
100
101	/* Always enable the oscillator.  Always disable both alarms. */
102	data = sc->sc_ctrl & ~DS3231_CTRL_MASK;
103	error = ds3231_write1(sc->sc_dev, DS3231_CONTROL, data);
104	if (error != 0)
105		device_printf(sc->sc_dev, "cannot write to RTC.\n");
106
107	return (error);
108}
109
110static int
111ds3231_status_read(struct ds3231_softc *sc)
112{
113	int error;
114
115	error = ds3231_read1(sc->sc_dev, DS3231_STATUS, &sc->sc_status);
116	if (error) {
117		device_printf(sc->sc_dev, "cannot read from RTC.\n");
118		return (error);
119	}
120
121	return (0);
122}
123
124static int
125ds3231_status_write(struct ds3231_softc *sc, int clear_a1, int clear_a2)
126{
127	int error;
128	uint8_t data;
129
130	data = sc->sc_status;
131	if (clear_a1 == 0)
132		data |= DS3231_STATUS_A1F;
133	if (clear_a2 == 0)
134		data |= DS3231_STATUS_A2F;
135	error = ds3231_write1(sc->sc_dev, DS3231_STATUS, data);
136	if (error != 0)
137		device_printf(sc->sc_dev, "cannot write to RTC.\n");
138
139	return (error);
140}
141
142static int
143ds3231_temp_read(struct ds3231_softc *sc, int *temp)
144{
145	int error, neg, t;
146	uint8_t buf8[2];
147	uint16_t buf;
148
149	error = iicdev_readfrom(sc->sc_dev, DS3231_TEMP, buf8, sizeof(buf8),
150	    IIC_INTRWAIT);
151	if (error != 0)
152		return (error);
153	buf = (buf8[0] << 8) | (buf8[1] & 0xff);
154	neg = 0;
155	if (buf & DS3231_NEG_BIT) {
156		buf = ~(buf & DS3231_TEMP_MASK) + 1;
157		neg = 1;
158	}
159	*temp = ((int16_t)buf >> 8) * 10;
160	t = 0;
161	if (buf & DS3231_0250C)
162		t += 250;
163	if (buf & DS3231_0500C)
164		t += 500;
165	t /= 100;
166	*temp += t;
167	if (neg)
168		*temp = -(*temp);
169	*temp += TZ_ZEROC;
170
171	return (0);
172}
173
174static int
175ds3231_temp_sysctl(SYSCTL_HANDLER_ARGS)
176{
177	int error, temp;
178	struct ds3231_softc *sc;
179
180	sc = (struct ds3231_softc *)arg1;
181	if (ds3231_temp_read(sc, &temp) != 0)
182		return (EIO);
183	error = sysctl_handle_int(oidp, &temp, 0, req);
184
185	return (error);
186}
187
188static int
189ds3231_conv_sysctl(SYSCTL_HANDLER_ARGS)
190{
191	int error, conv, newc;
192	struct ds3231_softc *sc;
193
194	sc = (struct ds3231_softc *)arg1;
195	error = ds3231_ctrl_read(sc);
196	if (error != 0)
197		return (error);
198	newc = conv = (sc->sc_ctrl & DS3231_CTRL_CONV) ? 1 : 0;
199	error = sysctl_handle_int(oidp, &newc, 0, req);
200	if (error != 0 || req->newptr == NULL)
201		return (error);
202	if (conv == 0 && newc != 0) {
203		error = ds3231_status_read(sc);
204		if (error != 0)
205			return (error);
206		if (sc->sc_status & DS3231_STATUS_BUSY)
207			return (0);
208		sc->sc_ctrl |= DS3231_CTRL_CONV;
209		error = ds3231_ctrl_write(sc);
210		if (error != 0)
211			return (error);
212	}
213
214	return (error);
215}
216
217static int
218ds3231_bbsqw_sysctl(SYSCTL_HANDLER_ARGS)
219{
220	int bbsqw, error, newb;
221	struct ds3231_softc *sc;
222
223	sc = (struct ds3231_softc *)arg1;
224	error = ds3231_ctrl_read(sc);
225	if (error != 0)
226		return (error);
227	bbsqw = newb = (sc->sc_ctrl & DS3231_CTRL_BBSQW) ? 1 : 0;
228	error = sysctl_handle_int(oidp, &newb, 0, req);
229	if (error != 0 || req->newptr == NULL)
230		return (error);
231	if (bbsqw != newb) {
232		sc->sc_ctrl &= ~DS3231_CTRL_BBSQW;
233		if (newb)
234			sc->sc_ctrl |= DS3231_CTRL_BBSQW;
235		error = ds3231_ctrl_write(sc);
236		if (error != 0)
237			return (error);
238	}
239
240	return (error);
241}
242
243static int
244ds3231_sqw_freq_sysctl(SYSCTL_HANDLER_ARGS)
245{
246	int ds3231_sqw_freq[] = { 1, 1024, 4096, 8192 };
247	int error, freq, i, newf, tmp;
248	struct ds3231_softc *sc;
249
250	sc = (struct ds3231_softc *)arg1;
251	error = ds3231_ctrl_read(sc);
252	if (error != 0)
253		return (error);
254	tmp = (sc->sc_ctrl & DS3231_CTRL_RS_MASK) >> DS3231_CTRL_RS_SHIFT;
255	if (tmp >= nitems(ds3231_sqw_freq))
256		tmp = nitems(ds3231_sqw_freq) - 1;
257	freq = ds3231_sqw_freq[tmp];
258	error = sysctl_handle_int(oidp, &freq, 0, req);
259	if (error != 0 || req->newptr == NULL)
260		return (error);
261	if (freq != ds3231_sqw_freq[tmp]) {
262		newf = 0;
263		for (i = 0; i < nitems(ds3231_sqw_freq); i++)
264			if (freq >= ds3231_sqw_freq[i])
265				newf = i;
266		sc->sc_ctrl &= ~DS3231_CTRL_RS_MASK;
267		sc->sc_ctrl |= newf << DS3231_CTRL_RS_SHIFT;
268		error = ds3231_ctrl_write(sc);
269		if (error != 0)
270			return (error);
271	}
272
273	return (error);
274}
275
276static int
277ds3231_str_sqw_mode(char *buf)
278{
279	int len, rtrn;
280
281	rtrn = -1;
282	len = strlen(buf);
283	if ((len > 2 && strncasecmp("interrupt", buf, len) == 0) ||
284	    (len > 2 && strncasecmp("int", buf, len) == 0)) {
285		rtrn = 1;
286	} else if ((len > 2 && strncasecmp("square-wave", buf, len) == 0) ||
287	    (len > 2 && strncasecmp("sqw", buf, len) == 0)) {
288		rtrn = 0;
289	}
290
291	return (rtrn);
292}
293
294static int
295ds3231_sqw_mode_sysctl(SYSCTL_HANDLER_ARGS)
296{
297	char buf[16];
298	int error, mode, newm;
299	struct ds3231_softc *sc;
300
301	sc = (struct ds3231_softc *)arg1;
302	error = ds3231_ctrl_read(sc);
303	if (error != 0)
304		return (error);
305	if (sc->sc_ctrl & DS3231_CTRL_INTCN) {
306		mode = 1;
307		strlcpy(buf, "interrupt", sizeof(buf));
308	} else {
309		mode = 0;
310		strlcpy(buf, "square-wave", sizeof(buf));
311	}
312	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
313	if (error != 0 || req->newptr == NULL)
314		return (error);
315	newm = ds3231_str_sqw_mode(buf);
316	if (newm != -1 && mode != newm) {
317		sc->sc_ctrl &= ~DS3231_CTRL_INTCN;
318		if (newm == 1)
319			sc->sc_ctrl |= DS3231_CTRL_INTCN;
320		error = ds3231_ctrl_write(sc);
321		if (error != 0)
322			return (error);
323	}
324
325	return (error);
326}
327
328static int
329ds3231_en32khz_sysctl(SYSCTL_HANDLER_ARGS)
330{
331	int error, en32khz, tmp;
332	struct ds3231_softc *sc;
333
334	sc = (struct ds3231_softc *)arg1;
335	error = ds3231_status_read(sc);
336	if (error != 0)
337		return (error);
338	tmp = en32khz = (sc->sc_status & DS3231_STATUS_EN32KHZ) ? 1 : 0;
339	error = sysctl_handle_int(oidp, &en32khz, 0, req);
340	if (error != 0 || req->newptr == NULL)
341		return (error);
342	if (en32khz != tmp) {
343		sc->sc_status &= ~DS3231_STATUS_EN32KHZ;
344		if (en32khz)
345			sc->sc_status |= DS3231_STATUS_EN32KHZ;
346		error = ds3231_status_write(sc, 0, 0);
347		if (error != 0)
348			return (error);
349	}
350
351	return (error);
352}
353
354static int
355ds3231_probe(device_t dev)
356{
357	int rc;
358
359#ifdef FDT
360	if (!ofw_bus_status_okay(dev))
361		return (ENXIO);
362	if (ofw_bus_is_compatible(dev, "maxim,ds3231"))
363		rc = BUS_PROBE_DEFAULT;
364	else
365#endif
366		rc = BUS_PROBE_NOWILDCARD;
367
368	device_set_desc(dev, "Maxim DS3231 RTC");
369
370	return (rc);
371}
372
373static int
374ds3231_attach(device_t dev)
375{
376	struct ds3231_softc *sc;
377
378	sc = device_get_softc(dev);
379	sc->sc_dev = dev;
380	sc->sc_addr = iicbus_get_addr(dev);
381	sc->sc_last_c = -1;
382	sc->sc_year0 = 0;
383	sc->enum_hook.ich_func = ds3231_start;
384	sc->enum_hook.ich_arg = dev;
385
386	/*
387	 * We have to wait until interrupts are enabled.  Usually I2C read
388	 * and write only works when the interrupts are available.
389	 */
390	if (config_intrhook_establish(&sc->enum_hook) != 0)
391		return (ENOMEM);
392
393	return (0);
394}
395
396static int
397ds3231_detach(device_t dev)
398{
399
400	clock_unregister(dev);
401	return (0);
402}
403
404static void
405ds3231_start(void *xdev)
406{
407	device_t dev;
408	struct ds3231_softc *sc;
409	struct sysctl_ctx_list *ctx;
410	struct sysctl_oid *tree_node;
411	struct sysctl_oid_list *tree;
412
413	dev = (device_t)xdev;
414	sc = device_get_softc(dev);
415	ctx = device_get_sysctl_ctx(dev);
416	tree_node = device_get_sysctl_tree(dev);
417	tree = SYSCTL_CHILDREN(tree_node);
418
419	config_intrhook_disestablish(&sc->enum_hook);
420	if (ds3231_ctrl_read(sc) != 0)
421		return;
422	if (ds3231_status_read(sc) != 0)
423		return;
424	/*
425	 * Warn if the clock stopped, but don't restart it until the first
426	 * clock_settime() call.
427	 */
428	if (sc->sc_status & DS3231_STATUS_OSF) {
429		device_printf(sc->sc_dev,
430		    "WARNING: RTC clock stopped, check the battery.\n");
431	}
432
433	/*
434	 * Ack any pending alarm interrupts and clear the EOSC bit to ensure the
435	 * clock runs even when on battery power.  Do not give up if these
436	 * writes fail, because a factory-fresh chip is in a special mode that
437	 * disables much of the chip to save battery power, and the only thing
438	 * that gets it out of that mode is writing to the time registers.  In
439	 * these pristine chips, the EOSC and alarm bits are zero already, so
440	 * the first valid write of time will get everything running properly.
441	 */
442	ds3231_status_write(sc, 1, 1);
443	ds3231_ctrl_write(sc);
444
445	/* Temperature. */
446	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "temperature",
447	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
448	    ds3231_temp_sysctl, "IK", "Current temperature");
449	/* Configuration parameters. */
450	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "temp_conv",
451	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_MPSAFE, sc, 0,
452	    ds3231_conv_sysctl, "IU",
453	    "DS3231 start a new temperature converstion");
454	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "bbsqw",
455	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_MPSAFE, sc, 0,
456	    ds3231_bbsqw_sysctl, "IU",
457	    "DS3231 battery-backed square-wave output enable");
458	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "sqw_freq",
459	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_MPSAFE, sc, 0,
460	    ds3231_sqw_freq_sysctl, "IU",
461	    "DS3231 square-wave output frequency");
462	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "sqw_mode",
463	    CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_MPSAFE, sc, 0,
464	    ds3231_sqw_mode_sysctl, "A", "DS3231 SQW output mode control");
465	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "32khz_enable",
466	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_MPSAFE, sc, 0,
467	    ds3231_en32khz_sysctl, "IU", "DS3231 enable the 32kHz output");
468
469	/*
470	 * Register as a clock with 1 second resolution.  Schedule the
471	 * clock_settime() method to be called just after top-of-second;
472	 * resetting the time resets top-of-second in the hardware.
473	 */
474	clock_register_flags(dev, 1000000, CLOCKF_SETTIME_NO_ADJ);
475	clock_schedule(dev, 1);
476}
477
478static int
479ds3231_gettime(device_t dev, struct timespec *ts)
480{
481	int c, error;
482	struct bcd_clocktime bct;
483	struct ds3231_softc *sc;
484	uint8_t data[7], hourmask;
485
486	sc = device_get_softc(dev);
487
488	/* If the clock halted, we don't have good data. */
489	if ((error = ds3231_status_read(sc)) != 0) {
490		device_printf(dev, "cannot read from RTC.\n");
491		return (error);
492	}
493	if (sc->sc_status & DS3231_STATUS_OSF)
494		return (EINVAL);
495
496	error = iicdev_readfrom(sc->sc_dev, DS3231_SECS, data, sizeof(data),
497	    IIC_INTRWAIT);
498	if (error != 0) {
499		device_printf(dev, "cannot read from RTC.\n");
500		return (error);
501	}
502
503	/* If chip is in AM/PM mode remember that. */
504	if (data[DS3231_HOUR] & DS3231_HOUR_USE_AMPM) {
505		sc->sc_use_ampm = true;
506		hourmask = DS3231_HOUR_MASK_12HR;
507	} else
508		hourmask = DS3231_HOUR_MASK_24HR;
509
510	bct.nsec = 0;
511	bct.sec  = data[DS3231_SECS]  & DS3231_SECS_MASK;
512	bct.min  = data[DS3231_MINS]  & DS3231_MINS_MASK;
513	bct.hour = data[DS3231_HOUR]  & hourmask;
514	bct.day  = data[DS3231_DATE]  & DS3231_DATE_MASK;
515	bct.mon  = data[DS3231_MONTH] & DS3231_MONTH_MASK;
516	bct.year = data[DS3231_YEAR]  & DS3231_YEAR_MASK;
517	bct.ispm = data[DS3231_HOUR]  & DS3231_HOUR_IS_PM;
518
519	/*
520	 * If the century flag has toggled since we last saw it, there has been
521	 * a century rollover.  If this is the first time we're seeing it,
522	 * remember the state so we can preserve its polarity on writes.
523	 */
524	c = (data[DS3231_MONTH] & DS3231_C_MASK) ? 1 : 0;
525	if (sc->sc_last_c == -1)
526		sc->sc_last_c = c;
527	else if (c != sc->sc_last_c) {
528		sc->sc_year0 += 0x100;
529		sc->sc_last_c = c;
530	}
531	bct.year |= sc->sc_year0;
532
533	clock_dbgprint_bcd(sc->sc_dev, CLOCK_DBG_READ, &bct);
534	return (clock_bcd_to_ts(&bct, ts, sc->sc_use_ampm));
535}
536
537static int
538ds3231_settime(device_t dev, struct timespec *ts)
539{
540	int error;
541	struct bcd_clocktime bct;
542	struct ds3231_softc *sc;
543	uint8_t data[7];
544	uint8_t pmflags;
545
546	sc = device_get_softc(dev);
547
548	/*
549	 * We request a timespec with no resolution-adjustment.  That also
550	 * disables utc adjustment, so apply that ourselves.
551	 */
552	ts->tv_sec -= utc_offset();
553	clock_ts_to_bcd(ts, &bct, sc->sc_use_ampm);
554	clock_dbgprint_bcd(sc->sc_dev, CLOCK_DBG_WRITE, &bct);
555
556	/* If the chip is in AM/PM mode, adjust hour and set flags as needed. */
557	if (sc->sc_use_ampm) {
558		pmflags = DS3231_HOUR_USE_AMPM;
559		if (bct.ispm)
560			pmflags |= DS3231_HOUR_IS_PM;
561	} else
562		pmflags = 0;
563
564	data[DS3231_SECS]    = bct.sec;
565	data[DS3231_MINS]    = bct.min;
566	data[DS3231_HOUR]    = bct.hour | pmflags;
567	data[DS3231_DATE]    = bct.day;
568	data[DS3231_WEEKDAY] = bct.dow + 1;
569	data[DS3231_MONTH]   = bct.mon;
570	data[DS3231_YEAR]    = bct.year & 0xff;
571	if (sc->sc_last_c)
572		data[DS3231_MONTH] |= DS3231_C_MASK;
573
574	/* Write the time back to RTC. */
575	error = iicdev_writeto(dev, DS3231_SECS, data, sizeof(data),
576	    IIC_INTRWAIT);
577	if (error != 0) {
578		device_printf(dev, "cannot write to RTC.\n");
579		return (error);
580	}
581
582	/*
583	 * Unlike most hardware, the osc-was-stopped bit does not clear itself
584	 * after setting the time, it has to be manually written to zero.
585	 */
586	if (sc->sc_status & DS3231_STATUS_OSF) {
587		if ((error = ds3231_status_read(sc)) != 0) {
588			device_printf(dev, "cannot read from RTC.\n");
589			return (error);
590		}
591		sc->sc_status &= ~DS3231_STATUS_OSF;
592		if ((error = ds3231_status_write(sc, 0, 0)) != 0) {
593			device_printf(dev, "cannot write to RTC.\n");
594			return (error);
595		}
596	}
597
598	return (error);
599}
600
601static device_method_t ds3231_methods[] = {
602	DEVMETHOD(device_probe,		ds3231_probe),
603	DEVMETHOD(device_attach,	ds3231_attach),
604	DEVMETHOD(device_detach,	ds3231_detach),
605
606	DEVMETHOD(clock_gettime,	ds3231_gettime),
607	DEVMETHOD(clock_settime,	ds3231_settime),
608
609	DEVMETHOD_END
610};
611
612static driver_t ds3231_driver = {
613	"ds3231",
614	ds3231_methods,
615	sizeof(struct ds3231_softc),
616};
617
618DRIVER_MODULE(ds3231, iicbus, ds3231_driver, NULL, NULL);
619MODULE_VERSION(ds3231, 1);
620MODULE_DEPEND(ds3231, iicbus, 1, 1, 1);
621