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