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