xref: /linux/drivers/base/power/wakeup.c (revision be54f8c558027a218423134dd9b8c7c46d92204a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/power/wakeup.c - System wakeup events framework
4  *
5  * Copyright (c) 2010 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.
6  */
7 #define pr_fmt(fmt) "PM: " fmt
8 
9 #include <linux/device.h>
10 #include <linux/slab.h>
11 #include <linux/sched/signal.h>
12 #include <linux/capability.h>
13 #include <linux/export.h>
14 #include <linux/suspend.h>
15 #include <linux/seq_file.h>
16 #include <linux/debugfs.h>
17 #include <linux/pm_wakeirq.h>
18 #include <trace/events/power.h>
19 
20 #include "power.h"
21 
22 #define list_for_each_entry_rcu_locked(pos, head, member) \
23 	list_for_each_entry_rcu(pos, head, member, \
24 		srcu_read_lock_held(&wakeup_srcu))
25 /*
26  * If set, the suspend/hibernate code will abort transitions to a sleep state
27  * if wakeup events are registered during or immediately before the transition.
28  */
29 bool events_check_enabled __read_mostly;
30 
31 /* First wakeup IRQ seen by the kernel in the last cycle. */
32 static unsigned int wakeup_irq[2] __read_mostly;
33 static DEFINE_RAW_SPINLOCK(wakeup_irq_lock);
34 
35 /* If greater than 0 and the system is suspending, terminate the suspend. */
36 static atomic_t pm_abort_suspend __read_mostly;
37 
38 /*
39  * Combined counters of registered wakeup events and wakeup events in progress.
40  * They need to be modified together atomically, so it's better to use one
41  * atomic variable to hold them both.
42  */
43 static atomic_t combined_event_count = ATOMIC_INIT(0);
44 
45 #define IN_PROGRESS_BITS	(sizeof(int) * 4)
46 #define MAX_IN_PROGRESS		((1 << IN_PROGRESS_BITS) - 1)
47 
split_counters(unsigned int * cnt,unsigned int * inpr)48 static void split_counters(unsigned int *cnt, unsigned int *inpr)
49 {
50 	unsigned int comb = atomic_read(&combined_event_count);
51 
52 	*cnt = (comb >> IN_PROGRESS_BITS);
53 	*inpr = comb & MAX_IN_PROGRESS;
54 }
55 
56 /* A preserved old value of the events counter. */
57 static unsigned int saved_count;
58 
59 static DEFINE_RAW_SPINLOCK(events_lock);
60 
61 static void pm_wakeup_timer_fn(struct timer_list *t);
62 
63 static LIST_HEAD(wakeup_sources);
64 
65 static DECLARE_WAIT_QUEUE_HEAD(wakeup_count_wait_queue);
66 
67 DEFINE_STATIC_SRCU(wakeup_srcu);
68 
69 static struct wakeup_source deleted_ws = {
70 	.name = "deleted",
71 	.lock =  __SPIN_LOCK_UNLOCKED(deleted_ws.lock),
72 };
73 
74 static DEFINE_IDA(wakeup_ida);
75 
76 /**
77  * wakeup_source_create - Create a struct wakeup_source object.
78  * @name: Name of the new wakeup source.
79  */
wakeup_source_create(const char * name)80 static struct wakeup_source *wakeup_source_create(const char *name)
81 {
82 	struct wakeup_source *ws;
83 	const char *ws_name;
84 	int id;
85 
86 	ws = kzalloc(sizeof(*ws), GFP_KERNEL);
87 	if (!ws)
88 		goto err_ws;
89 
90 	ws_name = kstrdup_const(name, GFP_KERNEL);
91 	if (!ws_name)
92 		goto err_name;
93 	ws->name = ws_name;
94 
95 	id = ida_alloc(&wakeup_ida, GFP_KERNEL);
96 	if (id < 0)
97 		goto err_id;
98 	ws->id = id;
99 
100 	return ws;
101 
102 err_id:
103 	kfree_const(ws->name);
104 err_name:
105 	kfree(ws);
106 err_ws:
107 	return NULL;
108 }
109 
110 /*
111  * Record wakeup_source statistics being deleted into a dummy wakeup_source.
112  */
wakeup_source_record(struct wakeup_source * ws)113 static void wakeup_source_record(struct wakeup_source *ws)
114 {
115 	unsigned long flags;
116 
117 	spin_lock_irqsave(&deleted_ws.lock, flags);
118 
119 	if (ws->event_count) {
120 		deleted_ws.total_time =
121 			ktime_add(deleted_ws.total_time, ws->total_time);
122 		deleted_ws.prevent_sleep_time =
123 			ktime_add(deleted_ws.prevent_sleep_time,
124 				  ws->prevent_sleep_time);
125 		deleted_ws.max_time =
126 			ktime_compare(deleted_ws.max_time, ws->max_time) > 0 ?
127 				deleted_ws.max_time : ws->max_time;
128 		deleted_ws.event_count += ws->event_count;
129 		deleted_ws.active_count += ws->active_count;
130 		deleted_ws.relax_count += ws->relax_count;
131 		deleted_ws.expire_count += ws->expire_count;
132 		deleted_ws.wakeup_count += ws->wakeup_count;
133 	}
134 
135 	spin_unlock_irqrestore(&deleted_ws.lock, flags);
136 }
137 
wakeup_source_free(struct wakeup_source * ws)138 static void wakeup_source_free(struct wakeup_source *ws)
139 {
140 	ida_free(&wakeup_ida, ws->id);
141 	kfree_const(ws->name);
142 	kfree(ws);
143 }
144 
145 /**
146  * wakeup_source_destroy - Destroy a struct wakeup_source object.
147  * @ws: Wakeup source to destroy.
148  *
149  * Use only for wakeup source objects created with wakeup_source_create().
150  */
wakeup_source_destroy(struct wakeup_source * ws)151 static void wakeup_source_destroy(struct wakeup_source *ws)
152 {
153 	if (!ws)
154 		return;
155 
156 	__pm_relax(ws);
157 	wakeup_source_record(ws);
158 	wakeup_source_free(ws);
159 }
160 
161 /**
162  * wakeup_source_add - Add given object to the list of wakeup sources.
163  * @ws: Wakeup source object to add to the list.
164  */
wakeup_source_add(struct wakeup_source * ws)165 static void wakeup_source_add(struct wakeup_source *ws)
166 {
167 	unsigned long flags;
168 
169 	if (WARN_ON(!ws))
170 		return;
171 
172 	spin_lock_init(&ws->lock);
173 	timer_setup(&ws->timer, pm_wakeup_timer_fn, 0);
174 	ws->active = false;
175 
176 	raw_spin_lock_irqsave(&events_lock, flags);
177 	list_add_rcu(&ws->entry, &wakeup_sources);
178 	raw_spin_unlock_irqrestore(&events_lock, flags);
179 }
180 
181 /**
182  * wakeup_source_remove - Remove given object from the wakeup sources list.
183  * @ws: Wakeup source object to remove from the list.
184  */
wakeup_source_remove(struct wakeup_source * ws)185 static void wakeup_source_remove(struct wakeup_source *ws)
186 {
187 	unsigned long flags;
188 
189 	if (WARN_ON(!ws))
190 		return;
191 
192 	raw_spin_lock_irqsave(&events_lock, flags);
193 	list_del_rcu(&ws->entry);
194 	raw_spin_unlock_irqrestore(&events_lock, flags);
195 	synchronize_srcu(&wakeup_srcu);
196 
197 	timer_delete_sync(&ws->timer);
198 	/*
199 	 * Clear timer.function to make wakeup_source_not_registered() treat
200 	 * this wakeup source as not registered.
201 	 */
202 	ws->timer.function = NULL;
203 }
204 
205 /**
206  * wakeup_source_register - Create wakeup source and add it to the list.
207  * @dev: Device this wakeup source is associated with (or NULL if virtual).
208  * @name: Name of the wakeup source to register.
209  */
wakeup_source_register(struct device * dev,const char * name)210 struct wakeup_source *wakeup_source_register(struct device *dev,
211 					     const char *name)
212 {
213 	struct wakeup_source *ws;
214 	int ret;
215 
216 	ws = wakeup_source_create(name);
217 	if (ws) {
218 		if (!dev || device_is_registered(dev)) {
219 			ret = wakeup_source_sysfs_add(dev, ws);
220 			if (ret) {
221 				wakeup_source_free(ws);
222 				return NULL;
223 			}
224 		}
225 		wakeup_source_add(ws);
226 	}
227 	return ws;
228 }
229 EXPORT_SYMBOL_GPL(wakeup_source_register);
230 
231 /**
232  * wakeup_source_unregister - Remove wakeup source from the list and remove it.
233  * @ws: Wakeup source object to unregister.
234  */
wakeup_source_unregister(struct wakeup_source * ws)235 void wakeup_source_unregister(struct wakeup_source *ws)
236 {
237 	if (ws) {
238 		wakeup_source_remove(ws);
239 		if (ws->dev)
240 			wakeup_source_sysfs_remove(ws);
241 
242 		wakeup_source_destroy(ws);
243 	}
244 }
245 EXPORT_SYMBOL_GPL(wakeup_source_unregister);
246 
247 /**
248  * wakeup_sources_read_lock - Lock wakeup source list for read.
249  *
250  * Returns an index of srcu lock for struct wakeup_srcu.
251  * This index must be passed to the matching wakeup_sources_read_unlock().
252  */
wakeup_sources_read_lock(void)253 int wakeup_sources_read_lock(void)
254 {
255 	return srcu_read_lock(&wakeup_srcu);
256 }
257 EXPORT_SYMBOL_GPL(wakeup_sources_read_lock);
258 
259 /**
260  * wakeup_sources_read_unlock - Unlock wakeup source list.
261  * @idx: return value from corresponding wakeup_sources_read_lock()
262  */
wakeup_sources_read_unlock(int idx)263 void wakeup_sources_read_unlock(int idx)
264 {
265 	srcu_read_unlock(&wakeup_srcu, idx);
266 }
267 EXPORT_SYMBOL_GPL(wakeup_sources_read_unlock);
268 
269 /**
270  * wakeup_sources_walk_start - Begin a walk on wakeup source list
271  *
272  * Returns first object of the list of wakeup sources.
273  *
274  * Note that to be safe, wakeup sources list needs to be locked by calling
275  * wakeup_source_read_lock() for this.
276  */
wakeup_sources_walk_start(void)277 struct wakeup_source *wakeup_sources_walk_start(void)
278 {
279 	struct list_head *ws_head = &wakeup_sources;
280 
281 	return list_entry_rcu(ws_head->next, struct wakeup_source, entry);
282 }
283 EXPORT_SYMBOL_GPL(wakeup_sources_walk_start);
284 
285 /**
286  * wakeup_sources_walk_next - Get next wakeup source from the list
287  * @ws: Previous wakeup source object
288  *
289  * Note that to be safe, wakeup sources list needs to be locked by calling
290  * wakeup_source_read_lock() for this.
291  */
wakeup_sources_walk_next(struct wakeup_source * ws)292 struct wakeup_source *wakeup_sources_walk_next(struct wakeup_source *ws)
293 {
294 	struct list_head *ws_head = &wakeup_sources;
295 
296 	return list_next_or_null_rcu(ws_head, &ws->entry,
297 				struct wakeup_source, entry);
298 }
299 EXPORT_SYMBOL_GPL(wakeup_sources_walk_next);
300 
301 /**
302  * device_wakeup_attach - Attach a wakeup source object to a device object.
303  * @dev: Device to handle.
304  * @ws: Wakeup source object to attach to @dev.
305  *
306  * This causes @dev to be treated as a wakeup device.
307  */
device_wakeup_attach(struct device * dev,struct wakeup_source * ws)308 static int device_wakeup_attach(struct device *dev, struct wakeup_source *ws)
309 {
310 	spin_lock_irq(&dev->power.lock);
311 	if (dev->power.wakeup) {
312 		spin_unlock_irq(&dev->power.lock);
313 		return -EEXIST;
314 	}
315 	dev->power.wakeup = ws;
316 	if (dev->power.wakeirq)
317 		device_wakeup_attach_irq(dev, dev->power.wakeirq);
318 	spin_unlock_irq(&dev->power.lock);
319 	return 0;
320 }
321 
322 /**
323  * device_wakeup_enable - Enable given device to be a wakeup source.
324  * @dev: Device to handle.
325  *
326  * Create a wakeup source object, register it and attach it to @dev.
327  */
device_wakeup_enable(struct device * dev)328 int device_wakeup_enable(struct device *dev)
329 {
330 	struct wakeup_source *ws;
331 	int ret;
332 
333 	if (!dev || !dev->power.can_wakeup)
334 		return -EINVAL;
335 
336 	if (pm_sleep_transition_in_progress())
337 		dev_dbg(dev, "Suspicious %s() during system transition!\n", __func__);
338 
339 	ws = wakeup_source_register(dev, dev_name(dev));
340 	if (!ws)
341 		return -ENOMEM;
342 
343 	ret = device_wakeup_attach(dev, ws);
344 	if (ret)
345 		wakeup_source_unregister(ws);
346 
347 	return ret;
348 }
349 EXPORT_SYMBOL_GPL(device_wakeup_enable);
350 
351 /**
352  * device_wakeup_attach_irq - Attach a wakeirq to a wakeup source
353  * @dev: Device to handle
354  * @wakeirq: Device specific wakeirq entry
355  *
356  * Attach a device wakeirq to the wakeup source so the device
357  * wake IRQ can be configured automatically for suspend and
358  * resume.
359  *
360  * Call under the device's power.lock lock.
361  */
device_wakeup_attach_irq(struct device * dev,struct wake_irq * wakeirq)362 void device_wakeup_attach_irq(struct device *dev,
363 			     struct wake_irq *wakeirq)
364 {
365 	struct wakeup_source *ws;
366 
367 	ws = dev->power.wakeup;
368 	if (!ws)
369 		return;
370 
371 	if (ws->wakeirq)
372 		dev_err(dev, "Leftover wakeup IRQ found, overriding\n");
373 
374 	ws->wakeirq = wakeirq;
375 }
376 
377 /**
378  * device_wakeup_detach_irq - Detach a wakeirq from a wakeup source
379  * @dev: Device to handle
380  *
381  * Removes a device wakeirq from the wakeup source.
382  *
383  * Call under the device's power.lock lock.
384  */
device_wakeup_detach_irq(struct device * dev)385 void device_wakeup_detach_irq(struct device *dev)
386 {
387 	struct wakeup_source *ws;
388 
389 	ws = dev->power.wakeup;
390 	if (ws)
391 		ws->wakeirq = NULL;
392 }
393 
394 /**
395  * device_wakeup_arm_wake_irqs -
396  *
397  * Iterates over the list of device wakeirqs to arm them.
398  */
device_wakeup_arm_wake_irqs(void)399 void device_wakeup_arm_wake_irqs(void)
400 {
401 	struct wakeup_source *ws;
402 	int srcuidx;
403 
404 	srcuidx = srcu_read_lock(&wakeup_srcu);
405 	list_for_each_entry_rcu_locked(ws, &wakeup_sources, entry)
406 		dev_pm_arm_wake_irq(ws->wakeirq);
407 	srcu_read_unlock(&wakeup_srcu, srcuidx);
408 }
409 
410 /**
411  * device_wakeup_disarm_wake_irqs -
412  *
413  * Iterates over the list of device wakeirqs to disarm them.
414  */
device_wakeup_disarm_wake_irqs(void)415 void device_wakeup_disarm_wake_irqs(void)
416 {
417 	struct wakeup_source *ws;
418 	int srcuidx;
419 
420 	srcuidx = srcu_read_lock(&wakeup_srcu);
421 	list_for_each_entry_rcu_locked(ws, &wakeup_sources, entry)
422 		dev_pm_disarm_wake_irq(ws->wakeirq);
423 	srcu_read_unlock(&wakeup_srcu, srcuidx);
424 }
425 
426 /**
427  * device_wakeup_detach - Detach a device's wakeup source object from it.
428  * @dev: Device to detach the wakeup source object from.
429  *
430  * After it returns, @dev will not be treated as a wakeup device any more.
431  */
device_wakeup_detach(struct device * dev)432 static struct wakeup_source *device_wakeup_detach(struct device *dev)
433 {
434 	struct wakeup_source *ws;
435 
436 	spin_lock_irq(&dev->power.lock);
437 	ws = dev->power.wakeup;
438 	dev->power.wakeup = NULL;
439 	spin_unlock_irq(&dev->power.lock);
440 	return ws;
441 }
442 
443 /**
444  * device_wakeup_disable - Do not regard a device as a wakeup source any more.
445  * @dev: Device to handle.
446  *
447  * Detach the @dev's wakeup source object from it, unregister this wakeup source
448  * object and destroy it.
449  */
device_wakeup_disable(struct device * dev)450 void device_wakeup_disable(struct device *dev)
451 {
452 	struct wakeup_source *ws;
453 
454 	if (!dev || !dev->power.can_wakeup)
455 		return;
456 
457 	ws = device_wakeup_detach(dev);
458 	wakeup_source_unregister(ws);
459 }
460 EXPORT_SYMBOL_GPL(device_wakeup_disable);
461 
462 /**
463  * device_set_wakeup_capable - Set/reset device wakeup capability flag.
464  * @dev: Device to handle.
465  * @capable: Whether or not @dev is capable of waking up the system from sleep.
466  *
467  * If @capable is set, set the @dev's power.can_wakeup flag and add its
468  * wakeup-related attributes to sysfs.  Otherwise, unset the @dev's
469  * power.can_wakeup flag and remove its wakeup-related attributes from sysfs.
470  *
471  * This function may sleep and it can't be called from any context where
472  * sleeping is not allowed.
473  */
device_set_wakeup_capable(struct device * dev,bool capable)474 void device_set_wakeup_capable(struct device *dev, bool capable)
475 {
476 	if (!!dev->power.can_wakeup == !!capable)
477 		return;
478 
479 	dev->power.can_wakeup = capable;
480 	if (device_is_registered(dev) && !list_empty(&dev->power.entry)) {
481 		if (capable) {
482 			int ret = wakeup_sysfs_add(dev);
483 
484 			if (ret)
485 				dev_info(dev, "Wakeup sysfs attributes not added\n");
486 		} else {
487 			wakeup_sysfs_remove(dev);
488 		}
489 	}
490 }
491 EXPORT_SYMBOL_GPL(device_set_wakeup_capable);
492 
493 /**
494  * device_set_wakeup_enable - Enable or disable a device to wake up the system.
495  * @dev: Device to handle.
496  * @enable: enable/disable flag
497  */
device_set_wakeup_enable(struct device * dev,bool enable)498 int device_set_wakeup_enable(struct device *dev, bool enable)
499 {
500 	if (enable)
501 		return device_wakeup_enable(dev);
502 
503 	device_wakeup_disable(dev);
504 	return 0;
505 }
506 EXPORT_SYMBOL_GPL(device_set_wakeup_enable);
507 
508 /**
509  * wakeup_source_not_registered - validate the given wakeup source.
510  * @ws: Wakeup source to be validated.
511  */
wakeup_source_not_registered(struct wakeup_source * ws)512 static bool wakeup_source_not_registered(struct wakeup_source *ws)
513 {
514 	/*
515 	 * Use timer struct to check if the given source is initialized
516 	 * by wakeup_source_add.
517 	 */
518 	return ws->timer.function != pm_wakeup_timer_fn;
519 }
520 
521 /*
522  * The functions below use the observation that each wakeup event starts a
523  * period in which the system should not be suspended.  The moment this period
524  * will end depends on how the wakeup event is going to be processed after being
525  * detected and all of the possible cases can be divided into two distinct
526  * groups.
527  *
528  * First, a wakeup event may be detected by the same functional unit that will
529  * carry out the entire processing of it and possibly will pass it to user space
530  * for further processing.  In that case the functional unit that has detected
531  * the event may later "close" the "no suspend" period associated with it
532  * directly as soon as it has been dealt with.  The pair of pm_stay_awake() and
533  * pm_relax(), balanced with each other, is supposed to be used in such
534  * situations.
535  *
536  * Second, a wakeup event may be detected by one functional unit and processed
537  * by another one.  In that case the unit that has detected it cannot really
538  * "close" the "no suspend" period associated with it, unless it knows in
539  * advance what's going to happen to the event during processing.  This
540  * knowledge, however, may not be available to it, so it can simply specify time
541  * to wait before the system can be suspended and pass it as the second
542  * argument of pm_wakeup_event().
543  *
544  * It is valid to call pm_relax() after pm_wakeup_event(), in which case the
545  * "no suspend" period will be ended either by the pm_relax(), or by the timer
546  * function executed when the timer expires, whichever comes first.
547  */
548 
549 /**
550  * wakeup_source_activate - Mark given wakeup source as active.
551  * @ws: Wakeup source to handle.
552  *
553  * Update the @ws' statistics and, if @ws has just been activated, notify the PM
554  * core of the event by incrementing the counter of the wakeup events being
555  * processed.
556  */
wakeup_source_activate(struct wakeup_source * ws)557 static void wakeup_source_activate(struct wakeup_source *ws)
558 {
559 	unsigned int cec;
560 
561 	if (WARN_ONCE(wakeup_source_not_registered(ws),
562 			"unregistered wakeup source\n"))
563 		return;
564 
565 	ws->active = true;
566 	ws->active_count++;
567 	ws->last_time = ktime_get();
568 	if (ws->autosleep_enabled)
569 		ws->start_prevent_time = ws->last_time;
570 
571 	/* Increment the counter of events in progress. */
572 	cec = atomic_inc_return(&combined_event_count);
573 
574 	trace_wakeup_source_activate(ws->name, cec);
575 }
576 
577 /**
578  * wakeup_source_report_event - Report wakeup event using the given source.
579  * @ws: Wakeup source to report the event for.
580  * @hard: If set, abort suspends in progress and wake up from suspend-to-idle.
581  */
wakeup_source_report_event(struct wakeup_source * ws,bool hard)582 static void wakeup_source_report_event(struct wakeup_source *ws, bool hard)
583 {
584 	ws->event_count++;
585 	/* This is racy, but the counter is approximate anyway. */
586 	if (events_check_enabled)
587 		ws->wakeup_count++;
588 
589 	if (!ws->active)
590 		wakeup_source_activate(ws);
591 
592 	if (hard)
593 		pm_system_wakeup();
594 }
595 
596 /**
597  * __pm_stay_awake - Notify the PM core of a wakeup event.
598  * @ws: Wakeup source object associated with the source of the event.
599  *
600  * It is safe to call this function from interrupt context.
601  */
__pm_stay_awake(struct wakeup_source * ws)602 void __pm_stay_awake(struct wakeup_source *ws)
603 {
604 	unsigned long flags;
605 
606 	if (!ws)
607 		return;
608 
609 	spin_lock_irqsave(&ws->lock, flags);
610 
611 	wakeup_source_report_event(ws, false);
612 	timer_delete(&ws->timer);
613 	ws->timer_expires = 0;
614 
615 	spin_unlock_irqrestore(&ws->lock, flags);
616 }
617 EXPORT_SYMBOL_GPL(__pm_stay_awake);
618 
619 /**
620  * pm_stay_awake - Notify the PM core that a wakeup event is being processed.
621  * @dev: Device the wakeup event is related to.
622  *
623  * Notify the PM core of a wakeup event (signaled by @dev) by calling
624  * __pm_stay_awake for the @dev's wakeup source object.
625  *
626  * Call this function after detecting of a wakeup event if pm_relax() is going
627  * to be called directly after processing the event (and possibly passing it to
628  * user space for further processing).
629  */
pm_stay_awake(struct device * dev)630 void pm_stay_awake(struct device *dev)
631 {
632 	unsigned long flags;
633 
634 	if (!dev)
635 		return;
636 
637 	spin_lock_irqsave(&dev->power.lock, flags);
638 	__pm_stay_awake(dev->power.wakeup);
639 	spin_unlock_irqrestore(&dev->power.lock, flags);
640 }
641 EXPORT_SYMBOL_GPL(pm_stay_awake);
642 
643 #ifdef CONFIG_PM_AUTOSLEEP
update_prevent_sleep_time(struct wakeup_source * ws,ktime_t now)644 static void update_prevent_sleep_time(struct wakeup_source *ws, ktime_t now)
645 {
646 	ktime_t delta = ktime_sub(now, ws->start_prevent_time);
647 	ws->prevent_sleep_time = ktime_add(ws->prevent_sleep_time, delta);
648 }
649 #else
update_prevent_sleep_time(struct wakeup_source * ws,ktime_t now)650 static inline void update_prevent_sleep_time(struct wakeup_source *ws,
651 					     ktime_t now) {}
652 #endif
653 
654 /**
655  * wakeup_source_deactivate - Mark given wakeup source as inactive.
656  * @ws: Wakeup source to handle.
657  *
658  * Update the @ws' statistics and notify the PM core that the wakeup source has
659  * become inactive by decrementing the counter of wakeup events being processed
660  * and incrementing the counter of registered wakeup events.
661  */
wakeup_source_deactivate(struct wakeup_source * ws)662 static void wakeup_source_deactivate(struct wakeup_source *ws)
663 {
664 	unsigned int cnt, inpr, cec;
665 	ktime_t duration;
666 	ktime_t now;
667 
668 	ws->relax_count++;
669 	/*
670 	 * __pm_relax() may be called directly or from a timer function.
671 	 * If it is called directly right after the timer function has been
672 	 * started, but before the timer function calls __pm_relax(), it is
673 	 * possible that __pm_stay_awake() will be called in the meantime and
674 	 * will set ws->active.  Then, ws->active may be cleared immediately
675 	 * by the __pm_relax() called from the timer function, but in such a
676 	 * case ws->relax_count will be different from ws->active_count.
677 	 */
678 	if (ws->relax_count != ws->active_count) {
679 		ws->relax_count--;
680 		return;
681 	}
682 
683 	ws->active = false;
684 
685 	now = ktime_get();
686 	duration = ktime_sub(now, ws->last_time);
687 	ws->total_time = ktime_add(ws->total_time, duration);
688 	if (ktime_to_ns(duration) > ktime_to_ns(ws->max_time))
689 		ws->max_time = duration;
690 
691 	ws->last_time = now;
692 	timer_delete(&ws->timer);
693 	ws->timer_expires = 0;
694 
695 	if (ws->autosleep_enabled)
696 		update_prevent_sleep_time(ws, now);
697 
698 	/*
699 	 * Increment the counter of registered wakeup events and decrement the
700 	 * counter of wakeup events in progress simultaneously.
701 	 */
702 	cec = atomic_add_return(MAX_IN_PROGRESS, &combined_event_count);
703 	trace_wakeup_source_deactivate(ws->name, cec);
704 
705 	split_counters(&cnt, &inpr);
706 	if (!inpr && waitqueue_active(&wakeup_count_wait_queue))
707 		wake_up(&wakeup_count_wait_queue);
708 }
709 
710 /**
711  * __pm_relax - Notify the PM core that processing of a wakeup event has ended.
712  * @ws: Wakeup source object associated with the source of the event.
713  *
714  * Call this function for wakeup events whose processing started with calling
715  * __pm_stay_awake().
716  *
717  * It is safe to call it from interrupt context.
718  */
__pm_relax(struct wakeup_source * ws)719 void __pm_relax(struct wakeup_source *ws)
720 {
721 	unsigned long flags;
722 
723 	if (!ws)
724 		return;
725 
726 	spin_lock_irqsave(&ws->lock, flags);
727 	if (ws->active)
728 		wakeup_source_deactivate(ws);
729 	spin_unlock_irqrestore(&ws->lock, flags);
730 }
731 EXPORT_SYMBOL_GPL(__pm_relax);
732 
733 /**
734  * pm_relax - Notify the PM core that processing of a wakeup event has ended.
735  * @dev: Device that signaled the event.
736  *
737  * Execute __pm_relax() for the @dev's wakeup source object.
738  */
pm_relax(struct device * dev)739 void pm_relax(struct device *dev)
740 {
741 	unsigned long flags;
742 
743 	if (!dev)
744 		return;
745 
746 	spin_lock_irqsave(&dev->power.lock, flags);
747 	__pm_relax(dev->power.wakeup);
748 	spin_unlock_irqrestore(&dev->power.lock, flags);
749 }
750 EXPORT_SYMBOL_GPL(pm_relax);
751 
752 /**
753  * pm_wakeup_timer_fn - Delayed finalization of a wakeup event.
754  * @t: timer list
755  *
756  * Call wakeup_source_deactivate() for the wakeup source whose address is stored
757  * in @data if it is currently active and its timer has not been canceled and
758  * the expiration time of the timer is not in future.
759  */
pm_wakeup_timer_fn(struct timer_list * t)760 static void pm_wakeup_timer_fn(struct timer_list *t)
761 {
762 	struct wakeup_source *ws = timer_container_of(ws, t, timer);
763 	unsigned long flags;
764 
765 	spin_lock_irqsave(&ws->lock, flags);
766 
767 	if (ws->active && ws->timer_expires
768 	    && time_after_eq(jiffies, ws->timer_expires)) {
769 		wakeup_source_deactivate(ws);
770 		ws->expire_count++;
771 	}
772 
773 	spin_unlock_irqrestore(&ws->lock, flags);
774 }
775 
776 /**
777  * pm_wakeup_ws_event - Notify the PM core of a wakeup event.
778  * @ws: Wakeup source object associated with the event source.
779  * @msec: Anticipated event processing time (in milliseconds).
780  * @hard: If set, abort suspends in progress and wake up from suspend-to-idle.
781  *
782  * Notify the PM core of a wakeup event whose source is @ws that will take
783  * approximately @msec milliseconds to be processed by the kernel.  If @ws is
784  * not active, activate it.  If @msec is nonzero, set up the @ws' timer to
785  * execute pm_wakeup_timer_fn() in future.
786  *
787  * It is safe to call this function from interrupt context.
788  */
pm_wakeup_ws_event(struct wakeup_source * ws,unsigned int msec,bool hard)789 void pm_wakeup_ws_event(struct wakeup_source *ws, unsigned int msec, bool hard)
790 {
791 	unsigned long flags;
792 	unsigned long expires;
793 
794 	if (!ws)
795 		return;
796 
797 	spin_lock_irqsave(&ws->lock, flags);
798 
799 	wakeup_source_report_event(ws, hard);
800 
801 	if (!msec) {
802 		wakeup_source_deactivate(ws);
803 		goto unlock;
804 	}
805 
806 	expires = jiffies + msecs_to_jiffies(msec);
807 	if (!expires)
808 		expires = 1;
809 
810 	if (!ws->timer_expires || time_after(expires, ws->timer_expires)) {
811 		mod_timer(&ws->timer, expires);
812 		ws->timer_expires = expires;
813 	}
814 
815  unlock:
816 	spin_unlock_irqrestore(&ws->lock, flags);
817 }
818 EXPORT_SYMBOL_GPL(pm_wakeup_ws_event);
819 
820 /**
821  * pm_wakeup_dev_event - Notify the PM core of a wakeup event.
822  * @dev: Device the wakeup event is related to.
823  * @msec: Anticipated event processing time (in milliseconds).
824  * @hard: If set, abort suspends in progress and wake up from suspend-to-idle.
825  *
826  * Call pm_wakeup_ws_event() for the @dev's wakeup source object.
827  */
pm_wakeup_dev_event(struct device * dev,unsigned int msec,bool hard)828 void pm_wakeup_dev_event(struct device *dev, unsigned int msec, bool hard)
829 {
830 	unsigned long flags;
831 
832 	if (!dev)
833 		return;
834 
835 	spin_lock_irqsave(&dev->power.lock, flags);
836 	pm_wakeup_ws_event(dev->power.wakeup, msec, hard);
837 	spin_unlock_irqrestore(&dev->power.lock, flags);
838 }
839 EXPORT_SYMBOL_GPL(pm_wakeup_dev_event);
840 
pm_print_active_wakeup_sources(void)841 void pm_print_active_wakeup_sources(void)
842 {
843 	struct wakeup_source *ws;
844 	int srcuidx, active = 0;
845 	struct wakeup_source *last_activity_ws = NULL;
846 
847 	srcuidx = srcu_read_lock(&wakeup_srcu);
848 	list_for_each_entry_rcu_locked(ws, &wakeup_sources, entry) {
849 		if (ws->active) {
850 			pm_pr_dbg("active wakeup source: %s\n", ws->name);
851 			active = 1;
852 		} else if (!active &&
853 			   (!last_activity_ws ||
854 			    ktime_to_ns(ws->last_time) >
855 			    ktime_to_ns(last_activity_ws->last_time))) {
856 			last_activity_ws = ws;
857 		}
858 	}
859 
860 	if (!active && last_activity_ws)
861 		pm_pr_dbg("last active wakeup source: %s\n",
862 			last_activity_ws->name);
863 	srcu_read_unlock(&wakeup_srcu, srcuidx);
864 }
865 EXPORT_SYMBOL_GPL(pm_print_active_wakeup_sources);
866 
867 /**
868  * pm_wakeup_pending - Check if power transition in progress should be aborted.
869  *
870  * Compare the current number of registered wakeup events with its preserved
871  * value from the past and return true if new wakeup events have been registered
872  * since the old value was stored.  Also return true if the current number of
873  * wakeup events being processed is different from zero.
874  */
pm_wakeup_pending(void)875 bool pm_wakeup_pending(void)
876 {
877 	unsigned long flags;
878 	bool ret = false;
879 
880 	raw_spin_lock_irqsave(&events_lock, flags);
881 	if (events_check_enabled) {
882 		unsigned int cnt, inpr;
883 
884 		split_counters(&cnt, &inpr);
885 		ret = (cnt != saved_count || inpr > 0);
886 		events_check_enabled = !ret;
887 	}
888 	raw_spin_unlock_irqrestore(&events_lock, flags);
889 
890 	if (ret) {
891 		pm_pr_dbg("Wakeup pending, aborting suspend\n");
892 		pm_print_active_wakeup_sources();
893 	}
894 
895 	return ret || atomic_read(&pm_abort_suspend) > 0;
896 }
897 EXPORT_SYMBOL_GPL(pm_wakeup_pending);
898 
pm_system_wakeup(void)899 void pm_system_wakeup(void)
900 {
901 	atomic_inc(&pm_abort_suspend);
902 	s2idle_wake();
903 }
904 EXPORT_SYMBOL_GPL(pm_system_wakeup);
905 
pm_system_cancel_wakeup(void)906 void pm_system_cancel_wakeup(void)
907 {
908 	atomic_dec_if_positive(&pm_abort_suspend);
909 }
910 
pm_wakeup_clear(unsigned int irq_number)911 void pm_wakeup_clear(unsigned int irq_number)
912 {
913 	raw_spin_lock_irq(&wakeup_irq_lock);
914 
915 	if (irq_number && wakeup_irq[0] == irq_number)
916 		wakeup_irq[0] = wakeup_irq[1];
917 	else
918 		wakeup_irq[0] = 0;
919 
920 	wakeup_irq[1] = 0;
921 
922 	raw_spin_unlock_irq(&wakeup_irq_lock);
923 
924 	if (!irq_number)
925 		atomic_set(&pm_abort_suspend, 0);
926 }
927 
pm_system_irq_wakeup(unsigned int irq_number)928 void pm_system_irq_wakeup(unsigned int irq_number)
929 {
930 	unsigned long flags;
931 
932 	raw_spin_lock_irqsave(&wakeup_irq_lock, flags);
933 
934 	if (wakeup_irq[0] == 0)
935 		wakeup_irq[0] = irq_number;
936 	else if (wakeup_irq[1] == 0)
937 		wakeup_irq[1] = irq_number;
938 	else
939 		irq_number = 0;
940 
941 	pm_pr_dbg("Triggering wakeup from IRQ %d\n", irq_number);
942 
943 	raw_spin_unlock_irqrestore(&wakeup_irq_lock, flags);
944 
945 	if (irq_number)
946 		pm_system_wakeup();
947 }
948 
pm_wakeup_irq(void)949 unsigned int pm_wakeup_irq(void)
950 {
951 	return wakeup_irq[0];
952 }
953 
954 /**
955  * pm_get_wakeup_count - Read the number of registered wakeup events.
956  * @count: Address to store the value at.
957  * @block: Whether or not to block.
958  *
959  * Store the number of registered wakeup events at the address in @count.  If
960  * @block is set, block until the current number of wakeup events being
961  * processed is zero.
962  *
963  * Return 'false' if the current number of wakeup events being processed is
964  * nonzero.  Otherwise return 'true'.
965  */
pm_get_wakeup_count(unsigned int * count,bool block)966 bool pm_get_wakeup_count(unsigned int *count, bool block)
967 {
968 	unsigned int cnt, inpr;
969 
970 	if (block) {
971 		DEFINE_WAIT(wait);
972 
973 		for (;;) {
974 			prepare_to_wait(&wakeup_count_wait_queue, &wait,
975 					TASK_INTERRUPTIBLE);
976 			split_counters(&cnt, &inpr);
977 			if (inpr == 0 || signal_pending(current))
978 				break;
979 			pm_print_active_wakeup_sources();
980 			schedule();
981 		}
982 		finish_wait(&wakeup_count_wait_queue, &wait);
983 	}
984 
985 	split_counters(&cnt, &inpr);
986 	*count = cnt;
987 	return !inpr;
988 }
989 
990 /**
991  * pm_save_wakeup_count - Save the current number of registered wakeup events.
992  * @count: Value to compare with the current number of registered wakeup events.
993  *
994  * If @count is equal to the current number of registered wakeup events and the
995  * current number of wakeup events being processed is zero, store @count as the
996  * old number of registered wakeup events for pm_check_wakeup_events(), enable
997  * wakeup events detection and return 'true'.  Otherwise disable wakeup events
998  * detection and return 'false'.
999  */
pm_save_wakeup_count(unsigned int count)1000 bool pm_save_wakeup_count(unsigned int count)
1001 {
1002 	unsigned int cnt, inpr;
1003 	unsigned long flags;
1004 
1005 	events_check_enabled = false;
1006 	raw_spin_lock_irqsave(&events_lock, flags);
1007 	split_counters(&cnt, &inpr);
1008 	if (cnt == count && inpr == 0) {
1009 		saved_count = count;
1010 		events_check_enabled = true;
1011 	}
1012 	raw_spin_unlock_irqrestore(&events_lock, flags);
1013 	return events_check_enabled;
1014 }
1015 
1016 #ifdef CONFIG_PM_AUTOSLEEP
1017 /**
1018  * pm_wakep_autosleep_enabled - Modify autosleep_enabled for all wakeup sources.
1019  * @set: Whether to set or to clear the autosleep_enabled flags.
1020  */
pm_wakep_autosleep_enabled(bool set)1021 void pm_wakep_autosleep_enabled(bool set)
1022 {
1023 	struct wakeup_source *ws;
1024 	ktime_t now = ktime_get();
1025 	int srcuidx;
1026 
1027 	srcuidx = srcu_read_lock(&wakeup_srcu);
1028 	list_for_each_entry_rcu_locked(ws, &wakeup_sources, entry) {
1029 		spin_lock_irq(&ws->lock);
1030 		if (ws->autosleep_enabled != set) {
1031 			ws->autosleep_enabled = set;
1032 			if (ws->active) {
1033 				if (set)
1034 					ws->start_prevent_time = now;
1035 				else
1036 					update_prevent_sleep_time(ws, now);
1037 			}
1038 		}
1039 		spin_unlock_irq(&ws->lock);
1040 	}
1041 	srcu_read_unlock(&wakeup_srcu, srcuidx);
1042 }
1043 #endif /* CONFIG_PM_AUTOSLEEP */
1044 
1045 /**
1046  * print_wakeup_source_stats - Print wakeup source statistics information.
1047  * @m: seq_file to print the statistics into.
1048  * @ws: Wakeup source object to print the statistics for.
1049  */
print_wakeup_source_stats(struct seq_file * m,struct wakeup_source * ws)1050 static int print_wakeup_source_stats(struct seq_file *m,
1051 				     struct wakeup_source *ws)
1052 {
1053 	unsigned long flags;
1054 	ktime_t total_time;
1055 	ktime_t max_time;
1056 	unsigned long active_count;
1057 	ktime_t active_time;
1058 	ktime_t prevent_sleep_time;
1059 
1060 	spin_lock_irqsave(&ws->lock, flags);
1061 
1062 	total_time = ws->total_time;
1063 	max_time = ws->max_time;
1064 	prevent_sleep_time = ws->prevent_sleep_time;
1065 	active_count = ws->active_count;
1066 	if (ws->active) {
1067 		ktime_t now = ktime_get();
1068 
1069 		active_time = ktime_sub(now, ws->last_time);
1070 		total_time = ktime_add(total_time, active_time);
1071 		if (active_time > max_time)
1072 			max_time = active_time;
1073 
1074 		if (ws->autosleep_enabled)
1075 			prevent_sleep_time = ktime_add(prevent_sleep_time,
1076 				ktime_sub(now, ws->start_prevent_time));
1077 	} else {
1078 		active_time = 0;
1079 	}
1080 
1081 	seq_printf(m, "%-12s\t%lu\t\t%lu\t\t%lu\t\t%lu\t\t%lld\t\t%lld\t\t%lld\t\t%lld\t\t%lld\n",
1082 		   ws->name, active_count, ws->event_count,
1083 		   ws->wakeup_count, ws->expire_count,
1084 		   ktime_to_ms(active_time), ktime_to_ms(total_time),
1085 		   ktime_to_ms(max_time), ktime_to_ms(ws->last_time),
1086 		   ktime_to_ms(prevent_sleep_time));
1087 
1088 	spin_unlock_irqrestore(&ws->lock, flags);
1089 
1090 	return 0;
1091 }
1092 
wakeup_sources_stats_seq_start(struct seq_file * m,loff_t * pos)1093 static void *wakeup_sources_stats_seq_start(struct seq_file *m,
1094 					loff_t *pos)
1095 {
1096 	struct wakeup_source *ws;
1097 	loff_t n = *pos;
1098 	int *srcuidx = m->private;
1099 
1100 	if (n == 0) {
1101 		seq_puts(m, "name\t\tactive_count\tevent_count\twakeup_count\t"
1102 			"expire_count\tactive_since\ttotal_time\tmax_time\t"
1103 			"last_change\tprevent_suspend_time\n");
1104 	}
1105 
1106 	*srcuidx = srcu_read_lock(&wakeup_srcu);
1107 	list_for_each_entry_rcu_locked(ws, &wakeup_sources, entry) {
1108 		if (n-- <= 0)
1109 			return ws;
1110 	}
1111 
1112 	return NULL;
1113 }
1114 
wakeup_sources_stats_seq_next(struct seq_file * m,void * v,loff_t * pos)1115 static void *wakeup_sources_stats_seq_next(struct seq_file *m,
1116 					void *v, loff_t *pos)
1117 {
1118 	struct wakeup_source *ws = v;
1119 	struct wakeup_source *next_ws = NULL;
1120 
1121 	++(*pos);
1122 
1123 	list_for_each_entry_continue_rcu(ws, &wakeup_sources, entry) {
1124 		next_ws = ws;
1125 		break;
1126 	}
1127 
1128 	if (!next_ws)
1129 		print_wakeup_source_stats(m, &deleted_ws);
1130 
1131 	return next_ws;
1132 }
1133 
wakeup_sources_stats_seq_stop(struct seq_file * m,void * v)1134 static void wakeup_sources_stats_seq_stop(struct seq_file *m, void *v)
1135 {
1136 	int *srcuidx = m->private;
1137 
1138 	srcu_read_unlock(&wakeup_srcu, *srcuidx);
1139 }
1140 
1141 /**
1142  * wakeup_sources_stats_seq_show - Print wakeup sources statistics information.
1143  * @m: seq_file to print the statistics into.
1144  * @v: wakeup_source of each iteration
1145  */
wakeup_sources_stats_seq_show(struct seq_file * m,void * v)1146 static int wakeup_sources_stats_seq_show(struct seq_file *m, void *v)
1147 {
1148 	struct wakeup_source *ws = v;
1149 
1150 	print_wakeup_source_stats(m, ws);
1151 
1152 	return 0;
1153 }
1154 
1155 static const struct seq_operations wakeup_sources_stats_seq_ops = {
1156 	.start = wakeup_sources_stats_seq_start,
1157 	.next  = wakeup_sources_stats_seq_next,
1158 	.stop  = wakeup_sources_stats_seq_stop,
1159 	.show  = wakeup_sources_stats_seq_show,
1160 };
1161 
wakeup_sources_stats_open(struct inode * inode,struct file * file)1162 static int wakeup_sources_stats_open(struct inode *inode, struct file *file)
1163 {
1164 	return seq_open_private(file, &wakeup_sources_stats_seq_ops, sizeof(int));
1165 }
1166 
1167 static const struct file_operations wakeup_sources_stats_fops = {
1168 	.owner = THIS_MODULE,
1169 	.open = wakeup_sources_stats_open,
1170 	.read = seq_read,
1171 	.llseek = seq_lseek,
1172 	.release = seq_release_private,
1173 };
1174 
wakeup_sources_debugfs_init(void)1175 static int __init wakeup_sources_debugfs_init(void)
1176 {
1177 	debugfs_create_file("wakeup_sources", 0444, NULL, NULL,
1178 			    &wakeup_sources_stats_fops);
1179 	return 0;
1180 }
1181 
1182 postcore_initcall(wakeup_sources_debugfs_init);
1183