xref: /openbmc/linux/drivers/rtc/interface.c (revision c48cadf5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * RTC subsystem, interface functions
4  *
5  * Copyright (C) 2005 Tower Technologies
6  * Author: Alessandro Zummo <a.zummo@towertech.it>
7  *
8  * based on arch/arm/common/rtctime.c
9  */
10 
11 #include <linux/rtc.h>
12 #include <linux/sched.h>
13 #include <linux/module.h>
14 #include <linux/log2.h>
15 #include <linux/workqueue.h>
16 
17 #define CREATE_TRACE_POINTS
18 #include <trace/events/rtc.h>
19 
20 static int rtc_timer_enqueue(struct rtc_device *rtc, struct rtc_timer *timer);
21 static void rtc_timer_remove(struct rtc_device *rtc, struct rtc_timer *timer);
22 
23 static void rtc_add_offset(struct rtc_device *rtc, struct rtc_time *tm)
24 {
25 	time64_t secs;
26 
27 	if (!rtc->offset_secs)
28 		return;
29 
30 	secs = rtc_tm_to_time64(tm);
31 
32 	/*
33 	 * Since the reading time values from RTC device are always in the RTC
34 	 * original valid range, but we need to skip the overlapped region
35 	 * between expanded range and original range, which is no need to add
36 	 * the offset.
37 	 */
38 	if ((rtc->start_secs > rtc->range_min && secs >= rtc->start_secs) ||
39 	    (rtc->start_secs < rtc->range_min &&
40 	     secs <= (rtc->start_secs + rtc->range_max - rtc->range_min)))
41 		return;
42 
43 	rtc_time64_to_tm(secs + rtc->offset_secs, tm);
44 }
45 
46 static void rtc_subtract_offset(struct rtc_device *rtc, struct rtc_time *tm)
47 {
48 	time64_t secs;
49 
50 	if (!rtc->offset_secs)
51 		return;
52 
53 	secs = rtc_tm_to_time64(tm);
54 
55 	/*
56 	 * If the setting time values are in the valid range of RTC hardware
57 	 * device, then no need to subtract the offset when setting time to RTC
58 	 * device. Otherwise we need to subtract the offset to make the time
59 	 * values are valid for RTC hardware device.
60 	 */
61 	if (secs >= rtc->range_min && secs <= rtc->range_max)
62 		return;
63 
64 	rtc_time64_to_tm(secs - rtc->offset_secs, tm);
65 }
66 
67 static int rtc_valid_range(struct rtc_device *rtc, struct rtc_time *tm)
68 {
69 	if (rtc->range_min != rtc->range_max) {
70 		time64_t time = rtc_tm_to_time64(tm);
71 		time64_t range_min = rtc->set_start_time ? rtc->start_secs :
72 			rtc->range_min;
73 		time64_t range_max = rtc->set_start_time ?
74 			(rtc->start_secs + rtc->range_max - rtc->range_min) :
75 			rtc->range_max;
76 
77 		if (time < range_min || time > range_max)
78 			return -ERANGE;
79 	}
80 
81 	return 0;
82 }
83 
84 static int __rtc_read_time(struct rtc_device *rtc, struct rtc_time *tm)
85 {
86 	int err;
87 
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 returned -EINVAL to signal that it has
577 	 * been configured without interrupts or they are not available at the
578 	 * moment.
579 	 */
580 	if (err == -EINVAL)
581 		err = rtc_dev_update_irq_enable_emul(rtc, enabled);
582 #endif
583 	return err;
584 }
585 EXPORT_SYMBOL_GPL(rtc_update_irq_enable);
586 
587 /**
588  * rtc_handle_legacy_irq - AIE, UIE and PIE event hook
589  * @rtc: pointer to the rtc device
590  *
591  * This function is called when an AIE, UIE or PIE mode interrupt
592  * has occurred (or been emulated).
593  *
594  */
595 void rtc_handle_legacy_irq(struct rtc_device *rtc, int num, int mode)
596 {
597 	unsigned long flags;
598 
599 	/* mark one irq of the appropriate mode */
600 	spin_lock_irqsave(&rtc->irq_lock, flags);
601 	rtc->irq_data = (rtc->irq_data + (num << 8)) | (RTC_IRQF | mode);
602 	spin_unlock_irqrestore(&rtc->irq_lock, flags);
603 
604 	wake_up_interruptible(&rtc->irq_queue);
605 	kill_fasync(&rtc->async_queue, SIGIO, POLL_IN);
606 }
607 
608 /**
609  * rtc_aie_update_irq - AIE mode rtctimer hook
610  * @rtc: pointer to the rtc_device
611  *
612  * This functions is called when the aie_timer expires.
613  */
614 void rtc_aie_update_irq(struct rtc_device *rtc)
615 {
616 	rtc_handle_legacy_irq(rtc, 1, RTC_AF);
617 }
618 
619 /**
620  * rtc_uie_update_irq - UIE mode rtctimer hook
621  * @rtc: pointer to the rtc_device
622  *
623  * This functions is called when the uie_timer expires.
624  */
625 void rtc_uie_update_irq(struct rtc_device *rtc)
626 {
627 	rtc_handle_legacy_irq(rtc, 1,  RTC_UF);
628 }
629 
630 /**
631  * rtc_pie_update_irq - PIE mode hrtimer hook
632  * @timer: pointer to the pie mode hrtimer
633  *
634  * This function is used to emulate PIE mode interrupts
635  * using an hrtimer. This function is called when the periodic
636  * hrtimer expires.
637  */
638 enum hrtimer_restart rtc_pie_update_irq(struct hrtimer *timer)
639 {
640 	struct rtc_device *rtc;
641 	ktime_t period;
642 	int count;
643 
644 	rtc = container_of(timer, struct rtc_device, pie_timer);
645 
646 	period = NSEC_PER_SEC / rtc->irq_freq;
647 	count = hrtimer_forward_now(timer, period);
648 
649 	rtc_handle_legacy_irq(rtc, count, RTC_PF);
650 
651 	return HRTIMER_RESTART;
652 }
653 
654 /**
655  * rtc_update_irq - Triggered when a RTC interrupt occurs.
656  * @rtc: the rtc device
657  * @num: how many irqs are being reported (usually one)
658  * @events: mask of RTC_IRQF with one or more of RTC_PF, RTC_AF, RTC_UF
659  * Context: any
660  */
661 void rtc_update_irq(struct rtc_device *rtc,
662 		    unsigned long num, unsigned long events)
663 {
664 	if (IS_ERR_OR_NULL(rtc))
665 		return;
666 
667 	pm_stay_awake(rtc->dev.parent);
668 	schedule_work(&rtc->irqwork);
669 }
670 EXPORT_SYMBOL_GPL(rtc_update_irq);
671 
672 static int __rtc_match(struct device *dev, const void *data)
673 {
674 	const char *name = data;
675 
676 	if (strcmp(dev_name(dev), name) == 0)
677 		return 1;
678 	return 0;
679 }
680 
681 struct rtc_device *rtc_class_open(const char *name)
682 {
683 	struct device *dev;
684 	struct rtc_device *rtc = NULL;
685 
686 	dev = class_find_device(rtc_class, NULL, name, __rtc_match);
687 	if (dev)
688 		rtc = to_rtc_device(dev);
689 
690 	if (rtc) {
691 		if (!try_module_get(rtc->owner)) {
692 			put_device(dev);
693 			rtc = NULL;
694 		}
695 	}
696 
697 	return rtc;
698 }
699 EXPORT_SYMBOL_GPL(rtc_class_open);
700 
701 void rtc_class_close(struct rtc_device *rtc)
702 {
703 	module_put(rtc->owner);
704 	put_device(&rtc->dev);
705 }
706 EXPORT_SYMBOL_GPL(rtc_class_close);
707 
708 static int rtc_update_hrtimer(struct rtc_device *rtc, int enabled)
709 {
710 	/*
711 	 * We always cancel the timer here first, because otherwise
712 	 * we could run into BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
713 	 * when we manage to start the timer before the callback
714 	 * returns HRTIMER_RESTART.
715 	 *
716 	 * We cannot use hrtimer_cancel() here as a running callback
717 	 * could be blocked on rtc->irq_task_lock and hrtimer_cancel()
718 	 * would spin forever.
719 	 */
720 	if (hrtimer_try_to_cancel(&rtc->pie_timer) < 0)
721 		return -1;
722 
723 	if (enabled) {
724 		ktime_t period = NSEC_PER_SEC / rtc->irq_freq;
725 
726 		hrtimer_start(&rtc->pie_timer, period, HRTIMER_MODE_REL);
727 	}
728 	return 0;
729 }
730 
731 /**
732  * rtc_irq_set_state - enable/disable 2^N Hz periodic IRQs
733  * @rtc: the rtc device
734  * @enabled: true to enable periodic IRQs
735  * Context: any
736  *
737  * Note that rtc_irq_set_freq() should previously have been used to
738  * specify the desired frequency of periodic IRQ.
739  */
740 int rtc_irq_set_state(struct rtc_device *rtc, int enabled)
741 {
742 	int err = 0;
743 
744 	while (rtc_update_hrtimer(rtc, enabled) < 0)
745 		cpu_relax();
746 
747 	rtc->pie_enabled = enabled;
748 
749 	trace_rtc_irq_set_state(enabled, err);
750 	return err;
751 }
752 
753 /**
754  * rtc_irq_set_freq - set 2^N Hz periodic IRQ frequency for IRQ
755  * @rtc: the rtc device
756  * @freq: positive frequency
757  * Context: any
758  *
759  * Note that rtc_irq_set_state() is used to enable or disable the
760  * periodic IRQs.
761  */
762 int rtc_irq_set_freq(struct rtc_device *rtc, int freq)
763 {
764 	int err = 0;
765 
766 	if (freq <= 0 || freq > RTC_MAX_FREQ)
767 		return -EINVAL;
768 
769 	rtc->irq_freq = freq;
770 	while (rtc->pie_enabled && rtc_update_hrtimer(rtc, 1) < 0)
771 		cpu_relax();
772 
773 	trace_rtc_irq_set_freq(freq, err);
774 	return err;
775 }
776 
777 /**
778  * rtc_timer_enqueue - Adds a rtc_timer to the rtc_device timerqueue
779  * @rtc rtc device
780  * @timer timer being added.
781  *
782  * Enqueues a timer onto the rtc devices timerqueue and sets
783  * the next alarm event appropriately.
784  *
785  * Sets the enabled bit on the added timer.
786  *
787  * Must hold ops_lock for proper serialization of timerqueue
788  */
789 static int rtc_timer_enqueue(struct rtc_device *rtc, struct rtc_timer *timer)
790 {
791 	struct timerqueue_node *next = timerqueue_getnext(&rtc->timerqueue);
792 	struct rtc_time tm;
793 	ktime_t now;
794 
795 	timer->enabled = 1;
796 	__rtc_read_time(rtc, &tm);
797 	now = rtc_tm_to_ktime(tm);
798 
799 	/* Skip over expired timers */
800 	while (next) {
801 		if (next->expires >= now)
802 			break;
803 		next = timerqueue_iterate_next(next);
804 	}
805 
806 	timerqueue_add(&rtc->timerqueue, &timer->node);
807 	trace_rtc_timer_enqueue(timer);
808 	if (!next || ktime_before(timer->node.expires, next->expires)) {
809 		struct rtc_wkalrm alarm;
810 		int err;
811 
812 		alarm.time = rtc_ktime_to_tm(timer->node.expires);
813 		alarm.enabled = 1;
814 		err = __rtc_set_alarm(rtc, &alarm);
815 		if (err == -ETIME) {
816 			pm_stay_awake(rtc->dev.parent);
817 			schedule_work(&rtc->irqwork);
818 		} else if (err) {
819 			timerqueue_del(&rtc->timerqueue, &timer->node);
820 			trace_rtc_timer_dequeue(timer);
821 			timer->enabled = 0;
822 			return err;
823 		}
824 	}
825 	return 0;
826 }
827 
828 static void rtc_alarm_disable(struct rtc_device *rtc)
829 {
830 	if (!rtc->ops || !rtc->ops->alarm_irq_enable)
831 		return;
832 
833 	rtc->ops->alarm_irq_enable(rtc->dev.parent, false);
834 	trace_rtc_alarm_irq_enable(0, 0);
835 }
836 
837 /**
838  * rtc_timer_remove - Removes a rtc_timer from the rtc_device timerqueue
839  * @rtc rtc device
840  * @timer timer being removed.
841  *
842  * Removes a timer onto the rtc devices timerqueue and sets
843  * the next alarm event appropriately.
844  *
845  * Clears the enabled bit on the removed timer.
846  *
847  * Must hold ops_lock for proper serialization of timerqueue
848  */
849 static void rtc_timer_remove(struct rtc_device *rtc, struct rtc_timer *timer)
850 {
851 	struct timerqueue_node *next = timerqueue_getnext(&rtc->timerqueue);
852 
853 	timerqueue_del(&rtc->timerqueue, &timer->node);
854 	trace_rtc_timer_dequeue(timer);
855 	timer->enabled = 0;
856 	if (next == &timer->node) {
857 		struct rtc_wkalrm alarm;
858 		int err;
859 
860 		next = timerqueue_getnext(&rtc->timerqueue);
861 		if (!next) {
862 			rtc_alarm_disable(rtc);
863 			return;
864 		}
865 		alarm.time = rtc_ktime_to_tm(next->expires);
866 		alarm.enabled = 1;
867 		err = __rtc_set_alarm(rtc, &alarm);
868 		if (err == -ETIME) {
869 			pm_stay_awake(rtc->dev.parent);
870 			schedule_work(&rtc->irqwork);
871 		}
872 	}
873 }
874 
875 /**
876  * rtc_timer_do_work - Expires rtc timers
877  * @rtc rtc device
878  * @timer timer being removed.
879  *
880  * Expires rtc timers. Reprograms next alarm event if needed.
881  * Called via worktask.
882  *
883  * Serializes access to timerqueue via ops_lock mutex
884  */
885 void rtc_timer_do_work(struct work_struct *work)
886 {
887 	struct rtc_timer *timer;
888 	struct timerqueue_node *next;
889 	ktime_t now;
890 	struct rtc_time tm;
891 
892 	struct rtc_device *rtc =
893 		container_of(work, struct rtc_device, irqwork);
894 
895 	mutex_lock(&rtc->ops_lock);
896 again:
897 	__rtc_read_time(rtc, &tm);
898 	now = rtc_tm_to_ktime(tm);
899 	while ((next = timerqueue_getnext(&rtc->timerqueue))) {
900 		if (next->expires > now)
901 			break;
902 
903 		/* expire timer */
904 		timer = container_of(next, struct rtc_timer, node);
905 		timerqueue_del(&rtc->timerqueue, &timer->node);
906 		trace_rtc_timer_dequeue(timer);
907 		timer->enabled = 0;
908 		if (timer->func)
909 			timer->func(timer->rtc);
910 
911 		trace_rtc_timer_fired(timer);
912 		/* Re-add/fwd periodic timers */
913 		if (ktime_to_ns(timer->period)) {
914 			timer->node.expires = ktime_add(timer->node.expires,
915 							timer->period);
916 			timer->enabled = 1;
917 			timerqueue_add(&rtc->timerqueue, &timer->node);
918 			trace_rtc_timer_enqueue(timer);
919 		}
920 	}
921 
922 	/* Set next alarm */
923 	if (next) {
924 		struct rtc_wkalrm alarm;
925 		int err;
926 		int retry = 3;
927 
928 		alarm.time = rtc_ktime_to_tm(next->expires);
929 		alarm.enabled = 1;
930 reprogram:
931 		err = __rtc_set_alarm(rtc, &alarm);
932 		if (err == -ETIME) {
933 			goto again;
934 		} else if (err) {
935 			if (retry-- > 0)
936 				goto reprogram;
937 
938 			timer = container_of(next, struct rtc_timer, node);
939 			timerqueue_del(&rtc->timerqueue, &timer->node);
940 			trace_rtc_timer_dequeue(timer);
941 			timer->enabled = 0;
942 			dev_err(&rtc->dev, "__rtc_set_alarm: err=%d\n", err);
943 			goto again;
944 		}
945 	} else {
946 		rtc_alarm_disable(rtc);
947 	}
948 
949 	pm_relax(rtc->dev.parent);
950 	mutex_unlock(&rtc->ops_lock);
951 }
952 
953 /* rtc_timer_init - Initializes an rtc_timer
954  * @timer: timer to be intiialized
955  * @f: function pointer to be called when timer fires
956  * @rtc: pointer to the rtc_device
957  *
958  * Kernel interface to initializing an rtc_timer.
959  */
960 void rtc_timer_init(struct rtc_timer *timer, void (*f)(struct rtc_device *r),
961 		    struct rtc_device *rtc)
962 {
963 	timerqueue_init(&timer->node);
964 	timer->enabled = 0;
965 	timer->func = f;
966 	timer->rtc = rtc;
967 }
968 
969 /* rtc_timer_start - Sets an rtc_timer to fire in the future
970  * @ rtc: rtc device to be used
971  * @ timer: timer being set
972  * @ expires: time at which to expire the timer
973  * @ period: period that the timer will recur
974  *
975  * Kernel interface to set an rtc_timer
976  */
977 int rtc_timer_start(struct rtc_device *rtc, struct rtc_timer *timer,
978 		    ktime_t expires, ktime_t period)
979 {
980 	int ret = 0;
981 
982 	mutex_lock(&rtc->ops_lock);
983 	if (timer->enabled)
984 		rtc_timer_remove(rtc, timer);
985 
986 	timer->node.expires = expires;
987 	timer->period = period;
988 
989 	ret = rtc_timer_enqueue(rtc, timer);
990 
991 	mutex_unlock(&rtc->ops_lock);
992 	return ret;
993 }
994 
995 /* rtc_timer_cancel - Stops an rtc_timer
996  * @ rtc: rtc device to be used
997  * @ timer: timer being set
998  *
999  * Kernel interface to cancel an rtc_timer
1000  */
1001 void rtc_timer_cancel(struct rtc_device *rtc, struct rtc_timer *timer)
1002 {
1003 	mutex_lock(&rtc->ops_lock);
1004 	if (timer->enabled)
1005 		rtc_timer_remove(rtc, timer);
1006 	mutex_unlock(&rtc->ops_lock);
1007 }
1008 
1009 /**
1010  * rtc_read_offset - Read the amount of rtc offset in parts per billion
1011  * @ rtc: rtc device to be used
1012  * @ offset: the offset in parts per billion
1013  *
1014  * see below for details.
1015  *
1016  * Kernel interface to read rtc clock offset
1017  * Returns 0 on success, or a negative number on error.
1018  * If read_offset() is not implemented for the rtc, return -EINVAL
1019  */
1020 int rtc_read_offset(struct rtc_device *rtc, long *offset)
1021 {
1022 	int ret;
1023 
1024 	if (!rtc->ops)
1025 		return -ENODEV;
1026 
1027 	if (!rtc->ops->read_offset)
1028 		return -EINVAL;
1029 
1030 	mutex_lock(&rtc->ops_lock);
1031 	ret = rtc->ops->read_offset(rtc->dev.parent, offset);
1032 	mutex_unlock(&rtc->ops_lock);
1033 
1034 	trace_rtc_read_offset(*offset, ret);
1035 	return ret;
1036 }
1037 
1038 /**
1039  * rtc_set_offset - Adjusts the duration of the average second
1040  * @ rtc: rtc device to be used
1041  * @ offset: the offset in parts per billion
1042  *
1043  * Some rtc's allow an adjustment to the average duration of a second
1044  * to compensate for differences in the actual clock rate due to temperature,
1045  * the crystal, capacitor, etc.
1046  *
1047  * The adjustment applied is as follows:
1048  *   t = t0 * (1 + offset * 1e-9)
1049  * where t0 is the measured length of 1 RTC second with offset = 0
1050  *
1051  * Kernel interface to adjust an rtc clock offset.
1052  * Return 0 on success, or a negative number on error.
1053  * If the rtc offset is not setable (or not implemented), return -EINVAL
1054  */
1055 int rtc_set_offset(struct rtc_device *rtc, long offset)
1056 {
1057 	int ret;
1058 
1059 	if (!rtc->ops)
1060 		return -ENODEV;
1061 
1062 	if (!rtc->ops->set_offset)
1063 		return -EINVAL;
1064 
1065 	mutex_lock(&rtc->ops_lock);
1066 	ret = rtc->ops->set_offset(rtc->dev.parent, offset);
1067 	mutex_unlock(&rtc->ops_lock);
1068 
1069 	trace_rtc_set_offset(offset, ret);
1070 	return ret;
1071 }
1072