xref: /linux/drivers/rtc/class.c (revision 4dd10fbbeb9c33709edc89916e19c03c780a0751)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * RTC subsystem, base class
4  *
5  * Copyright (C) 2005 Tower Technologies
6  * Author: Alessandro Zummo <a.zummo@towertech.it>
7  *
8  * class skeleton from drivers/hwmon/hwmon.c
9  */
10 
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/module.h>
14 #include <linux/of.h>
15 #include <linux/rtc.h>
16 #include <linux/kdev_t.h>
17 #include <linux/idr.h>
18 #include <linux/slab.h>
19 #include <linux/workqueue.h>
20 
21 #include "rtc-core.h"
22 
23 static DEFINE_IDA(rtc_ida);
24 
25 static void rtc_device_release(struct device *dev)
26 {
27 	struct rtc_device *rtc = to_rtc_device(dev);
28 	struct timerqueue_head *head = &rtc->timerqueue;
29 	struct timerqueue_node *node;
30 
31 	mutex_lock(&rtc->ops_lock);
32 	while ((node = timerqueue_getnext(head)))
33 		timerqueue_del(head, node);
34 	mutex_unlock(&rtc->ops_lock);
35 
36 	cancel_work_sync(&rtc->irqwork);
37 
38 	ida_free(&rtc_ida, rtc->id);
39 	mutex_destroy(&rtc->ops_lock);
40 	kfree(rtc);
41 }
42 
43 #ifdef CONFIG_RTC_HCTOSYS_DEVICE
44 /* Result of the last RTC to system clock attempt. */
45 int rtc_hctosys_ret = -ENODEV;
46 
47 /* IMPORTANT: the RTC only stores whole seconds. It is arbitrary
48  * whether it stores the most close value or the value with partial
49  * seconds truncated. However, it is important that we use it to store
50  * the truncated value. This is because otherwise it is necessary,
51  * in an rtc sync function, to read both xtime.tv_sec and
52  * xtime.tv_nsec. On some processors (i.e. ARM), an atomic read
53  * of >32bits is not possible. So storing the most close value would
54  * slow down the sync API. So here we have the truncated value and
55  * the best guess is to add 0.5s.
56  */
57 
58 static void rtc_hctosys(struct rtc_device *rtc)
59 {
60 	int err;
61 	struct rtc_time tm;
62 	struct timespec64 tv64 = {
63 		.tv_nsec = NSEC_PER_SEC >> 1,
64 	};
65 
66 	err = rtc_read_time(rtc, &tm);
67 	if (err) {
68 		dev_err(rtc->dev.parent,
69 			"hctosys: unable to read the hardware clock\n");
70 		goto err_read;
71 	}
72 
73 	tv64.tv_sec = rtc_tm_to_time64(&tm);
74 
75 	if (IS_ENABLED(CONFIG_RTC_HCTOSYS_TIME32_LIMIT) &&
76 	    tv64.tv_sec > INT_MAX) {
77 		dev_warn(rtc->dev.parent,
78 			 "hctosys: rejecting %ptR UTC due to CONFIG_RTC_HCTOSYS_TIME32_LIMIT=y\n",
79 			 &tm);
80 		err = -ERANGE;
81 		goto err_read;
82 	}
83 
84 	err = do_settimeofday64(&tv64);
85 
86 	dev_info(rtc->dev.parent, "setting system clock to %ptR UTC (%lld)\n",
87 		 &tm, (long long)tv64.tv_sec);
88 
89 err_read:
90 	rtc_hctosys_ret = err;
91 }
92 #endif
93 
94 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
95 /*
96  * On suspend(), measure the delta between one RTC and the
97  * system's wall clock; restore it on resume().
98  */
99 
100 static struct timespec64 old_rtc, old_system, old_delta;
101 
102 static int rtc_suspend(struct device *dev)
103 {
104 	struct rtc_device	*rtc = to_rtc_device(dev);
105 	struct rtc_time		tm;
106 	struct timespec64	delta, delta_delta;
107 	int err;
108 
109 	if (timekeeping_rtc_skipsuspend())
110 		return 0;
111 
112 	if (strcmp(dev_name(&rtc->dev), CONFIG_RTC_HCTOSYS_DEVICE) != 0)
113 		return 0;
114 
115 	/* snapshot the current RTC and system time at suspend*/
116 	err = rtc_read_time(rtc, &tm);
117 	if (err < 0) {
118 		pr_debug("%s:  fail to read rtc time\n", dev_name(&rtc->dev));
119 		return 0;
120 	}
121 
122 	ktime_get_real_ts64(&old_system);
123 	old_rtc.tv_sec = rtc_tm_to_time64(&tm);
124 
125 	/*
126 	 * To avoid drift caused by repeated suspend/resumes,
127 	 * which each can add ~1 second drift error,
128 	 * try to compensate so the difference in system time
129 	 * and rtc time stays close to constant.
130 	 */
131 	delta = timespec64_sub(old_system, old_rtc);
132 	delta_delta = timespec64_sub(delta, old_delta);
133 	if (delta_delta.tv_sec < -2 || delta_delta.tv_sec >= 2) {
134 		/*
135 		 * if delta_delta is too large, assume time correction
136 		 * has occurred and set old_delta to the current delta.
137 		 */
138 		old_delta = delta;
139 	} else {
140 		/* Otherwise try to adjust old_system to compensate */
141 		old_system = timespec64_sub(old_system, delta_delta);
142 	}
143 
144 	return 0;
145 }
146 
147 static int rtc_resume(struct device *dev)
148 {
149 	struct rtc_device	*rtc = to_rtc_device(dev);
150 	struct rtc_time		tm;
151 	struct timespec64	new_system, new_rtc;
152 	struct timespec64	sleep_time;
153 	int err;
154 
155 	if (timekeeping_rtc_skipresume())
156 		return 0;
157 
158 	rtc_hctosys_ret = -ENODEV;
159 	if (strcmp(dev_name(&rtc->dev), CONFIG_RTC_HCTOSYS_DEVICE) != 0)
160 		return 0;
161 
162 	/* snapshot the current rtc and system time at resume */
163 	ktime_get_real_ts64(&new_system);
164 	err = rtc_read_time(rtc, &tm);
165 	if (err < 0) {
166 		pr_debug("%s:  fail to read rtc time\n", dev_name(&rtc->dev));
167 		return 0;
168 	}
169 
170 	new_rtc.tv_sec = rtc_tm_to_time64(&tm);
171 	new_rtc.tv_nsec = 0;
172 
173 	if (new_rtc.tv_sec < old_rtc.tv_sec) {
174 		pr_debug("%s:  time travel!\n", dev_name(&rtc->dev));
175 		return 0;
176 	}
177 
178 	/* calculate the RTC time delta (sleep time)*/
179 	sleep_time = timespec64_sub(new_rtc, old_rtc);
180 
181 	/*
182 	 * Since these RTC suspend/resume handlers are not called
183 	 * at the very end of suspend or the start of resume,
184 	 * some run-time may pass on either sides of the sleep time
185 	 * so subtract kernel run-time between rtc_suspend to rtc_resume
186 	 * to keep things accurate.
187 	 */
188 	sleep_time = timespec64_sub(sleep_time,
189 				    timespec64_sub(new_system, old_system));
190 
191 	if (sleep_time.tv_sec >= 0)
192 		timekeeping_inject_sleeptime64(&sleep_time);
193 	rtc_hctosys_ret = 0;
194 	return 0;
195 }
196 
197 static SIMPLE_DEV_PM_OPS(rtc_class_dev_pm_ops, rtc_suspend, rtc_resume);
198 #define RTC_CLASS_DEV_PM_OPS	(&rtc_class_dev_pm_ops)
199 #else
200 #define RTC_CLASS_DEV_PM_OPS	NULL
201 #endif
202 
203 const struct class rtc_class = {
204 	.name = "rtc",
205 	.pm = RTC_CLASS_DEV_PM_OPS,
206 };
207 
208 /* Ensure the caller will set the id before releasing the device */
209 static struct rtc_device *rtc_allocate_device(void)
210 {
211 	struct rtc_device *rtc;
212 
213 	rtc = kzalloc_obj(*rtc);
214 	if (!rtc)
215 		return NULL;
216 
217 	device_initialize(&rtc->dev);
218 
219 	/*
220 	 * Drivers can revise this default after allocating the device.
221 	 * The default is what most RTCs do: Increment seconds exactly one
222 	 * second after the write happened. This adds a default transport
223 	 * time of 5ms which is at least halfways close to reality.
224 	 */
225 	rtc->set_offset_nsec = NSEC_PER_SEC + 5 * NSEC_PER_MSEC;
226 
227 	rtc->irq_freq = 1;
228 	rtc->max_user_freq = 64;
229 	rtc->dev.class = &rtc_class;
230 	rtc->dev.groups = rtc_get_dev_attribute_groups();
231 	rtc->dev.release = rtc_device_release;
232 
233 	mutex_init(&rtc->ops_lock);
234 	spin_lock_init(&rtc->irq_lock);
235 	init_waitqueue_head(&rtc->irq_queue);
236 
237 	/* Init timerqueue */
238 	timerqueue_init_head(&rtc->timerqueue);
239 	INIT_WORK(&rtc->irqwork, rtc_timer_do_work);
240 	/* Init aie timer */
241 	rtc_timer_init(&rtc->aie_timer, rtc_aie_update_irq, rtc);
242 	/* Init uie timer */
243 	rtc_timer_init(&rtc->uie_rtctimer, rtc_uie_update_irq, rtc);
244 	/* Init pie timer */
245 	hrtimer_setup(&rtc->pie_timer, rtc_pie_update_irq, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
246 	rtc->pie_enabled = 0;
247 
248 	set_bit(RTC_FEATURE_ALARM, rtc->features);
249 	set_bit(RTC_FEATURE_UPDATE_INTERRUPT, rtc->features);
250 
251 	return rtc;
252 }
253 
254 static int rtc_device_get_id(struct device *dev)
255 {
256 	int of_id = -1, id = -1;
257 
258 	if (dev->of_node)
259 		of_id = of_alias_get_id(dev->of_node, "rtc");
260 	else if (dev->parent && dev->parent->of_node)
261 		of_id = of_alias_get_id(dev->parent->of_node, "rtc");
262 
263 	if (of_id >= 0) {
264 		id = ida_alloc_range(&rtc_ida, of_id, of_id, GFP_KERNEL);
265 		if (id < 0)
266 			dev_warn(dev, "/aliases ID %d not available\n", of_id);
267 	}
268 
269 	if (id < 0)
270 		id = ida_alloc(&rtc_ida, GFP_KERNEL);
271 
272 	return id;
273 }
274 
275 static void rtc_device_get_offset(struct rtc_device *rtc)
276 {
277 	time64_t range_secs;
278 	u32 start_year;
279 	int ret;
280 
281 	/*
282 	 * If RTC driver did not implement the range of RTC hardware device,
283 	 * then we can not expand the RTC range by adding or subtracting one
284 	 * offset.
285 	 */
286 	if (rtc->range_min == rtc->range_max)
287 		return;
288 
289 	ret = device_property_read_u32(rtc->dev.parent, "start-year",
290 				       &start_year);
291 	if (!ret) {
292 		rtc->start_secs = mktime64(start_year, 1, 1, 0, 0, 0);
293 		rtc->set_start_time = true;
294 	}
295 
296 	/*
297 	 * If user did not implement the start time for RTC driver, then no
298 	 * need to expand the RTC range.
299 	 */
300 	if (!rtc->set_start_time)
301 		return;
302 
303 	range_secs = rtc->range_max - rtc->range_min + 1;
304 
305 	/*
306 	 * If the start_secs is larger than the maximum seconds (rtc->range_max)
307 	 * supported by RTC hardware or the maximum seconds of new expanded
308 	 * range (start_secs + rtc->range_max - rtc->range_min) is less than
309 	 * rtc->range_min, which means the minimum seconds (rtc->range_min) of
310 	 * RTC hardware will be mapped to start_secs by adding one offset, so
311 	 * the offset seconds calculation formula should be:
312 	 * rtc->offset_secs = rtc->start_secs - rtc->range_min;
313 	 *
314 	 * If the start_secs is larger than the minimum seconds (rtc->range_min)
315 	 * supported by RTC hardware, then there is one region is overlapped
316 	 * between the original RTC hardware range and the new expanded range,
317 	 * and this overlapped region do not need to be mapped into the new
318 	 * expanded range due to it is valid for RTC device. So the minimum
319 	 * seconds of RTC hardware (rtc->range_min) should be mapped to
320 	 * rtc->range_max + 1, then the offset seconds formula should be:
321 	 * rtc->offset_secs = rtc->range_max - rtc->range_min + 1;
322 	 *
323 	 * If the start_secs is less than the minimum seconds (rtc->range_min),
324 	 * which is similar to case 2. So the start_secs should be mapped to
325 	 * start_secs + rtc->range_max - rtc->range_min + 1, then the
326 	 * offset seconds formula should be:
327 	 * rtc->offset_secs = -(rtc->range_max - rtc->range_min + 1);
328 	 *
329 	 * Otherwise the offset seconds should be 0.
330 	 */
331 	if ((rtc->start_secs >= 0 && rtc->start_secs > rtc->range_max) ||
332 	    rtc->start_secs + range_secs - 1 < rtc->range_min)
333 		rtc->offset_secs = rtc->start_secs - rtc->range_min;
334 	else if (rtc->start_secs > rtc->range_min)
335 		rtc->offset_secs = range_secs;
336 	else if (rtc->start_secs < rtc->range_min)
337 		rtc->offset_secs = -range_secs;
338 	else
339 		rtc->offset_secs = 0;
340 }
341 
342 static void devm_rtc_unregister_device(void *data)
343 {
344 	struct rtc_device *rtc = data;
345 
346 	mutex_lock(&rtc->ops_lock);
347 	/*
348 	 * Remove innards of this RTC, then disable it, before
349 	 * letting any rtc_class_open() users access it again
350 	 */
351 	rtc_proc_del_device(rtc);
352 	if (!test_bit(RTC_NO_CDEV, &rtc->flags))
353 		cdev_device_del(&rtc->char_dev, &rtc->dev);
354 	rtc->ops = NULL;
355 	mutex_unlock(&rtc->ops_lock);
356 }
357 
358 static void devm_rtc_release_device(void *res)
359 {
360 	struct rtc_device *rtc = res;
361 
362 	put_device(&rtc->dev);
363 }
364 
365 struct rtc_device *devm_rtc_allocate_device(struct device *dev)
366 {
367 	struct rtc_device *rtc;
368 	int id, err;
369 
370 	id = rtc_device_get_id(dev);
371 	if (id < 0)
372 		return ERR_PTR(id);
373 
374 	rtc = rtc_allocate_device();
375 	if (!rtc) {
376 		ida_free(&rtc_ida, id);
377 		return ERR_PTR(-ENOMEM);
378 	}
379 
380 	rtc->id = id;
381 	rtc->dev.parent = dev;
382 	err = devm_add_action_or_reset(dev, devm_rtc_release_device, rtc);
383 	if (err)
384 		return ERR_PTR(err);
385 
386 	err = dev_set_name(&rtc->dev, "rtc%d", id);
387 	if (err)
388 		return ERR_PTR(err);
389 
390 	return rtc;
391 }
392 EXPORT_SYMBOL_GPL(devm_rtc_allocate_device);
393 
394 int __devm_rtc_register_device(struct module *owner, struct rtc_device *rtc)
395 {
396 	struct rtc_wkalrm alrm;
397 	int err;
398 
399 	if (!rtc->ops) {
400 		dev_dbg(&rtc->dev, "no ops set\n");
401 		return -EINVAL;
402 	}
403 
404 	if (!rtc->ops->set_alarm)
405 		clear_bit(RTC_FEATURE_ALARM, rtc->features);
406 
407 	if (rtc->ops->set_offset)
408 		set_bit(RTC_FEATURE_CORRECTION, rtc->features);
409 
410 	rtc->owner = owner;
411 	rtc_device_get_offset(rtc);
412 
413 	/* Check to see if there is an ALARM already set in hw */
414 	err = __rtc_read_alarm(rtc, &alrm);
415 	if (!err)
416 		rtc_initialize_alarm(rtc, &alrm);
417 
418 	rtc_dev_prepare(rtc);
419 
420 	err = cdev_device_add(&rtc->char_dev, &rtc->dev);
421 	if (err) {
422 		set_bit(RTC_NO_CDEV, &rtc->flags);
423 		dev_warn(rtc->dev.parent, "failed to add char device %d:%d\n",
424 			 MAJOR(rtc->dev.devt), rtc->id);
425 	} else {
426 		dev_dbg(rtc->dev.parent, "char device (%d:%d)\n",
427 			MAJOR(rtc->dev.devt), rtc->id);
428 	}
429 
430 	rtc_proc_add_device(rtc);
431 
432 	dev_info(rtc->dev.parent, "registered as %s\n",
433 		 dev_name(&rtc->dev));
434 
435 #ifdef CONFIG_RTC_HCTOSYS_DEVICE
436 	if (!strcmp(dev_name(&rtc->dev), CONFIG_RTC_HCTOSYS_DEVICE))
437 		rtc_hctosys(rtc);
438 #endif
439 
440 	return devm_add_action_or_reset(rtc->dev.parent,
441 					devm_rtc_unregister_device, rtc);
442 }
443 EXPORT_SYMBOL_GPL(__devm_rtc_register_device);
444 
445 /**
446  * devm_rtc_device_register - resource managed rtc_device_register()
447  * @dev: the device to register
448  * @name: the name of the device (unused)
449  * @ops: the rtc operations structure
450  * @owner: the module owner
451  *
452  * @return a struct rtc on success, or an ERR_PTR on error
453  *
454  * Managed rtc_device_register(). The rtc_device returned from this function
455  * are automatically freed on driver detach.
456  * This function is deprecated, use devm_rtc_allocate_device and
457  * rtc_register_device instead
458  */
459 struct rtc_device *devm_rtc_device_register(struct device *dev,
460 					    const char *name,
461 					    const struct rtc_class_ops *ops,
462 					    struct module *owner)
463 {
464 	struct rtc_device *rtc;
465 	int err;
466 
467 	rtc = devm_rtc_allocate_device(dev);
468 	if (IS_ERR(rtc))
469 		return rtc;
470 
471 	rtc->ops = ops;
472 
473 	err = __devm_rtc_register_device(owner, rtc);
474 	if (err)
475 		return ERR_PTR(err);
476 
477 	return rtc;
478 }
479 EXPORT_SYMBOL_GPL(devm_rtc_device_register);
480 
481 static int __init rtc_init(void)
482 {
483 	int err;
484 
485 	err = class_register(&rtc_class);
486 	if (err)
487 		return err;
488 
489 	rtc_dev_init();
490 
491 	return 0;
492 }
493 subsys_initcall(rtc_init);
494