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