• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/power/runtime.c - Helper functions for device runtime PM
4  *
5  * Copyright (c) 2009 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.
6  * Copyright (C) 2010 Alan Stern <stern@rowland.harvard.edu>
7  */
8 #include <linux/sched/mm.h>
9 #include <linux/ktime.h>
10 #include <linux/hrtimer.h>
11 #include <linux/export.h>
12 #include <linux/pm_runtime.h>
13 #include <linux/pm_wakeirq.h>
14 #include <trace/events/rpm.h>
15 
16 #include "../base.h"
17 #include "power.h"
18 
19 typedef int (*pm_callback_t)(struct device *);
20 
__rpm_get_callback(struct device * dev,size_t cb_offset)21 static pm_callback_t __rpm_get_callback(struct device *dev, size_t cb_offset)
22 {
23 	pm_callback_t cb;
24 	const struct dev_pm_ops *ops;
25 
26 	if (dev->pm_domain)
27 		ops = &dev->pm_domain->ops;
28 	else if (dev->type && dev->type->pm)
29 		ops = dev->type->pm;
30 	else if (dev->class && dev->class->pm)
31 		ops = dev->class->pm;
32 	else if (dev->bus && dev->bus->pm)
33 		ops = dev->bus->pm;
34 	else
35 		ops = NULL;
36 
37 	if (ops)
38 		cb = *(pm_callback_t *)((void *)ops + cb_offset);
39 	else
40 		cb = NULL;
41 
42 	if (!cb && dev->driver && dev->driver->pm)
43 		cb = *(pm_callback_t *)((void *)dev->driver->pm + cb_offset);
44 
45 	return cb;
46 }
47 
48 #define RPM_GET_CALLBACK(dev, callback) \
49 		__rpm_get_callback(dev, offsetof(struct dev_pm_ops, callback))
50 
51 static int rpm_resume(struct device *dev, int rpmflags);
52 static int rpm_suspend(struct device *dev, int rpmflags);
53 
54 /**
55  * update_pm_runtime_accounting - Update the time accounting of power states
56  * @dev: Device to update the accounting for
57  *
58  * In order to be able to have time accounting of the various power states
59  * (as used by programs such as PowerTOP to show the effectiveness of runtime
60  * PM), we need to track the time spent in each state.
61  * update_pm_runtime_accounting must be called each time before the
62  * runtime_status field is updated, to account the time in the old state
63  * correctly.
64  */
update_pm_runtime_accounting(struct device * dev)65 static void update_pm_runtime_accounting(struct device *dev)
66 {
67 	u64 now, last, delta;
68 
69 	if (dev->power.disable_depth > 0)
70 		return;
71 
72 	last = dev->power.accounting_timestamp;
73 
74 	now = ktime_get_mono_fast_ns();
75 	dev->power.accounting_timestamp = now;
76 
77 	/*
78 	 * Because ktime_get_mono_fast_ns() is not monotonic during
79 	 * timekeeping updates, ensure that 'now' is after the last saved
80 	 * timesptamp.
81 	 */
82 	if (now < last)
83 		return;
84 
85 	delta = now - last;
86 
87 	if (dev->power.runtime_status == RPM_SUSPENDED)
88 		dev->power.suspended_time += delta;
89 	else
90 		dev->power.active_time += delta;
91 }
92 
__update_runtime_status(struct device * dev,enum rpm_status status)93 static void __update_runtime_status(struct device *dev, enum rpm_status status)
94 {
95 	update_pm_runtime_accounting(dev);
96 	dev->power.runtime_status = status;
97 }
98 
rpm_get_accounted_time(struct device * dev,bool suspended)99 static u64 rpm_get_accounted_time(struct device *dev, bool suspended)
100 {
101 	u64 time;
102 	unsigned long flags;
103 
104 	spin_lock_irqsave(&dev->power.lock, flags);
105 
106 	update_pm_runtime_accounting(dev);
107 	time = suspended ? dev->power.suspended_time : dev->power.active_time;
108 
109 	spin_unlock_irqrestore(&dev->power.lock, flags);
110 
111 	return time;
112 }
113 
pm_runtime_active_time(struct device * dev)114 u64 pm_runtime_active_time(struct device *dev)
115 {
116 	return rpm_get_accounted_time(dev, false);
117 }
118 
pm_runtime_suspended_time(struct device * dev)119 u64 pm_runtime_suspended_time(struct device *dev)
120 {
121 	return rpm_get_accounted_time(dev, true);
122 }
123 EXPORT_SYMBOL_GPL(pm_runtime_suspended_time);
124 
125 /**
126  * pm_runtime_deactivate_timer - Deactivate given device's suspend timer.
127  * @dev: Device to handle.
128  */
pm_runtime_deactivate_timer(struct device * dev)129 static void pm_runtime_deactivate_timer(struct device *dev)
130 {
131 	if (dev->power.timer_expires > 0) {
132 		hrtimer_try_to_cancel(&dev->power.suspend_timer);
133 		dev->power.timer_expires = 0;
134 	}
135 }
136 
137 /**
138  * pm_runtime_cancel_pending - Deactivate suspend timer and cancel requests.
139  * @dev: Device to handle.
140  */
pm_runtime_cancel_pending(struct device * dev)141 static void pm_runtime_cancel_pending(struct device *dev)
142 {
143 	pm_runtime_deactivate_timer(dev);
144 	/*
145 	 * In case there's a request pending, make sure its work function will
146 	 * return without doing anything.
147 	 */
148 	dev->power.request = RPM_REQ_NONE;
149 }
150 
151 /*
152  * pm_runtime_autosuspend_expiration - Get a device's autosuspend-delay expiration time.
153  * @dev: Device to handle.
154  *
155  * Compute the autosuspend-delay expiration time based on the device's
156  * power.last_busy time.  If the delay has already expired or is disabled
157  * (negative) or the power.use_autosuspend flag isn't set, return 0.
158  * Otherwise return the expiration time in nanoseconds (adjusted to be nonzero).
159  *
160  * This function may be called either with or without dev->power.lock held.
161  * Either way it can be racy, since power.last_busy may be updated at any time.
162  */
pm_runtime_autosuspend_expiration(struct device * dev)163 u64 pm_runtime_autosuspend_expiration(struct device *dev)
164 {
165 	int autosuspend_delay;
166 	u64 expires;
167 
168 	if (!dev->power.use_autosuspend)
169 		return 0;
170 
171 	autosuspend_delay = READ_ONCE(dev->power.autosuspend_delay);
172 	if (autosuspend_delay < 0)
173 		return 0;
174 
175 	expires  = READ_ONCE(dev->power.last_busy);
176 	expires += (u64)autosuspend_delay * NSEC_PER_MSEC;
177 	if (expires > ktime_get_mono_fast_ns())
178 		return expires;	/* Expires in the future */
179 
180 	return 0;
181 }
182 EXPORT_SYMBOL_GPL(pm_runtime_autosuspend_expiration);
183 
dev_memalloc_noio(struct device * dev,void * data)184 static int dev_memalloc_noio(struct device *dev, void *data)
185 {
186 	return dev->power.memalloc_noio;
187 }
188 
189 /*
190  * pm_runtime_set_memalloc_noio - Set a device's memalloc_noio flag.
191  * @dev: Device to handle.
192  * @enable: True for setting the flag and False for clearing the flag.
193  *
194  * Set the flag for all devices in the path from the device to the
195  * root device in the device tree if @enable is true, otherwise clear
196  * the flag for devices in the path whose siblings don't set the flag.
197  *
198  * The function should only be called by block device, or network
199  * device driver for solving the deadlock problem during runtime
200  * resume/suspend:
201  *
202  *     If memory allocation with GFP_KERNEL is called inside runtime
203  *     resume/suspend callback of any one of its ancestors(or the
204  *     block device itself), the deadlock may be triggered inside the
205  *     memory allocation since it might not complete until the block
206  *     device becomes active and the involed page I/O finishes. The
207  *     situation is pointed out first by Alan Stern. Network device
208  *     are involved in iSCSI kind of situation.
209  *
210  * The lock of dev_hotplug_mutex is held in the function for handling
211  * hotplug race because pm_runtime_set_memalloc_noio() may be called
212  * in async probe().
213  *
214  * The function should be called between device_add() and device_del()
215  * on the affected device(block/network device).
216  */
pm_runtime_set_memalloc_noio(struct device * dev,bool enable)217 void pm_runtime_set_memalloc_noio(struct device *dev, bool enable)
218 {
219 	static DEFINE_MUTEX(dev_hotplug_mutex);
220 
221 	mutex_lock(&dev_hotplug_mutex);
222 	for (;;) {
223 		bool enabled;
224 
225 		/* hold power lock since bitfield is not SMP-safe. */
226 		spin_lock_irq(&dev->power.lock);
227 		enabled = dev->power.memalloc_noio;
228 		dev->power.memalloc_noio = enable;
229 		spin_unlock_irq(&dev->power.lock);
230 
231 		/*
232 		 * not need to enable ancestors any more if the device
233 		 * has been enabled.
234 		 */
235 		if (enabled && enable)
236 			break;
237 
238 		dev = dev->parent;
239 
240 		/*
241 		 * clear flag of the parent device only if all the
242 		 * children don't set the flag because ancestor's
243 		 * flag was set by any one of the descendants.
244 		 */
245 		if (!dev || (!enable &&
246 			     device_for_each_child(dev, NULL,
247 						   dev_memalloc_noio)))
248 			break;
249 	}
250 	mutex_unlock(&dev_hotplug_mutex);
251 }
252 EXPORT_SYMBOL_GPL(pm_runtime_set_memalloc_noio);
253 
254 /**
255  * rpm_check_suspend_allowed - Test whether a device may be suspended.
256  * @dev: Device to test.
257  */
rpm_check_suspend_allowed(struct device * dev)258 static int rpm_check_suspend_allowed(struct device *dev)
259 {
260 	int retval = 0;
261 
262 	if (dev->power.runtime_error)
263 		retval = -EINVAL;
264 	else if (dev->power.disable_depth > 0)
265 		retval = -EACCES;
266 	else if (atomic_read(&dev->power.usage_count) > 0)
267 		retval = -EAGAIN;
268 	else if (!dev->power.ignore_children &&
269 			atomic_read(&dev->power.child_count))
270 		retval = -EBUSY;
271 
272 	/* Pending resume requests take precedence over suspends. */
273 	else if ((dev->power.deferred_resume
274 			&& dev->power.runtime_status == RPM_SUSPENDING)
275 	    || (dev->power.request_pending
276 			&& dev->power.request == RPM_REQ_RESUME))
277 		retval = -EAGAIN;
278 	else if (__dev_pm_qos_resume_latency(dev) == 0)
279 		retval = -EPERM;
280 	else if (dev->power.runtime_status == RPM_SUSPENDED)
281 		retval = 1;
282 
283 	return retval;
284 }
285 
rpm_get_suppliers(struct device * dev)286 static int rpm_get_suppliers(struct device *dev)
287 {
288 	struct device_link *link;
289 
290 	list_for_each_entry_rcu(link, &dev->links.suppliers, c_node,
291 				device_links_read_lock_held()) {
292 		int retval;
293 
294 		if (!(link->flags & DL_FLAG_PM_RUNTIME))
295 			continue;
296 
297 		retval = pm_runtime_get_sync(link->supplier);
298 		/* Ignore suppliers with disabled runtime PM. */
299 		if (retval < 0 && retval != -EACCES) {
300 			pm_runtime_put_noidle(link->supplier);
301 			return retval;
302 		}
303 		refcount_inc(&link->rpm_active);
304 	}
305 	return 0;
306 }
307 
308 /**
309  * pm_runtime_release_supplier - Drop references to device link's supplier.
310  * @link: Target device link.
311  *
312  * Drop all runtime PM references associated with @link to its supplier device.
313  */
pm_runtime_release_supplier(struct device_link * link)314 void pm_runtime_release_supplier(struct device_link *link)
315 {
316 	struct device *supplier = link->supplier;
317 
318 	/*
319 	 * The additional power.usage_count check is a safety net in case
320 	 * the rpm_active refcount becomes saturated, in which case
321 	 * refcount_dec_not_one() would return true forever, but it is not
322 	 * strictly necessary.
323 	 */
324 	while (refcount_dec_not_one(&link->rpm_active) &&
325 	       atomic_read(&supplier->power.usage_count) > 0)
326 		pm_runtime_put_noidle(supplier);
327 }
328 
__rpm_put_suppliers(struct device * dev,bool try_to_suspend)329 static void __rpm_put_suppliers(struct device *dev, bool try_to_suspend)
330 {
331 	struct device_link *link;
332 
333 	list_for_each_entry_rcu(link, &dev->links.suppliers, c_node,
334 				device_links_read_lock_held()) {
335 		pm_runtime_release_supplier(link);
336 		if (try_to_suspend)
337 			pm_request_idle(link->supplier);
338 	}
339 }
340 
rpm_put_suppliers(struct device * dev)341 static void rpm_put_suppliers(struct device *dev)
342 {
343 	__rpm_put_suppliers(dev, true);
344 }
345 
rpm_suspend_suppliers(struct device * dev)346 static void rpm_suspend_suppliers(struct device *dev)
347 {
348 	struct device_link *link;
349 	int idx = device_links_read_lock();
350 
351 	list_for_each_entry_rcu(link, &dev->links.suppliers, c_node,
352 				device_links_read_lock_held())
353 		pm_request_idle(link->supplier);
354 
355 	device_links_read_unlock(idx);
356 }
357 
358 /**
359  * __rpm_callback - Run a given runtime PM callback for a given device.
360  * @cb: Runtime PM callback to run.
361  * @dev: Device to run the callback for.
362  */
__rpm_callback(int (* cb)(struct device *),struct device * dev)363 static int __rpm_callback(int (*cb)(struct device *), struct device *dev)
364 	__releases(&dev->power.lock) __acquires(&dev->power.lock)
365 {
366 	int retval, idx;
367 	bool use_links = dev->power.links_count > 0;
368 
369 	if (dev->power.irq_safe) {
370 		spin_unlock(&dev->power.lock);
371 	} else {
372 		spin_unlock_irq(&dev->power.lock);
373 
374 		/*
375 		 * Resume suppliers if necessary.
376 		 *
377 		 * The device's runtime PM status cannot change until this
378 		 * routine returns, so it is safe to read the status outside of
379 		 * the lock.
380 		 */
381 		if (use_links && dev->power.runtime_status == RPM_RESUMING) {
382 			idx = device_links_read_lock();
383 
384 			retval = rpm_get_suppliers(dev);
385 			if (retval) {
386 				rpm_put_suppliers(dev);
387 				goto fail;
388 			}
389 
390 			device_links_read_unlock(idx);
391 		}
392 	}
393 
394 	retval = cb(dev);
395 
396 	if (dev->power.irq_safe) {
397 		spin_lock(&dev->power.lock);
398 	} else {
399 		/*
400 		 * If the device is suspending and the callback has returned
401 		 * success, drop the usage counters of the suppliers that have
402 		 * been reference counted on its resume.
403 		 *
404 		 * Do that if resume fails too.
405 		 */
406 		if (use_links
407 		    && ((dev->power.runtime_status == RPM_SUSPENDING && !retval)
408 		    || (dev->power.runtime_status == RPM_RESUMING && retval))) {
409 			idx = device_links_read_lock();
410 
411 			__rpm_put_suppliers(dev, false);
412 
413 fail:
414 			device_links_read_unlock(idx);
415 		}
416 
417 		spin_lock_irq(&dev->power.lock);
418 	}
419 
420 	return retval;
421 }
422 
423 /**
424  * rpm_idle - Notify device bus type if the device can be suspended.
425  * @dev: Device to notify the bus type about.
426  * @rpmflags: Flag bits.
427  *
428  * Check if the device's runtime PM status allows it to be suspended.  If
429  * another idle notification has been started earlier, return immediately.  If
430  * the RPM_ASYNC flag is set then queue an idle-notification request; otherwise
431  * run the ->runtime_idle() callback directly. If the ->runtime_idle callback
432  * doesn't exist or if it returns 0, call rpm_suspend with the RPM_AUTO flag.
433  *
434  * This function must be called under dev->power.lock with interrupts disabled.
435  */
rpm_idle(struct device * dev,int rpmflags)436 static int rpm_idle(struct device *dev, int rpmflags)
437 {
438 	int (*callback)(struct device *);
439 	int retval;
440 
441 	trace_rpm_idle_rcuidle(dev, rpmflags);
442 	retval = rpm_check_suspend_allowed(dev);
443 	if (retval < 0)
444 		;	/* Conditions are wrong. */
445 
446 	/* Idle notifications are allowed only in the RPM_ACTIVE state. */
447 	else if (dev->power.runtime_status != RPM_ACTIVE)
448 		retval = -EAGAIN;
449 
450 	/*
451 	 * Any pending request other than an idle notification takes
452 	 * precedence over us, except that the timer may be running.
453 	 */
454 	else if (dev->power.request_pending &&
455 	    dev->power.request > RPM_REQ_IDLE)
456 		retval = -EAGAIN;
457 
458 	/* Act as though RPM_NOWAIT is always set. */
459 	else if (dev->power.idle_notification)
460 		retval = -EINPROGRESS;
461 	if (retval)
462 		goto out;
463 
464 	/* Pending requests need to be canceled. */
465 	dev->power.request = RPM_REQ_NONE;
466 
467 	callback = RPM_GET_CALLBACK(dev, runtime_idle);
468 
469 	/* If no callback assume success. */
470 	if (!callback || dev->power.no_callbacks)
471 		goto out;
472 
473 	/* Carry out an asynchronous or a synchronous idle notification. */
474 	if (rpmflags & RPM_ASYNC) {
475 		dev->power.request = RPM_REQ_IDLE;
476 		if (!dev->power.request_pending) {
477 			dev->power.request_pending = true;
478 			queue_work(pm_wq, &dev->power.work);
479 		}
480 		trace_rpm_return_int_rcuidle(dev, _THIS_IP_, 0);
481 		return 0;
482 	}
483 
484 	dev->power.idle_notification = true;
485 
486 	if (dev->power.irq_safe)
487 		spin_unlock(&dev->power.lock);
488 	else
489 		spin_unlock_irq(&dev->power.lock);
490 
491 	retval = callback(dev);
492 
493 	if (dev->power.irq_safe)
494 		spin_lock(&dev->power.lock);
495 	else
496 		spin_lock_irq(&dev->power.lock);
497 
498 	dev->power.idle_notification = false;
499 	wake_up_all(&dev->power.wait_queue);
500 
501  out:
502 	trace_rpm_return_int_rcuidle(dev, _THIS_IP_, retval);
503 	return retval ? retval : rpm_suspend(dev, rpmflags | RPM_AUTO);
504 }
505 
506 /**
507  * rpm_callback - Run a given runtime PM callback for a given device.
508  * @cb: Runtime PM callback to run.
509  * @dev: Device to run the callback for.
510  */
rpm_callback(int (* cb)(struct device *),struct device * dev)511 static int rpm_callback(int (*cb)(struct device *), struct device *dev)
512 {
513 	int retval;
514 
515 	if (!cb)
516 		return -ENOSYS;
517 
518 	if (dev->power.memalloc_noio) {
519 		unsigned int noio_flag;
520 
521 		/*
522 		 * Deadlock might be caused if memory allocation with
523 		 * GFP_KERNEL happens inside runtime_suspend and
524 		 * runtime_resume callbacks of one block device's
525 		 * ancestor or the block device itself. Network
526 		 * device might be thought as part of iSCSI block
527 		 * device, so network device and its ancestor should
528 		 * be marked as memalloc_noio too.
529 		 */
530 		noio_flag = memalloc_noio_save();
531 		retval = __rpm_callback(cb, dev);
532 		memalloc_noio_restore(noio_flag);
533 	} else {
534 		retval = __rpm_callback(cb, dev);
535 	}
536 
537 	dev->power.runtime_error = retval;
538 	return retval != -EACCES ? retval : -EIO;
539 }
540 
541 /**
542  * rpm_suspend - Carry out runtime suspend of given device.
543  * @dev: Device to suspend.
544  * @rpmflags: Flag bits.
545  *
546  * Check if the device's runtime PM status allows it to be suspended.
547  * Cancel a pending idle notification, autosuspend or suspend. If
548  * another suspend has been started earlier, either return immediately
549  * or wait for it to finish, depending on the RPM_NOWAIT and RPM_ASYNC
550  * flags. If the RPM_ASYNC flag is set then queue a suspend request;
551  * otherwise run the ->runtime_suspend() callback directly. When
552  * ->runtime_suspend succeeded, if a deferred resume was requested while
553  * the callback was running then carry it out, otherwise send an idle
554  * notification for its parent (if the suspend succeeded and both
555  * ignore_children of parent->power and irq_safe of dev->power are not set).
556  * If ->runtime_suspend failed with -EAGAIN or -EBUSY, and if the RPM_AUTO
557  * flag is set and the next autosuspend-delay expiration time is in the
558  * future, schedule another autosuspend attempt.
559  *
560  * This function must be called under dev->power.lock with interrupts disabled.
561  */
rpm_suspend(struct device * dev,int rpmflags)562 static int rpm_suspend(struct device *dev, int rpmflags)
563 	__releases(&dev->power.lock) __acquires(&dev->power.lock)
564 {
565 	int (*callback)(struct device *);
566 	struct device *parent = NULL;
567 	int retval;
568 
569 	trace_rpm_suspend_rcuidle(dev, rpmflags);
570 
571  repeat:
572 	retval = rpm_check_suspend_allowed(dev);
573 	if (retval < 0)
574 		goto out;	/* Conditions are wrong. */
575 
576 	/* Synchronous suspends are not allowed in the RPM_RESUMING state. */
577 	if (dev->power.runtime_status == RPM_RESUMING && !(rpmflags & RPM_ASYNC))
578 		retval = -EAGAIN;
579 	if (retval)
580 		goto out;
581 
582 	/* If the autosuspend_delay time hasn't expired yet, reschedule. */
583 	if ((rpmflags & RPM_AUTO)
584 	    && dev->power.runtime_status != RPM_SUSPENDING) {
585 		u64 expires = pm_runtime_autosuspend_expiration(dev);
586 
587 		if (expires != 0) {
588 			/* Pending requests need to be canceled. */
589 			dev->power.request = RPM_REQ_NONE;
590 
591 			/*
592 			 * Optimization: If the timer is already running and is
593 			 * set to expire at or before the autosuspend delay,
594 			 * avoid the overhead of resetting it.  Just let it
595 			 * expire; pm_suspend_timer_fn() will take care of the
596 			 * rest.
597 			 */
598 			if (!(dev->power.timer_expires &&
599 					dev->power.timer_expires <= expires)) {
600 				/*
601 				 * We add a slack of 25% to gather wakeups
602 				 * without sacrificing the granularity.
603 				 */
604 				u64 slack = (u64)READ_ONCE(dev->power.autosuspend_delay) *
605 						    (NSEC_PER_MSEC >> 2);
606 
607 				dev->power.timer_expires = expires;
608 				hrtimer_start_range_ns(&dev->power.suspend_timer,
609 						ns_to_ktime(expires),
610 						slack,
611 						HRTIMER_MODE_ABS);
612 			}
613 			dev->power.timer_autosuspends = 1;
614 			goto out;
615 		}
616 	}
617 
618 	/* Other scheduled or pending requests need to be canceled. */
619 	pm_runtime_cancel_pending(dev);
620 
621 	if (dev->power.runtime_status == RPM_SUSPENDING) {
622 		DEFINE_WAIT(wait);
623 
624 		if (rpmflags & (RPM_ASYNC | RPM_NOWAIT)) {
625 			retval = -EINPROGRESS;
626 			goto out;
627 		}
628 
629 		if (dev->power.irq_safe) {
630 			spin_unlock(&dev->power.lock);
631 
632 			cpu_relax();
633 
634 			spin_lock(&dev->power.lock);
635 			goto repeat;
636 		}
637 
638 		/* Wait for the other suspend running in parallel with us. */
639 		for (;;) {
640 			prepare_to_wait(&dev->power.wait_queue, &wait,
641 					TASK_UNINTERRUPTIBLE);
642 			if (dev->power.runtime_status != RPM_SUSPENDING)
643 				break;
644 
645 			spin_unlock_irq(&dev->power.lock);
646 
647 			schedule();
648 
649 			spin_lock_irq(&dev->power.lock);
650 		}
651 		finish_wait(&dev->power.wait_queue, &wait);
652 		goto repeat;
653 	}
654 
655 	if (dev->power.no_callbacks)
656 		goto no_callback;	/* Assume success. */
657 
658 	/* Carry out an asynchronous or a synchronous suspend. */
659 	if (rpmflags & RPM_ASYNC) {
660 		dev->power.request = (rpmflags & RPM_AUTO) ?
661 		    RPM_REQ_AUTOSUSPEND : RPM_REQ_SUSPEND;
662 		if (!dev->power.request_pending) {
663 			dev->power.request_pending = true;
664 			queue_work(pm_wq, &dev->power.work);
665 		}
666 		goto out;
667 	}
668 
669 	__update_runtime_status(dev, RPM_SUSPENDING);
670 
671 	callback = RPM_GET_CALLBACK(dev, runtime_suspend);
672 
673 	dev_pm_enable_wake_irq_check(dev, true);
674 	retval = rpm_callback(callback, dev);
675 	if (retval)
676 		goto fail;
677 
678  no_callback:
679 	__update_runtime_status(dev, RPM_SUSPENDED);
680 	pm_runtime_deactivate_timer(dev);
681 
682 	if (dev->parent) {
683 		parent = dev->parent;
684 		atomic_add_unless(&parent->power.child_count, -1, 0);
685 	}
686 	wake_up_all(&dev->power.wait_queue);
687 
688 	if (dev->power.deferred_resume) {
689 		dev->power.deferred_resume = false;
690 		rpm_resume(dev, 0);
691 		retval = -EAGAIN;
692 		goto out;
693 	}
694 
695 	if (dev->power.irq_safe)
696 		goto out;
697 
698 	/* Maybe the parent is now able to suspend. */
699 	if (parent && !parent->power.ignore_children) {
700 		spin_unlock(&dev->power.lock);
701 
702 		spin_lock(&parent->power.lock);
703 		rpm_idle(parent, RPM_ASYNC);
704 		spin_unlock(&parent->power.lock);
705 
706 		spin_lock(&dev->power.lock);
707 	}
708 	/* Maybe the suppliers are now able to suspend. */
709 	if (dev->power.links_count > 0) {
710 		spin_unlock_irq(&dev->power.lock);
711 
712 		rpm_suspend_suppliers(dev);
713 
714 		spin_lock_irq(&dev->power.lock);
715 	}
716 
717  out:
718 	trace_rpm_return_int_rcuidle(dev, _THIS_IP_, retval);
719 
720 	return retval;
721 
722  fail:
723 	dev_pm_disable_wake_irq_check(dev);
724 	__update_runtime_status(dev, RPM_ACTIVE);
725 	dev->power.deferred_resume = false;
726 	wake_up_all(&dev->power.wait_queue);
727 
728 	if (retval == -EAGAIN || retval == -EBUSY) {
729 		dev->power.runtime_error = 0;
730 
731 		/*
732 		 * If the callback routine failed an autosuspend, and
733 		 * if the last_busy time has been updated so that there
734 		 * is a new autosuspend expiration time, automatically
735 		 * reschedule another autosuspend.
736 		 */
737 		if ((rpmflags & RPM_AUTO) &&
738 		    pm_runtime_autosuspend_expiration(dev) != 0)
739 			goto repeat;
740 	} else {
741 		pm_runtime_cancel_pending(dev);
742 	}
743 	goto out;
744 }
745 
746 /**
747  * rpm_resume - Carry out runtime resume of given device.
748  * @dev: Device to resume.
749  * @rpmflags: Flag bits.
750  *
751  * Check if the device's runtime PM status allows it to be resumed.  Cancel
752  * any scheduled or pending requests.  If another resume has been started
753  * earlier, either return immediately or wait for it to finish, depending on the
754  * RPM_NOWAIT and RPM_ASYNC flags.  Similarly, if there's a suspend running in
755  * parallel with this function, either tell the other process to resume after
756  * suspending (deferred_resume) or wait for it to finish.  If the RPM_ASYNC
757  * flag is set then queue a resume request; otherwise run the
758  * ->runtime_resume() callback directly.  Queue an idle notification for the
759  * device if the resume succeeded.
760  *
761  * This function must be called under dev->power.lock with interrupts disabled.
762  */
rpm_resume(struct device * dev,int rpmflags)763 static int rpm_resume(struct device *dev, int rpmflags)
764 	__releases(&dev->power.lock) __acquires(&dev->power.lock)
765 {
766 	int (*callback)(struct device *);
767 	struct device *parent = NULL;
768 	int retval = 0;
769 
770 	trace_rpm_resume_rcuidle(dev, rpmflags);
771 
772  repeat:
773 	if (dev->power.runtime_error)
774 		retval = -EINVAL;
775 	else if (dev->power.disable_depth == 1 && dev->power.is_suspended
776 	    && dev->power.runtime_status == RPM_ACTIVE)
777 		retval = 1;
778 	else if (dev->power.disable_depth > 0)
779 		retval = -EACCES;
780 	if (retval)
781 		goto out;
782 
783 	/*
784 	 * Other scheduled or pending requests need to be canceled.  Small
785 	 * optimization: If an autosuspend timer is running, leave it running
786 	 * rather than cancelling it now only to restart it again in the near
787 	 * future.
788 	 */
789 	dev->power.request = RPM_REQ_NONE;
790 	if (!dev->power.timer_autosuspends)
791 		pm_runtime_deactivate_timer(dev);
792 
793 	if (dev->power.runtime_status == RPM_ACTIVE) {
794 		retval = 1;
795 		goto out;
796 	}
797 
798 	if (dev->power.runtime_status == RPM_RESUMING
799 	    || dev->power.runtime_status == RPM_SUSPENDING) {
800 		DEFINE_WAIT(wait);
801 
802 		if (rpmflags & (RPM_ASYNC | RPM_NOWAIT)) {
803 			if (dev->power.runtime_status == RPM_SUSPENDING)
804 				dev->power.deferred_resume = true;
805 			else
806 				retval = -EINPROGRESS;
807 			goto out;
808 		}
809 
810 		if (dev->power.irq_safe) {
811 			spin_unlock(&dev->power.lock);
812 
813 			cpu_relax();
814 
815 			spin_lock(&dev->power.lock);
816 			goto repeat;
817 		}
818 
819 		/* Wait for the operation carried out in parallel with us. */
820 		for (;;) {
821 			prepare_to_wait(&dev->power.wait_queue, &wait,
822 					TASK_UNINTERRUPTIBLE);
823 			if (dev->power.runtime_status != RPM_RESUMING
824 			    && dev->power.runtime_status != RPM_SUSPENDING)
825 				break;
826 
827 			spin_unlock_irq(&dev->power.lock);
828 
829 			schedule();
830 
831 			spin_lock_irq(&dev->power.lock);
832 		}
833 		finish_wait(&dev->power.wait_queue, &wait);
834 		goto repeat;
835 	}
836 
837 	/*
838 	 * See if we can skip waking up the parent.  This is safe only if
839 	 * power.no_callbacks is set, because otherwise we don't know whether
840 	 * the resume will actually succeed.
841 	 */
842 	if (dev->power.no_callbacks && !parent && dev->parent) {
843 		spin_lock_nested(&dev->parent->power.lock, SINGLE_DEPTH_NESTING);
844 		if (dev->parent->power.disable_depth > 0
845 		    || dev->parent->power.ignore_children
846 		    || dev->parent->power.runtime_status == RPM_ACTIVE) {
847 			atomic_inc(&dev->parent->power.child_count);
848 			spin_unlock(&dev->parent->power.lock);
849 			retval = 1;
850 			goto no_callback;	/* Assume success. */
851 		}
852 		spin_unlock(&dev->parent->power.lock);
853 	}
854 
855 	/* Carry out an asynchronous or a synchronous resume. */
856 	if (rpmflags & RPM_ASYNC) {
857 		dev->power.request = RPM_REQ_RESUME;
858 		if (!dev->power.request_pending) {
859 			dev->power.request_pending = true;
860 			queue_work(pm_wq, &dev->power.work);
861 		}
862 		retval = 0;
863 		goto out;
864 	}
865 
866 	if (!parent && dev->parent) {
867 		/*
868 		 * Increment the parent's usage counter and resume it if
869 		 * necessary.  Not needed if dev is irq-safe; then the
870 		 * parent is permanently resumed.
871 		 */
872 		parent = dev->parent;
873 		if (dev->power.irq_safe)
874 			goto skip_parent;
875 		spin_unlock(&dev->power.lock);
876 
877 		pm_runtime_get_noresume(parent);
878 
879 		spin_lock(&parent->power.lock);
880 		/*
881 		 * Resume the parent if it has runtime PM enabled and not been
882 		 * set to ignore its children.
883 		 */
884 		if (!parent->power.disable_depth
885 		    && !parent->power.ignore_children) {
886 			rpm_resume(parent, 0);
887 			if (parent->power.runtime_status != RPM_ACTIVE)
888 				retval = -EBUSY;
889 		}
890 		spin_unlock(&parent->power.lock);
891 
892 		spin_lock(&dev->power.lock);
893 		if (retval)
894 			goto out;
895 		goto repeat;
896 	}
897  skip_parent:
898 
899 	if (dev->power.no_callbacks)
900 		goto no_callback;	/* Assume success. */
901 
902 	__update_runtime_status(dev, RPM_RESUMING);
903 
904 	callback = RPM_GET_CALLBACK(dev, runtime_resume);
905 
906 	dev_pm_disable_wake_irq_check(dev);
907 	retval = rpm_callback(callback, dev);
908 	if (retval) {
909 		__update_runtime_status(dev, RPM_SUSPENDED);
910 		pm_runtime_cancel_pending(dev);
911 		dev_pm_enable_wake_irq_check(dev, false);
912 	} else {
913  no_callback:
914 		__update_runtime_status(dev, RPM_ACTIVE);
915 		pm_runtime_mark_last_busy(dev);
916 		if (parent)
917 			atomic_inc(&parent->power.child_count);
918 	}
919 	wake_up_all(&dev->power.wait_queue);
920 
921 	if (retval >= 0)
922 		rpm_idle(dev, RPM_ASYNC);
923 
924  out:
925 	if (parent && !dev->power.irq_safe) {
926 		spin_unlock_irq(&dev->power.lock);
927 
928 		pm_runtime_put(parent);
929 
930 		spin_lock_irq(&dev->power.lock);
931 	}
932 
933 	trace_rpm_return_int_rcuidle(dev, _THIS_IP_, retval);
934 
935 	return retval;
936 }
937 
938 /**
939  * pm_runtime_work - Universal runtime PM work function.
940  * @work: Work structure used for scheduling the execution of this function.
941  *
942  * Use @work to get the device object the work is to be done for, determine what
943  * is to be done and execute the appropriate runtime PM function.
944  */
pm_runtime_work(struct work_struct * work)945 static void pm_runtime_work(struct work_struct *work)
946 {
947 	struct device *dev = container_of(work, struct device, power.work);
948 	enum rpm_request req;
949 
950 	spin_lock_irq(&dev->power.lock);
951 
952 	if (!dev->power.request_pending)
953 		goto out;
954 
955 	req = dev->power.request;
956 	dev->power.request = RPM_REQ_NONE;
957 	dev->power.request_pending = false;
958 
959 	switch (req) {
960 	case RPM_REQ_NONE:
961 		break;
962 	case RPM_REQ_IDLE:
963 		rpm_idle(dev, RPM_NOWAIT);
964 		break;
965 	case RPM_REQ_SUSPEND:
966 		rpm_suspend(dev, RPM_NOWAIT);
967 		break;
968 	case RPM_REQ_AUTOSUSPEND:
969 		rpm_suspend(dev, RPM_NOWAIT | RPM_AUTO);
970 		break;
971 	case RPM_REQ_RESUME:
972 		rpm_resume(dev, RPM_NOWAIT);
973 		break;
974 	}
975 
976  out:
977 	spin_unlock_irq(&dev->power.lock);
978 }
979 
980 /**
981  * pm_suspend_timer_fn - Timer function for pm_schedule_suspend().
982  * @data: Device pointer passed by pm_schedule_suspend().
983  *
984  * Check if the time is right and queue a suspend request.
985  */
pm_suspend_timer_fn(struct hrtimer * timer)986 static enum hrtimer_restart  pm_suspend_timer_fn(struct hrtimer *timer)
987 {
988 	struct device *dev = container_of(timer, struct device, power.suspend_timer);
989 	unsigned long flags;
990 	u64 expires;
991 
992 	spin_lock_irqsave(&dev->power.lock, flags);
993 
994 	expires = dev->power.timer_expires;
995 	/*
996 	 * If 'expires' is after the current time, we've been called
997 	 * too early.
998 	 */
999 	if (expires > 0 && expires < ktime_get_mono_fast_ns()) {
1000 		dev->power.timer_expires = 0;
1001 		rpm_suspend(dev, dev->power.timer_autosuspends ?
1002 		    (RPM_ASYNC | RPM_AUTO) : RPM_ASYNC);
1003 	}
1004 
1005 	spin_unlock_irqrestore(&dev->power.lock, flags);
1006 
1007 	return HRTIMER_NORESTART;
1008 }
1009 
1010 /**
1011  * pm_schedule_suspend - Set up a timer to submit a suspend request in future.
1012  * @dev: Device to suspend.
1013  * @delay: Time to wait before submitting a suspend request, in milliseconds.
1014  */
pm_schedule_suspend(struct device * dev,unsigned int delay)1015 int pm_schedule_suspend(struct device *dev, unsigned int delay)
1016 {
1017 	unsigned long flags;
1018 	u64 expires;
1019 	int retval;
1020 
1021 	spin_lock_irqsave(&dev->power.lock, flags);
1022 
1023 	if (!delay) {
1024 		retval = rpm_suspend(dev, RPM_ASYNC);
1025 		goto out;
1026 	}
1027 
1028 	retval = rpm_check_suspend_allowed(dev);
1029 	if (retval)
1030 		goto out;
1031 
1032 	/* Other scheduled or pending requests need to be canceled. */
1033 	pm_runtime_cancel_pending(dev);
1034 
1035 	expires = ktime_get_mono_fast_ns() + (u64)delay * NSEC_PER_MSEC;
1036 	dev->power.timer_expires = expires;
1037 	dev->power.timer_autosuspends = 0;
1038 	hrtimer_start(&dev->power.suspend_timer, expires, HRTIMER_MODE_ABS);
1039 
1040  out:
1041 	spin_unlock_irqrestore(&dev->power.lock, flags);
1042 
1043 	return retval;
1044 }
1045 EXPORT_SYMBOL_GPL(pm_schedule_suspend);
1046 
1047 /**
1048  * __pm_runtime_idle - Entry point for runtime idle operations.
1049  * @dev: Device to send idle notification for.
1050  * @rpmflags: Flag bits.
1051  *
1052  * If the RPM_GET_PUT flag is set, decrement the device's usage count and
1053  * return immediately if it is larger than zero.  Then carry out an idle
1054  * notification, either synchronous or asynchronous.
1055  *
1056  * This routine may be called in atomic context if the RPM_ASYNC flag is set,
1057  * or if pm_runtime_irq_safe() has been called.
1058  */
__pm_runtime_idle(struct device * dev,int rpmflags)1059 int __pm_runtime_idle(struct device *dev, int rpmflags)
1060 {
1061 	unsigned long flags;
1062 	int retval;
1063 
1064 	if (rpmflags & RPM_GET_PUT) {
1065 		if (!atomic_dec_and_test(&dev->power.usage_count)) {
1066 			trace_rpm_usage_rcuidle(dev, rpmflags);
1067 			return 0;
1068 		}
1069 	}
1070 
1071 	might_sleep_if(!(rpmflags & RPM_ASYNC) && !dev->power.irq_safe);
1072 
1073 	spin_lock_irqsave(&dev->power.lock, flags);
1074 	retval = rpm_idle(dev, rpmflags);
1075 	spin_unlock_irqrestore(&dev->power.lock, flags);
1076 
1077 	return retval;
1078 }
1079 EXPORT_SYMBOL_GPL(__pm_runtime_idle);
1080 
1081 /**
1082  * __pm_runtime_suspend - Entry point for runtime put/suspend operations.
1083  * @dev: Device to suspend.
1084  * @rpmflags: Flag bits.
1085  *
1086  * If the RPM_GET_PUT flag is set, decrement the device's usage count and
1087  * return immediately if it is larger than zero.  Then carry out a suspend,
1088  * either synchronous or asynchronous.
1089  *
1090  * This routine may be called in atomic context if the RPM_ASYNC flag is set,
1091  * or if pm_runtime_irq_safe() has been called.
1092  */
__pm_runtime_suspend(struct device * dev,int rpmflags)1093 int __pm_runtime_suspend(struct device *dev, int rpmflags)
1094 {
1095 	unsigned long flags;
1096 	int retval;
1097 
1098 	if (rpmflags & RPM_GET_PUT) {
1099 		if (!atomic_dec_and_test(&dev->power.usage_count)) {
1100 			trace_rpm_usage_rcuidle(dev, rpmflags);
1101 			return 0;
1102 		}
1103 	}
1104 
1105 	might_sleep_if(!(rpmflags & RPM_ASYNC) && !dev->power.irq_safe);
1106 
1107 	spin_lock_irqsave(&dev->power.lock, flags);
1108 	retval = rpm_suspend(dev, rpmflags);
1109 	spin_unlock_irqrestore(&dev->power.lock, flags);
1110 
1111 	return retval;
1112 }
1113 EXPORT_SYMBOL_GPL(__pm_runtime_suspend);
1114 
1115 /**
1116  * __pm_runtime_resume - Entry point for runtime resume operations.
1117  * @dev: Device to resume.
1118  * @rpmflags: Flag bits.
1119  *
1120  * If the RPM_GET_PUT flag is set, increment the device's usage count.  Then
1121  * carry out a resume, either synchronous or asynchronous.
1122  *
1123  * This routine may be called in atomic context if the RPM_ASYNC flag is set,
1124  * or if pm_runtime_irq_safe() has been called.
1125  */
__pm_runtime_resume(struct device * dev,int rpmflags)1126 int __pm_runtime_resume(struct device *dev, int rpmflags)
1127 {
1128 	unsigned long flags;
1129 	int retval;
1130 
1131 	might_sleep_if(!(rpmflags & RPM_ASYNC) && !dev->power.irq_safe &&
1132 			dev->power.runtime_status != RPM_ACTIVE);
1133 
1134 	if (rpmflags & RPM_GET_PUT)
1135 		atomic_inc(&dev->power.usage_count);
1136 
1137 	spin_lock_irqsave(&dev->power.lock, flags);
1138 	retval = rpm_resume(dev, rpmflags);
1139 	spin_unlock_irqrestore(&dev->power.lock, flags);
1140 
1141 	return retval;
1142 }
1143 EXPORT_SYMBOL_GPL(__pm_runtime_resume);
1144 
1145 /**
1146  * pm_runtime_get_if_active - Conditionally bump up device usage counter.
1147  * @dev: Device to handle.
1148  * @ign_usage_count: Whether or not to look at the current usage counter value.
1149  *
1150  * Return -EINVAL if runtime PM is disabled for @dev.
1151  *
1152  * Otherwise, if the runtime PM status of @dev is %RPM_ACTIVE and either
1153  * @ign_usage_count is %true or the runtime PM usage counter of @dev is not
1154  * zero, increment the usage counter of @dev and return 1. Otherwise, return 0
1155  * without changing the usage counter.
1156  *
1157  * If @ign_usage_count is %true, this function can be used to prevent suspending
1158  * the device when its runtime PM status is %RPM_ACTIVE.
1159  *
1160  * If @ign_usage_count is %false, this function can be used to prevent
1161  * suspending the device when both its runtime PM status is %RPM_ACTIVE and its
1162  * runtime PM usage counter is not zero.
1163  *
1164  * The caller is resposible for decrementing the runtime PM usage counter of
1165  * @dev after this function has returned a positive value for it.
1166  */
pm_runtime_get_if_active(struct device * dev,bool ign_usage_count)1167 int pm_runtime_get_if_active(struct device *dev, bool ign_usage_count)
1168 {
1169 	unsigned long flags;
1170 	int retval;
1171 
1172 	spin_lock_irqsave(&dev->power.lock, flags);
1173 	if (dev->power.disable_depth > 0) {
1174 		retval = -EINVAL;
1175 	} else if (dev->power.runtime_status != RPM_ACTIVE) {
1176 		retval = 0;
1177 	} else if (ign_usage_count) {
1178 		retval = 1;
1179 		atomic_inc(&dev->power.usage_count);
1180 	} else {
1181 		retval = atomic_inc_not_zero(&dev->power.usage_count);
1182 	}
1183 	trace_rpm_usage_rcuidle(dev, 0);
1184 	spin_unlock_irqrestore(&dev->power.lock, flags);
1185 
1186 	return retval;
1187 }
1188 EXPORT_SYMBOL_GPL(pm_runtime_get_if_active);
1189 
1190 /**
1191  * __pm_runtime_set_status - Set runtime PM status of a device.
1192  * @dev: Device to handle.
1193  * @status: New runtime PM status of the device.
1194  *
1195  * If runtime PM of the device is disabled or its power.runtime_error field is
1196  * different from zero, the status may be changed either to RPM_ACTIVE, or to
1197  * RPM_SUSPENDED, as long as that reflects the actual state of the device.
1198  * However, if the device has a parent and the parent is not active, and the
1199  * parent's power.ignore_children flag is unset, the device's status cannot be
1200  * set to RPM_ACTIVE, so -EBUSY is returned in that case.
1201  *
1202  * If successful, __pm_runtime_set_status() clears the power.runtime_error field
1203  * and the device parent's counter of unsuspended children is modified to
1204  * reflect the new status.  If the new status is RPM_SUSPENDED, an idle
1205  * notification request for the parent is submitted.
1206  *
1207  * If @dev has any suppliers (as reflected by device links to them), and @status
1208  * is RPM_ACTIVE, they will be activated upfront and if the activation of one
1209  * of them fails, the status of @dev will be changed to RPM_SUSPENDED (instead
1210  * of the @status value) and the suppliers will be deacticated on exit.  The
1211  * error returned by the failing supplier activation will be returned in that
1212  * case.
1213  */
__pm_runtime_set_status(struct device * dev,unsigned int status)1214 int __pm_runtime_set_status(struct device *dev, unsigned int status)
1215 {
1216 	struct device *parent = dev->parent;
1217 	bool notify_parent = false;
1218 	int error = 0;
1219 
1220 	if (status != RPM_ACTIVE && status != RPM_SUSPENDED)
1221 		return -EINVAL;
1222 
1223 	spin_lock_irq(&dev->power.lock);
1224 
1225 	/*
1226 	 * Prevent PM-runtime from being enabled for the device or return an
1227 	 * error if it is enabled already and working.
1228 	 */
1229 	if (dev->power.runtime_error || dev->power.disable_depth)
1230 		dev->power.disable_depth++;
1231 	else
1232 		error = -EAGAIN;
1233 
1234 	spin_unlock_irq(&dev->power.lock);
1235 
1236 	if (error)
1237 		return error;
1238 
1239 	/*
1240 	 * If the new status is RPM_ACTIVE, the suppliers can be activated
1241 	 * upfront regardless of the current status, because next time
1242 	 * rpm_put_suppliers() runs, the rpm_active refcounts of the links
1243 	 * involved will be dropped down to one anyway.
1244 	 */
1245 	if (status == RPM_ACTIVE) {
1246 		int idx = device_links_read_lock();
1247 
1248 		error = rpm_get_suppliers(dev);
1249 		if (error)
1250 			status = RPM_SUSPENDED;
1251 
1252 		device_links_read_unlock(idx);
1253 	}
1254 
1255 	spin_lock_irq(&dev->power.lock);
1256 
1257 	if (dev->power.runtime_status == status || !parent)
1258 		goto out_set;
1259 
1260 	if (status == RPM_SUSPENDED) {
1261 		atomic_add_unless(&parent->power.child_count, -1, 0);
1262 		notify_parent = !parent->power.ignore_children;
1263 	} else {
1264 		spin_lock_nested(&parent->power.lock, SINGLE_DEPTH_NESTING);
1265 
1266 		/*
1267 		 * It is invalid to put an active child under a parent that is
1268 		 * not active, has runtime PM enabled and the
1269 		 * 'power.ignore_children' flag unset.
1270 		 */
1271 		if (!parent->power.disable_depth
1272 		    && !parent->power.ignore_children
1273 		    && parent->power.runtime_status != RPM_ACTIVE) {
1274 			dev_err(dev, "runtime PM trying to activate child device %s but parent (%s) is not active\n",
1275 				dev_name(dev),
1276 				dev_name(parent));
1277 			error = -EBUSY;
1278 		} else if (dev->power.runtime_status == RPM_SUSPENDED) {
1279 			atomic_inc(&parent->power.child_count);
1280 		}
1281 
1282 		spin_unlock(&parent->power.lock);
1283 
1284 		if (error) {
1285 			status = RPM_SUSPENDED;
1286 			goto out;
1287 		}
1288 	}
1289 
1290  out_set:
1291 	__update_runtime_status(dev, status);
1292 	if (!error)
1293 		dev->power.runtime_error = 0;
1294 
1295  out:
1296 	spin_unlock_irq(&dev->power.lock);
1297 
1298 	if (notify_parent)
1299 		pm_request_idle(parent);
1300 
1301 	if (status == RPM_SUSPENDED) {
1302 		int idx = device_links_read_lock();
1303 
1304 		rpm_put_suppliers(dev);
1305 
1306 		device_links_read_unlock(idx);
1307 	}
1308 
1309 	pm_runtime_enable(dev);
1310 
1311 	return error;
1312 }
1313 EXPORT_SYMBOL_GPL(__pm_runtime_set_status);
1314 
1315 /**
1316  * __pm_runtime_barrier - Cancel pending requests and wait for completions.
1317  * @dev: Device to handle.
1318  *
1319  * Flush all pending requests for the device from pm_wq and wait for all
1320  * runtime PM operations involving the device in progress to complete.
1321  *
1322  * Should be called under dev->power.lock with interrupts disabled.
1323  */
__pm_runtime_barrier(struct device * dev)1324 static void __pm_runtime_barrier(struct device *dev)
1325 {
1326 	pm_runtime_deactivate_timer(dev);
1327 
1328 	if (dev->power.request_pending) {
1329 		dev->power.request = RPM_REQ_NONE;
1330 		spin_unlock_irq(&dev->power.lock);
1331 
1332 		cancel_work_sync(&dev->power.work);
1333 
1334 		spin_lock_irq(&dev->power.lock);
1335 		dev->power.request_pending = false;
1336 	}
1337 
1338 	if (dev->power.runtime_status == RPM_SUSPENDING
1339 	    || dev->power.runtime_status == RPM_RESUMING
1340 	    || dev->power.idle_notification) {
1341 		DEFINE_WAIT(wait);
1342 
1343 		/* Suspend, wake-up or idle notification in progress. */
1344 		for (;;) {
1345 			prepare_to_wait(&dev->power.wait_queue, &wait,
1346 					TASK_UNINTERRUPTIBLE);
1347 			if (dev->power.runtime_status != RPM_SUSPENDING
1348 			    && dev->power.runtime_status != RPM_RESUMING
1349 			    && !dev->power.idle_notification)
1350 				break;
1351 			spin_unlock_irq(&dev->power.lock);
1352 
1353 			schedule();
1354 
1355 			spin_lock_irq(&dev->power.lock);
1356 		}
1357 		finish_wait(&dev->power.wait_queue, &wait);
1358 	}
1359 }
1360 
1361 /**
1362  * pm_runtime_barrier - Flush pending requests and wait for completions.
1363  * @dev: Device to handle.
1364  *
1365  * Prevent the device from being suspended by incrementing its usage counter and
1366  * if there's a pending resume request for the device, wake the device up.
1367  * Next, make sure that all pending requests for the device have been flushed
1368  * from pm_wq and wait for all runtime PM operations involving the device in
1369  * progress to complete.
1370  *
1371  * Return value:
1372  * 1, if there was a resume request pending and the device had to be woken up,
1373  * 0, otherwise
1374  */
pm_runtime_barrier(struct device * dev)1375 int pm_runtime_barrier(struct device *dev)
1376 {
1377 	int retval = 0;
1378 
1379 	pm_runtime_get_noresume(dev);
1380 	spin_lock_irq(&dev->power.lock);
1381 
1382 	if (dev->power.request_pending
1383 	    && dev->power.request == RPM_REQ_RESUME) {
1384 		rpm_resume(dev, 0);
1385 		retval = 1;
1386 	}
1387 
1388 	__pm_runtime_barrier(dev);
1389 
1390 	spin_unlock_irq(&dev->power.lock);
1391 	pm_runtime_put_noidle(dev);
1392 
1393 	return retval;
1394 }
1395 EXPORT_SYMBOL_GPL(pm_runtime_barrier);
1396 
1397 /**
1398  * __pm_runtime_disable - Disable runtime PM of a device.
1399  * @dev: Device to handle.
1400  * @check_resume: If set, check if there's a resume request for the device.
1401  *
1402  * Increment power.disable_depth for the device and if it was zero previously,
1403  * cancel all pending runtime PM requests for the device and wait for all
1404  * operations in progress to complete.  The device can be either active or
1405  * suspended after its runtime PM has been disabled.
1406  *
1407  * If @check_resume is set and there's a resume request pending when
1408  * __pm_runtime_disable() is called and power.disable_depth is zero, the
1409  * function will wake up the device before disabling its runtime PM.
1410  */
__pm_runtime_disable(struct device * dev,bool check_resume)1411 void __pm_runtime_disable(struct device *dev, bool check_resume)
1412 {
1413 	spin_lock_irq(&dev->power.lock);
1414 
1415 	if (dev->power.disable_depth > 0) {
1416 		dev->power.disable_depth++;
1417 		goto out;
1418 	}
1419 
1420 	/*
1421 	 * Wake up the device if there's a resume request pending, because that
1422 	 * means there probably is some I/O to process and disabling runtime PM
1423 	 * shouldn't prevent the device from processing the I/O.
1424 	 */
1425 	if (check_resume && dev->power.request_pending
1426 	    && dev->power.request == RPM_REQ_RESUME) {
1427 		/*
1428 		 * Prevent suspends and idle notifications from being carried
1429 		 * out after we have woken up the device.
1430 		 */
1431 		pm_runtime_get_noresume(dev);
1432 
1433 		rpm_resume(dev, 0);
1434 
1435 		pm_runtime_put_noidle(dev);
1436 	}
1437 
1438 	/* Update time accounting before disabling PM-runtime. */
1439 	update_pm_runtime_accounting(dev);
1440 
1441 	if (!dev->power.disable_depth++)
1442 		__pm_runtime_barrier(dev);
1443 
1444  out:
1445 	spin_unlock_irq(&dev->power.lock);
1446 }
1447 EXPORT_SYMBOL_GPL(__pm_runtime_disable);
1448 
1449 /**
1450  * pm_runtime_enable - Enable runtime PM of a device.
1451  * @dev: Device to handle.
1452  */
pm_runtime_enable(struct device * dev)1453 void pm_runtime_enable(struct device *dev)
1454 {
1455 	unsigned long flags;
1456 
1457 	spin_lock_irqsave(&dev->power.lock, flags);
1458 
1459 	if (dev->power.disable_depth > 0) {
1460 		dev->power.disable_depth--;
1461 
1462 		/* About to enable runtime pm, set accounting_timestamp to now */
1463 		if (!dev->power.disable_depth)
1464 			dev->power.accounting_timestamp = ktime_get_mono_fast_ns();
1465 	} else {
1466 		dev_warn(dev, "Unbalanced %s!\n", __func__);
1467 	}
1468 
1469 	WARN(!dev->power.disable_depth &&
1470 	     dev->power.runtime_status == RPM_SUSPENDED &&
1471 	     !dev->power.ignore_children &&
1472 	     atomic_read(&dev->power.child_count) > 0,
1473 	     "Enabling runtime PM for inactive device (%s) with active children\n",
1474 	     dev_name(dev));
1475 
1476 	spin_unlock_irqrestore(&dev->power.lock, flags);
1477 }
1478 EXPORT_SYMBOL_GPL(pm_runtime_enable);
1479 
1480 /**
1481  * pm_runtime_forbid - Block runtime PM of a device.
1482  * @dev: Device to handle.
1483  *
1484  * Increase the device's usage count and clear its power.runtime_auto flag,
1485  * so that it cannot be suspended at run time until pm_runtime_allow() is called
1486  * for it.
1487  */
pm_runtime_forbid(struct device * dev)1488 void pm_runtime_forbid(struct device *dev)
1489 {
1490 	spin_lock_irq(&dev->power.lock);
1491 	if (!dev->power.runtime_auto)
1492 		goto out;
1493 
1494 	dev->power.runtime_auto = false;
1495 	atomic_inc(&dev->power.usage_count);
1496 	rpm_resume(dev, 0);
1497 
1498  out:
1499 	spin_unlock_irq(&dev->power.lock);
1500 }
1501 EXPORT_SYMBOL_GPL(pm_runtime_forbid);
1502 
1503 /**
1504  * pm_runtime_allow - Unblock runtime PM of a device.
1505  * @dev: Device to handle.
1506  *
1507  * Decrease the device's usage count and set its power.runtime_auto flag.
1508  */
pm_runtime_allow(struct device * dev)1509 void pm_runtime_allow(struct device *dev)
1510 {
1511 	spin_lock_irq(&dev->power.lock);
1512 	if (dev->power.runtime_auto)
1513 		goto out;
1514 
1515 	dev->power.runtime_auto = true;
1516 	if (atomic_dec_and_test(&dev->power.usage_count))
1517 		rpm_idle(dev, RPM_AUTO | RPM_ASYNC);
1518 	else
1519 		trace_rpm_usage_rcuidle(dev, RPM_AUTO | RPM_ASYNC);
1520 
1521  out:
1522 	spin_unlock_irq(&dev->power.lock);
1523 }
1524 EXPORT_SYMBOL_GPL(pm_runtime_allow);
1525 
1526 /**
1527  * pm_runtime_no_callbacks - Ignore runtime PM callbacks for a device.
1528  * @dev: Device to handle.
1529  *
1530  * Set the power.no_callbacks flag, which tells the PM core that this
1531  * device is power-managed through its parent and has no runtime PM
1532  * callbacks of its own.  The runtime sysfs attributes will be removed.
1533  */
pm_runtime_no_callbacks(struct device * dev)1534 void pm_runtime_no_callbacks(struct device *dev)
1535 {
1536 	spin_lock_irq(&dev->power.lock);
1537 	dev->power.no_callbacks = 1;
1538 	spin_unlock_irq(&dev->power.lock);
1539 	if (device_is_registered(dev))
1540 		rpm_sysfs_remove(dev);
1541 }
1542 EXPORT_SYMBOL_GPL(pm_runtime_no_callbacks);
1543 
1544 /**
1545  * pm_runtime_irq_safe - Leave interrupts disabled during callbacks.
1546  * @dev: Device to handle
1547  *
1548  * Set the power.irq_safe flag, which tells the PM core that the
1549  * ->runtime_suspend() and ->runtime_resume() callbacks for this device should
1550  * always be invoked with the spinlock held and interrupts disabled.  It also
1551  * causes the parent's usage counter to be permanently incremented, preventing
1552  * the parent from runtime suspending -- otherwise an irq-safe child might have
1553  * to wait for a non-irq-safe parent.
1554  */
pm_runtime_irq_safe(struct device * dev)1555 void pm_runtime_irq_safe(struct device *dev)
1556 {
1557 	if (dev->parent)
1558 		pm_runtime_get_sync(dev->parent);
1559 	spin_lock_irq(&dev->power.lock);
1560 	dev->power.irq_safe = 1;
1561 	spin_unlock_irq(&dev->power.lock);
1562 }
1563 EXPORT_SYMBOL_GPL(pm_runtime_irq_safe);
1564 
1565 /**
1566  * update_autosuspend - Handle a change to a device's autosuspend settings.
1567  * @dev: Device to handle.
1568  * @old_delay: The former autosuspend_delay value.
1569  * @old_use: The former use_autosuspend value.
1570  *
1571  * Prevent runtime suspend if the new delay is negative and use_autosuspend is
1572  * set; otherwise allow it.  Send an idle notification if suspends are allowed.
1573  *
1574  * This function must be called under dev->power.lock with interrupts disabled.
1575  */
update_autosuspend(struct device * dev,int old_delay,int old_use)1576 static void update_autosuspend(struct device *dev, int old_delay, int old_use)
1577 {
1578 	int delay = dev->power.autosuspend_delay;
1579 
1580 	/* Should runtime suspend be prevented now? */
1581 	if (dev->power.use_autosuspend && delay < 0) {
1582 
1583 		/* If it used to be allowed then prevent it. */
1584 		if (!old_use || old_delay >= 0) {
1585 			atomic_inc(&dev->power.usage_count);
1586 			rpm_resume(dev, 0);
1587 		} else {
1588 			trace_rpm_usage_rcuidle(dev, 0);
1589 		}
1590 	}
1591 
1592 	/* Runtime suspend should be allowed now. */
1593 	else {
1594 
1595 		/* If it used to be prevented then allow it. */
1596 		if (old_use && old_delay < 0)
1597 			atomic_dec(&dev->power.usage_count);
1598 
1599 		/* Maybe we can autosuspend now. */
1600 		rpm_idle(dev, RPM_AUTO);
1601 	}
1602 }
1603 
1604 /**
1605  * pm_runtime_set_autosuspend_delay - Set a device's autosuspend_delay value.
1606  * @dev: Device to handle.
1607  * @delay: Value of the new delay in milliseconds.
1608  *
1609  * Set the device's power.autosuspend_delay value.  If it changes to negative
1610  * and the power.use_autosuspend flag is set, prevent runtime suspends.  If it
1611  * changes the other way, allow runtime suspends.
1612  */
pm_runtime_set_autosuspend_delay(struct device * dev,int delay)1613 void pm_runtime_set_autosuspend_delay(struct device *dev, int delay)
1614 {
1615 	int old_delay, old_use;
1616 
1617 	spin_lock_irq(&dev->power.lock);
1618 	old_delay = dev->power.autosuspend_delay;
1619 	old_use = dev->power.use_autosuspend;
1620 	dev->power.autosuspend_delay = delay;
1621 	update_autosuspend(dev, old_delay, old_use);
1622 	spin_unlock_irq(&dev->power.lock);
1623 }
1624 EXPORT_SYMBOL_GPL(pm_runtime_set_autosuspend_delay);
1625 
1626 /**
1627  * __pm_runtime_use_autosuspend - Set a device's use_autosuspend flag.
1628  * @dev: Device to handle.
1629  * @use: New value for use_autosuspend.
1630  *
1631  * Set the device's power.use_autosuspend flag, and allow or prevent runtime
1632  * suspends as needed.
1633  */
__pm_runtime_use_autosuspend(struct device * dev,bool use)1634 void __pm_runtime_use_autosuspend(struct device *dev, bool use)
1635 {
1636 	int old_delay, old_use;
1637 
1638 	spin_lock_irq(&dev->power.lock);
1639 	old_delay = dev->power.autosuspend_delay;
1640 	old_use = dev->power.use_autosuspend;
1641 	dev->power.use_autosuspend = use;
1642 	update_autosuspend(dev, old_delay, old_use);
1643 	spin_unlock_irq(&dev->power.lock);
1644 }
1645 EXPORT_SYMBOL_GPL(__pm_runtime_use_autosuspend);
1646 
1647 /**
1648  * pm_runtime_init - Initialize runtime PM fields in given device object.
1649  * @dev: Device object to initialize.
1650  */
pm_runtime_init(struct device * dev)1651 void pm_runtime_init(struct device *dev)
1652 {
1653 	dev->power.runtime_status = RPM_SUSPENDED;
1654 	dev->power.idle_notification = false;
1655 
1656 	dev->power.disable_depth = 1;
1657 	atomic_set(&dev->power.usage_count, 0);
1658 
1659 	dev->power.runtime_error = 0;
1660 
1661 	atomic_set(&dev->power.child_count, 0);
1662 	pm_suspend_ignore_children(dev, false);
1663 	dev->power.runtime_auto = true;
1664 
1665 	dev->power.request_pending = false;
1666 	dev->power.request = RPM_REQ_NONE;
1667 	dev->power.deferred_resume = false;
1668 	dev->power.needs_force_resume = 0;
1669 	INIT_WORK(&dev->power.work, pm_runtime_work);
1670 
1671 	dev->power.timer_expires = 0;
1672 	hrtimer_init(&dev->power.suspend_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1673 	dev->power.suspend_timer.function = pm_suspend_timer_fn;
1674 
1675 	init_waitqueue_head(&dev->power.wait_queue);
1676 }
1677 
1678 /**
1679  * pm_runtime_reinit - Re-initialize runtime PM fields in given device object.
1680  * @dev: Device object to re-initialize.
1681  */
pm_runtime_reinit(struct device * dev)1682 void pm_runtime_reinit(struct device *dev)
1683 {
1684 	if (!pm_runtime_enabled(dev)) {
1685 		if (dev->power.runtime_status == RPM_ACTIVE)
1686 			pm_runtime_set_suspended(dev);
1687 		if (dev->power.irq_safe) {
1688 			spin_lock_irq(&dev->power.lock);
1689 			dev->power.irq_safe = 0;
1690 			spin_unlock_irq(&dev->power.lock);
1691 			if (dev->parent)
1692 				pm_runtime_put(dev->parent);
1693 		}
1694 	}
1695 }
1696 
1697 /**
1698  * pm_runtime_remove - Prepare for removing a device from device hierarchy.
1699  * @dev: Device object being removed from device hierarchy.
1700  */
pm_runtime_remove(struct device * dev)1701 void pm_runtime_remove(struct device *dev)
1702 {
1703 	__pm_runtime_disable(dev, false);
1704 	pm_runtime_reinit(dev);
1705 }
1706 
1707 /**
1708  * pm_runtime_get_suppliers - Resume and reference-count supplier devices.
1709  * @dev: Consumer device.
1710  */
pm_runtime_get_suppliers(struct device * dev)1711 void pm_runtime_get_suppliers(struct device *dev)
1712 {
1713 	struct device_link *link;
1714 	int idx;
1715 
1716 	idx = device_links_read_lock();
1717 
1718 	list_for_each_entry_rcu(link, &dev->links.suppliers, c_node,
1719 				device_links_read_lock_held())
1720 		if (link->flags & DL_FLAG_PM_RUNTIME) {
1721 			link->supplier_preactivated = true;
1722 			pm_runtime_get_sync(link->supplier);
1723 			refcount_inc(&link->rpm_active);
1724 		}
1725 
1726 	device_links_read_unlock(idx);
1727 }
1728 
1729 /**
1730  * pm_runtime_put_suppliers - Drop references to supplier devices.
1731  * @dev: Consumer device.
1732  */
pm_runtime_put_suppliers(struct device * dev)1733 void pm_runtime_put_suppliers(struct device *dev)
1734 {
1735 	struct device_link *link;
1736 	unsigned long flags;
1737 	bool put;
1738 	int idx;
1739 
1740 	idx = device_links_read_lock();
1741 
1742 	list_for_each_entry_rcu(link, &dev->links.suppliers, c_node,
1743 				device_links_read_lock_held())
1744 		if (link->supplier_preactivated) {
1745 			link->supplier_preactivated = false;
1746 			spin_lock_irqsave(&dev->power.lock, flags);
1747 			put = pm_runtime_status_suspended(dev) &&
1748 			      refcount_dec_not_one(&link->rpm_active);
1749 			spin_unlock_irqrestore(&dev->power.lock, flags);
1750 			if (put)
1751 				pm_runtime_put(link->supplier);
1752 		}
1753 
1754 	device_links_read_unlock(idx);
1755 }
1756 
pm_runtime_new_link(struct device * dev)1757 void pm_runtime_new_link(struct device *dev)
1758 {
1759 	spin_lock_irq(&dev->power.lock);
1760 	dev->power.links_count++;
1761 	spin_unlock_irq(&dev->power.lock);
1762 }
1763 
pm_runtime_drop_link_count(struct device * dev)1764 static void pm_runtime_drop_link_count(struct device *dev)
1765 {
1766 	spin_lock_irq(&dev->power.lock);
1767 	WARN_ON(dev->power.links_count == 0);
1768 	dev->power.links_count--;
1769 	spin_unlock_irq(&dev->power.lock);
1770 }
1771 
1772 /**
1773  * pm_runtime_drop_link - Prepare for device link removal.
1774  * @link: Device link going away.
1775  *
1776  * Drop the link count of the consumer end of @link and decrement the supplier
1777  * device's runtime PM usage counter as many times as needed to drop all of the
1778  * PM runtime reference to it from the consumer.
1779  */
pm_runtime_drop_link(struct device_link * link)1780 void pm_runtime_drop_link(struct device_link *link)
1781 {
1782 	if (!(link->flags & DL_FLAG_PM_RUNTIME))
1783 		return;
1784 
1785 	pm_runtime_drop_link_count(link->consumer);
1786 	pm_runtime_release_supplier(link);
1787 	pm_request_idle(link->supplier);
1788 }
1789 
pm_runtime_need_not_resume(struct device * dev)1790 static bool pm_runtime_need_not_resume(struct device *dev)
1791 {
1792 	return atomic_read(&dev->power.usage_count) <= 1 &&
1793 		(atomic_read(&dev->power.child_count) == 0 ||
1794 		 dev->power.ignore_children);
1795 }
1796 
1797 /**
1798  * pm_runtime_force_suspend - Force a device into suspend state if needed.
1799  * @dev: Device to suspend.
1800  *
1801  * Disable runtime PM so we safely can check the device's runtime PM status and
1802  * if it is active, invoke its ->runtime_suspend callback to suspend it and
1803  * change its runtime PM status field to RPM_SUSPENDED.  Also, if the device's
1804  * usage and children counters don't indicate that the device was in use before
1805  * the system-wide transition under way, decrement its parent's children counter
1806  * (if there is a parent).  Keep runtime PM disabled to preserve the state
1807  * unless we encounter errors.
1808  *
1809  * Typically this function may be invoked from a system suspend callback to make
1810  * sure the device is put into low power state and it should only be used during
1811  * system-wide PM transitions to sleep states.  It assumes that the analogous
1812  * pm_runtime_force_resume() will be used to resume the device.
1813  */
pm_runtime_force_suspend(struct device * dev)1814 int pm_runtime_force_suspend(struct device *dev)
1815 {
1816 	int (*callback)(struct device *);
1817 	int ret;
1818 
1819 	pm_runtime_disable(dev);
1820 	if (pm_runtime_status_suspended(dev))
1821 		return 0;
1822 
1823 	callback = RPM_GET_CALLBACK(dev, runtime_suspend);
1824 
1825 	ret = callback ? callback(dev) : 0;
1826 	if (ret)
1827 		goto err;
1828 
1829 	/*
1830 	 * If the device can stay in suspend after the system-wide transition
1831 	 * to the working state that will follow, drop the children counter of
1832 	 * its parent, but set its status to RPM_SUSPENDED anyway in case this
1833 	 * function will be called again for it in the meantime.
1834 	 */
1835 	if (pm_runtime_need_not_resume(dev)) {
1836 		pm_runtime_set_suspended(dev);
1837 	} else {
1838 		__update_runtime_status(dev, RPM_SUSPENDED);
1839 		dev->power.needs_force_resume = 1;
1840 	}
1841 
1842 	return 0;
1843 
1844 err:
1845 	pm_runtime_enable(dev);
1846 	return ret;
1847 }
1848 EXPORT_SYMBOL_GPL(pm_runtime_force_suspend);
1849 
1850 /**
1851  * pm_runtime_force_resume - Force a device into resume state if needed.
1852  * @dev: Device to resume.
1853  *
1854  * Prior invoking this function we expect the user to have brought the device
1855  * into low power state by a call to pm_runtime_force_suspend(). Here we reverse
1856  * those actions and bring the device into full power, if it is expected to be
1857  * used on system resume.  In the other case, we defer the resume to be managed
1858  * via runtime PM.
1859  *
1860  * Typically this function may be invoked from a system resume callback.
1861  */
pm_runtime_force_resume(struct device * dev)1862 int pm_runtime_force_resume(struct device *dev)
1863 {
1864 	int (*callback)(struct device *);
1865 	int ret = 0;
1866 
1867 	if (!pm_runtime_status_suspended(dev) || !dev->power.needs_force_resume)
1868 		goto out;
1869 
1870 	/*
1871 	 * The value of the parent's children counter is correct already, so
1872 	 * just update the status of the device.
1873 	 */
1874 	__update_runtime_status(dev, RPM_ACTIVE);
1875 
1876 	callback = RPM_GET_CALLBACK(dev, runtime_resume);
1877 
1878 	ret = callback ? callback(dev) : 0;
1879 	if (ret) {
1880 		pm_runtime_set_suspended(dev);
1881 		goto out;
1882 	}
1883 
1884 	pm_runtime_mark_last_busy(dev);
1885 out:
1886 	dev->power.needs_force_resume = 0;
1887 	pm_runtime_enable(dev);
1888 	return ret;
1889 }
1890 EXPORT_SYMBOL_GPL(pm_runtime_force_resume);
1891