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