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