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