xref: /linux/drivers/rtc/interface.c (revision 4202e4254403156a00711990ec99982f43bd99f5)
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 		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 
84 static 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 
110 int 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 }
124 EXPORT_SYMBOL_GPL(rtc_read_time);
125 
126 int 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 }
176 EXPORT_SYMBOL_GPL(rtc_set_time);
177 
178 static 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 (!test_bit(RTC_FEATURE_ALARM, rtc->features) || !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(err?0:rtc_tm_to_time64(&alarm->time), err);
209 	return err;
210 }
211 
212 int __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 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 		err = rtc_valid_tm(&alarm->time);
278 		if (!err)
279 			goto done;
280 
281 		/* get the "after" timestamp, to detect wrapped fields */
282 		err = rtc_read_time(rtc, &now);
283 		if (err < 0)
284 			return err;
285 
286 		/* note that tm_sec is a "don't care" value here: */
287 	} while (before.tm_min  != now.tm_min ||
288 		 before.tm_hour != now.tm_hour ||
289 		 before.tm_mon  != now.tm_mon ||
290 		 before.tm_year != now.tm_year);
291 
292 	/* Fill in the missing alarm fields using the timestamp; we
293 	 * know there's at least one since alarm->time is invalid.
294 	 */
295 	if (alarm->time.tm_sec == -1)
296 		alarm->time.tm_sec = now.tm_sec;
297 	if (alarm->time.tm_min == -1)
298 		alarm->time.tm_min = now.tm_min;
299 	if (alarm->time.tm_hour == -1)
300 		alarm->time.tm_hour = now.tm_hour;
301 
302 	/* For simplicity, only support date rollover for now */
303 	if (alarm->time.tm_mday < 1 || alarm->time.tm_mday > 31) {
304 		alarm->time.tm_mday = now.tm_mday;
305 		missing = day;
306 	}
307 	if ((unsigned int)alarm->time.tm_mon >= 12) {
308 		alarm->time.tm_mon = now.tm_mon;
309 		if (missing == none)
310 			missing = month;
311 	}
312 	if (alarm->time.tm_year == -1) {
313 		alarm->time.tm_year = now.tm_year;
314 		if (missing == none)
315 			missing = year;
316 	}
317 
318 	/* Can't proceed if alarm is still invalid after replacing
319 	 * missing fields.
320 	 */
321 	err = rtc_valid_tm(&alarm->time);
322 	if (err)
323 		goto done;
324 
325 	/* with luck, no rollover is needed */
326 	t_now = rtc_tm_to_time64(&now);
327 	t_alm = rtc_tm_to_time64(&alarm->time);
328 	if (t_now < t_alm)
329 		goto done;
330 
331 	switch (missing) {
332 	/* 24 hour rollover ... if it's now 10am Monday, an alarm that
333 	 * that will trigger at 5am will do so at 5am Tuesday, which
334 	 * could also be in the next month or year.  This is a common
335 	 * case, especially for PCs.
336 	 */
337 	case day:
338 		dev_dbg(&rtc->dev, "alarm rollover: %s\n", "day");
339 		t_alm += 24 * 60 * 60;
340 		rtc_time64_to_tm(t_alm, &alarm->time);
341 		break;
342 
343 	/* Month rollover ... if it's the 31th, an alarm on the 3rd will
344 	 * be next month.  An alarm matching on the 30th, 29th, or 28th
345 	 * may end up in the month after that!  Many newer PCs support
346 	 * this type of alarm.
347 	 */
348 	case month:
349 		dev_dbg(&rtc->dev, "alarm rollover: %s\n", "month");
350 		do {
351 			if (alarm->time.tm_mon < 11) {
352 				alarm->time.tm_mon++;
353 			} else {
354 				alarm->time.tm_mon = 0;
355 				alarm->time.tm_year++;
356 			}
357 			days = rtc_month_days(alarm->time.tm_mon,
358 					      alarm->time.tm_year);
359 		} while (days < alarm->time.tm_mday);
360 		break;
361 
362 	/* Year rollover ... easy except for leap years! */
363 	case year:
364 		dev_dbg(&rtc->dev, "alarm rollover: %s\n", "year");
365 		do {
366 			alarm->time.tm_year++;
367 		} while (!is_leap_year(alarm->time.tm_year + 1900) &&
368 			 rtc_valid_tm(&alarm->time) != 0);
369 		break;
370 
371 	default:
372 		dev_warn(&rtc->dev, "alarm rollover not handled\n");
373 	}
374 
375 	err = rtc_valid_tm(&alarm->time);
376 
377 done:
378 	if (err && alarm->enabled)
379 		dev_warn(&rtc->dev, "invalid alarm value: %ptR\n",
380 			 &alarm->time);
381 	else
382 		rtc_add_offset(rtc, &alarm->time);
383 
384 	return err;
385 }
386 
387 /**
388  * rtc_read_next_alarm - read the next expiring alarm
389  * @rtc: RTC device
390  * @alarm: storage for the alarm information
391  *
392  * Read the next expiring alarm from the RTC timerqueue. This returns
393  * the alarm that will actually fire next, which may be different from
394  * rtc_read_alarm() if multiple timers are queued (e.g., alarmtimer
395  * and wakealarm sysfs both active).
396  *
397  * Returns: 0 on success, -ENOENT if no alarm is pending, or other error.
398  */
399 int rtc_read_next_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
400 {
401 	struct timerqueue_node *next;
402 	int err;
403 
404 	if (!rtc || !alarm)
405 		return -EINVAL;
406 
407 	err = mutex_lock_interruptible(&rtc->ops_lock);
408 	if (err)
409 		return err;
410 
411 	next = timerqueue_getnext(&rtc->timerqueue);
412 	if (!next) {
413 		err = -ENOENT;
414 		goto unlock;
415 	}
416 
417 	memset(alarm, 0, sizeof(struct rtc_wkalrm));
418 	alarm->time = rtc_ktime_to_tm(next->expires);
419 	alarm->enabled = 1;
420 
421 unlock:
422 	mutex_unlock(&rtc->ops_lock);
423 	return err;
424 }
425 EXPORT_SYMBOL_GPL(rtc_read_next_alarm);
426 
427 int rtc_read_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
428 {
429 	int err;
430 
431 	err = mutex_lock_interruptible(&rtc->ops_lock);
432 	if (err)
433 		return err;
434 	if (!rtc->ops) {
435 		err = -ENODEV;
436 	} else if (!test_bit(RTC_FEATURE_ALARM, rtc->features)) {
437 		err = -EINVAL;
438 	} else {
439 		memset(alarm, 0, sizeof(struct rtc_wkalrm));
440 		alarm->enabled = rtc->aie_timer.enabled;
441 		alarm->time = rtc_ktime_to_tm(rtc->aie_timer.node.expires);
442 	}
443 	mutex_unlock(&rtc->ops_lock);
444 
445 	trace_rtc_read_alarm(rtc_tm_to_time64(&alarm->time), err);
446 	return err;
447 }
448 EXPORT_SYMBOL_GPL(rtc_read_alarm);
449 
450 static int __rtc_set_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
451 {
452 	struct rtc_time tm;
453 	time64_t now, scheduled;
454 	int err;
455 
456 	err = rtc_valid_tm(&alarm->time);
457 	if (err)
458 		return err;
459 
460 	scheduled = rtc_tm_to_time64(&alarm->time);
461 
462 	/* Make sure we're not setting alarms in the past */
463 	err = __rtc_read_time(rtc, &tm);
464 	if (err)
465 		return err;
466 	now = rtc_tm_to_time64(&tm);
467 
468 	if (scheduled <= now)
469 		return -ETIME;
470 	/*
471 	 * XXX - We just checked to make sure the alarm time is not
472 	 * in the past, but there is still a race window where if
473 	 * the is alarm set for the next second and the second ticks
474 	 * over right here, before we set the alarm.
475 	 */
476 
477 	rtc_subtract_offset(rtc, &alarm->time);
478 
479 	if (!rtc->ops)
480 		err = -ENODEV;
481 	else if (!test_bit(RTC_FEATURE_ALARM, rtc->features))
482 		err = -EINVAL;
483 	else
484 		err = rtc->ops->set_alarm(rtc->dev.parent, alarm);
485 
486 	/*
487 	 * Check for potential race described above. If the waiting for next
488 	 * second, and the second just ticked since the check above, either
489 	 *
490 	 * 1) It ticked after the alarm was set, and an alarm irq should be
491 	 *    generated.
492 	 *
493 	 * 2) It ticked before the alarm was set, and alarm irq most likely will
494 	 * not be generated.
495 	 *
496 	 * While we cannot easily check for which of these two scenarios we
497 	 * are in, we can return -ETIME to signal that the timer has already
498 	 * expired, which is true in both cases.
499 	 */
500 	if (!err && (scheduled - now) <= 1) {
501 		err = __rtc_read_time(rtc, &tm);
502 		if (err)
503 			return err;
504 		now = rtc_tm_to_time64(&tm);
505 		if (scheduled <= now)
506 			return -ETIME;
507 	}
508 
509 	trace_rtc_set_alarm(rtc_tm_to_time64(&alarm->time), err);
510 	return err;
511 }
512 
513 int rtc_set_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
514 {
515 	ktime_t alarm_time;
516 	int err;
517 
518 	if (!rtc->ops)
519 		return -ENODEV;
520 	else if (!test_bit(RTC_FEATURE_ALARM, rtc->features))
521 		return -EINVAL;
522 
523 	err = rtc_valid_tm(&alarm->time);
524 	if (err != 0)
525 		return err;
526 
527 	err = rtc_valid_range(rtc, &alarm->time);
528 	if (err)
529 		return err;
530 
531 	err = mutex_lock_interruptible(&rtc->ops_lock);
532 	if (err)
533 		return err;
534 	if (rtc->aie_timer.enabled)
535 		rtc_timer_remove(rtc, &rtc->aie_timer);
536 
537 	alarm_time = rtc_tm_to_ktime(alarm->time);
538 	/*
539 	 * Round down so we never miss a deadline, checking for past deadline is
540 	 * done in __rtc_set_alarm
541 	 */
542 	if (test_bit(RTC_FEATURE_ALARM_RES_MINUTE, rtc->features))
543 		alarm_time = ktime_sub_ns(alarm_time, (u64)alarm->time.tm_sec * NSEC_PER_SEC);
544 
545 	rtc->aie_timer.node.expires = alarm_time;
546 	rtc->aie_timer.period = 0;
547 	if (alarm->enabled)
548 		err = rtc_timer_enqueue(rtc, &rtc->aie_timer);
549 
550 	mutex_unlock(&rtc->ops_lock);
551 
552 	return err;
553 }
554 EXPORT_SYMBOL_GPL(rtc_set_alarm);
555 
556 /* Called once per device from rtc_device_register */
557 int rtc_initialize_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm)
558 {
559 	int err;
560 	struct rtc_time now;
561 
562 	err = rtc_valid_tm(&alarm->time);
563 	if (err != 0)
564 		return err;
565 
566 	err = rtc_read_time(rtc, &now);
567 	if (err)
568 		return err;
569 
570 	err = mutex_lock_interruptible(&rtc->ops_lock);
571 	if (err)
572 		return err;
573 
574 	rtc->aie_timer.node.expires = rtc_tm_to_ktime(alarm->time);
575 	rtc->aie_timer.period = 0;
576 
577 	/* Alarm has to be enabled & in the future for us to enqueue it */
578 	if (alarm->enabled && (rtc_tm_to_ktime(now) <
579 			 rtc->aie_timer.node.expires)) {
580 		rtc->aie_timer.enabled = 1;
581 		timerqueue_add(&rtc->timerqueue, &rtc->aie_timer.node);
582 		trace_rtc_timer_enqueue(&rtc->aie_timer);
583 	}
584 	mutex_unlock(&rtc->ops_lock);
585 	return err;
586 }
587 EXPORT_SYMBOL_GPL(rtc_initialize_alarm);
588 
589 int rtc_alarm_irq_enable(struct rtc_device *rtc, unsigned int enabled)
590 {
591 	int err;
592 
593 	err = mutex_lock_interruptible(&rtc->ops_lock);
594 	if (err)
595 		return err;
596 
597 	if (rtc->aie_timer.enabled != enabled) {
598 		if (enabled)
599 			err = rtc_timer_enqueue(rtc, &rtc->aie_timer);
600 		else
601 			rtc_timer_remove(rtc, &rtc->aie_timer);
602 	}
603 
604 	if (err)
605 		/* nothing */;
606 	else if (!rtc->ops)
607 		err = -ENODEV;
608 	else if (!test_bit(RTC_FEATURE_ALARM, rtc->features) || !rtc->ops->alarm_irq_enable)
609 		err = -EINVAL;
610 	else
611 		err = rtc->ops->alarm_irq_enable(rtc->dev.parent, enabled);
612 
613 	mutex_unlock(&rtc->ops_lock);
614 
615 	trace_rtc_alarm_irq_enable(enabled, err);
616 	return err;
617 }
618 EXPORT_SYMBOL_GPL(rtc_alarm_irq_enable);
619 
620 int rtc_update_irq_enable(struct rtc_device *rtc, unsigned int enabled)
621 {
622 	int err;
623 
624 	err = mutex_lock_interruptible(&rtc->ops_lock);
625 	if (err)
626 		return err;
627 
628 #ifdef CONFIG_RTC_INTF_DEV_UIE_EMUL
629 	if (enabled == 0 && rtc->uie_irq_active) {
630 		mutex_unlock(&rtc->ops_lock);
631 		return rtc_dev_update_irq_enable_emul(rtc, 0);
632 	}
633 #endif
634 	/* make sure we're changing state */
635 	if (rtc->uie_rtctimer.enabled == enabled)
636 		goto out;
637 
638 	if (!test_bit(RTC_FEATURE_UPDATE_INTERRUPT, rtc->features) ||
639 	    !test_bit(RTC_FEATURE_ALARM, rtc->features)) {
640 		mutex_unlock(&rtc->ops_lock);
641 #ifdef CONFIG_RTC_INTF_DEV_UIE_EMUL
642 		return rtc_dev_update_irq_enable_emul(rtc, enabled);
643 #else
644 		return -EINVAL;
645 #endif
646 	}
647 
648 	if (enabled) {
649 		struct rtc_time tm;
650 		ktime_t now, onesec;
651 
652 		err = __rtc_read_time(rtc, &tm);
653 		if (err)
654 			goto out;
655 		onesec = ktime_set(1, 0);
656 		now = rtc_tm_to_ktime(tm);
657 		rtc->uie_rtctimer.node.expires = ktime_add(now, onesec);
658 		rtc->uie_rtctimer.period = ktime_set(1, 0);
659 		err = rtc_timer_enqueue(rtc, &rtc->uie_rtctimer);
660 		if (!err && rtc->ops && rtc->ops->alarm_irq_enable)
661 			err = rtc->ops->alarm_irq_enable(rtc->dev.parent, 1);
662 		if (err)
663 			goto out;
664 	} else {
665 		rtc_timer_remove(rtc, &rtc->uie_rtctimer);
666 	}
667 
668 out:
669 	mutex_unlock(&rtc->ops_lock);
670 
671 	return err;
672 }
673 EXPORT_SYMBOL_GPL(rtc_update_irq_enable);
674 
675 /**
676  * rtc_handle_legacy_irq - AIE, UIE and PIE event hook
677  * @rtc: pointer to the rtc device
678  * @num: number of occurrence of the event
679  * @mode: type of the event, RTC_AF, RTC_UF or RTC_PF
680  *
681  * This function is called when an AIE, UIE or PIE mode interrupt
682  * has occurred (or been emulated).
683  *
684  */
685 void rtc_handle_legacy_irq(struct rtc_device *rtc, int num, int mode)
686 {
687 	unsigned long flags;
688 
689 	/* mark one irq of the appropriate mode */
690 	spin_lock_irqsave(&rtc->irq_lock, flags);
691 	rtc->irq_data = (rtc->irq_data + (num << 8)) | (RTC_IRQF | mode);
692 	spin_unlock_irqrestore(&rtc->irq_lock, flags);
693 
694 	wake_up_interruptible(&rtc->irq_queue);
695 	kill_fasync(&rtc->async_queue, SIGIO, POLL_IN);
696 }
697 
698 /**
699  * rtc_aie_update_irq - AIE mode rtctimer hook
700  * @rtc: pointer to the rtc_device
701  *
702  * This functions is called when the aie_timer expires.
703  */
704 void rtc_aie_update_irq(struct rtc_device *rtc)
705 {
706 	rtc_handle_legacy_irq(rtc, 1, RTC_AF);
707 }
708 
709 /**
710  * rtc_uie_update_irq - UIE mode rtctimer hook
711  * @rtc: pointer to the rtc_device
712  *
713  * This functions is called when the uie_timer expires.
714  */
715 void rtc_uie_update_irq(struct rtc_device *rtc)
716 {
717 	rtc_handle_legacy_irq(rtc, 1,  RTC_UF);
718 }
719 
720 /**
721  * rtc_pie_update_irq - PIE mode hrtimer hook
722  * @timer: pointer to the pie mode hrtimer
723  *
724  * This function is used to emulate PIE mode interrupts
725  * using an hrtimer. This function is called when the periodic
726  * hrtimer expires.
727  */
728 enum hrtimer_restart rtc_pie_update_irq(struct hrtimer *timer)
729 {
730 	struct rtc_device *rtc;
731 	ktime_t period;
732 	u64 count;
733 
734 	rtc = container_of(timer, struct rtc_device, pie_timer);
735 
736 	period = NSEC_PER_SEC / rtc->irq_freq;
737 	count = hrtimer_forward_now(timer, period);
738 
739 	rtc_handle_legacy_irq(rtc, count, RTC_PF);
740 
741 	return HRTIMER_RESTART;
742 }
743 
744 /**
745  * rtc_update_irq - Triggered when a RTC interrupt occurs.
746  * @rtc: the rtc device
747  * @num: how many irqs are being reported (usually one)
748  * @events: mask of RTC_IRQF with one or more of RTC_PF, RTC_AF, RTC_UF
749  * Context: any
750  */
751 void rtc_update_irq(struct rtc_device *rtc,
752 		    unsigned long num, unsigned long events)
753 {
754 	if (IS_ERR_OR_NULL(rtc))
755 		return;
756 
757 	pm_stay_awake(rtc->dev.parent);
758 	schedule_work(&rtc->irqwork);
759 }
760 EXPORT_SYMBOL_GPL(rtc_update_irq);
761 
762 struct rtc_device *rtc_class_open(const char *name)
763 {
764 	struct device *dev;
765 	struct rtc_device *rtc = NULL;
766 
767 	dev = class_find_device_by_name(&rtc_class, name);
768 	if (dev)
769 		rtc = to_rtc_device(dev);
770 
771 	if (rtc) {
772 		if (!try_module_get(rtc->owner)) {
773 			put_device(dev);
774 			rtc = NULL;
775 		}
776 	}
777 
778 	return rtc;
779 }
780 EXPORT_SYMBOL_GPL(rtc_class_open);
781 
782 void rtc_class_close(struct rtc_device *rtc)
783 {
784 	module_put(rtc->owner);
785 	put_device(&rtc->dev);
786 }
787 EXPORT_SYMBOL_GPL(rtc_class_close);
788 
789 static int rtc_update_hrtimer(struct rtc_device *rtc, int enabled)
790 {
791 	/*
792 	 * We always cancel the timer here first, because otherwise
793 	 * we could run into BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
794 	 * when we manage to start the timer before the callback
795 	 * returns HRTIMER_RESTART.
796 	 *
797 	 * We cannot use hrtimer_cancel() here as a running callback
798 	 * could be blocked on rtc->irq_task_lock and hrtimer_cancel()
799 	 * would spin forever.
800 	 */
801 	if (hrtimer_try_to_cancel(&rtc->pie_timer) < 0)
802 		return -1;
803 
804 	if (enabled) {
805 		ktime_t period = NSEC_PER_SEC / rtc->irq_freq;
806 
807 		hrtimer_start(&rtc->pie_timer, period, HRTIMER_MODE_REL);
808 	}
809 	return 0;
810 }
811 
812 /**
813  * rtc_irq_set_state - enable/disable 2^N Hz periodic IRQs
814  * @rtc: the rtc device
815  * @enabled: true to enable periodic IRQs
816  * Context: any
817  *
818  * Note that rtc_irq_set_freq() should previously have been used to
819  * specify the desired frequency of periodic IRQ.
820  */
821 int rtc_irq_set_state(struct rtc_device *rtc, int enabled)
822 {
823 	int err = 0;
824 
825 	while (rtc_update_hrtimer(rtc, enabled) < 0)
826 		cpu_relax();
827 
828 	rtc->pie_enabled = enabled;
829 
830 	trace_rtc_irq_set_state(enabled, err);
831 	return err;
832 }
833 
834 /**
835  * rtc_irq_set_freq - set 2^N Hz periodic IRQ frequency for IRQ
836  * @rtc: the rtc device
837  * @freq: positive frequency
838  * Context: any
839  *
840  * Note that rtc_irq_set_state() is used to enable or disable the
841  * periodic IRQs.
842  */
843 int rtc_irq_set_freq(struct rtc_device *rtc, int freq)
844 {
845 	int err = 0;
846 
847 	if (freq <= 0 || freq > RTC_MAX_FREQ)
848 		return -EINVAL;
849 
850 	rtc->irq_freq = freq;
851 	while (rtc->pie_enabled && rtc_update_hrtimer(rtc, 1) < 0)
852 		cpu_relax();
853 
854 	trace_rtc_irq_set_freq(freq, err);
855 	return err;
856 }
857 
858 /**
859  * rtc_timer_enqueue - Adds a rtc_timer to the rtc_device timerqueue
860  * @rtc: rtc device
861  * @timer: timer being added.
862  *
863  * Enqueues a timer onto the rtc devices timerqueue and sets
864  * the next alarm event appropriately.
865  *
866  * Sets the enabled bit on the added timer.
867  *
868  * Must hold ops_lock for proper serialization of timerqueue
869  */
870 static int rtc_timer_enqueue(struct rtc_device *rtc, struct rtc_timer *timer)
871 {
872 	struct timerqueue_node *next = timerqueue_getnext(&rtc->timerqueue);
873 	struct rtc_time tm;
874 	ktime_t now;
875 	int err;
876 
877 	err = __rtc_read_time(rtc, &tm);
878 	if (err)
879 		return err;
880 
881 	timer->enabled = 1;
882 	now = rtc_tm_to_ktime(tm);
883 
884 	/* Skip over expired timers */
885 	while (next) {
886 		if (next->expires >= now)
887 			break;
888 		next = timerqueue_iterate_next(next);
889 	}
890 
891 	timerqueue_add(&rtc->timerqueue, &timer->node);
892 	trace_rtc_timer_enqueue(timer);
893 	if (!next || ktime_before(timer->node.expires, next->expires)) {
894 		struct rtc_wkalrm alarm;
895 
896 		alarm.time = rtc_ktime_to_tm(timer->node.expires);
897 		alarm.enabled = 1;
898 		err = __rtc_set_alarm(rtc, &alarm);
899 		if (err == -ETIME) {
900 			pm_stay_awake(rtc->dev.parent);
901 			schedule_work(&rtc->irqwork);
902 		} else if (err) {
903 			timerqueue_del(&rtc->timerqueue, &timer->node);
904 			trace_rtc_timer_dequeue(timer);
905 			timer->enabled = 0;
906 			return err;
907 		}
908 	}
909 	return 0;
910 }
911 
912 static void rtc_alarm_disable(struct rtc_device *rtc)
913 {
914 	if (!rtc->ops || !test_bit(RTC_FEATURE_ALARM, rtc->features) || !rtc->ops->alarm_irq_enable)
915 		return;
916 
917 	rtc->ops->alarm_irq_enable(rtc->dev.parent, false);
918 	trace_rtc_alarm_irq_enable(0, 0);
919 }
920 
921 /**
922  * rtc_timer_remove - Removes a rtc_timer from the rtc_device timerqueue
923  * @rtc: rtc device
924  * @timer: timer being removed.
925  *
926  * Removes a timer onto the rtc devices timerqueue and sets
927  * the next alarm event appropriately.
928  *
929  * Clears the enabled bit on the removed timer.
930  *
931  * Must hold ops_lock for proper serialization of timerqueue
932  */
933 static void rtc_timer_remove(struct rtc_device *rtc, struct rtc_timer *timer)
934 {
935 	struct timerqueue_node *next = timerqueue_getnext(&rtc->timerqueue);
936 
937 	timerqueue_del(&rtc->timerqueue, &timer->node);
938 	trace_rtc_timer_dequeue(timer);
939 	timer->enabled = 0;
940 	if (next == &timer->node) {
941 		struct rtc_wkalrm alarm;
942 		int err;
943 
944 		next = timerqueue_getnext(&rtc->timerqueue);
945 		if (!next) {
946 			rtc_alarm_disable(rtc);
947 			return;
948 		}
949 		alarm.time = rtc_ktime_to_tm(next->expires);
950 		alarm.enabled = 1;
951 		err = __rtc_set_alarm(rtc, &alarm);
952 		if (err == -ETIME) {
953 			pm_stay_awake(rtc->dev.parent);
954 			schedule_work(&rtc->irqwork);
955 		}
956 	}
957 }
958 
959 /**
960  * rtc_timer_do_work - Expires rtc timers
961  * @work: work item
962  *
963  * Expires rtc timers. Reprograms next alarm event if needed.
964  * Called via worktask.
965  *
966  * Serializes access to timerqueue via ops_lock mutex
967  */
968 void rtc_timer_do_work(struct work_struct *work)
969 {
970 	struct rtc_timer *timer;
971 	struct timerqueue_node *next;
972 	ktime_t now;
973 	struct rtc_time tm;
974 	int err;
975 
976 	struct rtc_device *rtc =
977 		container_of(work, struct rtc_device, irqwork);
978 
979 	mutex_lock(&rtc->ops_lock);
980 again:
981 	err = __rtc_read_time(rtc, &tm);
982 	if (err) {
983 		mutex_unlock(&rtc->ops_lock);
984 		return;
985 	}
986 	now = rtc_tm_to_ktime(tm);
987 	while ((next = timerqueue_getnext(&rtc->timerqueue))) {
988 		if (next->expires > now)
989 			break;
990 
991 		/* expire timer */
992 		timer = container_of(next, struct rtc_timer, node);
993 		timerqueue_del(&rtc->timerqueue, &timer->node);
994 		trace_rtc_timer_dequeue(timer);
995 		timer->enabled = 0;
996 		if (timer->func)
997 			timer->func(timer->rtc);
998 
999 		trace_rtc_timer_fired(timer);
1000 		/* Re-add/fwd periodic timers */
1001 		if (ktime_to_ns(timer->period)) {
1002 			timer->node.expires = ktime_add(timer->node.expires,
1003 							timer->period);
1004 			timer->enabled = 1;
1005 			timerqueue_add(&rtc->timerqueue, &timer->node);
1006 			trace_rtc_timer_enqueue(timer);
1007 		}
1008 	}
1009 
1010 	/* Set next alarm */
1011 	if (next) {
1012 		struct rtc_wkalrm alarm;
1013 		int err;
1014 		int retry = 3;
1015 
1016 		alarm.time = rtc_ktime_to_tm(next->expires);
1017 		alarm.enabled = 1;
1018 reprogram:
1019 		err = __rtc_set_alarm(rtc, &alarm);
1020 		if (err == -ETIME) {
1021 			goto again;
1022 		} else if (err) {
1023 			if (retry-- > 0)
1024 				goto reprogram;
1025 
1026 			timer = container_of(next, struct rtc_timer, node);
1027 			timerqueue_del(&rtc->timerqueue, &timer->node);
1028 			trace_rtc_timer_dequeue(timer);
1029 			timer->enabled = 0;
1030 			dev_err(&rtc->dev, "__rtc_set_alarm: err=%d\n", err);
1031 			goto again;
1032 		}
1033 	} else {
1034 		rtc_alarm_disable(rtc);
1035 	}
1036 
1037 	pm_relax(rtc->dev.parent);
1038 	mutex_unlock(&rtc->ops_lock);
1039 }
1040 
1041 /* rtc_timer_init - Initializes an rtc_timer
1042  * @timer: timer to be intiialized
1043  * @f: function pointer to be called when timer fires
1044  * @rtc: pointer to the rtc_device
1045  *
1046  * Kernel interface to initializing an rtc_timer.
1047  */
1048 void rtc_timer_init(struct rtc_timer *timer, void (*f)(struct rtc_device *r),
1049 		    struct rtc_device *rtc)
1050 {
1051 	timerqueue_init(&timer->node);
1052 	timer->enabled = 0;
1053 	timer->func = f;
1054 	timer->rtc = rtc;
1055 }
1056 
1057 /* rtc_timer_start - Sets an rtc_timer to fire in the future
1058  * @ rtc: rtc device to be used
1059  * @ timer: timer being set
1060  * @ expires: time at which to expire the timer
1061  * @ period: period that the timer will recur
1062  *
1063  * Kernel interface to set an rtc_timer
1064  */
1065 int rtc_timer_start(struct rtc_device *rtc, struct rtc_timer *timer,
1066 		    ktime_t expires, ktime_t period)
1067 {
1068 	int ret = 0;
1069 
1070 	mutex_lock(&rtc->ops_lock);
1071 	if (timer->enabled)
1072 		rtc_timer_remove(rtc, timer);
1073 
1074 	timer->node.expires = expires;
1075 	timer->period = period;
1076 
1077 	ret = rtc_timer_enqueue(rtc, timer);
1078 
1079 	mutex_unlock(&rtc->ops_lock);
1080 	return ret;
1081 }
1082 
1083 /* rtc_timer_cancel - Stops an rtc_timer
1084  * @ rtc: rtc device to be used
1085  * @ timer: timer being set
1086  *
1087  * Kernel interface to cancel an rtc_timer
1088  */
1089 void rtc_timer_cancel(struct rtc_device *rtc, struct rtc_timer *timer)
1090 {
1091 	mutex_lock(&rtc->ops_lock);
1092 	if (timer->enabled)
1093 		rtc_timer_remove(rtc, timer);
1094 	mutex_unlock(&rtc->ops_lock);
1095 }
1096 
1097 /**
1098  * rtc_read_offset - Read the amount of rtc offset in parts per billion
1099  * @rtc: rtc device to be used
1100  * @offset: the offset in parts per billion
1101  *
1102  * see below for details.
1103  *
1104  * Kernel interface to read rtc clock offset
1105  * Returns 0 on success, or a negative number on error.
1106  * If read_offset() is not implemented for the rtc, return -EINVAL
1107  */
1108 int rtc_read_offset(struct rtc_device *rtc, long *offset)
1109 {
1110 	int ret;
1111 
1112 	if (!rtc->ops)
1113 		return -ENODEV;
1114 
1115 	if (!rtc->ops->read_offset)
1116 		return -EINVAL;
1117 
1118 	mutex_lock(&rtc->ops_lock);
1119 	ret = rtc->ops->read_offset(rtc->dev.parent, offset);
1120 	mutex_unlock(&rtc->ops_lock);
1121 
1122 	trace_rtc_read_offset(*offset, ret);
1123 	return ret;
1124 }
1125 
1126 /**
1127  * rtc_set_offset - Adjusts the duration of the average second
1128  * @rtc: rtc device to be used
1129  * @offset: the offset in parts per billion
1130  *
1131  * Some rtc's allow an adjustment to the average duration of a second
1132  * to compensate for differences in the actual clock rate due to temperature,
1133  * the crystal, capacitor, etc.
1134  *
1135  * The adjustment applied is as follows:
1136  *   t = t0 * (1 + offset * 1e-9)
1137  * where t0 is the measured length of 1 RTC second with offset = 0
1138  *
1139  * Kernel interface to adjust an rtc clock offset.
1140  * Return 0 on success, or a negative number on error.
1141  * If the rtc offset is not setable (or not implemented), return -EINVAL
1142  */
1143 int rtc_set_offset(struct rtc_device *rtc, long offset)
1144 {
1145 	int ret;
1146 
1147 	if (!rtc->ops)
1148 		return -ENODEV;
1149 
1150 	if (!rtc->ops->set_offset)
1151 		return -EINVAL;
1152 
1153 	mutex_lock(&rtc->ops_lock);
1154 	ret = rtc->ops->set_offset(rtc->dev.parent, offset);
1155 	mutex_unlock(&rtc->ops_lock);
1156 
1157 	trace_rtc_set_offset(offset, ret);
1158 	return ret;
1159 }
1160