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