1// SPDX-License-Identifier: GPL-2.0
2/*
3 * RTC subsystem, interface functions
4 *
5 * Copyright (C) 2005 Tower Technologies
6 * Author: Alessandro Zummo <a.zummo@towertech.it>
7 *
8 * based on arch/arm/common/rtctime.c
9 */
10
11#include <linux/rtc.h>
12#include <linux/sched.h>
13#include <linux/module.h>
14#include <linux/log2.h>
15#include <linux/workqueue.h>
16
17#define CREATE_TRACE_POINTS
18#include <trace/events/rtc.h>
19
20static int rtc_timer_enqueue(struct rtc_device *rtc, struct rtc_timer *timer);
21static void rtc_timer_remove(struct rtc_device *rtc, struct rtc_timer *timer);
22
23static void rtc_add_offset(struct rtc_device *rtc, struct rtc_time *tm)
24{
25	time64_t secs;
26
27	if (!rtc->offset_secs)
28		return;
29
30	secs = rtc_tm_to_time64(tm);
31
32	/*
33	 * Since the reading time values from RTC device are always in the RTC
34	 * original valid range, but we need to skip the overlapped region
35	 * between expanded range and original range, which is no need to add
36	 * the offset.
37	 */
38	if ((rtc->start_secs > rtc->range_min && secs >= rtc->start_secs) ||
39	    (rtc->start_secs < rtc->range_min &&
40	     secs <= (rtc->start_secs + rtc->range_max - rtc->range_min)))
41		return;
42
43	rtc_time64_to_tm(secs + rtc->offset_secs, tm);
44}
45
46static void rtc_subtract_offset(struct rtc_device *rtc, struct rtc_time *tm)
47{
48	time64_t secs;
49
50	if (!rtc->offset_secs)
51		return;
52
53	secs = rtc_tm_to_time64(tm);
54
55	/*
56	 * If the setting time values are in the valid range of RTC hardware
57	 * device, then no need to subtract the offset when setting time to RTC
58	 * device. Otherwise we need to subtract the offset to make the time
59	 * values are valid for RTC hardware device.
60	 */
61	if (secs >= rtc->range_min && secs <= rtc->range_max)
62		return;
63
64	rtc_time64_to_tm(secs - rtc->offset_secs, tm);
65}
66
67static int rtc_valid_range(struct rtc_device *rtc, struct rtc_time *tm)
68{
69	if (rtc->range_min != rtc->range_max) {
70		time64_t time = rtc_tm_to_time64(tm);
71		time64_t range_min = rtc->set_start_time ? rtc->start_secs :
72			rtc->range_min;
73		timeu64_t range_max = rtc->set_start_time ?
74			(rtc->start_secs + rtc->range_max - rtc->range_min) :
75			rtc->range_max;
76
77		if (time < range_min || time > range_max)
78			return -ERANGE;
79	}
80
81	return 0;
82}
83
84static int __rtc_read_time(struct rtc_device *rtc, struct rtc_time *tm)
85{
86	int err;
87
88	if (!rtc->ops) {
89		err = -ENODEV;
90	} else if (!rtc->ops->read_time) {
91		err = -EINVAL;
92	} else {
93		memset(tm, 0, sizeof(struct rtc_time));
94		err = rtc->ops->read_time(rtc->dev.parent, tm);
95		if (err < 0) {
96			dev_dbg(&rtc->dev, "read_time: fail to read: %d\n",
97				err);
98			return err;
99		}
100
101		rtc_add_offset(rtc, tm);
102
103		err = rtc_valid_tm(tm);
104		if (err < 0)
105			dev_dbg(&rtc->dev, "read_time: rtc_time isn't valid\n");
106	}
107	return err;
108}
109
110int rtc_read_time(struct rtc_device *rtc, struct rtc_time *tm)
111{
112	int err;
113
114	err = mutex_lock_interruptible(&rtc->ops_lock);
115	if (err)
116		return err;
117
118	err = __rtc_read_time(rtc, tm);
119	mutex_unlock(&rtc->ops_lock);
120
121	trace_rtc_read_time(rtc_tm_to_time64(tm), err);
122	return err;
123}
124EXPORT_SYMBOL_GPL(rtc_read_time);
125
126int rtc_set_time(struct rtc_device *rtc, struct rtc_time *tm)
127{
128	int err, uie;
129
130	err = rtc_valid_tm(tm);
131	if (err != 0)
132		return err;
133
134	err = rtc_valid_range(rtc, tm);
135	if (err)
136		return err;
137
138	rtc_subtract_offset(rtc, tm);
139
140#ifdef CONFIG_RTC_INTF_DEV_UIE_EMUL
141	uie = rtc->uie_rtctimer.enabled || rtc->uie_irq_active;
142#else
143	uie = rtc->uie_rtctimer.enabled;
144#endif
145	if (uie) {
146		err = rtc_update_irq_enable(rtc, 0);
147		if (err)
148			return err;
149	}
150
151	err = mutex_lock_interruptible(&rtc->ops_lock);
152	if (err)
153		return err;
154
155	if (!rtc->ops)
156		err = -ENODEV;
157	else if (rtc->ops->set_time)
158		err = rtc->ops->set_time(rtc->dev.parent, tm);
159	else
160		err = -EINVAL;
161
162	pm_stay_awake(rtc->dev.parent);
163	mutex_unlock(&rtc->ops_lock);
164	/* A timer might have just expired */
165	schedule_work(&rtc->irqwork);
166
167	if (uie) {
168		err = rtc_update_irq_enable(rtc, 1);
169		if (err)
170			return err;
171	}
172
173	trace_rtc_set_time(rtc_tm_to_time64(tm), err);
174	return err;
175}
176EXPORT_SYMBOL_GPL(rtc_set_time);
177
178static int rtc_read_alarm_internal(struct rtc_device *rtc,
179				   struct rtc_wkalrm *alarm)
180{
181	int err;
182
183	err = mutex_lock_interruptible(&rtc->ops_lock);
184	if (err)
185		return err;
186
187	if (!rtc->ops) {
188		err = -ENODEV;
189	} else if (!rtc->ops->read_alarm) {
190		err = -EINVAL;
191	} else {
192		alarm->enabled = 0;
193		alarm->pending = 0;
194		alarm->time.tm_sec = -1;
195		alarm->time.tm_min = -1;
196		alarm->time.tm_hour = -1;
197		alarm->time.tm_mday = -1;
198		alarm->time.tm_mon = -1;
199		alarm->time.tm_year = -1;
200		alarm->time.tm_wday = -1;
201		alarm->time.tm_yday = -1;
202		alarm->time.tm_isdst = -1;
203		err = rtc->ops->read_alarm(rtc->dev.parent, alarm);
204	}
205
206	mutex_unlock(&rtc->ops_lock);
207
208	trace_rtc_read_alarm(rtc_tm_to_time64(&alarm->time), err);
209	return err;
210}
211
212int __rtc_read_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
213{
214	int err;
215	struct rtc_time before, now;
216	int first_time = 1;
217	time64_t t_now, t_alm;
218	enum { none, day, month, year } missing = none;
219	unsigned int days;
220
221	/* The lower level RTC driver may return -1 in some fields,
222	 * creating invalid alarm->time values, for reasons like:
223	 *
224	 *   - The hardware may not be capable of filling them in;
225	 *     many alarms match only on time-of-day fields, not
226	 *     day/month/year calendar data.
227	 *
228	 *   - Some hardware uses illegal values as "wildcard" match
229	 *     values, which non-Linux firmware (like a BIOS) may try
230	 *     to set up as e.g. "alarm 15 minutes after each hour".
231	 *     Linux uses only oneshot alarms.
232	 *
233	 * When we see that here, we deal with it by using values from
234	 * a current RTC timestamp for any missing (-1) values.  The
235	 * RTC driver prevents "periodic alarm" modes.
236	 *
237	 * But this can be racey, because some fields of the RTC timestamp
238	 * may have wrapped in the interval since we read the RTC alarm,
239	 * which would lead to us inserting inconsistent values in place
240	 * of the -1 fields.
241	 *
242	 * Reading the alarm and timestamp in the reverse sequence
243	 * would have the same race condition, and not solve the issue.
244	 *
245	 * So, we must first read the RTC timestamp,
246	 * then read the RTC alarm value,
247	 * and then read a second RTC timestamp.
248	 *
249	 * If any fields of the second timestamp have changed
250	 * when compared with the first timestamp, then we know
251	 * our timestamp may be inconsistent with that used by
252	 * the low-level rtc_read_alarm_internal() function.
253	 *
254	 * So, when the two timestamps disagree, we just loop and do
255	 * the process again to get a fully consistent set of values.
256	 *
257	 * This could all instead be done in the lower level driver,
258	 * but since more than one lower level RTC implementation needs it,
259	 * then it's probably best best to do it here instead of there..
260	 */
261
262	/* Get the "before" timestamp */
263	err = rtc_read_time(rtc, &before);
264	if (err < 0)
265		return err;
266	do {
267		if (!first_time)
268			memcpy(&before, &now, sizeof(struct rtc_time));
269		first_time = 0;
270
271		/* get the RTC alarm values, which may be incomplete */
272		err = rtc_read_alarm_internal(rtc, alarm);
273		if (err)
274			return err;
275
276		/* full-function RTCs won't have such missing fields */
277		if (rtc_valid_tm(&alarm->time) == 0) {
278			rtc_add_offset(rtc, &alarm->time);
279			return 0;
280		}
281
282		/* get the "after" timestamp, to detect wrapped fields */
283		err = rtc_read_time(rtc, &now);
284		if (err < 0)
285			return err;
286
287		/* note that tm_sec is a "don't care" value here: */
288	} while (before.tm_min  != now.tm_min ||
289		 before.tm_hour != now.tm_hour ||
290		 before.tm_mon  != now.tm_mon ||
291		 before.tm_year != now.tm_year);
292
293	/* Fill in the missing alarm fields using the timestamp; we
294	 * know there's at least one since alarm->time is invalid.
295	 */
296	if (alarm->time.tm_sec == -1)
297		alarm->time.tm_sec = now.tm_sec;
298	if (alarm->time.tm_min == -1)
299		alarm->time.tm_min = now.tm_min;
300	if (alarm->time.tm_hour == -1)
301		alarm->time.tm_hour = now.tm_hour;
302
303	/* For simplicity, only support date rollover for now */
304	if (alarm->time.tm_mday < 1 || alarm->time.tm_mday > 31) {
305		alarm->time.tm_mday = now.tm_mday;
306		missing = day;
307	}
308	if ((unsigned int)alarm->time.tm_mon >= 12) {
309		alarm->time.tm_mon = now.tm_mon;
310		if (missing == none)
311			missing = month;
312	}
313	if (alarm->time.tm_year == -1) {
314		alarm->time.tm_year = now.tm_year;
315		if (missing == none)
316			missing = year;
317	}
318
319	/* Can't proceed if alarm is still invalid after replacing
320	 * missing fields.
321	 */
322	err = rtc_valid_tm(&alarm->time);
323	if (err)
324		goto done;
325
326	/* with luck, no rollover is needed */
327	t_now = rtc_tm_to_time64(&now);
328	t_alm = rtc_tm_to_time64(&alarm->time);
329	if (t_now < t_alm)
330		goto done;
331
332	switch (missing) {
333	/* 24 hour rollover ... if it's now 10am Monday, an alarm that
334	 * that will trigger at 5am will do so at 5am Tuesday, which
335	 * could also be in the next month or year.  This is a common
336	 * case, especially for PCs.
337	 */
338	case day:
339		dev_dbg(&rtc->dev, "alarm rollover: %s\n", "day");
340		t_alm += 24 * 60 * 60;
341		rtc_time64_to_tm(t_alm, &alarm->time);
342		break;
343
344	/* Month rollover ... if it's the 31th, an alarm on the 3rd will
345	 * be next month.  An alarm matching on the 30th, 29th, or 28th
346	 * may end up in the month after that!  Many newer PCs support
347	 * this type of alarm.
348	 */
349	case month:
350		dev_dbg(&rtc->dev, "alarm rollover: %s\n", "month");
351		do {
352			if (alarm->time.tm_mon < 11) {
353				alarm->time.tm_mon++;
354			} else {
355				alarm->time.tm_mon = 0;
356				alarm->time.tm_year++;
357			}
358			days = rtc_month_days(alarm->time.tm_mon,
359					      alarm->time.tm_year);
360		} while (days < alarm->time.tm_mday);
361		break;
362
363	/* Year rollover ... easy except for leap years! */
364	case year:
365		dev_dbg(&rtc->dev, "alarm rollover: %s\n", "year");
366		do {
367			alarm->time.tm_year++;
368		} while (!is_leap_year(alarm->time.tm_year + 1900) &&
369			 rtc_valid_tm(&alarm->time) != 0);
370		break;
371
372	default:
373		dev_warn(&rtc->dev, "alarm rollover not handled\n");
374	}
375
376	err = rtc_valid_tm(&alarm->time);
377
378done:
379	if (err)
380		dev_warn(&rtc->dev, "invalid alarm value: %ptR\n",
381			 &alarm->time);
382
383	return err;
384}
385
386int rtc_read_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
387{
388	int err;
389
390	err = mutex_lock_interruptible(&rtc->ops_lock);
391	if (err)
392		return err;
393	if (!rtc->ops) {
394		err = -ENODEV;
395	} else if (!rtc->ops->read_alarm) {
396		err = -EINVAL;
397	} else {
398		memset(alarm, 0, sizeof(struct rtc_wkalrm));
399		alarm->enabled = rtc->aie_timer.enabled;
400		alarm->time = rtc_ktime_to_tm(rtc->aie_timer.node.expires);
401	}
402	mutex_unlock(&rtc->ops_lock);
403
404	trace_rtc_read_alarm(rtc_tm_to_time64(&alarm->time), err);
405	return err;
406}
407EXPORT_SYMBOL_GPL(rtc_read_alarm);
408
409static int __rtc_set_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
410{
411	struct rtc_time tm;
412	time64_t now, scheduled;
413	int err;
414
415	err = rtc_valid_tm(&alarm->time);
416	if (err)
417		return err;
418
419	scheduled = rtc_tm_to_time64(&alarm->time);
420
421	/* Make sure we're not setting alarms in the past */
422	err = __rtc_read_time(rtc, &tm);
423	if (err)
424		return err;
425	now = rtc_tm_to_time64(&tm);
426	if (scheduled <= now)
427		return -ETIME;
428	/*
429	 * XXX - We just checked to make sure the alarm time is not
430	 * in the past, but there is still a race window where if
431	 * the is alarm set for the next second and the second ticks
432	 * over right here, before we set the alarm.
433	 */
434
435	rtc_subtract_offset(rtc, &alarm->time);
436
437	if (!rtc->ops)
438		err = -ENODEV;
439	else if (!rtc->ops->set_alarm)
440		err = -EINVAL;
441	else
442		err = rtc->ops->set_alarm(rtc->dev.parent, alarm);
443
444	trace_rtc_set_alarm(rtc_tm_to_time64(&alarm->time), err);
445	return err;
446}
447
448int rtc_set_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
449{
450	int err;
451
452	if (!rtc->ops)
453		return -ENODEV;
454	else if (!rtc->ops->set_alarm)
455		return -EINVAL;
456
457	err = rtc_valid_tm(&alarm->time);
458	if (err != 0)
459		return err;
460
461	err = rtc_valid_range(rtc, &alarm->time);
462	if (err)
463		return err;
464
465	err = mutex_lock_interruptible(&rtc->ops_lock);
466	if (err)
467		return err;
468	if (rtc->aie_timer.enabled)
469		rtc_timer_remove(rtc, &rtc->aie_timer);
470
471	rtc->aie_timer.node.expires = rtc_tm_to_ktime(alarm->time);
472	rtc->aie_timer.period = 0;
473	if (alarm->enabled)
474		err = rtc_timer_enqueue(rtc, &rtc->aie_timer);
475
476	mutex_unlock(&rtc->ops_lock);
477
478	return err;
479}
480EXPORT_SYMBOL_GPL(rtc_set_alarm);
481
482/* Called once per device from rtc_device_register */
483int rtc_initialize_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
484{
485	int err;
486	struct rtc_time now;
487
488	err = rtc_valid_tm(&alarm->time);
489	if (err != 0)
490		return err;
491
492	err = rtc_read_time(rtc, &now);
493	if (err)
494		return err;
495
496	err = mutex_lock_interruptible(&rtc->ops_lock);
497	if (err)
498		return err;
499
500	rtc->aie_timer.node.expires = rtc_tm_to_ktime(alarm->time);
501	rtc->aie_timer.period = 0;
502
503	/* Alarm has to be enabled & in the future for us to enqueue it */
504	if (alarm->enabled && (rtc_tm_to_ktime(now) <
505			 rtc->aie_timer.node.expires)) {
506		rtc->aie_timer.enabled = 1;
507		timerqueue_add(&rtc->timerqueue, &rtc->aie_timer.node);
508		trace_rtc_timer_enqueue(&rtc->aie_timer);
509	}
510	mutex_unlock(&rtc->ops_lock);
511	return err;
512}
513EXPORT_SYMBOL_GPL(rtc_initialize_alarm);
514
515int rtc_alarm_irq_enable(struct rtc_device *rtc, unsigned int enabled)
516{
517	int err;
518
519	err = mutex_lock_interruptible(&rtc->ops_lock);
520	if (err)
521		return err;
522
523	if (rtc->aie_timer.enabled != enabled) {
524		if (enabled)
525			err = rtc_timer_enqueue(rtc, &rtc->aie_timer);
526		else
527			rtc_timer_remove(rtc, &rtc->aie_timer);
528	}
529
530	if (err)
531		/* nothing */;
532	else if (!rtc->ops)
533		err = -ENODEV;
534	else if (!rtc->ops->alarm_irq_enable)
535		err = -EINVAL;
536	else
537		err = rtc->ops->alarm_irq_enable(rtc->dev.parent, enabled);
538
539	mutex_unlock(&rtc->ops_lock);
540
541	trace_rtc_alarm_irq_enable(enabled, err);
542	return err;
543}
544EXPORT_SYMBOL_GPL(rtc_alarm_irq_enable);
545
546int rtc_update_irq_enable(struct rtc_device *rtc, unsigned int enabled)
547{
548	int rc = 0, err;
549
550	err = mutex_lock_interruptible(&rtc->ops_lock);
551	if (err)
552		return err;
553
554#ifdef CONFIG_RTC_INTF_DEV_UIE_EMUL
555	if (enabled == 0 && rtc->uie_irq_active) {
556		mutex_unlock(&rtc->ops_lock);
557		return rtc_dev_update_irq_enable_emul(rtc, 0);
558	}
559#endif
560	/* make sure we're changing state */
561	if (rtc->uie_rtctimer.enabled == enabled)
562		goto out;
563
564	if (rtc->uie_unsupported) {
565		err = -EINVAL;
566		goto out;
567	}
568
569	if (enabled) {
570		struct rtc_time tm;
571		ktime_t now, onesec;
572
573		rc = __rtc_read_time(rtc, &tm);
574		if (rc)
575			goto out;
576		onesec = ktime_set(1, 0);
577		now = rtc_tm_to_ktime(tm);
578		rtc->uie_rtctimer.node.expires = ktime_add(now, onesec);
579		rtc->uie_rtctimer.period = ktime_set(1, 0);
580		err = rtc_timer_enqueue(rtc, &rtc->uie_rtctimer);
581	} else {
582		rtc_timer_remove(rtc, &rtc->uie_rtctimer);
583	}
584
585out:
586	mutex_unlock(&rtc->ops_lock);
587
588	/*
589	 * __rtc_read_time() failed, this probably means that the RTC time has
590	 * never been set or less probably there is a transient error on the
591	 * bus. In any case, avoid enabling emulation has this will fail when
592	 * reading the time too.
593	 */
594	if (rc)
595		return rc;
596
597#ifdef CONFIG_RTC_INTF_DEV_UIE_EMUL
598	/*
599	 * Enable emulation if the driver returned -EINVAL to signal that it has
600	 * been configured without interrupts or they are not available at the
601	 * moment.
602	 */
603	if (err == -EINVAL)
604		err = rtc_dev_update_irq_enable_emul(rtc, enabled);
605#endif
606	return err;
607}
608EXPORT_SYMBOL_GPL(rtc_update_irq_enable);
609
610/**
611 * rtc_handle_legacy_irq - AIE, UIE and PIE event hook
612 * @rtc: pointer to the rtc device
613 * @num: number of occurence of the event
614 * @mode: type of the event, RTC_AF, RTC_UF of RTC_PF
615 *
616 * This function is called when an AIE, UIE or PIE mode interrupt
617 * has occurred (or been emulated).
618 *
619 */
620void rtc_handle_legacy_irq(struct rtc_device *rtc, int num, int mode)
621{
622	unsigned long flags;
623
624	/* mark one irq of the appropriate mode */
625	spin_lock_irqsave(&rtc->irq_lock, flags);
626	rtc->irq_data = (rtc->irq_data + (num << 8)) | (RTC_IRQF | mode);
627	spin_unlock_irqrestore(&rtc->irq_lock, flags);
628
629	wake_up_interruptible(&rtc->irq_queue);
630	kill_fasync(&rtc->async_queue, SIGIO, POLL_IN);
631}
632
633/**
634 * rtc_aie_update_irq - AIE mode rtctimer hook
635 * @rtc: pointer to the rtc_device
636 *
637 * This functions is called when the aie_timer expires.
638 */
639void rtc_aie_update_irq(struct rtc_device *rtc)
640{
641	rtc_handle_legacy_irq(rtc, 1, RTC_AF);
642}
643
644/**
645 * rtc_uie_update_irq - UIE mode rtctimer hook
646 * @rtc: pointer to the rtc_device
647 *
648 * This functions is called when the uie_timer expires.
649 */
650void rtc_uie_update_irq(struct rtc_device *rtc)
651{
652	rtc_handle_legacy_irq(rtc, 1,  RTC_UF);
653}
654
655/**
656 * rtc_pie_update_irq - PIE mode hrtimer hook
657 * @timer: pointer to the pie mode hrtimer
658 *
659 * This function is used to emulate PIE mode interrupts
660 * using an hrtimer. This function is called when the periodic
661 * hrtimer expires.
662 */
663enum hrtimer_restart rtc_pie_update_irq(struct hrtimer *timer)
664{
665	struct rtc_device *rtc;
666	ktime_t period;
667	u64 count;
668
669	rtc = container_of(timer, struct rtc_device, pie_timer);
670
671	period = NSEC_PER_SEC / rtc->irq_freq;
672	count = hrtimer_forward_now(timer, period);
673
674	rtc_handle_legacy_irq(rtc, count, RTC_PF);
675
676	return HRTIMER_RESTART;
677}
678
679/**
680 * rtc_update_irq - Triggered when a RTC interrupt occurs.
681 * @rtc: the rtc device
682 * @num: how many irqs are being reported (usually one)
683 * @events: mask of RTC_IRQF with one or more of RTC_PF, RTC_AF, RTC_UF
684 * Context: any
685 */
686void rtc_update_irq(struct rtc_device *rtc,
687		    unsigned long num, unsigned long events)
688{
689	if (IS_ERR_OR_NULL(rtc))
690		return;
691
692	pm_stay_awake(rtc->dev.parent);
693	schedule_work(&rtc->irqwork);
694}
695EXPORT_SYMBOL_GPL(rtc_update_irq);
696
697struct rtc_device *rtc_class_open(const char *name)
698{
699	struct device *dev;
700	struct rtc_device *rtc = NULL;
701
702	dev = class_find_device_by_name(rtc_class, name);
703	if (dev)
704		rtc = to_rtc_device(dev);
705
706	if (rtc) {
707		if (!try_module_get(rtc->owner)) {
708			put_device(dev);
709			rtc = NULL;
710		}
711	}
712
713	return rtc;
714}
715EXPORT_SYMBOL_GPL(rtc_class_open);
716
717void rtc_class_close(struct rtc_device *rtc)
718{
719	module_put(rtc->owner);
720	put_device(&rtc->dev);
721}
722EXPORT_SYMBOL_GPL(rtc_class_close);
723
724static int rtc_update_hrtimer(struct rtc_device *rtc, int enabled)
725{
726	/*
727	 * We always cancel the timer here first, because otherwise
728	 * we could run into BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
729	 * when we manage to start the timer before the callback
730	 * returns HRTIMER_RESTART.
731	 *
732	 * We cannot use hrtimer_cancel() here as a running callback
733	 * could be blocked on rtc->irq_task_lock and hrtimer_cancel()
734	 * would spin forever.
735	 */
736	if (hrtimer_try_to_cancel(&rtc->pie_timer) < 0)
737		return -1;
738
739	if (enabled) {
740		ktime_t period = NSEC_PER_SEC / rtc->irq_freq;
741
742		hrtimer_start(&rtc->pie_timer, period, HRTIMER_MODE_REL);
743	}
744	return 0;
745}
746
747/**
748 * rtc_irq_set_state - enable/disable 2^N Hz periodic IRQs
749 * @rtc: the rtc device
750 * @enabled: true to enable periodic IRQs
751 * Context: any
752 *
753 * Note that rtc_irq_set_freq() should previously have been used to
754 * specify the desired frequency of periodic IRQ.
755 */
756int rtc_irq_set_state(struct rtc_device *rtc, int enabled)
757{
758	int err = 0;
759
760	while (rtc_update_hrtimer(rtc, enabled) < 0)
761		cpu_relax();
762
763	rtc->pie_enabled = enabled;
764
765	trace_rtc_irq_set_state(enabled, err);
766	return err;
767}
768
769/**
770 * rtc_irq_set_freq - set 2^N Hz periodic IRQ frequency for IRQ
771 * @rtc: the rtc device
772 * @freq: positive frequency
773 * Context: any
774 *
775 * Note that rtc_irq_set_state() is used to enable or disable the
776 * periodic IRQs.
777 */
778int rtc_irq_set_freq(struct rtc_device *rtc, int freq)
779{
780	int err = 0;
781
782	if (freq <= 0 || freq > RTC_MAX_FREQ)
783		return -EINVAL;
784
785	rtc->irq_freq = freq;
786	while (rtc->pie_enabled && rtc_update_hrtimer(rtc, 1) < 0)
787		cpu_relax();
788
789	trace_rtc_irq_set_freq(freq, err);
790	return err;
791}
792
793/**
794 * rtc_timer_enqueue - Adds a rtc_timer to the rtc_device timerqueue
795 * @rtc: rtc device
796 * @timer: timer being added.
797 *
798 * Enqueues a timer onto the rtc devices timerqueue and sets
799 * the next alarm event appropriately.
800 *
801 * Sets the enabled bit on the added timer.
802 *
803 * Must hold ops_lock for proper serialization of timerqueue
804 */
805static int rtc_timer_enqueue(struct rtc_device *rtc, struct rtc_timer *timer)
806{
807	struct timerqueue_node *next = timerqueue_getnext(&rtc->timerqueue);
808	struct rtc_time tm;
809	ktime_t now;
810	int err;
811
812	err = __rtc_read_time(rtc, &tm);
813	if (err)
814		return err;
815
816	timer->enabled = 1;
817	now = rtc_tm_to_ktime(tm);
818
819	/* Skip over expired timers */
820	while (next) {
821		if (next->expires >= now)
822			break;
823		next = timerqueue_iterate_next(next);
824	}
825
826	timerqueue_add(&rtc->timerqueue, &timer->node);
827	trace_rtc_timer_enqueue(timer);
828	if (!next || ktime_before(timer->node.expires, next->expires)) {
829		struct rtc_wkalrm alarm;
830
831		alarm.time = rtc_ktime_to_tm(timer->node.expires);
832		alarm.enabled = 1;
833		err = __rtc_set_alarm(rtc, &alarm);
834		if (err == -ETIME) {
835			pm_stay_awake(rtc->dev.parent);
836			schedule_work(&rtc->irqwork);
837		} else if (err) {
838			timerqueue_del(&rtc->timerqueue, &timer->node);
839			trace_rtc_timer_dequeue(timer);
840			timer->enabled = 0;
841			return err;
842		}
843	}
844	return 0;
845}
846
847static void rtc_alarm_disable(struct rtc_device *rtc)
848{
849	if (!rtc->ops || !rtc->ops->alarm_irq_enable)
850		return;
851
852	rtc->ops->alarm_irq_enable(rtc->dev.parent, false);
853	trace_rtc_alarm_irq_enable(0, 0);
854}
855
856/**
857 * rtc_timer_remove - Removes a rtc_timer from the rtc_device timerqueue
858 * @rtc: rtc device
859 * @timer: timer being removed.
860 *
861 * Removes a timer onto the rtc devices timerqueue and sets
862 * the next alarm event appropriately.
863 *
864 * Clears the enabled bit on the removed timer.
865 *
866 * Must hold ops_lock for proper serialization of timerqueue
867 */
868static void rtc_timer_remove(struct rtc_device *rtc, struct rtc_timer *timer)
869{
870	struct timerqueue_node *next = timerqueue_getnext(&rtc->timerqueue);
871
872	timerqueue_del(&rtc->timerqueue, &timer->node);
873	trace_rtc_timer_dequeue(timer);
874	timer->enabled = 0;
875	if (next == &timer->node) {
876		struct rtc_wkalrm alarm;
877		int err;
878
879		next = timerqueue_getnext(&rtc->timerqueue);
880		if (!next) {
881			rtc_alarm_disable(rtc);
882			return;
883		}
884		alarm.time = rtc_ktime_to_tm(next->expires);
885		alarm.enabled = 1;
886		err = __rtc_set_alarm(rtc, &alarm);
887		if (err == -ETIME) {
888			pm_stay_awake(rtc->dev.parent);
889			schedule_work(&rtc->irqwork);
890		}
891	}
892}
893
894/**
895 * rtc_timer_do_work - Expires rtc timers
896 * @work: work item
897 *
898 * Expires rtc timers. Reprograms next alarm event if needed.
899 * Called via worktask.
900 *
901 * Serializes access to timerqueue via ops_lock mutex
902 */
903void rtc_timer_do_work(struct work_struct *work)
904{
905	struct rtc_timer *timer;
906	struct timerqueue_node *next;
907	ktime_t now;
908	struct rtc_time tm;
909
910	struct rtc_device *rtc =
911		container_of(work, struct rtc_device, irqwork);
912
913	mutex_lock(&rtc->ops_lock);
914again:
915	__rtc_read_time(rtc, &tm);
916	now = rtc_tm_to_ktime(tm);
917	while ((next = timerqueue_getnext(&rtc->timerqueue))) {
918		if (next->expires > now)
919			break;
920
921		/* expire timer */
922		timer = container_of(next, struct rtc_timer, node);
923		timerqueue_del(&rtc->timerqueue, &timer->node);
924		trace_rtc_timer_dequeue(timer);
925		timer->enabled = 0;
926		if (timer->func)
927			timer->func(timer->rtc);
928
929		trace_rtc_timer_fired(timer);
930		/* Re-add/fwd periodic timers */
931		if (ktime_to_ns(timer->period)) {
932			timer->node.expires = ktime_add(timer->node.expires,
933							timer->period);
934			timer->enabled = 1;
935			timerqueue_add(&rtc->timerqueue, &timer->node);
936			trace_rtc_timer_enqueue(timer);
937		}
938	}
939
940	/* Set next alarm */
941	if (next) {
942		struct rtc_wkalrm alarm;
943		int err;
944		int retry = 3;
945
946		alarm.time = rtc_ktime_to_tm(next->expires);
947		alarm.enabled = 1;
948reprogram:
949		err = __rtc_set_alarm(rtc, &alarm);
950		if (err == -ETIME) {
951			goto again;
952		} else if (err) {
953			if (retry-- > 0)
954				goto reprogram;
955
956			timer = container_of(next, struct rtc_timer, node);
957			timerqueue_del(&rtc->timerqueue, &timer->node);
958			trace_rtc_timer_dequeue(timer);
959			timer->enabled = 0;
960			dev_err(&rtc->dev, "__rtc_set_alarm: err=%d\n", err);
961			goto again;
962		}
963	} else {
964		rtc_alarm_disable(rtc);
965	}
966
967	pm_relax(rtc->dev.parent);
968	mutex_unlock(&rtc->ops_lock);
969}
970
971/* rtc_timer_init - Initializes an rtc_timer
972 * @timer: timer to be intiialized
973 * @f: function pointer to be called when timer fires
974 * @rtc: pointer to the rtc_device
975 *
976 * Kernel interface to initializing an rtc_timer.
977 */
978void rtc_timer_init(struct rtc_timer *timer, void (*f)(struct rtc_device *r),
979		    struct rtc_device *rtc)
980{
981	timerqueue_init(&timer->node);
982	timer->enabled = 0;
983	timer->func = f;
984	timer->rtc = rtc;
985}
986
987/* rtc_timer_start - Sets an rtc_timer to fire in the future
988 * @ rtc: rtc device to be used
989 * @ timer: timer being set
990 * @ expires: time at which to expire the timer
991 * @ period: period that the timer will recur
992 *
993 * Kernel interface to set an rtc_timer
994 */
995int rtc_timer_start(struct rtc_device *rtc, struct rtc_timer *timer,
996		    ktime_t expires, ktime_t period)
997{
998	int ret = 0;
999
1000	mutex_lock(&rtc->ops_lock);
1001	if (timer->enabled)
1002		rtc_timer_remove(rtc, timer);
1003
1004	timer->node.expires = expires;
1005	timer->period = period;
1006
1007	ret = rtc_timer_enqueue(rtc, timer);
1008
1009	mutex_unlock(&rtc->ops_lock);
1010	return ret;
1011}
1012
1013/* rtc_timer_cancel - Stops an rtc_timer
1014 * @ rtc: rtc device to be used
1015 * @ timer: timer being set
1016 *
1017 * Kernel interface to cancel an rtc_timer
1018 */
1019void rtc_timer_cancel(struct rtc_device *rtc, struct rtc_timer *timer)
1020{
1021	mutex_lock(&rtc->ops_lock);
1022	if (timer->enabled)
1023		rtc_timer_remove(rtc, timer);
1024	mutex_unlock(&rtc->ops_lock);
1025}
1026
1027/**
1028 * rtc_read_offset - Read the amount of rtc offset in parts per billion
1029 * @rtc: rtc device to be used
1030 * @offset: the offset in parts per billion
1031 *
1032 * see below for details.
1033 *
1034 * Kernel interface to read rtc clock offset
1035 * Returns 0 on success, or a negative number on error.
1036 * If read_offset() is not implemented for the rtc, return -EINVAL
1037 */
1038int rtc_read_offset(struct rtc_device *rtc, long *offset)
1039{
1040	int ret;
1041
1042	if (!rtc->ops)
1043		return -ENODEV;
1044
1045	if (!rtc->ops->read_offset)
1046		return -EINVAL;
1047
1048	mutex_lock(&rtc->ops_lock);
1049	ret = rtc->ops->read_offset(rtc->dev.parent, offset);
1050	mutex_unlock(&rtc->ops_lock);
1051
1052	trace_rtc_read_offset(*offset, ret);
1053	return ret;
1054}
1055
1056/**
1057 * rtc_set_offset - Adjusts the duration of the average second
1058 * @rtc: rtc device to be used
1059 * @offset: the offset in parts per billion
1060 *
1061 * Some rtc's allow an adjustment to the average duration of a second
1062 * to compensate for differences in the actual clock rate due to temperature,
1063 * the crystal, capacitor, etc.
1064 *
1065 * The adjustment applied is as follows:
1066 *   t = t0 * (1 + offset * 1e-9)
1067 * where t0 is the measured length of 1 RTC second with offset = 0
1068 *
1069 * Kernel interface to adjust an rtc clock offset.
1070 * Return 0 on success, or a negative number on error.
1071 * If the rtc offset is not setable (or not implemented), return -EINVAL
1072 */
1073int rtc_set_offset(struct rtc_device *rtc, long offset)
1074{
1075	int ret;
1076
1077	if (!rtc->ops)
1078		return -ENODEV;
1079
1080	if (!rtc->ops->set_offset)
1081		return -EINVAL;
1082
1083	mutex_lock(&rtc->ops_lock);
1084	ret = rtc->ops->set_offset(rtc->dev.parent, offset);
1085	mutex_unlock(&rtc->ops_lock);
1086
1087	trace_rtc_set_offset(offset, ret);
1088	return ret;
1089}
1090