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