xref: /linux/drivers/regulator/core.c (revision 5c458073553f0ef74f5c8db1bd459c87c722a299)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 //
3 // core.c  --  Voltage/Current Regulator framework.
4 //
5 // Copyright 2007, 2008 Wolfson Microelectronics PLC.
6 // Copyright 2008 SlimLogic Ltd.
7 //
8 // Author: Liam Girdwood <lrg@slimlogic.co.uk>
9 
10 #include <linux/kernel.h>
11 #include <linux/init.h>
12 #include <linux/debugfs.h>
13 #include <linux/device.h>
14 #include <linux/slab.h>
15 #include <linux/async.h>
16 #include <linux/err.h>
17 #include <linux/mutex.h>
18 #include <linux/suspend.h>
19 #include <linux/delay.h>
20 #include <linux/gpio/consumer.h>
21 #include <linux/of.h>
22 #include <linux/reboot.h>
23 #include <linux/regmap.h>
24 #include <linux/regulator/of_regulator.h>
25 #include <linux/regulator/consumer.h>
26 #include <linux/regulator/coupler.h>
27 #include <linux/regulator/driver.h>
28 #include <linux/regulator/machine.h>
29 #include <linux/module.h>
30 
31 #define CREATE_TRACE_POINTS
32 #include <trace/events/regulator.h>
33 
34 #include "dummy.h"
35 #include "internal.h"
36 #include "regnl.h"
37 
38 static DEFINE_WW_CLASS(regulator_ww_class);
39 static DEFINE_MUTEX(regulator_nesting_mutex);
40 static DEFINE_MUTEX(regulator_list_mutex);
41 static LIST_HEAD(regulator_map_list);
42 static LIST_HEAD(regulator_ena_gpio_list);
43 static LIST_HEAD(regulator_supply_alias_list);
44 static LIST_HEAD(regulator_coupler_list);
45 static bool has_full_constraints;
46 
47 static const struct bus_type regulator_bus;
48 
49 static struct dentry *debugfs_root;
50 
51 /*
52  * struct regulator_map
53  *
54  * Used to provide symbolic supply names to devices.
55  */
56 struct regulator_map {
57 	struct list_head list;
58 	const char *dev_name;   /* The dev_name() for the consumer */
59 	const char *supply;
60 	struct regulator_dev *regulator;
61 };
62 
63 /*
64  * struct regulator_enable_gpio
65  *
66  * Management for shared enable GPIO pin
67  */
68 struct regulator_enable_gpio {
69 	struct list_head list;
70 	struct gpio_desc *gpiod;
71 	u32 enable_count;	/* a number of enabled shared GPIO */
72 	u32 request_count;	/* a number of requested shared GPIO */
73 };
74 
75 /*
76  * struct regulator_supply_alias
77  *
78  * Used to map lookups for a supply onto an alternative device.
79  */
80 struct regulator_supply_alias {
81 	struct list_head list;
82 	struct device *src_dev;
83 	const char *src_supply;
84 	struct device *alias_dev;
85 	const char *alias_supply;
86 };
87 
88 /*
89  * Work item used to forward regulator events.
90  *
91  * @work: workqueue entry
92  * @rdev: regulator device to notify (consumer receiving the forwarded event)
93  * @event: event code to be forwarded
94  */
95 struct regulator_event_work {
96 	struct work_struct work;
97 	struct regulator_dev *rdev;
98 	unsigned long event;
99 };
100 
101 static int _regulator_enable(struct regulator *regulator);
102 static int _regulator_is_enabled(struct regulator_dev *rdev);
103 static int _regulator_disable(struct regulator *regulator);
104 static int _regulator_get_error_flags(struct regulator_dev *rdev, unsigned int *flags);
105 static int _regulator_get_current_limit(struct regulator_dev *rdev);
106 static unsigned int _regulator_get_mode(struct regulator_dev *rdev);
107 static int _notifier_call_chain(struct regulator_dev *rdev,
108 				  unsigned long event, void *data);
109 static int _regulator_do_set_voltage(struct regulator_dev *rdev,
110 				     int min_uV, int max_uV);
111 static int regulator_balance_voltage(struct regulator_dev *rdev,
112 				     suspend_state_t state);
113 static struct regulator *create_regulator(struct regulator_dev *rdev,
114 					  struct device *dev,
115 					  const char *supply_name);
116 static void destroy_regulator(struct regulator *regulator);
117 static void _regulator_put(struct regulator *regulator);
118 
119 const char *rdev_get_name(struct regulator_dev *rdev)
120 {
121 	if (rdev->constraints && rdev->constraints->name)
122 		return rdev->constraints->name;
123 	else if (rdev->desc->name)
124 		return rdev->desc->name;
125 	else
126 		return "";
127 }
128 EXPORT_SYMBOL_GPL(rdev_get_name);
129 
130 static bool have_full_constraints(void)
131 {
132 	return has_full_constraints || of_have_populated_dt();
133 }
134 
135 static bool regulator_ops_is_valid(struct regulator_dev *rdev, int ops)
136 {
137 	if (!rdev->constraints) {
138 		rdev_err(rdev, "no constraints\n");
139 		return false;
140 	}
141 
142 	if (rdev->constraints->valid_ops_mask & ops)
143 		return true;
144 
145 	return false;
146 }
147 
148 /**
149  * regulator_lock_nested - lock a single regulator
150  * @rdev:		regulator source
151  * @ww_ctx:		w/w mutex acquire context
152  *
153  * This function can be called many times by one task on
154  * a single regulator and its mutex will be locked only
155  * once. If a task, which is calling this function is other
156  * than the one, which initially locked the mutex, it will
157  * wait on mutex.
158  *
159  * Return: 0 on success or a negative error number on failure.
160  */
161 static inline int regulator_lock_nested(struct regulator_dev *rdev,
162 					struct ww_acquire_ctx *ww_ctx)
163 {
164 	bool lock = false;
165 	int ret = 0;
166 
167 	mutex_lock(&regulator_nesting_mutex);
168 
169 	if (!ww_mutex_trylock(&rdev->mutex, ww_ctx)) {
170 		if (rdev->mutex_owner == current)
171 			rdev->ref_cnt++;
172 		else
173 			lock = true;
174 
175 		if (lock) {
176 			mutex_unlock(&regulator_nesting_mutex);
177 			ret = ww_mutex_lock(&rdev->mutex, ww_ctx);
178 			mutex_lock(&regulator_nesting_mutex);
179 		}
180 	} else {
181 		lock = true;
182 	}
183 
184 	if (lock && ret != -EDEADLK) {
185 		rdev->ref_cnt++;
186 		rdev->mutex_owner = current;
187 	}
188 
189 	mutex_unlock(&regulator_nesting_mutex);
190 
191 	return ret;
192 }
193 
194 /**
195  * regulator_lock - lock a single regulator
196  * @rdev:		regulator source
197  *
198  * This function can be called many times by one task on
199  * a single regulator and its mutex will be locked only
200  * once. If a task, which is calling this function is other
201  * than the one, which initially locked the mutex, it will
202  * wait on mutex.
203  */
204 static void regulator_lock(struct regulator_dev *rdev)
205 {
206 	regulator_lock_nested(rdev, NULL);
207 }
208 
209 /**
210  * regulator_unlock - unlock a single regulator
211  * @rdev:		regulator_source
212  *
213  * This function unlocks the mutex when the
214  * reference counter reaches 0.
215  */
216 static void regulator_unlock(struct regulator_dev *rdev)
217 {
218 	mutex_lock(&regulator_nesting_mutex);
219 
220 	if (--rdev->ref_cnt == 0) {
221 		rdev->mutex_owner = NULL;
222 		ww_mutex_unlock(&rdev->mutex);
223 	}
224 
225 	WARN_ON_ONCE(rdev->ref_cnt < 0);
226 
227 	mutex_unlock(&regulator_nesting_mutex);
228 }
229 
230 /**
231  * regulator_lock_two - lock two regulators
232  * @rdev1:		first regulator
233  * @rdev2:		second regulator
234  * @ww_ctx:		w/w mutex acquire context
235  *
236  * Locks both rdevs using the regulator_ww_class.
237  */
238 static void regulator_lock_two(struct regulator_dev *rdev1,
239 			       struct regulator_dev *rdev2,
240 			       struct ww_acquire_ctx *ww_ctx)
241 {
242 	struct regulator_dev *held, *contended;
243 	int ret;
244 
245 	ww_acquire_init(ww_ctx, &regulator_ww_class);
246 
247 	/* Try to just grab both of them */
248 	ret = regulator_lock_nested(rdev1, ww_ctx);
249 	WARN_ON(ret);
250 	ret = regulator_lock_nested(rdev2, ww_ctx);
251 	if (ret != -EDEADLK) {
252 		WARN_ON(ret);
253 		goto exit;
254 	}
255 
256 	held = rdev1;
257 	contended = rdev2;
258 	while (true) {
259 		regulator_unlock(held);
260 
261 		ww_mutex_lock_slow(&contended->mutex, ww_ctx);
262 		contended->ref_cnt++;
263 		contended->mutex_owner = current;
264 		swap(held, contended);
265 		ret = regulator_lock_nested(contended, ww_ctx);
266 
267 		if (ret != -EDEADLK) {
268 			WARN_ON(ret);
269 			break;
270 		}
271 	}
272 
273 exit:
274 	ww_acquire_done(ww_ctx);
275 }
276 
277 /**
278  * regulator_unlock_two - unlock two regulators
279  * @rdev1:		first regulator
280  * @rdev2:		second regulator
281  * @ww_ctx:		w/w mutex acquire context
282  *
283  * The inverse of regulator_lock_two().
284  */
285 
286 static void regulator_unlock_two(struct regulator_dev *rdev1,
287 				 struct regulator_dev *rdev2,
288 				 struct ww_acquire_ctx *ww_ctx)
289 {
290 	regulator_unlock(rdev2);
291 	regulator_unlock(rdev1);
292 	ww_acquire_fini(ww_ctx);
293 }
294 
295 static bool regulator_supply_is_couple(struct regulator_dev *rdev)
296 {
297 	struct regulator_dev *c_rdev;
298 	int i;
299 
300 	for (i = 1; i < rdev->coupling_desc.n_coupled; i++) {
301 		c_rdev = rdev->coupling_desc.coupled_rdevs[i];
302 
303 		if (rdev->supply->rdev == c_rdev)
304 			return true;
305 	}
306 
307 	return false;
308 }
309 
310 static void regulator_unlock_recursive(struct regulator_dev *rdev,
311 				       unsigned int n_coupled)
312 {
313 	struct regulator_dev *c_rdev, *supply_rdev;
314 	int i, supply_n_coupled;
315 
316 	for (i = n_coupled; i > 0; i--) {
317 		c_rdev = rdev->coupling_desc.coupled_rdevs[i - 1];
318 
319 		if (!c_rdev)
320 			continue;
321 
322 		if (c_rdev->supply && !regulator_supply_is_couple(c_rdev)) {
323 			supply_rdev = c_rdev->supply->rdev;
324 			supply_n_coupled = supply_rdev->coupling_desc.n_coupled;
325 
326 			regulator_unlock_recursive(supply_rdev,
327 						   supply_n_coupled);
328 		}
329 
330 		regulator_unlock(c_rdev);
331 	}
332 }
333 
334 static int regulator_lock_recursive(struct regulator_dev *rdev,
335 				    struct regulator_dev **new_contended_rdev,
336 				    struct regulator_dev **old_contended_rdev,
337 				    struct ww_acquire_ctx *ww_ctx)
338 {
339 	struct regulator_dev *c_rdev;
340 	int i, err;
341 
342 	for (i = 0; i < rdev->coupling_desc.n_coupled; i++) {
343 		c_rdev = rdev->coupling_desc.coupled_rdevs[i];
344 
345 		if (!c_rdev)
346 			continue;
347 
348 		if (c_rdev != *old_contended_rdev) {
349 			err = regulator_lock_nested(c_rdev, ww_ctx);
350 			if (err) {
351 				if (err == -EDEADLK) {
352 					*new_contended_rdev = c_rdev;
353 					goto err_unlock;
354 				}
355 
356 				/* shouldn't happen */
357 				WARN_ON_ONCE(err != -EALREADY);
358 			}
359 		} else {
360 			*old_contended_rdev = NULL;
361 		}
362 
363 		if (c_rdev->supply && !regulator_supply_is_couple(c_rdev)) {
364 			err = regulator_lock_recursive(c_rdev->supply->rdev,
365 						       new_contended_rdev,
366 						       old_contended_rdev,
367 						       ww_ctx);
368 			if (err) {
369 				regulator_unlock(c_rdev);
370 				goto err_unlock;
371 			}
372 		}
373 	}
374 
375 	return 0;
376 
377 err_unlock:
378 	regulator_unlock_recursive(rdev, i);
379 
380 	return err;
381 }
382 
383 /**
384  * regulator_unlock_dependent - unlock regulator's suppliers and coupled
385  *				regulators
386  * @rdev:			regulator source
387  * @ww_ctx:			w/w mutex acquire context
388  *
389  * Unlock all regulators related with rdev by coupling or supplying.
390  */
391 static void regulator_unlock_dependent(struct regulator_dev *rdev,
392 				       struct ww_acquire_ctx *ww_ctx)
393 {
394 	regulator_unlock_recursive(rdev, rdev->coupling_desc.n_coupled);
395 	ww_acquire_fini(ww_ctx);
396 }
397 
398 /**
399  * regulator_lock_dependent - lock regulator's suppliers and coupled regulators
400  * @rdev:			regulator source
401  * @ww_ctx:			w/w mutex acquire context
402  *
403  * This function as a wrapper on regulator_lock_recursive(), which locks
404  * all regulators related with rdev by coupling or supplying.
405  */
406 static void regulator_lock_dependent(struct regulator_dev *rdev,
407 				     struct ww_acquire_ctx *ww_ctx)
408 {
409 	struct regulator_dev *new_contended_rdev = NULL;
410 	struct regulator_dev *old_contended_rdev = NULL;
411 	int err;
412 
413 	mutex_lock(&regulator_list_mutex);
414 
415 	ww_acquire_init(ww_ctx, &regulator_ww_class);
416 
417 	do {
418 		if (new_contended_rdev) {
419 			ww_mutex_lock_slow(&new_contended_rdev->mutex, ww_ctx);
420 			old_contended_rdev = new_contended_rdev;
421 			old_contended_rdev->ref_cnt++;
422 			old_contended_rdev->mutex_owner = current;
423 		}
424 
425 		err = regulator_lock_recursive(rdev,
426 					       &new_contended_rdev,
427 					       &old_contended_rdev,
428 					       ww_ctx);
429 
430 		if (old_contended_rdev)
431 			regulator_unlock(old_contended_rdev);
432 
433 	} while (err == -EDEADLK);
434 
435 	ww_acquire_done(ww_ctx);
436 
437 	mutex_unlock(&regulator_list_mutex);
438 }
439 
440 /* Platform voltage constraint check */
441 int regulator_check_voltage(struct regulator_dev *rdev,
442 			    int *min_uV, int *max_uV)
443 {
444 	BUG_ON(*min_uV > *max_uV);
445 
446 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_VOLTAGE)) {
447 		rdev_err(rdev, "voltage operation not allowed\n");
448 		return -EPERM;
449 	}
450 
451 	if (*max_uV > rdev->constraints->max_uV)
452 		*max_uV = rdev->constraints->max_uV;
453 	if (*min_uV < rdev->constraints->min_uV)
454 		*min_uV = rdev->constraints->min_uV;
455 
456 	if (*min_uV > *max_uV) {
457 		rdev_err(rdev, "unsupportable voltage range: %d-%duV\n",
458 			 *min_uV, *max_uV);
459 		return -EINVAL;
460 	}
461 
462 	return 0;
463 }
464 
465 /* return 0 if the state is valid */
466 static int regulator_check_states(suspend_state_t state)
467 {
468 	return (state > PM_SUSPEND_MAX || state == PM_SUSPEND_TO_IDLE);
469 }
470 
471 /* Make sure we select a voltage that suits the needs of all
472  * regulator consumers
473  */
474 int regulator_check_consumers(struct regulator_dev *rdev,
475 			      int *min_uV, int *max_uV,
476 			      suspend_state_t state)
477 {
478 	struct regulator *regulator;
479 	struct regulator_voltage *voltage;
480 
481 	list_for_each_entry(regulator, &rdev->consumer_list, list) {
482 		voltage = &regulator->voltage[state];
483 		/*
484 		 * Assume consumers that didn't say anything are OK
485 		 * with anything in the constraint range.
486 		 */
487 		if (!voltage->min_uV && !voltage->max_uV)
488 			continue;
489 
490 		if (*max_uV > voltage->max_uV)
491 			*max_uV = voltage->max_uV;
492 		if (*min_uV < voltage->min_uV)
493 			*min_uV = voltage->min_uV;
494 	}
495 
496 	if (*min_uV > *max_uV) {
497 		rdev_err(rdev, "Restricting voltage, %u-%uuV\n",
498 			*min_uV, *max_uV);
499 		return -EINVAL;
500 	}
501 
502 	return 0;
503 }
504 
505 /* current constraint check */
506 static int regulator_check_current_limit(struct regulator_dev *rdev,
507 					int *min_uA, int *max_uA)
508 {
509 	BUG_ON(*min_uA > *max_uA);
510 
511 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_CURRENT)) {
512 		rdev_err(rdev, "current operation not allowed\n");
513 		return -EPERM;
514 	}
515 
516 	if (*max_uA > rdev->constraints->max_uA &&
517 	    rdev->constraints->max_uA)
518 		*max_uA = rdev->constraints->max_uA;
519 	if (*min_uA < rdev->constraints->min_uA)
520 		*min_uA = rdev->constraints->min_uA;
521 
522 	if (*min_uA > *max_uA) {
523 		rdev_err(rdev, "unsupportable current range: %d-%duA\n",
524 			 *min_uA, *max_uA);
525 		return -EINVAL;
526 	}
527 
528 	return 0;
529 }
530 
531 /* operating mode constraint check */
532 static int regulator_mode_constrain(struct regulator_dev *rdev,
533 				    unsigned int *mode)
534 {
535 	switch (*mode) {
536 	case REGULATOR_MODE_FAST:
537 	case REGULATOR_MODE_NORMAL:
538 	case REGULATOR_MODE_IDLE:
539 	case REGULATOR_MODE_STANDBY:
540 		break;
541 	default:
542 		rdev_err(rdev, "invalid mode %x specified\n", *mode);
543 		return -EINVAL;
544 	}
545 
546 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_MODE)) {
547 		rdev_err(rdev, "mode operation not allowed\n");
548 		return -EPERM;
549 	}
550 
551 	/* The modes are bitmasks, the most power hungry modes having
552 	 * the lowest values. If the requested mode isn't supported
553 	 * try higher modes.
554 	 */
555 	while (*mode) {
556 		if (rdev->constraints->valid_modes_mask & *mode)
557 			return 0;
558 		*mode /= 2;
559 	}
560 
561 	return -EINVAL;
562 }
563 
564 static inline struct regulator_state *
565 regulator_get_suspend_state(struct regulator_dev *rdev, suspend_state_t state)
566 {
567 	if (rdev->constraints == NULL)
568 		return NULL;
569 
570 	switch (state) {
571 	case PM_SUSPEND_STANDBY:
572 		return &rdev->constraints->state_standby;
573 	case PM_SUSPEND_MEM:
574 		return &rdev->constraints->state_mem;
575 	case PM_SUSPEND_MAX:
576 		return &rdev->constraints->state_disk;
577 	default:
578 		return NULL;
579 	}
580 }
581 
582 static const struct regulator_state *
583 regulator_get_suspend_state_check(struct regulator_dev *rdev, suspend_state_t state)
584 {
585 	const struct regulator_state *rstate;
586 
587 	rstate = regulator_get_suspend_state(rdev, state);
588 	if (rstate == NULL)
589 		return NULL;
590 
591 	/* If we have no suspend mode configuration don't set anything;
592 	 * only warn if the driver implements set_suspend_voltage or
593 	 * set_suspend_mode callback.
594 	 */
595 	if (rstate->enabled != ENABLE_IN_SUSPEND &&
596 	    rstate->enabled != DISABLE_IN_SUSPEND) {
597 		if (rdev->desc->ops->set_suspend_voltage ||
598 		    rdev->desc->ops->set_suspend_mode)
599 			rdev_warn(rdev, "No configuration\n");
600 		return NULL;
601 	}
602 
603 	return rstate;
604 }
605 
606 static ssize_t microvolts_show(struct device *dev,
607 			       struct device_attribute *attr, char *buf)
608 {
609 	struct regulator_dev *rdev = dev_get_drvdata(dev);
610 	int uV;
611 
612 	regulator_lock(rdev);
613 	uV = regulator_get_voltage_rdev(rdev);
614 	regulator_unlock(rdev);
615 
616 	if (uV < 0)
617 		return uV;
618 	return sprintf(buf, "%d\n", uV);
619 }
620 static DEVICE_ATTR_RO(microvolts);
621 
622 static ssize_t microamps_show(struct device *dev,
623 			      struct device_attribute *attr, char *buf)
624 {
625 	struct regulator_dev *rdev = dev_get_drvdata(dev);
626 
627 	return sprintf(buf, "%d\n", _regulator_get_current_limit(rdev));
628 }
629 static DEVICE_ATTR_RO(microamps);
630 
631 static ssize_t name_show(struct device *dev, struct device_attribute *attr,
632 			 char *buf)
633 {
634 	struct regulator_dev *rdev = dev_get_drvdata(dev);
635 
636 	return sprintf(buf, "%s\n", rdev_get_name(rdev));
637 }
638 static DEVICE_ATTR_RO(name);
639 
640 static const char *regulator_opmode_to_str(int mode)
641 {
642 	switch (mode) {
643 	case REGULATOR_MODE_FAST:
644 		return "fast";
645 	case REGULATOR_MODE_NORMAL:
646 		return "normal";
647 	case REGULATOR_MODE_IDLE:
648 		return "idle";
649 	case REGULATOR_MODE_STANDBY:
650 		return "standby";
651 	}
652 	return "unknown";
653 }
654 
655 static ssize_t regulator_print_opmode(char *buf, int mode)
656 {
657 	return sprintf(buf, "%s\n", regulator_opmode_to_str(mode));
658 }
659 
660 static ssize_t opmode_show(struct device *dev,
661 			   struct device_attribute *attr, char *buf)
662 {
663 	struct regulator_dev *rdev = dev_get_drvdata(dev);
664 
665 	return regulator_print_opmode(buf, _regulator_get_mode(rdev));
666 }
667 static DEVICE_ATTR_RO(opmode);
668 
669 static ssize_t regulator_print_state(char *buf, int state)
670 {
671 	if (state > 0)
672 		return sprintf(buf, "enabled\n");
673 	else if (state == 0)
674 		return sprintf(buf, "disabled\n");
675 	else
676 		return sprintf(buf, "unknown\n");
677 }
678 
679 static ssize_t state_show(struct device *dev,
680 			  struct device_attribute *attr, char *buf)
681 {
682 	struct regulator_dev *rdev = dev_get_drvdata(dev);
683 	ssize_t ret;
684 
685 	regulator_lock(rdev);
686 	ret = regulator_print_state(buf, _regulator_is_enabled(rdev));
687 	regulator_unlock(rdev);
688 
689 	return ret;
690 }
691 static DEVICE_ATTR_RO(state);
692 
693 static ssize_t status_show(struct device *dev,
694 			   struct device_attribute *attr, char *buf)
695 {
696 	struct regulator_dev *rdev = dev_get_drvdata(dev);
697 	int status;
698 	char *label;
699 
700 	status = rdev->desc->ops->get_status(rdev);
701 	if (status < 0)
702 		return status;
703 
704 	switch (status) {
705 	case REGULATOR_STATUS_OFF:
706 		label = "off";
707 		break;
708 	case REGULATOR_STATUS_ON:
709 		label = "on";
710 		break;
711 	case REGULATOR_STATUS_ERROR:
712 		label = "error";
713 		break;
714 	case REGULATOR_STATUS_FAST:
715 		label = "fast";
716 		break;
717 	case REGULATOR_STATUS_NORMAL:
718 		label = "normal";
719 		break;
720 	case REGULATOR_STATUS_IDLE:
721 		label = "idle";
722 		break;
723 	case REGULATOR_STATUS_STANDBY:
724 		label = "standby";
725 		break;
726 	case REGULATOR_STATUS_BYPASS:
727 		label = "bypass";
728 		break;
729 	case REGULATOR_STATUS_UNDEFINED:
730 		label = "undefined";
731 		break;
732 	default:
733 		return -ERANGE;
734 	}
735 
736 	return sprintf(buf, "%s\n", label);
737 }
738 static DEVICE_ATTR_RO(status);
739 
740 static ssize_t min_microamps_show(struct device *dev,
741 				  struct device_attribute *attr, char *buf)
742 {
743 	struct regulator_dev *rdev = dev_get_drvdata(dev);
744 
745 	if (!rdev->constraints)
746 		return sprintf(buf, "constraint not defined\n");
747 
748 	return sprintf(buf, "%d\n", rdev->constraints->min_uA);
749 }
750 static DEVICE_ATTR_RO(min_microamps);
751 
752 static ssize_t max_microamps_show(struct device *dev,
753 				  struct device_attribute *attr, char *buf)
754 {
755 	struct regulator_dev *rdev = dev_get_drvdata(dev);
756 
757 	if (!rdev->constraints)
758 		return sprintf(buf, "constraint not defined\n");
759 
760 	return sprintf(buf, "%d\n", rdev->constraints->max_uA);
761 }
762 static DEVICE_ATTR_RO(max_microamps);
763 
764 static ssize_t min_microvolts_show(struct device *dev,
765 				   struct device_attribute *attr, char *buf)
766 {
767 	struct regulator_dev *rdev = dev_get_drvdata(dev);
768 
769 	if (!rdev->constraints)
770 		return sprintf(buf, "constraint not defined\n");
771 
772 	return sprintf(buf, "%d\n", rdev->constraints->min_uV);
773 }
774 static DEVICE_ATTR_RO(min_microvolts);
775 
776 static ssize_t max_microvolts_show(struct device *dev,
777 				   struct device_attribute *attr, char *buf)
778 {
779 	struct regulator_dev *rdev = dev_get_drvdata(dev);
780 
781 	if (!rdev->constraints)
782 		return sprintf(buf, "constraint not defined\n");
783 
784 	return sprintf(buf, "%d\n", rdev->constraints->max_uV);
785 }
786 static DEVICE_ATTR_RO(max_microvolts);
787 
788 static ssize_t requested_microamps_show(struct device *dev,
789 					struct device_attribute *attr, char *buf)
790 {
791 	struct regulator_dev *rdev = dev_get_drvdata(dev);
792 	struct regulator *regulator;
793 	int uA = 0;
794 
795 	regulator_lock(rdev);
796 	list_for_each_entry(regulator, &rdev->consumer_list, list) {
797 		if (regulator->enable_count)
798 			uA += regulator->uA_load;
799 	}
800 	regulator_unlock(rdev);
801 	return sprintf(buf, "%d\n", uA);
802 }
803 static DEVICE_ATTR_RO(requested_microamps);
804 
805 static ssize_t num_users_show(struct device *dev, struct device_attribute *attr,
806 			      char *buf)
807 {
808 	struct regulator_dev *rdev = dev_get_drvdata(dev);
809 	return sprintf(buf, "%d\n", rdev->use_count);
810 }
811 static DEVICE_ATTR_RO(num_users);
812 
813 static ssize_t type_show(struct device *dev, struct device_attribute *attr,
814 			 char *buf)
815 {
816 	struct regulator_dev *rdev = dev_get_drvdata(dev);
817 
818 	switch (rdev->desc->type) {
819 	case REGULATOR_VOLTAGE:
820 		return sprintf(buf, "voltage\n");
821 	case REGULATOR_CURRENT:
822 		return sprintf(buf, "current\n");
823 	}
824 	return sprintf(buf, "unknown\n");
825 }
826 static DEVICE_ATTR_RO(type);
827 
828 static ssize_t suspend_mem_microvolts_show(struct device *dev,
829 					   struct device_attribute *attr, char *buf)
830 {
831 	struct regulator_dev *rdev = dev_get_drvdata(dev);
832 
833 	return sprintf(buf, "%d\n", rdev->constraints->state_mem.uV);
834 }
835 static DEVICE_ATTR_RO(suspend_mem_microvolts);
836 
837 static ssize_t suspend_disk_microvolts_show(struct device *dev,
838 					    struct device_attribute *attr, char *buf)
839 {
840 	struct regulator_dev *rdev = dev_get_drvdata(dev);
841 
842 	return sprintf(buf, "%d\n", rdev->constraints->state_disk.uV);
843 }
844 static DEVICE_ATTR_RO(suspend_disk_microvolts);
845 
846 static ssize_t suspend_standby_microvolts_show(struct device *dev,
847 					       struct device_attribute *attr, char *buf)
848 {
849 	struct regulator_dev *rdev = dev_get_drvdata(dev);
850 
851 	return sprintf(buf, "%d\n", rdev->constraints->state_standby.uV);
852 }
853 static DEVICE_ATTR_RO(suspend_standby_microvolts);
854 
855 static ssize_t suspend_mem_mode_show(struct device *dev,
856 				     struct device_attribute *attr, char *buf)
857 {
858 	struct regulator_dev *rdev = dev_get_drvdata(dev);
859 
860 	return regulator_print_opmode(buf,
861 		rdev->constraints->state_mem.mode);
862 }
863 static DEVICE_ATTR_RO(suspend_mem_mode);
864 
865 static ssize_t suspend_disk_mode_show(struct device *dev,
866 				      struct device_attribute *attr, char *buf)
867 {
868 	struct regulator_dev *rdev = dev_get_drvdata(dev);
869 
870 	return regulator_print_opmode(buf,
871 		rdev->constraints->state_disk.mode);
872 }
873 static DEVICE_ATTR_RO(suspend_disk_mode);
874 
875 static ssize_t suspend_standby_mode_show(struct device *dev,
876 					 struct device_attribute *attr, char *buf)
877 {
878 	struct regulator_dev *rdev = dev_get_drvdata(dev);
879 
880 	return regulator_print_opmode(buf,
881 		rdev->constraints->state_standby.mode);
882 }
883 static DEVICE_ATTR_RO(suspend_standby_mode);
884 
885 static ssize_t suspend_mem_state_show(struct device *dev,
886 				      struct device_attribute *attr, char *buf)
887 {
888 	struct regulator_dev *rdev = dev_get_drvdata(dev);
889 
890 	return regulator_print_state(buf,
891 			rdev->constraints->state_mem.enabled);
892 }
893 static DEVICE_ATTR_RO(suspend_mem_state);
894 
895 static ssize_t suspend_disk_state_show(struct device *dev,
896 				       struct device_attribute *attr, char *buf)
897 {
898 	struct regulator_dev *rdev = dev_get_drvdata(dev);
899 
900 	return regulator_print_state(buf,
901 			rdev->constraints->state_disk.enabled);
902 }
903 static DEVICE_ATTR_RO(suspend_disk_state);
904 
905 static ssize_t suspend_standby_state_show(struct device *dev,
906 					  struct device_attribute *attr, char *buf)
907 {
908 	struct regulator_dev *rdev = dev_get_drvdata(dev);
909 
910 	return regulator_print_state(buf,
911 			rdev->constraints->state_standby.enabled);
912 }
913 static DEVICE_ATTR_RO(suspend_standby_state);
914 
915 static ssize_t bypass_show(struct device *dev,
916 			   struct device_attribute *attr, char *buf)
917 {
918 	struct regulator_dev *rdev = dev_get_drvdata(dev);
919 	const char *report;
920 	bool bypass;
921 	int ret;
922 
923 	ret = rdev->desc->ops->get_bypass(rdev, &bypass);
924 
925 	if (ret != 0)
926 		report = "unknown";
927 	else if (bypass)
928 		report = "enabled";
929 	else
930 		report = "disabled";
931 
932 	return sprintf(buf, "%s\n", report);
933 }
934 static DEVICE_ATTR_RO(bypass);
935 
936 static ssize_t power_budget_milliwatt_show(struct device *dev,
937 					   struct device_attribute *attr,
938 					   char *buf)
939 {
940 	struct regulator_dev *rdev = dev_get_drvdata(dev);
941 
942 	return sprintf(buf, "%d\n", rdev->constraints->pw_budget_mW);
943 }
944 static DEVICE_ATTR_RO(power_budget_milliwatt);
945 
946 static ssize_t power_requested_milliwatt_show(struct device *dev,
947 					      struct device_attribute *attr,
948 					      char *buf)
949 {
950 	struct regulator_dev *rdev = dev_get_drvdata(dev);
951 
952 	return sprintf(buf, "%d\n", rdev->pw_requested_mW);
953 }
954 static DEVICE_ATTR_RO(power_requested_milliwatt);
955 
956 #define REGULATOR_ERROR_ATTR(name, bit)							\
957 	static ssize_t name##_show(struct device *dev, struct device_attribute *attr,	\
958 				   char *buf)						\
959 	{										\
960 		int ret;								\
961 		unsigned int flags;							\
962 		struct regulator_dev *rdev = dev_get_drvdata(dev);			\
963 		ret = _regulator_get_error_flags(rdev, &flags);				\
964 		if (ret)								\
965 			return ret;							\
966 		return sysfs_emit(buf, "%d\n", !!(flags & (bit)));			\
967 	}										\
968 	static DEVICE_ATTR_RO(name)
969 
970 REGULATOR_ERROR_ATTR(under_voltage, REGULATOR_ERROR_UNDER_VOLTAGE);
971 REGULATOR_ERROR_ATTR(over_current, REGULATOR_ERROR_OVER_CURRENT);
972 REGULATOR_ERROR_ATTR(regulation_out, REGULATOR_ERROR_REGULATION_OUT);
973 REGULATOR_ERROR_ATTR(fail, REGULATOR_ERROR_FAIL);
974 REGULATOR_ERROR_ATTR(over_temp, REGULATOR_ERROR_OVER_TEMP);
975 REGULATOR_ERROR_ATTR(under_voltage_warn, REGULATOR_ERROR_UNDER_VOLTAGE_WARN);
976 REGULATOR_ERROR_ATTR(over_current_warn, REGULATOR_ERROR_OVER_CURRENT_WARN);
977 REGULATOR_ERROR_ATTR(over_voltage_warn, REGULATOR_ERROR_OVER_VOLTAGE_WARN);
978 REGULATOR_ERROR_ATTR(over_temp_warn, REGULATOR_ERROR_OVER_TEMP_WARN);
979 
980 /* Calculate the new optimum regulator operating mode based on the new total
981  * consumer load. All locks held by caller
982  */
983 static int drms_uA_update(struct regulator_dev *rdev)
984 {
985 	struct regulator *sibling;
986 	int current_uA = 0, output_uV, input_uV, err;
987 	unsigned int mode;
988 
989 	/*
990 	 * first check to see if we can set modes at all, otherwise just
991 	 * tell the consumer everything is OK.
992 	 */
993 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_DRMS)) {
994 		rdev_dbg(rdev, "DRMS operation not allowed\n");
995 		return 0;
996 	}
997 
998 	if (!rdev->desc->ops->get_optimum_mode &&
999 	    !rdev->desc->ops->set_load)
1000 		return 0;
1001 
1002 	if (!rdev->desc->ops->set_mode &&
1003 	    !rdev->desc->ops->set_load)
1004 		return -EINVAL;
1005 
1006 	/* calc total requested load */
1007 	list_for_each_entry(sibling, &rdev->consumer_list, list) {
1008 		if (sibling->enable_count)
1009 			current_uA += sibling->uA_load;
1010 	}
1011 
1012 	current_uA += rdev->constraints->system_load;
1013 
1014 	if (rdev->desc->ops->set_load) {
1015 		/* set the optimum mode for our new total regulator load */
1016 		err = rdev->desc->ops->set_load(rdev, current_uA);
1017 		if (err < 0)
1018 			rdev_err(rdev, "failed to set load %d: %pe\n",
1019 				 current_uA, ERR_PTR(err));
1020 	} else {
1021 		/*
1022 		 * Unfortunately in some cases the constraints->valid_ops has
1023 		 * REGULATOR_CHANGE_DRMS but there are no valid modes listed.
1024 		 * That's not really legit but we won't consider it a fatal
1025 		 * error here. We'll treat it as if REGULATOR_CHANGE_DRMS
1026 		 * wasn't set.
1027 		 */
1028 		if (!rdev->constraints->valid_modes_mask) {
1029 			rdev_dbg(rdev, "Can change modes; but no valid mode\n");
1030 			return 0;
1031 		}
1032 
1033 		/* get output voltage */
1034 		output_uV = regulator_get_voltage_rdev(rdev);
1035 
1036 		/*
1037 		 * Don't return an error; if regulator driver cares about
1038 		 * output_uV then it's up to the driver to validate.
1039 		 */
1040 		if (output_uV <= 0)
1041 			rdev_dbg(rdev, "invalid output voltage found\n");
1042 
1043 		/* get input voltage */
1044 		input_uV = 0;
1045 		if (rdev->supply)
1046 			input_uV = regulator_get_voltage_rdev(rdev->supply->rdev);
1047 		if (input_uV <= 0)
1048 			input_uV = rdev->constraints->input_uV;
1049 
1050 		/*
1051 		 * Don't return an error; if regulator driver cares about
1052 		 * input_uV then it's up to the driver to validate.
1053 		 */
1054 		if (input_uV <= 0)
1055 			rdev_dbg(rdev, "invalid input voltage found\n");
1056 
1057 		/* now get the optimum mode for our new total regulator load */
1058 		mode = rdev->desc->ops->get_optimum_mode(rdev, input_uV,
1059 							 output_uV, current_uA);
1060 
1061 		/* check the new mode is allowed */
1062 		err = regulator_mode_constrain(rdev, &mode);
1063 		if (err < 0) {
1064 			rdev_err(rdev, "failed to get optimum mode @ %d uA %d -> %d uV: %pe\n",
1065 				 current_uA, input_uV, output_uV, ERR_PTR(err));
1066 			return err;
1067 		}
1068 
1069 		err = rdev->desc->ops->set_mode(rdev, mode);
1070 		if (err < 0)
1071 			rdev_err(rdev, "failed to set optimum mode %x: %pe\n",
1072 				 mode, ERR_PTR(err));
1073 	}
1074 
1075 	return err;
1076 }
1077 
1078 static int __suspend_set_state(struct regulator_dev *rdev,
1079 			       const struct regulator_state *rstate)
1080 {
1081 	int ret = 0;
1082 
1083 	if (rstate->enabled == ENABLE_IN_SUSPEND &&
1084 		rdev->desc->ops->set_suspend_enable)
1085 		ret = rdev->desc->ops->set_suspend_enable(rdev);
1086 	else if (rstate->enabled == DISABLE_IN_SUSPEND &&
1087 		rdev->desc->ops->set_suspend_disable)
1088 		ret = rdev->desc->ops->set_suspend_disable(rdev);
1089 	else /* OK if set_suspend_enable or set_suspend_disable is NULL */
1090 		ret = 0;
1091 
1092 	if (ret < 0) {
1093 		rdev_err(rdev, "failed to enabled/disable: %pe\n", ERR_PTR(ret));
1094 		return ret;
1095 	}
1096 
1097 	if (rdev->desc->ops->set_suspend_voltage && rstate->uV > 0) {
1098 		ret = rdev->desc->ops->set_suspend_voltage(rdev, rstate->uV);
1099 		if (ret < 0) {
1100 			rdev_err(rdev, "failed to set voltage: %pe\n", ERR_PTR(ret));
1101 			return ret;
1102 		}
1103 	}
1104 
1105 	if (rdev->desc->ops->set_suspend_mode && rstate->mode > 0) {
1106 		ret = rdev->desc->ops->set_suspend_mode(rdev, rstate->mode);
1107 		if (ret < 0) {
1108 			rdev_err(rdev, "failed to set mode: %pe\n", ERR_PTR(ret));
1109 			return ret;
1110 		}
1111 	}
1112 
1113 	return ret;
1114 }
1115 
1116 static int suspend_set_initial_state(struct regulator_dev *rdev)
1117 {
1118 	const struct regulator_state *rstate;
1119 
1120 	rstate = regulator_get_suspend_state_check(rdev,
1121 			rdev->constraints->initial_state);
1122 	if (!rstate)
1123 		return 0;
1124 
1125 	return __suspend_set_state(rdev, rstate);
1126 }
1127 
1128 #if defined(DEBUG) || defined(CONFIG_DYNAMIC_DEBUG)
1129 static void print_constraints_debug(struct regulator_dev *rdev)
1130 {
1131 	struct regulation_constraints *constraints = rdev->constraints;
1132 	char buf[160] = "";
1133 	size_t len = sizeof(buf) - 1;
1134 	int count = 0;
1135 	int ret;
1136 
1137 	if (constraints->min_uV && constraints->max_uV) {
1138 		if (constraints->min_uV == constraints->max_uV)
1139 			count += scnprintf(buf + count, len - count, "%d mV ",
1140 					   constraints->min_uV / 1000);
1141 		else
1142 			count += scnprintf(buf + count, len - count,
1143 					   "%d <--> %d mV ",
1144 					   constraints->min_uV / 1000,
1145 					   constraints->max_uV / 1000);
1146 	}
1147 
1148 	if (!constraints->min_uV ||
1149 	    constraints->min_uV != constraints->max_uV) {
1150 		ret = regulator_get_voltage_rdev(rdev);
1151 		if (ret > 0)
1152 			count += scnprintf(buf + count, len - count,
1153 					   "at %d mV ", ret / 1000);
1154 	}
1155 
1156 	if (constraints->uV_offset)
1157 		count += scnprintf(buf + count, len - count, "%dmV offset ",
1158 				   constraints->uV_offset / 1000);
1159 
1160 	if (constraints->min_uA && constraints->max_uA) {
1161 		if (constraints->min_uA == constraints->max_uA)
1162 			count += scnprintf(buf + count, len - count, "%d mA ",
1163 					   constraints->min_uA / 1000);
1164 		else
1165 			count += scnprintf(buf + count, len - count,
1166 					   "%d <--> %d mA ",
1167 					   constraints->min_uA / 1000,
1168 					   constraints->max_uA / 1000);
1169 	}
1170 
1171 	if (!constraints->min_uA ||
1172 	    constraints->min_uA != constraints->max_uA) {
1173 		ret = _regulator_get_current_limit(rdev);
1174 		if (ret > 0)
1175 			count += scnprintf(buf + count, len - count,
1176 					   "at %d mA ", ret / 1000);
1177 	}
1178 
1179 	if (constraints->valid_modes_mask & REGULATOR_MODE_FAST)
1180 		count += scnprintf(buf + count, len - count, "fast ");
1181 	if (constraints->valid_modes_mask & REGULATOR_MODE_NORMAL)
1182 		count += scnprintf(buf + count, len - count, "normal ");
1183 	if (constraints->valid_modes_mask & REGULATOR_MODE_IDLE)
1184 		count += scnprintf(buf + count, len - count, "idle ");
1185 	if (constraints->valid_modes_mask & REGULATOR_MODE_STANDBY)
1186 		count += scnprintf(buf + count, len - count, "standby ");
1187 
1188 	if (constraints->pw_budget_mW)
1189 		count += scnprintf(buf + count, len - count, "%d mW budget ",
1190 				   constraints->pw_budget_mW);
1191 
1192 	if (!count)
1193 		count = scnprintf(buf, len, "no parameters");
1194 	else
1195 		--count;
1196 
1197 	count += scnprintf(buf + count, len - count, ", %s",
1198 		_regulator_is_enabled(rdev) ? "enabled" : "disabled");
1199 
1200 	rdev_dbg(rdev, "%s\n", buf);
1201 }
1202 #else /* !DEBUG && !CONFIG_DYNAMIC_DEBUG */
1203 static inline void print_constraints_debug(struct regulator_dev *rdev) {}
1204 #endif /* !DEBUG && !CONFIG_DYNAMIC_DEBUG */
1205 
1206 static void print_constraints(struct regulator_dev *rdev)
1207 {
1208 	struct regulation_constraints *constraints = rdev->constraints;
1209 
1210 	print_constraints_debug(rdev);
1211 
1212 	if ((constraints->min_uV != constraints->max_uV) &&
1213 	    !regulator_ops_is_valid(rdev, REGULATOR_CHANGE_VOLTAGE))
1214 		rdev_warn(rdev,
1215 			  "Voltage range but no REGULATOR_CHANGE_VOLTAGE\n");
1216 }
1217 
1218 static int machine_constraints_voltage(struct regulator_dev *rdev,
1219 	struct regulation_constraints *constraints)
1220 {
1221 	const struct regulator_ops *ops = rdev->desc->ops;
1222 	int ret;
1223 	bool apply_uV;
1224 
1225 	/*
1226 	 * Decide up front, from the constraints as handed to us, whether
1227 	 * apply_uV needs to run below. The clamping pass right after this
1228 	 * may rewrite constraints->min_uV/max_uV (e.g. the fixed-voltage
1229 	 * autoconfigure case), and we don't want that to change whether
1230 	 * apply_uV fires.
1231 	 */
1232 	apply_uV = rdev->constraints->apply_uV &&
1233 		   rdev->constraints->min_uV && rdev->constraints->max_uV;
1234 
1235 	/*
1236 	 * Constrain machine-level voltage specs to fit the actual range
1237 	 * supported by this regulator before apply_uV (below) tries to
1238 	 * force hardware to a value from that range: otherwise apply_uV
1239 	 * can target a constraint value that doesn't correspond to any
1240 	 * real voltage selector and fail registration outright, even
1241 	 * though the clamping pass would have narrowed it to a value
1242 	 * the regulator can actually hit.
1243 	 */
1244 	if (ops->list_voltage && rdev->desc->n_voltages) {
1245 		int	count = rdev->desc->n_voltages;
1246 		int	i;
1247 		int	min_uV = INT_MAX;
1248 		int	max_uV = INT_MIN;
1249 		int	cmin = constraints->min_uV;
1250 		int	cmax = constraints->max_uV;
1251 
1252 		/* it's safe to autoconfigure fixed-voltage supplies
1253 		 * and the constraints are used by list_voltage.
1254 		 */
1255 		if (count == 1 && !cmin) {
1256 			cmin = 1;
1257 			cmax = INT_MAX;
1258 			constraints->min_uV = cmin;
1259 			constraints->max_uV = cmax;
1260 		}
1261 
1262 		/* voltage constraints are optional */
1263 		if ((cmin == 0) && (cmax == 0)) {
1264 			/* nothing more to do */
1265 
1266 		/* else require explicit machine-level constraints */
1267 		} else if (cmin <= 0 || cmax <= 0 || cmax < cmin) {
1268 			rdev_err(rdev, "invalid voltage constraints\n");
1269 			return -EINVAL;
1270 
1271 		/* no need to loop voltages if range is continuous */
1272 		} else if (rdev->desc->continuous_voltage_range) {
1273 			/* nothing more to do */
1274 
1275 		} else {
1276 			/* initial: [cmin..cmax] valid, [min_uV..max_uV] not */
1277 			for (i = 0; i < count; i++) {
1278 				int	value;
1279 
1280 				value = ops->list_voltage(rdev, i);
1281 				if (value <= 0)
1282 					continue;
1283 
1284 				/* maybe adjust [min_uV..max_uV] */
1285 				if (value >= cmin && value < min_uV)
1286 					min_uV = value;
1287 				if (value <= cmax && value > max_uV)
1288 					max_uV = value;
1289 			}
1290 
1291 			/* final: [min_uV..max_uV] valid iff constraints valid */
1292 			if (max_uV < min_uV) {
1293 				rdev_err(rdev,
1294 					 "unsupportable voltage constraints %u-%uuV\n",
1295 					 min_uV, max_uV);
1296 				return -EINVAL;
1297 			}
1298 
1299 			/* use regulator's subset of machine constraints */
1300 			if (constraints->min_uV < min_uV) {
1301 				rdev_dbg(rdev, "override min_uV, %d -> %d\n",
1302 					 constraints->min_uV, min_uV);
1303 				constraints->min_uV = min_uV;
1304 			}
1305 			if (constraints->max_uV > max_uV) {
1306 				rdev_dbg(rdev, "override max_uV, %d -> %d\n",
1307 					 constraints->max_uV, max_uV);
1308 				constraints->max_uV = max_uV;
1309 			}
1310 		}
1311 	}
1312 
1313 	/* do we need to apply the constraint voltage */
1314 	if (apply_uV) {
1315 		int target_min, target_max;
1316 		int current_uV = regulator_get_voltage_rdev(rdev);
1317 
1318 		if (current_uV == -ENOTRECOVERABLE) {
1319 			/* This regulator can't be read and must be initialized */
1320 			rdev_info(rdev, "Setting %d-%duV\n",
1321 				  rdev->constraints->min_uV,
1322 				  rdev->constraints->max_uV);
1323 			_regulator_do_set_voltage(rdev,
1324 						  rdev->constraints->min_uV,
1325 						  rdev->constraints->max_uV);
1326 			current_uV = regulator_get_voltage_rdev(rdev);
1327 		}
1328 
1329 		if (current_uV < 0) {
1330 			if (current_uV != -EPROBE_DEFER)
1331 				rdev_err(rdev,
1332 					 "failed to get the current voltage: %pe\n",
1333 					 ERR_PTR(current_uV));
1334 			return current_uV;
1335 		}
1336 
1337 		/*
1338 		 * If we're below the minimum voltage move up to the
1339 		 * minimum voltage, if we're above the maximum voltage
1340 		 * then move down to the maximum.
1341 		 */
1342 		target_min = current_uV;
1343 		target_max = current_uV;
1344 
1345 		if (current_uV < rdev->constraints->min_uV) {
1346 			target_min = rdev->constraints->min_uV;
1347 			target_max = rdev->constraints->min_uV;
1348 		}
1349 
1350 		if (current_uV > rdev->constraints->max_uV) {
1351 			target_min = rdev->constraints->max_uV;
1352 			target_max = rdev->constraints->max_uV;
1353 		}
1354 
1355 		if (target_min != current_uV || target_max != current_uV) {
1356 			rdev_info(rdev, "Bringing %duV into %d-%duV\n",
1357 				  current_uV, target_min, target_max);
1358 			ret = _regulator_do_set_voltage(
1359 				rdev, target_min, target_max);
1360 			if (ret < 0) {
1361 				rdev_err(rdev,
1362 					"failed to apply %d-%duV constraint: %pe\n",
1363 					target_min, target_max, ERR_PTR(ret));
1364 				return ret;
1365 			}
1366 		}
1367 	}
1368 
1369 	return 0;
1370 }
1371 
1372 static int machine_constraints_current(struct regulator_dev *rdev,
1373 	struct regulation_constraints *constraints)
1374 {
1375 	const struct regulator_ops *ops = rdev->desc->ops;
1376 	int ret;
1377 
1378 	if (!constraints->min_uA && !constraints->max_uA)
1379 		return 0;
1380 
1381 	if (constraints->min_uA > constraints->max_uA) {
1382 		rdev_err(rdev, "Invalid current constraints\n");
1383 		return -EINVAL;
1384 	}
1385 
1386 	if (!ops->set_current_limit || !ops->get_current_limit) {
1387 		rdev_warn(rdev, "Operation of current configuration missing\n");
1388 		return 0;
1389 	}
1390 
1391 	/* Set regulator current in constraints range */
1392 	ret = ops->set_current_limit(rdev, constraints->min_uA,
1393 			constraints->max_uA);
1394 	if (ret < 0) {
1395 		rdev_err(rdev, "Failed to set current constraint, %d\n", ret);
1396 		return ret;
1397 	}
1398 
1399 	return 0;
1400 }
1401 
1402 static int _regulator_do_enable(struct regulator_dev *rdev);
1403 
1404 static int notif_set_limit(struct regulator_dev *rdev,
1405 			   int (*set)(struct regulator_dev *, int, int, bool),
1406 			   int limit, int severity)
1407 {
1408 	bool enable;
1409 
1410 	if (limit == REGULATOR_NOTIF_LIMIT_DISABLE) {
1411 		enable = false;
1412 		limit = 0;
1413 	} else {
1414 		enable = true;
1415 	}
1416 
1417 	if (limit == REGULATOR_NOTIF_LIMIT_ENABLE)
1418 		limit = 0;
1419 
1420 	return set(rdev, limit, severity, enable);
1421 }
1422 
1423 static int handle_notify_limits(struct regulator_dev *rdev,
1424 			int (*set)(struct regulator_dev *, int, int, bool),
1425 			struct notification_limit *limits)
1426 {
1427 	int ret = 0;
1428 
1429 	if (!set)
1430 		return -EOPNOTSUPP;
1431 
1432 	if (limits->prot)
1433 		ret = notif_set_limit(rdev, set, limits->prot,
1434 				      REGULATOR_SEVERITY_PROT);
1435 	if (ret)
1436 		return ret;
1437 
1438 	if (limits->err)
1439 		ret = notif_set_limit(rdev, set, limits->err,
1440 				      REGULATOR_SEVERITY_ERR);
1441 	if (ret)
1442 		return ret;
1443 
1444 	if (limits->warn)
1445 		ret = notif_set_limit(rdev, set, limits->warn,
1446 				      REGULATOR_SEVERITY_WARN);
1447 
1448 	return ret;
1449 }
1450 /**
1451  * set_machine_constraints - sets regulator constraints
1452  * @rdev: regulator source
1453  * @is_locked: whether or not this is called with locks held already
1454  *
1455  * Allows platform initialisation code to define and constrain
1456  * regulator circuits e.g. valid voltage/current ranges, etc.  NOTE:
1457  * Constraints *must* be set by platform code in order for some
1458  * regulator operations to proceed i.e. set_voltage, set_current_limit,
1459  * set_mode.
1460  *
1461  * Return: 0 on success or a negative error number on failure.
1462  */
1463 static int set_machine_constraints(struct regulator_dev *rdev,
1464 				   bool is_locked)
1465 {
1466 	int ret = 0;
1467 	const struct regulator_ops *ops = rdev->desc->ops;
1468 
1469 	/*
1470 	 * If there is no mechanism for controlling the regulator then
1471 	 * flag it as always_on so we don't end up duplicating checks
1472 	 * for this so much.  Note that we could control the state of
1473 	 * a supply to control the output on a regulator that has no
1474 	 * direct control.
1475 	 */
1476 	if (!rdev->ena_pin && !ops->enable) {
1477 		if (rdev->supply_name && !rdev->supply)
1478 			return -EPROBE_DEFER;
1479 
1480 		if (rdev->supply)
1481 			rdev->constraints->always_on =
1482 				rdev->supply->rdev->constraints->always_on;
1483 		else
1484 			rdev->constraints->always_on = true;
1485 	}
1486 
1487 	/*
1488 	 * If we want to enable this regulator, make sure that we know the
1489 	 * supplying regulator.
1490 	 */
1491 	if (rdev->constraints->always_on || rdev->constraints->boot_on) {
1492 		if (rdev->supply_name && !rdev->supply)
1493 			return -EPROBE_DEFER;
1494 	}
1495 
1496 	ret = machine_constraints_voltage(rdev, rdev->constraints);
1497 	if (ret != 0)
1498 		return ret;
1499 
1500 	ret = machine_constraints_current(rdev, rdev->constraints);
1501 	if (ret != 0)
1502 		return ret;
1503 
1504 	if (rdev->constraints->ilim_uA && ops->set_input_current_limit) {
1505 		ret = ops->set_input_current_limit(rdev,
1506 						   rdev->constraints->ilim_uA);
1507 		if (ret < 0) {
1508 			rdev_err(rdev, "failed to set input limit: %pe\n", ERR_PTR(ret));
1509 			return ret;
1510 		}
1511 	}
1512 
1513 	/* do we need to setup our suspend state */
1514 	if (rdev->constraints->initial_state) {
1515 		ret = suspend_set_initial_state(rdev);
1516 		if (ret < 0) {
1517 			rdev_err(rdev, "failed to set suspend state: %pe\n", ERR_PTR(ret));
1518 			return ret;
1519 		}
1520 	}
1521 
1522 	if (rdev->constraints->initial_mode) {
1523 		if (!ops->set_mode) {
1524 			rdev_err(rdev, "no set_mode operation\n");
1525 			return -EINVAL;
1526 		}
1527 
1528 		ret = ops->set_mode(rdev, rdev->constraints->initial_mode);
1529 		if (ret < 0) {
1530 			rdev_err(rdev, "failed to set initial mode: %pe\n", ERR_PTR(ret));
1531 			return ret;
1532 		}
1533 	} else if (rdev->constraints->system_load) {
1534 		/*
1535 		 * We'll only apply the initial system load if an
1536 		 * initial mode wasn't specified.
1537 		 */
1538 		drms_uA_update(rdev);
1539 	}
1540 
1541 	if ((rdev->constraints->ramp_delay || rdev->constraints->ramp_disable)
1542 		&& ops->set_ramp_delay) {
1543 		ret = ops->set_ramp_delay(rdev, rdev->constraints->ramp_delay);
1544 		if (ret < 0) {
1545 			rdev_err(rdev, "failed to set ramp_delay: %pe\n", ERR_PTR(ret));
1546 			return ret;
1547 		}
1548 	}
1549 
1550 	if (rdev->constraints->pull_down && ops->set_pull_down) {
1551 		ret = ops->set_pull_down(rdev);
1552 		if (ret < 0) {
1553 			rdev_err(rdev, "failed to set pull down: %pe\n", ERR_PTR(ret));
1554 			return ret;
1555 		}
1556 	}
1557 
1558 	if (rdev->constraints->soft_start && ops->set_soft_start) {
1559 		ret = ops->set_soft_start(rdev);
1560 		if (ret < 0) {
1561 			rdev_err(rdev, "failed to set soft start: %pe\n", ERR_PTR(ret));
1562 			return ret;
1563 		}
1564 	}
1565 
1566 	/*
1567 	 * Existing logic does not warn if over_current_protection is given as
1568 	 * a constraint but driver does not support that. I think we should
1569 	 * warn about this type of issues as it is possible someone changes
1570 	 * PMIC on board to another type - and the other PMIC's driver does
1571 	 * not support setting protection. Board composer may happily believe
1572 	 * the DT limits are respected - especially if the new PMIC HW also
1573 	 * supports protection but the driver does not. I won't change the logic
1574 	 * without hearing more experienced opinion on this though.
1575 	 *
1576 	 * If warning is seen as a good idea then we can merge handling the
1577 	 * over-curret protection and detection and get rid of this special
1578 	 * handling.
1579 	 */
1580 	if (rdev->constraints->over_current_protection
1581 		&& ops->set_over_current_protection) {
1582 		int lim = rdev->constraints->over_curr_limits.prot;
1583 
1584 		ret = ops->set_over_current_protection(rdev, lim,
1585 						       REGULATOR_SEVERITY_PROT,
1586 						       true);
1587 		if (ret < 0) {
1588 			rdev_err(rdev, "failed to set over current protection: %pe\n",
1589 				 ERR_PTR(ret));
1590 			return ret;
1591 		}
1592 	}
1593 
1594 	if (rdev->constraints->over_current_detection)
1595 		ret = handle_notify_limits(rdev,
1596 					   ops->set_over_current_protection,
1597 					   &rdev->constraints->over_curr_limits);
1598 	if (ret) {
1599 		if (ret != -EOPNOTSUPP) {
1600 			rdev_err(rdev, "failed to set over current limits: %pe\n",
1601 				 ERR_PTR(ret));
1602 			return ret;
1603 		}
1604 		rdev_warn(rdev,
1605 			  "IC does not support requested over-current limits\n");
1606 	}
1607 
1608 	if (rdev->constraints->over_voltage_detection)
1609 		ret = handle_notify_limits(rdev,
1610 					   ops->set_over_voltage_protection,
1611 					   &rdev->constraints->over_voltage_limits);
1612 	if (ret) {
1613 		if (ret != -EOPNOTSUPP) {
1614 			rdev_err(rdev, "failed to set over voltage limits %pe\n",
1615 				 ERR_PTR(ret));
1616 			return ret;
1617 		}
1618 		rdev_warn(rdev,
1619 			  "IC does not support requested over voltage limits\n");
1620 	}
1621 
1622 	if (rdev->constraints->under_voltage_detection)
1623 		ret = handle_notify_limits(rdev,
1624 					   ops->set_under_voltage_protection,
1625 					   &rdev->constraints->under_voltage_limits);
1626 	if (ret) {
1627 		if (ret != -EOPNOTSUPP) {
1628 			rdev_err(rdev, "failed to set under voltage limits %pe\n",
1629 				 ERR_PTR(ret));
1630 			return ret;
1631 		}
1632 		rdev_warn(rdev,
1633 			  "IC does not support requested under voltage limits\n");
1634 	}
1635 
1636 	if (rdev->constraints->over_temp_detection)
1637 		ret = handle_notify_limits(rdev,
1638 					   ops->set_thermal_protection,
1639 					   &rdev->constraints->temp_limits);
1640 	if (ret) {
1641 		if (ret != -EOPNOTSUPP) {
1642 			rdev_err(rdev, "failed to set temperature limits %pe\n",
1643 				 ERR_PTR(ret));
1644 			return ret;
1645 		}
1646 		rdev_warn(rdev,
1647 			  "IC does not support requested temperature limits\n");
1648 	}
1649 
1650 	if (rdev->constraints->active_discharge && ops->set_active_discharge) {
1651 		bool ad_state = rdev->constraints->active_discharge ==
1652 			      REGULATOR_ACTIVE_DISCHARGE_ENABLE;
1653 
1654 		ret = ops->set_active_discharge(rdev, ad_state);
1655 		if (ret < 0) {
1656 			rdev_err(rdev, "failed to set active discharge: %pe\n", ERR_PTR(ret));
1657 			return ret;
1658 		}
1659 	}
1660 
1661 	/* If the constraints say the regulator should be on at this point
1662 	 * and we have control then make sure it is enabled.
1663 	 */
1664 	if (rdev->constraints->always_on || rdev->constraints->boot_on) {
1665 		bool supply_enabled = false;
1666 
1667 		/* We have ensured a potential supply has been resolved above.
1668 		 *
1669 		 * If supplying regulator has already been enabled,
1670 		 * it's not intended to have use_count increment
1671 		 * when rdev is only boot-on.
1672 		 */
1673 		if (rdev->supply &&
1674 		    (rdev->constraints->always_on ||
1675 		     !regulator_is_enabled(rdev->supply))) {
1676 			ret = (is_locked
1677 			       ? _regulator_enable(rdev->supply)
1678 			       : regulator_enable(rdev->supply));
1679 			if (ret < 0) {
1680 				_regulator_put(rdev->supply);
1681 				rdev->supply = NULL;
1682 				return ret;
1683 			}
1684 			supply_enabled = true;
1685 		}
1686 
1687 		ret = _regulator_do_enable(rdev);
1688 		if (ret < 0 && ret != -EINVAL) {
1689 			rdev_err(rdev, "failed to enable: %pe\n", ERR_PTR(ret));
1690 			if (supply_enabled)
1691 				regulator_disable(rdev->supply);
1692 			return ret;
1693 		}
1694 
1695 		if (rdev->constraints->always_on)
1696 			rdev->use_count++;
1697 	} else if (rdev->desc->off_on_delay) {
1698 		rdev->last_off = ktime_get();
1699 	}
1700 
1701 	if (!rdev->constraints->pw_budget_mW)
1702 		rdev->constraints->pw_budget_mW = INT_MAX;
1703 
1704 	print_constraints(rdev);
1705 	return 0;
1706 }
1707 
1708 /**
1709  * regulator_event_work_fn - process a deferred regulator event
1710  * @work: work_struct queued by the notifier
1711  *
1712  * Calls the regulator's notifier chain in process context while holding
1713  * the rdev lock, then releases the device reference.
1714  */
1715 static void regulator_event_work_fn(struct work_struct *work)
1716 {
1717 	struct regulator_event_work *rew =
1718 		container_of(work, struct regulator_event_work, work);
1719 	struct regulator_dev *rdev = rew->rdev;
1720 	int ret;
1721 
1722 	regulator_lock(rdev);
1723 	ret = regulator_notifier_call_chain(rdev, rew->event, NULL);
1724 	regulator_unlock(rdev);
1725 	if (ret == NOTIFY_BAD)
1726 		dev_err(rdev_get_dev(rdev), "failed to forward regulator event\n");
1727 
1728 	put_device(rdev_get_dev(rdev));
1729 	kfree(rew);
1730 }
1731 
1732 /**
1733  * regulator_event_forward_notifier - notifier callback for supply events
1734  * @nb:    notifier block embedded in the regulator
1735  * @event: regulator event code
1736  * @data:  unused
1737  *
1738  * Packages the event into a work item and schedules it in process context.
1739  * Takes a reference on @rdev->dev to pin the regulator until the work
1740  * completes (see put_device() in the worker).
1741  *
1742  * Return: NOTIFY_OK on success, NOTIFY_DONE for events that are not forwarded.
1743  */
1744 static int regulator_event_forward_notifier(struct notifier_block *nb,
1745 					    unsigned long event,
1746 					    void __always_unused *data)
1747 {
1748 	struct regulator_dev *rdev = container_of(nb, struct regulator_dev,
1749 						  supply_fwd_nb);
1750 	struct regulator_event_work *rew;
1751 
1752 	switch (event) {
1753 	case REGULATOR_EVENT_UNDER_VOLTAGE:
1754 		break;
1755 	default:
1756 		/* Only forward allowed events downstream. */
1757 		return NOTIFY_DONE;
1758 	}
1759 
1760 	rew = kmalloc_obj(*rew, GFP_ATOMIC);
1761 	if (!rew)
1762 		return NOTIFY_DONE;
1763 
1764 	get_device(rdev_get_dev(rdev));
1765 	rew->rdev = rdev;
1766 	rew->event = event;
1767 	INIT_WORK(&rew->work, regulator_event_work_fn);
1768 
1769 	queue_work(system_highpri_wq, &rew->work);
1770 
1771 	return NOTIFY_OK;
1772 }
1773 
1774 /**
1775  * register_regulator_event_forwarding - enable supply event forwarding
1776  * @rdev: regulator device
1777  *
1778  * Registers a notifier on the regulator's supply so that supply events
1779  * are forwarded to the consumer regulator via the deferred work handler.
1780  *
1781  * Return: 0 on success, -EALREADY if already enabled, or a negative error code.
1782  */
1783 static int register_regulator_event_forwarding(struct regulator_dev *rdev)
1784 {
1785 	int ret;
1786 
1787 	if (!rdev->supply)
1788 		return 0; /* top-level regulator: nothing to forward */
1789 
1790 	if (rdev->supply_fwd_nb.notifier_call)
1791 		return -EALREADY;
1792 
1793 	rdev->supply_fwd_nb.notifier_call = regulator_event_forward_notifier;
1794 
1795 	ret = regulator_register_notifier(rdev->supply, &rdev->supply_fwd_nb);
1796 	if (ret) {
1797 		dev_err(&rdev->dev, "failed to register supply notifier: %pe\n",
1798 			ERR_PTR(ret));
1799 		rdev->supply_fwd_nb.notifier_call = NULL;
1800 		return ret;
1801 	}
1802 
1803 	return 0;
1804 }
1805 
1806 static void unregister_regulator_event_forwarding(struct regulator_dev *rdev)
1807 {
1808 	if (!rdev->supply_fwd_nb.notifier_call)
1809 		return;
1810 
1811 	regulator_unregister_notifier(rdev->supply, &rdev->supply_fwd_nb);
1812 	rdev->supply_fwd_nb.notifier_call = NULL;
1813 }
1814 
1815 /**
1816  * set_supply - set regulator supply regulator
1817  * @rdev: regulator (locked)
1818  * @supply_rdev: supply regulator (locked))
1819  *
1820  * Called by platform initialisation code to set the supply regulator for this
1821  * regulator. This ensures that a regulators supply will also be enabled by the
1822  * core if it's child is enabled.
1823  *
1824  * Return: 0 on success or a negative error number on failure.
1825  */
1826 static int set_supply(struct regulator_dev *rdev,
1827 		      struct regulator_dev *supply_rdev)
1828 {
1829 	int err;
1830 
1831 	rdev_dbg(rdev, "supplied by %s\n", rdev_get_name(supply_rdev));
1832 
1833 	if (!try_module_get(supply_rdev->owner))
1834 		return -ENODEV;
1835 
1836 	rdev->supply = create_regulator(supply_rdev, &rdev->dev, "SUPPLY");
1837 	if (rdev->supply == NULL) {
1838 		module_put(supply_rdev->owner);
1839 		err = -ENOMEM;
1840 		return err;
1841 	}
1842 	supply_rdev->open_count++;
1843 
1844 	return 0;
1845 }
1846 
1847 /**
1848  * set_consumer_device_supply - Bind a regulator to a symbolic supply
1849  * @rdev:         regulator source
1850  * @consumer_dev_name: dev_name() string for device supply applies to
1851  * @supply:       symbolic name for supply
1852  *
1853  * Allows platform initialisation code to map physical regulator
1854  * sources to symbolic names for supplies for use by devices.  Devices
1855  * should use these symbolic names to request regulators, avoiding the
1856  * need to provide board-specific regulator names as platform data.
1857  *
1858  * Return: 0 on success or a negative error number on failure.
1859  */
1860 static int set_consumer_device_supply(struct regulator_dev *rdev,
1861 				      const char *consumer_dev_name,
1862 				      const char *supply)
1863 {
1864 	struct regulator_map *node, *new_node;
1865 	int has_dev;
1866 
1867 	if (supply == NULL)
1868 		return -EINVAL;
1869 
1870 	if (consumer_dev_name != NULL)
1871 		has_dev = 1;
1872 	else
1873 		has_dev = 0;
1874 
1875 	new_node = kzalloc_obj(struct regulator_map);
1876 	if (new_node == NULL)
1877 		return -ENOMEM;
1878 
1879 	new_node->regulator = rdev;
1880 	new_node->supply = supply;
1881 
1882 	if (has_dev) {
1883 		new_node->dev_name = kstrdup(consumer_dev_name, GFP_KERNEL);
1884 		if (new_node->dev_name == NULL) {
1885 			kfree(new_node);
1886 			return -ENOMEM;
1887 		}
1888 	}
1889 
1890 	mutex_lock(&regulator_list_mutex);
1891 	list_for_each_entry(node, &regulator_map_list, list) {
1892 		if (node->dev_name && consumer_dev_name) {
1893 			if (strcmp(node->dev_name, consumer_dev_name) != 0)
1894 				continue;
1895 		} else if (node->dev_name || consumer_dev_name) {
1896 			continue;
1897 		}
1898 
1899 		if (strcmp(node->supply, supply) != 0)
1900 			continue;
1901 
1902 		pr_debug("%s: %s/%s is '%s' supply; fail %s/%s\n",
1903 			 consumer_dev_name,
1904 			 dev_name(&node->regulator->dev),
1905 			 node->regulator->desc->name,
1906 			 supply,
1907 			 dev_name(&rdev->dev), rdev_get_name(rdev));
1908 		goto fail;
1909 	}
1910 
1911 	list_add(&new_node->list, &regulator_map_list);
1912 	mutex_unlock(&regulator_list_mutex);
1913 
1914 	return 0;
1915 
1916 fail:
1917 	mutex_unlock(&regulator_list_mutex);
1918 	kfree(new_node->dev_name);
1919 	kfree(new_node);
1920 	return -EBUSY;
1921 }
1922 
1923 static void unset_regulator_supplies(struct regulator_dev *rdev)
1924 {
1925 	struct regulator_map *node, *n;
1926 
1927 	list_for_each_entry_safe(node, n, &regulator_map_list, list) {
1928 		if (rdev == node->regulator) {
1929 			list_del(&node->list);
1930 			kfree(node->dev_name);
1931 			kfree(node);
1932 		}
1933 	}
1934 }
1935 
1936 #ifdef CONFIG_DEBUG_FS
1937 static ssize_t constraint_flags_read_file(struct file *file,
1938 					  char __user *user_buf,
1939 					  size_t count, loff_t *ppos)
1940 {
1941 	const struct regulator *regulator = file->private_data;
1942 	const struct regulation_constraints *c = regulator->rdev->constraints;
1943 	char *buf;
1944 	ssize_t ret;
1945 
1946 	if (!c)
1947 		return 0;
1948 
1949 	buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
1950 	if (!buf)
1951 		return -ENOMEM;
1952 
1953 	ret = snprintf(buf, PAGE_SIZE,
1954 			"always_on: %u\n"
1955 			"boot_on: %u\n"
1956 			"apply_uV: %u\n"
1957 			"ramp_disable: %u\n"
1958 			"soft_start: %u\n"
1959 			"pull_down: %u\n"
1960 			"over_current_protection: %u\n",
1961 			c->always_on,
1962 			c->boot_on,
1963 			c->apply_uV,
1964 			c->ramp_disable,
1965 			c->soft_start,
1966 			c->pull_down,
1967 			c->over_current_protection);
1968 
1969 	ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret);
1970 	kfree(buf);
1971 
1972 	return ret;
1973 }
1974 
1975 #endif
1976 
1977 static const struct file_operations constraint_flags_fops = {
1978 #ifdef CONFIG_DEBUG_FS
1979 	.open = simple_open,
1980 	.read = constraint_flags_read_file,
1981 	.llseek = default_llseek,
1982 #endif
1983 };
1984 
1985 static void link_and_create_debugfs(struct regulator *regulator, struct regulator_dev *rdev,
1986 				    struct device *dev)
1987 {
1988 	int err = 0;
1989 
1990 	if (dev) {
1991 		regulator->dev = dev;
1992 
1993 		/* Add a link to the device sysfs entry */
1994 		err = sysfs_create_link_nowarn(&rdev->dev.kobj, &dev->kobj,
1995 					       regulator->supply_name);
1996 		if (err) {
1997 			rdev_dbg(rdev, "could not add device link %s: %pe\n",
1998 				 dev->kobj.name, ERR_PTR(err));
1999 			/* non-fatal */
2000 		}
2001 	}
2002 
2003 	if (err != -EEXIST) {
2004 		regulator->debugfs = debugfs_create_dir(regulator->supply_name, rdev->debugfs);
2005 		if (IS_ERR(regulator->debugfs)) {
2006 			rdev_dbg(rdev, "Failed to create debugfs directory\n");
2007 			regulator->debugfs = NULL;
2008 		}
2009 	}
2010 
2011 	if (regulator->debugfs) {
2012 		debugfs_create_u32("uA_load", 0444, regulator->debugfs,
2013 				   &regulator->uA_load);
2014 		debugfs_create_u32("min_uV", 0444, regulator->debugfs,
2015 				   &regulator->voltage[PM_SUSPEND_ON].min_uV);
2016 		debugfs_create_u32("max_uV", 0444, regulator->debugfs,
2017 				   &regulator->voltage[PM_SUSPEND_ON].max_uV);
2018 		debugfs_create_file("constraint_flags", 0444, regulator->debugfs,
2019 				    regulator, &constraint_flags_fops);
2020 	}
2021 }
2022 
2023 static struct regulator *create_regulator(struct regulator_dev *rdev,
2024 					  struct device *dev,
2025 					  const char *supply_name)
2026 {
2027 	struct regulator *regulator;
2028 
2029 	lockdep_assert_held_once(&rdev->mutex.base);
2030 
2031 	if (dev) {
2032 		supply_name = kasprintf(GFP_KERNEL, "%s-%s", dev->kobj.name, supply_name);
2033 		if (supply_name == NULL)
2034 			return NULL;
2035 	} else {
2036 		supply_name = kstrdup_const(supply_name, GFP_KERNEL);
2037 		if (supply_name == NULL)
2038 			return NULL;
2039 	}
2040 
2041 	regulator = kzalloc_obj(*regulator);
2042 	if (regulator == NULL) {
2043 		kfree_const(supply_name);
2044 		return NULL;
2045 	}
2046 
2047 	regulator->rdev = rdev;
2048 	regulator->supply_name = supply_name;
2049 
2050 	list_add(&regulator->list, &rdev->consumer_list);
2051 
2052 	/*
2053 	 * Check now if the regulator is an always on regulator - if
2054 	 * it is then we don't need to do nearly so much work for
2055 	 * enable/disable calls.
2056 	 */
2057 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_STATUS) &&
2058 	    _regulator_is_enabled(rdev))
2059 		regulator->always_on = true;
2060 
2061 	return regulator;
2062 }
2063 
2064 static int _regulator_get_enable_time(struct regulator_dev *rdev)
2065 {
2066 	if (rdev->constraints && rdev->constraints->enable_time)
2067 		return rdev->constraints->enable_time;
2068 	if (rdev->desc->ops->enable_time)
2069 		return rdev->desc->ops->enable_time(rdev);
2070 	return rdev->desc->enable_time;
2071 }
2072 
2073 static struct regulator_supply_alias *regulator_find_supply_alias(
2074 		struct device *dev, const char *supply)
2075 {
2076 	struct regulator_supply_alias *map;
2077 
2078 	list_for_each_entry(map, &regulator_supply_alias_list, list)
2079 		if (map->src_dev == dev && strcmp(map->src_supply, supply) == 0)
2080 			return map;
2081 
2082 	return NULL;
2083 }
2084 
2085 static void regulator_supply_alias(struct device **dev, const char **supply)
2086 {
2087 	struct regulator_supply_alias *map;
2088 
2089 	mutex_lock(&regulator_list_mutex);
2090 	map = regulator_find_supply_alias(*dev, *supply);
2091 	if (map) {
2092 		dev_dbg(*dev, "Mapping supply %s to %s,%s\n",
2093 				*supply, map->alias_supply,
2094 				dev_name(map->alias_dev));
2095 		*dev = map->alias_dev;
2096 		*supply = map->alias_supply;
2097 	}
2098 	mutex_unlock(&regulator_list_mutex);
2099 }
2100 
2101 static int regulator_match(struct device *dev, const void *data)
2102 {
2103 	struct regulator_dev *r = dev_to_rdev(dev);
2104 
2105 	return strcmp(rdev_get_name(r), data) == 0;
2106 }
2107 
2108 static struct regulator_dev *regulator_lookup_by_name(const char *name)
2109 {
2110 	struct device *dev;
2111 
2112 	dev = class_find_device(&regulator_class, NULL, name, regulator_match);
2113 
2114 	return dev ? dev_to_rdev(dev) : NULL;
2115 }
2116 
2117 static struct regulator_dev *regulator_dt_lookup(struct device *dev,
2118 						 const char *supply)
2119 {
2120 	struct regulator_dev *r = NULL;
2121 
2122 	if (dev_of_node(dev)) {
2123 		r = of_regulator_dev_lookup(dev, dev_of_node(dev), supply);
2124 		if (PTR_ERR(r) == -ENODEV)
2125 			r = NULL;
2126 	}
2127 
2128 	return r;
2129 }
2130 
2131 /**
2132  * regulator_dev_lookup - lookup a regulator device.
2133  * @dev: device for regulator "consumer".
2134  * @supply: Supply name or regulator ID.
2135  *
2136  * Return: pointer to &struct regulator_dev or ERR_PTR() encoded negative error number.
2137  *
2138  * If successful, returns a struct regulator_dev that corresponds to the name
2139  * @supply and with the embedded struct device refcount incremented by one.
2140  * The refcount must be dropped by calling put_device().
2141  * On failure one of the following ERR_PTR() encoded values is returned:
2142  * -%ENODEV if lookup fails permanently, -%EPROBE_DEFER if lookup could succeed
2143  * in the future.
2144  */
2145 static struct regulator_dev *regulator_dev_lookup(struct device *dev,
2146 						  const char *supply)
2147 {
2148 	struct regulator_dev *r = NULL;
2149 	struct regulator_map *map;
2150 	const char *devname = NULL;
2151 
2152 	regulator_supply_alias(&dev, &supply);
2153 
2154 	/* first do a dt based lookup */
2155 	r = regulator_dt_lookup(dev, supply);
2156 	if (r)
2157 		return r;
2158 
2159 	/* if not found, try doing it non-dt way */
2160 	if (dev)
2161 		devname = dev_name(dev);
2162 
2163 	mutex_lock(&regulator_list_mutex);
2164 	list_for_each_entry(map, &regulator_map_list, list) {
2165 		/* If the mapping has a device set up it must match */
2166 		if (map->dev_name &&
2167 		    (!devname || strcmp(map->dev_name, devname)))
2168 			continue;
2169 
2170 		if (strcmp(map->supply, supply) == 0 &&
2171 		    get_device(&map->regulator->dev)) {
2172 			r = map->regulator;
2173 			break;
2174 		}
2175 	}
2176 	mutex_unlock(&regulator_list_mutex);
2177 
2178 	if (r)
2179 		return r;
2180 
2181 	r = regulator_lookup_by_name(supply);
2182 	if (r)
2183 		return r;
2184 
2185 	return ERR_PTR(-ENODEV);
2186 }
2187 
2188 static int regulator_resolve_supply(struct regulator_dev *rdev)
2189 {
2190 	struct regulator_dev *r;
2191 	struct device *dev = rdev->dev.parent;
2192 	struct ww_acquire_ctx ww_ctx;
2193 	struct regulator *supply;
2194 	bool do_final_setup;
2195 	int ret = 0;
2196 
2197 	/* No supply to resolve? */
2198 	if (!rdev->supply_name)
2199 		return 0;
2200 
2201 	/* Supply already resolved? (fast-path without locking contention) */
2202 	if (rdev->supply && !rdev->constraints_pending)
2203 		return 0;
2204 
2205 	/* first do a dt based lookup on the node described in the virtual
2206 	 * device.
2207 	 */
2208 	r = regulator_dt_lookup(&rdev->dev, rdev->supply_name);
2209 
2210 	/* If regulator not found use usual search path in the parent
2211 	 * device.
2212 	 */
2213 	if (!r)
2214 		r = regulator_dev_lookup(dev, rdev->supply_name);
2215 
2216 	if (IS_ERR(r)) {
2217 		ret = PTR_ERR(r);
2218 
2219 		/* Did the lookup explicitly defer for us? */
2220 		if (ret == -EPROBE_DEFER)
2221 			goto out;
2222 
2223 		if (have_full_constraints()) {
2224 			r = dummy_regulator_rdev;
2225 			if (!r) {
2226 				ret = -EPROBE_DEFER;
2227 				goto out;
2228 			}
2229 			get_device(&r->dev);
2230 		} else {
2231 			dev_err(dev, "Failed to resolve %s-supply for %s\n",
2232 				rdev->supply_name, rdev->desc->name);
2233 			ret = -EPROBE_DEFER;
2234 			goto out;
2235 		}
2236 	}
2237 
2238 	if (r == rdev) {
2239 		dev_err(dev, "Supply for %s (%s) resolved to itself\n",
2240 			rdev->desc->name, rdev->supply_name);
2241 		if (!have_full_constraints()) {
2242 			ret = -EINVAL;
2243 			goto out;
2244 		}
2245 		r = dummy_regulator_rdev;
2246 		if (!r) {
2247 			ret = -EPROBE_DEFER;
2248 			goto out;
2249 		}
2250 		get_device(&r->dev);
2251 	}
2252 
2253 	/*
2254 	 * If the supply's parent device is not the same as the
2255 	 * regulator's parent device, then ensure the parent device
2256 	 * is bound before we resolve the supply, in case the parent
2257 	 * device get probe deferred and unregisters the supply.
2258 	 */
2259 	if (r->dev.parent && r->dev.parent != rdev->dev.parent) {
2260 		if (!device_is_bound(r->dev.parent)) {
2261 			put_device(&r->dev);
2262 			ret = -EPROBE_DEFER;
2263 			goto out;
2264 		}
2265 	}
2266 
2267 	/* Recursively resolve the supply of the supply */
2268 	ret = regulator_resolve_supply(r);
2269 	if (ret < 0) {
2270 		put_device(&r->dev);
2271 		goto out;
2272 	}
2273 
2274 	/*
2275 	 * Recheck rdev->supply with rdev->mutex lock held to avoid a race
2276 	 * between rdev->supply null check and setting rdev->supply in
2277 	 * set_supply() from concurrent tasks.
2278 	 */
2279 	regulator_lock_two(rdev, r, &ww_ctx);
2280 
2281 	/* Supply just resolved by a concurrent task? */
2282 	if (rdev->supply) {
2283 		/* Constraints might still be pending due to concurrency. */
2284 		bool done = !rdev->constraints_pending;
2285 
2286 		supply = rdev->supply;
2287 
2288 		regulator_unlock_two(rdev, r, &ww_ctx);
2289 		put_device(&r->dev);
2290 
2291 		/*
2292 		 * Supply resolved by concurrent task, and constraints set as
2293 		 * well (or not required): fast path.
2294 		 */
2295 		if (done)
2296 			goto out;
2297 
2298 		do_final_setup = false;
2299 	} else {
2300 		ret = set_supply(rdev, r);
2301 		if (ret < 0) {
2302 			regulator_unlock_two(rdev, r, &ww_ctx);
2303 			put_device(&r->dev);
2304 			goto out;
2305 		}
2306 
2307 		supply = rdev->supply;
2308 
2309 		/*
2310 		 * Automatically register for event forwarding from the new
2311 		 * supply. This creates the downstream propagation link for
2312 		 * events like under-voltage.
2313 		 */
2314 		ret = register_regulator_event_forwarding(rdev);
2315 		if (ret < 0) {
2316 			rdev_warn(rdev,
2317 				  "Failed to register event forwarding: %pe\n",
2318 				  ERR_PTR(ret));
2319 
2320 			goto unset_supply;
2321 		}
2322 
2323 		regulator_unlock_two(rdev, r, &ww_ctx);
2324 
2325 		do_final_setup = true;
2326 	}
2327 
2328 	/*
2329 	 * Now that we have the supply, we can retry setting the machine
2330 	 * constraints, if necessary.
2331 	 */
2332 	regulator_lock_dependent(rdev, &ww_ctx);
2333 	if (rdev->constraints_pending) {
2334 		if (!rdev->supply) {
2335 			/*
2336 			 * Supply could have been released by another task that
2337 			 * failed to set the constraints or event forwarding.
2338 			 */
2339 			regulator_unlock_dependent(rdev, &ww_ctx);
2340 			ret = -EPROBE_DEFER;
2341 			goto out;
2342 		}
2343 
2344 		ret = set_machine_constraints(rdev, true);
2345 		if (ret < 0) {
2346 			regulator_unlock_dependent(rdev, &ww_ctx);
2347 
2348 			rdev_warn(rdev,
2349 				  "Failed to set machine constraints: %pe\n",
2350 				  ERR_PTR(ret));
2351 
2352 			regulator_lock_two(rdev, r, &ww_ctx);
2353 
2354 			if (supply != rdev->supply) {
2355 				/*
2356 				 * Supply could have been released by another
2357 				 * task that got here before us. If it did, it
2358 				 * will have released 'supply' (i.e. the
2359 				 * previous rdev->supply) and we shouldn't do
2360 				 * that again via unset_supply.
2361 				 */
2362 				regulator_unlock_two(rdev, r, &ww_ctx);
2363 				goto out;
2364 			}
2365 
2366 			unregister_regulator_event_forwarding(rdev);
2367 			rdev->constraints_pending = true;
2368 			goto unset_supply;
2369 		}
2370 		rdev->constraints_pending = false;
2371 	}
2372 	regulator_unlock_dependent(rdev, &ww_ctx);
2373 
2374 	if (!do_final_setup)
2375 		goto out;
2376 
2377 	/* rdev->supply was created in set_supply() */
2378 	link_and_create_debugfs(rdev->supply, rdev->supply->rdev, &rdev->dev);
2379 
2380 out:
2381 	return ret;
2382 
2383 unset_supply:
2384 	lockdep_assert_held_once(&rdev->mutex.base);
2385 	lockdep_assert_held_once(&r->mutex.base);
2386 	rdev->supply = NULL;
2387 	regulator_unlock_two(rdev, supply->rdev, &ww_ctx);
2388 
2389 	regulator_put(supply);
2390 
2391 	return ret;
2392 }
2393 
2394 /* common pre-checks for regulator requests */
2395 int _regulator_get_common_check(struct device *dev, const char *id,
2396 				enum regulator_get_type get_type)
2397 {
2398 	if (get_type >= MAX_GET_TYPE) {
2399 		dev_err(dev, "invalid type %d in %s\n", get_type, __func__);
2400 		return -EINVAL;
2401 	}
2402 
2403 	if (id == NULL) {
2404 		dev_err(dev, "regulator request with no identifier\n");
2405 		return -EINVAL;
2406 	}
2407 
2408 	return 0;
2409 }
2410 
2411 /**
2412  * _regulator_get_common - Common code for regulator requests
2413  * @rdev: regulator device pointer as returned by *regulator_dev_lookup()
2414  *       Its reference count is expected to have been incremented.
2415  * @dev: device used for dev_printk messages
2416  * @id: Supply name or regulator ID
2417  * @get_type: enum regulator_get_type value corresponding to type of request
2418  *
2419  * Returns: pointer to struct regulator corresponding to @rdev, or ERR_PTR()
2420  *	    encoded error.
2421  *
2422  * This function should be chained with *regulator_dev_lookup() functions.
2423  */
2424 struct regulator *_regulator_get_common(struct regulator_dev *rdev, struct device *dev,
2425 					const char *id, enum regulator_get_type get_type)
2426 {
2427 	struct regulator *regulator;
2428 	struct device_link *link;
2429 	int ret;
2430 
2431 	if (IS_ERR(rdev)) {
2432 		ret = PTR_ERR(rdev);
2433 
2434 		/*
2435 		 * If regulator_dev_lookup() fails with error other
2436 		 * than -ENODEV our job here is done, we simply return it.
2437 		 */
2438 		if (ret != -ENODEV)
2439 			return ERR_PTR(ret);
2440 
2441 		if (!have_full_constraints()) {
2442 			dev_warn(dev,
2443 				 "incomplete constraints, dummy supplies not allowed (id=%s)\n", id);
2444 			return ERR_PTR(-ENODEV);
2445 		}
2446 
2447 		switch (get_type) {
2448 		case NORMAL_GET:
2449 			/*
2450 			 * Assume that a regulator is physically present and
2451 			 * enabled, even if it isn't hooked up, and just
2452 			 * provide a dummy.
2453 			 */
2454 			rdev = dummy_regulator_rdev;
2455 			if (!rdev)
2456 				return ERR_PTR(-EPROBE_DEFER);
2457 			dev_warn(dev, "supply %s not found, using dummy regulator\n", id);
2458 			get_device(&rdev->dev);
2459 			break;
2460 
2461 		case EXCLUSIVE_GET:
2462 			dev_warn(dev,
2463 				 "dummy supplies not allowed for exclusive requests (id=%s)\n", id);
2464 			fallthrough;
2465 
2466 		default:
2467 			return ERR_PTR(-ENODEV);
2468 		}
2469 	}
2470 
2471 	if (rdev->exclusive) {
2472 		regulator = ERR_PTR(-EPERM);
2473 		put_device(&rdev->dev);
2474 		return regulator;
2475 	}
2476 
2477 	if (get_type == EXCLUSIVE_GET && rdev->open_count) {
2478 		regulator = ERR_PTR(-EBUSY);
2479 		put_device(&rdev->dev);
2480 		return regulator;
2481 	}
2482 
2483 	mutex_lock(&regulator_list_mutex);
2484 	ret = (rdev->coupling_desc.n_resolved != rdev->coupling_desc.n_coupled);
2485 	mutex_unlock(&regulator_list_mutex);
2486 
2487 	if (ret != 0) {
2488 		regulator = ERR_PTR(-EPROBE_DEFER);
2489 		put_device(&rdev->dev);
2490 		return regulator;
2491 	}
2492 
2493 	ret = regulator_resolve_supply(rdev);
2494 	if (ret < 0) {
2495 		regulator = ERR_PTR(ret);
2496 		put_device(&rdev->dev);
2497 		return regulator;
2498 	}
2499 
2500 	if (!try_module_get(rdev->owner)) {
2501 		regulator = ERR_PTR(-EPROBE_DEFER);
2502 		put_device(&rdev->dev);
2503 		return regulator;
2504 	}
2505 
2506 	regulator_lock(rdev);
2507 	regulator = create_regulator(rdev, dev, id);
2508 	regulator_unlock(rdev);
2509 	if (regulator == NULL) {
2510 		regulator = ERR_PTR(-ENOMEM);
2511 		module_put(rdev->owner);
2512 		put_device(&rdev->dev);
2513 		return regulator;
2514 	}
2515 
2516 	link_and_create_debugfs(regulator, rdev, dev);
2517 
2518 	rdev->open_count++;
2519 	if (get_type == EXCLUSIVE_GET) {
2520 		rdev->exclusive = 1;
2521 
2522 		ret = _regulator_is_enabled(rdev);
2523 		if (ret > 0) {
2524 			rdev->use_count = 1;
2525 			regulator->enable_count = 1;
2526 
2527 			/* Propagate the regulator state to its supply */
2528 			if (rdev->supply) {
2529 				ret = regulator_enable(rdev->supply);
2530 				if (ret < 0) {
2531 					destroy_regulator(regulator);
2532 					module_put(rdev->owner);
2533 					put_device(&rdev->dev);
2534 					return ERR_PTR(ret);
2535 				}
2536 			}
2537 		} else {
2538 			rdev->use_count = 0;
2539 			regulator->enable_count = 0;
2540 		}
2541 	}
2542 
2543 	link = device_link_add(dev, &rdev->dev, DL_FLAG_STATELESS);
2544 	if (!IS_ERR_OR_NULL(link))
2545 		regulator->device_link = true;
2546 
2547 	return regulator;
2548 }
2549 
2550 /* Internal regulator request function */
2551 struct regulator *_regulator_get(struct device *dev, const char *id,
2552 				 enum regulator_get_type get_type)
2553 {
2554 	struct regulator_dev *rdev;
2555 	int ret;
2556 
2557 	ret = _regulator_get_common_check(dev, id, get_type);
2558 	if (ret)
2559 		return ERR_PTR(ret);
2560 
2561 	rdev = regulator_dev_lookup(dev, id);
2562 	return _regulator_get_common(rdev, dev, id, get_type);
2563 }
2564 
2565 /**
2566  * regulator_get - lookup and obtain a reference to a regulator.
2567  * @dev: device for regulator "consumer"
2568  * @id: Supply name or regulator ID.
2569  *
2570  * Use of supply names configured via set_consumer_device_supply() is
2571  * strongly encouraged.  It is recommended that the supply name used
2572  * should match the name used for the supply and/or the relevant
2573  * device pins in the datasheet.
2574  *
2575  * Return: Pointer to a &struct regulator corresponding to the regulator
2576  *	   producer, or an ERR_PTR() encoded negative error number.
2577  */
2578 struct regulator *regulator_get(struct device *dev, const char *id)
2579 {
2580 	return _regulator_get(dev, id, NORMAL_GET);
2581 }
2582 EXPORT_SYMBOL_GPL(regulator_get);
2583 
2584 /**
2585  * regulator_get_exclusive - obtain exclusive access to a regulator.
2586  * @dev: device for regulator "consumer"
2587  * @id: Supply name or regulator ID.
2588  *
2589  * Other consumers will be unable to obtain this regulator while this
2590  * reference is held and the use count for the regulator will be
2591  * initialised to reflect the current state of the regulator.
2592  *
2593  * This is intended for use by consumers which cannot tolerate shared
2594  * use of the regulator such as those which need to force the
2595  * regulator off for correct operation of the hardware they are
2596  * controlling.
2597  *
2598  * Use of supply names configured via set_consumer_device_supply() is
2599  * strongly encouraged.  It is recommended that the supply name used
2600  * should match the name used for the supply and/or the relevant
2601  * device pins in the datasheet.
2602  *
2603  * Return: Pointer to a &struct regulator corresponding to the regulator
2604  *	   producer, or an ERR_PTR() encoded negative error number.
2605  */
2606 struct regulator *regulator_get_exclusive(struct device *dev, const char *id)
2607 {
2608 	return _regulator_get(dev, id, EXCLUSIVE_GET);
2609 }
2610 EXPORT_SYMBOL_GPL(regulator_get_exclusive);
2611 
2612 /**
2613  * regulator_get_optional - obtain optional access to a regulator.
2614  * @dev: device for regulator "consumer"
2615  * @id: Supply name or regulator ID.
2616  *
2617  * This is intended for use by consumers for devices which can have
2618  * some supplies unconnected in normal use, such as some MMC devices.
2619  * It can allow the regulator core to provide stub supplies for other
2620  * supplies requested using normal regulator_get() calls without
2621  * disrupting the operation of drivers that can handle absent
2622  * supplies.
2623  *
2624  * Use of supply names configured via set_consumer_device_supply() is
2625  * strongly encouraged.  It is recommended that the supply name used
2626  * should match the name used for the supply and/or the relevant
2627  * device pins in the datasheet.
2628  *
2629  * Return: Pointer to a &struct regulator corresponding to the regulator
2630  *	   producer, or an ERR_PTR() encoded negative error number.
2631  */
2632 struct regulator *regulator_get_optional(struct device *dev, const char *id)
2633 {
2634 	return _regulator_get(dev, id, OPTIONAL_GET);
2635 }
2636 EXPORT_SYMBOL_GPL(regulator_get_optional);
2637 
2638 static void destroy_regulator(struct regulator *regulator)
2639 {
2640 	struct regulator_dev *rdev = regulator->rdev;
2641 
2642 	debugfs_remove_recursive(regulator->debugfs);
2643 
2644 	if (regulator->dev) {
2645 		if (regulator->device_link)
2646 			device_link_remove(regulator->dev, &rdev->dev);
2647 
2648 		/* remove any sysfs entries */
2649 		sysfs_remove_link(&rdev->dev.kobj, regulator->supply_name);
2650 	}
2651 
2652 	regulator_lock(rdev);
2653 	list_del(&regulator->list);
2654 
2655 	rdev->open_count--;
2656 	rdev->exclusive = 0;
2657 	regulator_unlock(rdev);
2658 
2659 	kfree_const(regulator->supply_name);
2660 	kfree(regulator);
2661 }
2662 
2663 /* regulator_list_mutex lock held by regulator_put() */
2664 static void _regulator_put(struct regulator *regulator)
2665 {
2666 	struct regulator_dev *rdev;
2667 
2668 	if (IS_ERR_OR_NULL(regulator))
2669 		return;
2670 
2671 	lockdep_assert_held_once(&regulator_list_mutex);
2672 
2673 	/* Docs say you must disable before calling regulator_put() */
2674 	WARN_ON(regulator->enable_count);
2675 
2676 	rdev = regulator->rdev;
2677 
2678 	destroy_regulator(regulator);
2679 
2680 	module_put(rdev->owner);
2681 	put_device(&rdev->dev);
2682 }
2683 
2684 /**
2685  * regulator_put - "free" the regulator source
2686  * @regulator: regulator source
2687  *
2688  * Note: drivers must ensure that all regulator_enable calls made on this
2689  * regulator source are balanced by regulator_disable calls prior to calling
2690  * this function.
2691  */
2692 void regulator_put(struct regulator *regulator)
2693 {
2694 	mutex_lock(&regulator_list_mutex);
2695 	_regulator_put(regulator);
2696 	mutex_unlock(&regulator_list_mutex);
2697 }
2698 EXPORT_SYMBOL_GPL(regulator_put);
2699 
2700 /**
2701  * regulator_register_supply_alias - Provide device alias for supply lookup
2702  *
2703  * @dev: device that will be given as the regulator "consumer"
2704  * @id: Supply name or regulator ID
2705  * @alias_dev: device that should be used to lookup the supply
2706  * @alias_id: Supply name or regulator ID that should be used to lookup the
2707  * supply
2708  *
2709  * All lookups for id on dev will instead be conducted for alias_id on
2710  * alias_dev.
2711  *
2712  * Return: 0 on success or a negative error number on failure.
2713  */
2714 int regulator_register_supply_alias(struct device *dev, const char *id,
2715 				    struct device *alias_dev,
2716 				    const char *alias_id)
2717 {
2718 	struct regulator_supply_alias *map;
2719 	struct regulator_supply_alias *new_map;
2720 
2721 	new_map = kzalloc_obj(struct regulator_supply_alias);
2722 	if (!new_map)
2723 		return -ENOMEM;
2724 
2725 	mutex_lock(&regulator_list_mutex);
2726 	map = regulator_find_supply_alias(dev, id);
2727 	if (map) {
2728 		mutex_unlock(&regulator_list_mutex);
2729 		kfree(new_map);
2730 		return -EEXIST;
2731 	}
2732 
2733 	new_map->src_dev = dev;
2734 	new_map->src_supply = id;
2735 	new_map->alias_dev = alias_dev;
2736 	new_map->alias_supply = alias_id;
2737 	list_add(&new_map->list, &regulator_supply_alias_list);
2738 	mutex_unlock(&regulator_list_mutex);
2739 	pr_info("Adding alias for supply %s,%s -> %s,%s\n",
2740 		id, dev_name(dev), alias_id, dev_name(alias_dev));
2741 
2742 	return 0;
2743 }
2744 EXPORT_SYMBOL_GPL(regulator_register_supply_alias);
2745 
2746 /**
2747  * regulator_unregister_supply_alias - Remove device alias
2748  *
2749  * @dev: device that will be given as the regulator "consumer"
2750  * @id: Supply name or regulator ID
2751  *
2752  * Remove a lookup alias if one exists for id on dev.
2753  */
2754 void regulator_unregister_supply_alias(struct device *dev, const char *id)
2755 {
2756 	struct regulator_supply_alias *map;
2757 
2758 	mutex_lock(&regulator_list_mutex);
2759 	map = regulator_find_supply_alias(dev, id);
2760 	if (map) {
2761 		list_del(&map->list);
2762 		kfree(map);
2763 	}
2764 	mutex_unlock(&regulator_list_mutex);
2765 }
2766 EXPORT_SYMBOL_GPL(regulator_unregister_supply_alias);
2767 
2768 /**
2769  * regulator_bulk_register_supply_alias - register multiple aliases
2770  *
2771  * @dev: device that will be given as the regulator "consumer"
2772  * @id: List of supply names or regulator IDs
2773  * @alias_dev: device that should be used to lookup the supply
2774  * @alias_id: List of supply names or regulator IDs that should be used to
2775  * lookup the supply
2776  * @num_id: Number of aliases to register
2777  *
2778  * This helper function allows drivers to register several supply
2779  * aliases in one operation.  If any of the aliases cannot be
2780  * registered any aliases that were registered will be removed
2781  * before returning to the caller.
2782  *
2783  * Return: 0 on success or a negative error number on failure.
2784  */
2785 int regulator_bulk_register_supply_alias(struct device *dev,
2786 					 const char *const *id,
2787 					 struct device *alias_dev,
2788 					 const char *const *alias_id,
2789 					 int num_id)
2790 {
2791 	int i;
2792 	int ret;
2793 
2794 	for (i = 0; i < num_id; ++i) {
2795 		ret = regulator_register_supply_alias(dev, id[i], alias_dev,
2796 						      alias_id[i]);
2797 		if (ret < 0)
2798 			goto err;
2799 	}
2800 
2801 	return 0;
2802 
2803 err:
2804 	dev_err(dev,
2805 		"Failed to create supply alias %s,%s -> %s,%s\n",
2806 		id[i], dev_name(dev), alias_id[i], dev_name(alias_dev));
2807 
2808 	while (--i >= 0)
2809 		regulator_unregister_supply_alias(dev, id[i]);
2810 
2811 	return ret;
2812 }
2813 EXPORT_SYMBOL_GPL(regulator_bulk_register_supply_alias);
2814 
2815 /**
2816  * regulator_bulk_unregister_supply_alias - unregister multiple aliases
2817  *
2818  * @dev: device that will be given as the regulator "consumer"
2819  * @id: List of supply names or regulator IDs
2820  * @num_id: Number of aliases to unregister
2821  *
2822  * This helper function allows drivers to unregister several supply
2823  * aliases in one operation.
2824  */
2825 void regulator_bulk_unregister_supply_alias(struct device *dev,
2826 					    const char *const *id,
2827 					    int num_id)
2828 {
2829 	int i;
2830 
2831 	for (i = 0; i < num_id; ++i)
2832 		regulator_unregister_supply_alias(dev, id[i]);
2833 }
2834 EXPORT_SYMBOL_GPL(regulator_bulk_unregister_supply_alias);
2835 
2836 
2837 /* Manage enable GPIO list. Same GPIO pin can be shared among regulators */
2838 static int regulator_ena_gpio_request(struct regulator_dev *rdev,
2839 				const struct regulator_config *config)
2840 {
2841 	struct regulator_enable_gpio *pin, *new_pin;
2842 	struct gpio_desc *gpiod;
2843 
2844 	gpiod = config->ena_gpiod;
2845 	new_pin = kzalloc_obj(*new_pin);
2846 
2847 	mutex_lock(&regulator_list_mutex);
2848 
2849 	if (gpiod_is_shared(gpiod))
2850 		/*
2851 		 * The sharing of this GPIO pin is managed internally by
2852 		 * GPIOLIB. We don't need to keep track of its enable count.
2853 		 */
2854 		goto skip_compare;
2855 
2856 	list_for_each_entry(pin, &regulator_ena_gpio_list, list) {
2857 		if (gpiod_is_equal(pin->gpiod, gpiod)) {
2858 			rdev_dbg(rdev, "GPIO is already used\n");
2859 			goto update_ena_gpio_to_rdev;
2860 		}
2861 	}
2862 
2863 	if (new_pin == NULL) {
2864 		mutex_unlock(&regulator_list_mutex);
2865 		return -ENOMEM;
2866 	}
2867 
2868 skip_compare:
2869 	pin = new_pin;
2870 	new_pin = NULL;
2871 
2872 	pin->gpiod = gpiod;
2873 	list_add(&pin->list, &regulator_ena_gpio_list);
2874 
2875 update_ena_gpio_to_rdev:
2876 	pin->request_count++;
2877 	rdev->ena_pin = pin;
2878 
2879 	mutex_unlock(&regulator_list_mutex);
2880 	kfree(new_pin);
2881 
2882 	return 0;
2883 }
2884 
2885 static void regulator_ena_gpio_free(struct regulator_dev *rdev)
2886 {
2887 	struct regulator_enable_gpio *pin, *n;
2888 
2889 	if (!rdev->ena_pin)
2890 		return;
2891 
2892 	/* Free the GPIO only in case of no use */
2893 	list_for_each_entry_safe(pin, n, &regulator_ena_gpio_list, list) {
2894 		if (pin != rdev->ena_pin)
2895 			continue;
2896 
2897 		if (--pin->request_count)
2898 			break;
2899 
2900 		gpiod_put(pin->gpiod);
2901 		list_del(&pin->list);
2902 		kfree(pin);
2903 		break;
2904 	}
2905 
2906 	rdev->ena_pin = NULL;
2907 }
2908 
2909 /**
2910  * regulator_ena_gpio_ctrl - balance enable_count of each GPIO and actual GPIO pin control
2911  * @rdev: regulator_dev structure
2912  * @enable: enable GPIO at initial use?
2913  *
2914  * GPIO is enabled in case of initial use. (enable_count is 0)
2915  * GPIO is disabled when it is not shared any more. (enable_count <= 1)
2916  *
2917  * Return: 0 on success or a negative error number on failure.
2918  */
2919 static int regulator_ena_gpio_ctrl(struct regulator_dev *rdev, bool enable)
2920 {
2921 	struct regulator_enable_gpio *pin = rdev->ena_pin;
2922 	int ret;
2923 
2924 	if (!pin)
2925 		return -EINVAL;
2926 
2927 	if (enable) {
2928 		/* Enable GPIO at initial use */
2929 		if (pin->enable_count == 0) {
2930 			ret = gpiod_set_value_cansleep(pin->gpiod, 1);
2931 			if (ret)
2932 				return ret;
2933 		}
2934 
2935 		pin->enable_count++;
2936 	} else {
2937 		if (pin->enable_count > 1) {
2938 			pin->enable_count--;
2939 			return 0;
2940 		}
2941 
2942 		/* Disable GPIO if not used */
2943 		if (pin->enable_count <= 1) {
2944 			ret = gpiod_set_value_cansleep(pin->gpiod, 0);
2945 			if (ret)
2946 				return ret;
2947 
2948 			pin->enable_count = 0;
2949 		}
2950 	}
2951 
2952 	return 0;
2953 }
2954 
2955 /**
2956  * _regulator_check_status_enabled - check if regulator status can be
2957  *				     interpreted as "regulator is enabled"
2958  * @rdev: the regulator device to check
2959  *
2960  * Return:
2961  * * 1			- if status shows regulator is in enabled state
2962  * * 0			- if not enabled state
2963  * * Error Value	- as received from ops->get_status()
2964  */
2965 static inline int _regulator_check_status_enabled(struct regulator_dev *rdev)
2966 {
2967 	int ret = rdev->desc->ops->get_status(rdev);
2968 
2969 	if (ret < 0) {
2970 		rdev_info(rdev, "get_status returned error: %d\n", ret);
2971 		return ret;
2972 	}
2973 
2974 	switch (ret) {
2975 	case REGULATOR_STATUS_OFF:
2976 	case REGULATOR_STATUS_ERROR:
2977 	case REGULATOR_STATUS_UNDEFINED:
2978 		return 0;
2979 	default:
2980 		return 1;
2981 	}
2982 }
2983 
2984 static int _regulator_do_enable(struct regulator_dev *rdev)
2985 {
2986 	int ret, delay;
2987 
2988 	/* Query before enabling in case configuration dependent.  */
2989 	ret = _regulator_get_enable_time(rdev);
2990 	if (ret >= 0) {
2991 		delay = ret;
2992 	} else {
2993 		rdev_warn(rdev, "enable_time() failed: %pe\n", ERR_PTR(ret));
2994 		delay = 0;
2995 	}
2996 
2997 	trace_regulator_enable(rdev_get_name(rdev));
2998 
2999 	if (rdev->desc->off_on_delay) {
3000 		/* if needed, keep a distance of off_on_delay from last time
3001 		 * this regulator was disabled.
3002 		 */
3003 		ktime_t end = ktime_add_us(rdev->last_off, rdev->desc->off_on_delay);
3004 		s64 remaining = ktime_us_delta(end, ktime_get_boottime());
3005 
3006 		if (remaining > 0)
3007 			fsleep(remaining);
3008 	}
3009 
3010 	if (rdev->ena_pin) {
3011 		if (!rdev->ena_gpio_state) {
3012 			ret = regulator_ena_gpio_ctrl(rdev, true);
3013 			if (ret < 0)
3014 				return ret;
3015 			rdev->ena_gpio_state = 1;
3016 		}
3017 	} else if (rdev->desc->ops->enable) {
3018 		ret = rdev->desc->ops->enable(rdev);
3019 		if (ret < 0)
3020 			return ret;
3021 	} else {
3022 		return -EINVAL;
3023 	}
3024 
3025 	/* Allow the regulator to ramp; it would be useful to extend
3026 	 * this for bulk operations so that the regulators can ramp
3027 	 * together.
3028 	 */
3029 	trace_regulator_enable_delay(rdev_get_name(rdev));
3030 
3031 	/* If poll_enabled_time is set, poll upto the delay calculated
3032 	 * above, delaying poll_enabled_time uS to check if the regulator
3033 	 * actually got enabled.
3034 	 * If the regulator isn't enabled after our delay helper has expired,
3035 	 * return -ETIMEDOUT.
3036 	 */
3037 	if (rdev->desc->poll_enabled_time) {
3038 		int time_remaining = delay;
3039 
3040 		while (time_remaining > 0) {
3041 			fsleep(rdev->desc->poll_enabled_time);
3042 
3043 			if (rdev->desc->ops->get_status) {
3044 				ret = _regulator_check_status_enabled(rdev);
3045 				if (ret < 0)
3046 					return ret;
3047 				else if (ret)
3048 					break;
3049 			} else if (rdev->desc->ops->is_enabled(rdev))
3050 				break;
3051 
3052 			time_remaining -= rdev->desc->poll_enabled_time;
3053 		}
3054 
3055 		if (time_remaining <= 0) {
3056 			rdev_err(rdev, "Enabled check timed out\n");
3057 			return -ETIMEDOUT;
3058 		}
3059 	} else {
3060 		fsleep(delay);
3061 	}
3062 
3063 	trace_regulator_enable_complete(rdev_get_name(rdev));
3064 
3065 	return 0;
3066 }
3067 
3068 /**
3069  * _regulator_handle_consumer_enable - handle that a consumer enabled
3070  * @regulator: regulator source
3071  *
3072  * Some things on a regulator consumer (like the contribution towards total
3073  * load on the regulator) only have an effect when the consumer wants the
3074  * regulator enabled.  Explained in example with two consumers of the same
3075  * regulator:
3076  *   consumer A: set_load(100);       => total load = 0
3077  *   consumer A: regulator_enable();  => total load = 100
3078  *   consumer B: set_load(1000);      => total load = 100
3079  *   consumer B: regulator_enable();  => total load = 1100
3080  *   consumer A: regulator_disable(); => total_load = 1000
3081  *
3082  * This function (together with _regulator_handle_consumer_disable) is
3083  * responsible for keeping track of the refcount for a given regulator consumer
3084  * and applying / unapplying these things.
3085  *
3086  * Return: 0 on success or negative error number on failure.
3087  */
3088 static int _regulator_handle_consumer_enable(struct regulator *regulator)
3089 {
3090 	int ret;
3091 	struct regulator_dev *rdev = regulator->rdev;
3092 
3093 	lockdep_assert_held_once(&rdev->mutex.base);
3094 
3095 	regulator->enable_count++;
3096 	if (regulator->uA_load && regulator->enable_count == 1) {
3097 		ret = drms_uA_update(rdev);
3098 		if (ret)
3099 			regulator->enable_count--;
3100 		return ret;
3101 	}
3102 
3103 	return 0;
3104 }
3105 
3106 /**
3107  * _regulator_handle_consumer_disable - handle that a consumer disabled
3108  * @regulator: regulator source
3109  *
3110  * The opposite of _regulator_handle_consumer_enable().
3111  *
3112  * Return: 0 on success or a negative error number on failure.
3113  */
3114 static int _regulator_handle_consumer_disable(struct regulator *regulator)
3115 {
3116 	struct regulator_dev *rdev = regulator->rdev;
3117 
3118 	lockdep_assert_held_once(&rdev->mutex.base);
3119 
3120 	if (!regulator->enable_count) {
3121 		rdev_err(rdev, "Underflow of regulator enable count\n");
3122 		return -EINVAL;
3123 	}
3124 
3125 	regulator->enable_count--;
3126 	if (regulator->uA_load && regulator->enable_count == 0)
3127 		return drms_uA_update(rdev);
3128 
3129 	return 0;
3130 }
3131 
3132 /* locks held by regulator_enable() */
3133 static int _regulator_enable(struct regulator *regulator)
3134 {
3135 	struct regulator_dev *rdev = regulator->rdev;
3136 	int ret;
3137 
3138 	lockdep_assert_held_once(&rdev->mutex.base);
3139 
3140 	if (rdev->use_count == 0 && rdev->supply) {
3141 		ret = _regulator_enable(rdev->supply);
3142 		if (ret < 0)
3143 			return ret;
3144 	}
3145 
3146 	/* balance only if there are regulators coupled */
3147 	if (rdev->coupling_desc.n_coupled > 1) {
3148 		ret = regulator_balance_voltage(rdev, PM_SUSPEND_ON);
3149 		if (ret < 0)
3150 			goto err_disable_supply;
3151 	}
3152 
3153 	ret = _regulator_handle_consumer_enable(regulator);
3154 	if (ret < 0)
3155 		goto err_disable_supply;
3156 
3157 	if (rdev->use_count == 0) {
3158 		/*
3159 		 * The regulator may already be enabled if it's not switchable
3160 		 * or was left on
3161 		 */
3162 		ret = _regulator_is_enabled(rdev);
3163 		if (ret == -EINVAL || ret == 0) {
3164 			if (!regulator_ops_is_valid(rdev,
3165 					REGULATOR_CHANGE_STATUS)) {
3166 				ret = -EPERM;
3167 				goto err_consumer_disable;
3168 			}
3169 
3170 			ret = _regulator_do_enable(rdev);
3171 			if (ret < 0)
3172 				goto err_consumer_disable;
3173 
3174 			_notifier_call_chain(rdev, REGULATOR_EVENT_ENABLE,
3175 					     NULL);
3176 		} else if (ret < 0) {
3177 			rdev_err(rdev, "is_enabled() failed: %pe\n", ERR_PTR(ret));
3178 			goto err_consumer_disable;
3179 		}
3180 		/* Fallthrough on positive return values - already enabled */
3181 	}
3182 
3183 	if (regulator->enable_count == 1)
3184 		rdev->use_count++;
3185 
3186 	return 0;
3187 
3188 err_consumer_disable:
3189 	_regulator_handle_consumer_disable(regulator);
3190 
3191 err_disable_supply:
3192 	if (rdev->use_count == 0 && rdev->supply)
3193 		_regulator_disable(rdev->supply);
3194 
3195 	return ret;
3196 }
3197 
3198 /**
3199  * regulator_enable - enable regulator output
3200  * @regulator: regulator source
3201  *
3202  * Request that the regulator be enabled with the regulator output at
3203  * the predefined voltage or current value.  Calls to regulator_enable()
3204  * must be balanced with calls to regulator_disable().
3205  *
3206  * NOTE: the output value can be set by other drivers, boot loader or may be
3207  * hardwired in the regulator.
3208  *
3209  * Return: 0 on success or a negative error number on failure.
3210  */
3211 int regulator_enable(struct regulator *regulator)
3212 {
3213 	struct regulator_dev *rdev = regulator->rdev;
3214 	struct ww_acquire_ctx ww_ctx;
3215 	int ret;
3216 
3217 	regulator_lock_dependent(rdev, &ww_ctx);
3218 	ret = _regulator_enable(regulator);
3219 	regulator_unlock_dependent(rdev, &ww_ctx);
3220 
3221 	return ret;
3222 }
3223 EXPORT_SYMBOL_GPL(regulator_enable);
3224 
3225 static int _regulator_do_disable(struct regulator_dev *rdev)
3226 {
3227 	int ret;
3228 
3229 	trace_regulator_disable(rdev_get_name(rdev));
3230 
3231 	if (rdev->ena_pin) {
3232 		if (rdev->ena_gpio_state) {
3233 			ret = regulator_ena_gpio_ctrl(rdev, false);
3234 			if (ret < 0)
3235 				return ret;
3236 			rdev->ena_gpio_state = 0;
3237 		}
3238 
3239 	} else if (rdev->desc->ops->disable) {
3240 		ret = rdev->desc->ops->disable(rdev);
3241 		if (ret != 0)
3242 			return ret;
3243 	}
3244 
3245 	if (rdev->desc->off_on_delay)
3246 		rdev->last_off = ktime_get_boottime();
3247 
3248 	trace_regulator_disable_complete(rdev_get_name(rdev));
3249 
3250 	return 0;
3251 }
3252 
3253 /* locks held by regulator_disable() */
3254 static int _regulator_disable(struct regulator *regulator)
3255 {
3256 	struct regulator_dev *rdev = regulator->rdev;
3257 	int ret = 0;
3258 
3259 	lockdep_assert_held_once(&rdev->mutex.base);
3260 
3261 	if (WARN(regulator->enable_count == 0,
3262 		 "unbalanced disables for %s\n", rdev_get_name(rdev)))
3263 		return -EIO;
3264 
3265 	if (regulator->enable_count == 1) {
3266 	/* disabling last enable_count from this regulator */
3267 		/* are we the last user and permitted to disable ? */
3268 		if (rdev->use_count == 1 &&
3269 		    (rdev->constraints && !rdev->constraints->always_on)) {
3270 
3271 			/* we are last user */
3272 			if (regulator_ops_is_valid(rdev, REGULATOR_CHANGE_STATUS)) {
3273 				ret = _notifier_call_chain(rdev,
3274 							   REGULATOR_EVENT_PRE_DISABLE,
3275 							   NULL);
3276 				if (ret & NOTIFY_STOP_MASK)
3277 					return -EINVAL;
3278 
3279 				ret = _regulator_do_disable(rdev);
3280 				if (ret < 0) {
3281 					rdev_err(rdev, "failed to disable: %pe\n", ERR_PTR(ret));
3282 					_notifier_call_chain(rdev,
3283 							REGULATOR_EVENT_ABORT_DISABLE,
3284 							NULL);
3285 					return ret;
3286 				}
3287 				_notifier_call_chain(rdev, REGULATOR_EVENT_DISABLE,
3288 						NULL);
3289 			}
3290 
3291 			rdev->use_count = 0;
3292 		} else if (rdev->use_count > 1) {
3293 			rdev->use_count--;
3294 		}
3295 	}
3296 
3297 	if (ret == 0)
3298 		ret = _regulator_handle_consumer_disable(regulator);
3299 
3300 	if (ret == 0 && rdev->coupling_desc.n_coupled > 1)
3301 		ret = regulator_balance_voltage(rdev, PM_SUSPEND_ON);
3302 
3303 	if (ret == 0 && rdev->use_count == 0 && rdev->supply)
3304 		ret = _regulator_disable(rdev->supply);
3305 
3306 	return ret;
3307 }
3308 
3309 /**
3310  * regulator_disable - disable regulator output
3311  * @regulator: regulator source
3312  *
3313  * Disable the regulator output voltage or current.  Calls to
3314  * regulator_enable() must be balanced with calls to
3315  * regulator_disable().
3316  *
3317  * NOTE: this will only disable the regulator output if no other consumer
3318  * devices have it enabled, the regulator device supports disabling and
3319  * machine constraints permit this operation.
3320  *
3321  * Return: 0 on success or a negative error number on failure.
3322  */
3323 int regulator_disable(struct regulator *regulator)
3324 {
3325 	struct regulator_dev *rdev = regulator->rdev;
3326 	struct ww_acquire_ctx ww_ctx;
3327 	int ret;
3328 
3329 	regulator_lock_dependent(rdev, &ww_ctx);
3330 	ret = _regulator_disable(regulator);
3331 	regulator_unlock_dependent(rdev, &ww_ctx);
3332 
3333 	return ret;
3334 }
3335 EXPORT_SYMBOL_GPL(regulator_disable);
3336 
3337 /* locks held by regulator_force_disable() */
3338 static int _regulator_force_disable(struct regulator_dev *rdev)
3339 {
3340 	int ret = 0;
3341 
3342 	lockdep_assert_held_once(&rdev->mutex.base);
3343 
3344 	ret = _notifier_call_chain(rdev, REGULATOR_EVENT_FORCE_DISABLE |
3345 			REGULATOR_EVENT_PRE_DISABLE, NULL);
3346 	if (ret & NOTIFY_STOP_MASK)
3347 		return -EINVAL;
3348 
3349 	ret = _regulator_do_disable(rdev);
3350 	if (ret < 0) {
3351 		rdev_err(rdev, "failed to force disable: %pe\n", ERR_PTR(ret));
3352 		_notifier_call_chain(rdev, REGULATOR_EVENT_FORCE_DISABLE |
3353 				REGULATOR_EVENT_ABORT_DISABLE, NULL);
3354 		return ret;
3355 	}
3356 
3357 	_notifier_call_chain(rdev, REGULATOR_EVENT_FORCE_DISABLE |
3358 			REGULATOR_EVENT_DISABLE, NULL);
3359 
3360 	return 0;
3361 }
3362 
3363 /**
3364  * regulator_force_disable - force disable regulator output
3365  * @regulator: regulator source
3366  *
3367  * Forcibly disable the regulator output voltage or current.
3368  * NOTE: this *will* disable the regulator output even if other consumer
3369  * devices have it enabled. This should be used for situations when device
3370  * damage will likely occur if the regulator is not disabled (e.g. over temp).
3371  *
3372  * Return: 0 on success or a negative error number on failure.
3373  */
3374 int regulator_force_disable(struct regulator *regulator)
3375 {
3376 	struct regulator_dev *rdev = regulator->rdev;
3377 	struct ww_acquire_ctx ww_ctx;
3378 	int ret;
3379 
3380 	regulator_lock_dependent(rdev, &ww_ctx);
3381 
3382 	ret = _regulator_force_disable(regulator->rdev);
3383 
3384 	if (rdev->coupling_desc.n_coupled > 1)
3385 		regulator_balance_voltage(rdev, PM_SUSPEND_ON);
3386 
3387 	if (regulator->uA_load) {
3388 		regulator->uA_load = 0;
3389 		ret = drms_uA_update(rdev);
3390 	}
3391 
3392 	if (rdev->use_count != 0 && rdev->supply)
3393 		_regulator_disable(rdev->supply);
3394 
3395 	regulator_unlock_dependent(rdev, &ww_ctx);
3396 
3397 	return ret;
3398 }
3399 EXPORT_SYMBOL_GPL(regulator_force_disable);
3400 
3401 static void regulator_disable_work(struct work_struct *work)
3402 {
3403 	struct regulator_dev *rdev = container_of(work, struct regulator_dev,
3404 						  disable_work.work);
3405 	struct ww_acquire_ctx ww_ctx;
3406 	int count, i, ret;
3407 	struct regulator *regulator;
3408 	int total_count = 0;
3409 
3410 	regulator_lock_dependent(rdev, &ww_ctx);
3411 
3412 	/*
3413 	 * Workqueue functions queue the new work instance while the previous
3414 	 * work instance is being processed. Cancel the queued work instance
3415 	 * as the work instance under processing does the job of the queued
3416 	 * work instance.
3417 	 */
3418 	cancel_delayed_work(&rdev->disable_work);
3419 
3420 	list_for_each_entry(regulator, &rdev->consumer_list, list) {
3421 		count = regulator->deferred_disables;
3422 
3423 		if (!count)
3424 			continue;
3425 
3426 		total_count += count;
3427 		regulator->deferred_disables = 0;
3428 
3429 		for (i = 0; i < count; i++) {
3430 			ret = _regulator_disable(regulator);
3431 			if (ret != 0)
3432 				rdev_err(rdev, "Deferred disable failed: %pe\n",
3433 					 ERR_PTR(ret));
3434 		}
3435 	}
3436 	WARN_ON(!total_count);
3437 
3438 	if (rdev->coupling_desc.n_coupled > 1)
3439 		regulator_balance_voltage(rdev, PM_SUSPEND_ON);
3440 
3441 	regulator_unlock_dependent(rdev, &ww_ctx);
3442 }
3443 
3444 /**
3445  * regulator_disable_deferred - disable regulator output with delay
3446  * @regulator: regulator source
3447  * @ms: milliseconds until the regulator is disabled
3448  *
3449  * Execute regulator_disable() on the regulator after a delay.  This
3450  * is intended for use with devices that require some time to quiesce.
3451  *
3452  * NOTE: this will only disable the regulator output if no other consumer
3453  * devices have it enabled, the regulator device supports disabling and
3454  * machine constraints permit this operation.
3455  *
3456  * Return: 0 on success or a negative error number on failure.
3457  */
3458 int regulator_disable_deferred(struct regulator *regulator, int ms)
3459 {
3460 	struct regulator_dev *rdev = regulator->rdev;
3461 
3462 	if (!ms)
3463 		return regulator_disable(regulator);
3464 
3465 	regulator_lock(rdev);
3466 	regulator->deferred_disables++;
3467 	mod_delayed_work(system_power_efficient_wq, &rdev->disable_work,
3468 			 msecs_to_jiffies(ms));
3469 	regulator_unlock(rdev);
3470 
3471 	return 0;
3472 }
3473 EXPORT_SYMBOL_GPL(regulator_disable_deferred);
3474 
3475 static int _regulator_is_enabled(struct regulator_dev *rdev)
3476 {
3477 	/* A GPIO control always takes precedence */
3478 	if (rdev->ena_pin)
3479 		return rdev->ena_gpio_state;
3480 
3481 	/* If we don't know then assume that the regulator is always on */
3482 	if (!rdev->desc->ops->is_enabled)
3483 		return 1;
3484 
3485 	return rdev->desc->ops->is_enabled(rdev);
3486 }
3487 
3488 static int _regulator_list_voltage(struct regulator_dev *rdev,
3489 				   unsigned selector, int lock)
3490 {
3491 	const struct regulator_ops *ops = rdev->desc->ops;
3492 	int ret;
3493 
3494 	if (rdev->desc->fixed_uV && rdev->desc->n_voltages == 1 && !selector)
3495 		return rdev->desc->fixed_uV;
3496 
3497 	if (ops->list_voltage) {
3498 		if (selector >= rdev->desc->n_voltages)
3499 			return -EINVAL;
3500 		if (selector < rdev->desc->linear_min_sel)
3501 			return 0;
3502 		if (lock)
3503 			regulator_lock(rdev);
3504 		ret = ops->list_voltage(rdev, selector);
3505 		if (lock)
3506 			regulator_unlock(rdev);
3507 	} else if (rdev->is_switch && rdev->supply) {
3508 		ret = _regulator_list_voltage(rdev->supply->rdev,
3509 					      selector, lock);
3510 	} else {
3511 		return -EINVAL;
3512 	}
3513 
3514 	if (ret > 0) {
3515 		if (ret < rdev->constraints->min_uV)
3516 			ret = 0;
3517 		else if (ret > rdev->constraints->max_uV)
3518 			ret = 0;
3519 	}
3520 
3521 	return ret;
3522 }
3523 
3524 /**
3525  * regulator_is_enabled - is the regulator output enabled
3526  * @regulator: regulator source
3527  *
3528  * Note that the device backing this regulator handle can have multiple
3529  * users, so it might be enabled even if regulator_enable() was never
3530  * called for this particular source.
3531  *
3532  * Return: Positive if the regulator driver backing the source/client
3533  *	   has requested that the device be enabled, zero if it hasn't,
3534  *	   else a negative error number.
3535  */
3536 int regulator_is_enabled(struct regulator *regulator)
3537 {
3538 	int ret;
3539 
3540 	if (regulator->always_on)
3541 		return 1;
3542 
3543 	regulator_lock(regulator->rdev);
3544 	ret = _regulator_is_enabled(regulator->rdev);
3545 	regulator_unlock(regulator->rdev);
3546 
3547 	return ret;
3548 }
3549 EXPORT_SYMBOL_GPL(regulator_is_enabled);
3550 
3551 /**
3552  * regulator_count_voltages - count regulator_list_voltage() selectors
3553  * @regulator: regulator source
3554  *
3555  * Return: Number of selectors for @regulator, or negative error number.
3556  *
3557  * Selectors are numbered starting at zero, and typically correspond to
3558  * bitfields in hardware registers.
3559  */
3560 int regulator_count_voltages(struct regulator *regulator)
3561 {
3562 	struct regulator_dev	*rdev = regulator->rdev;
3563 
3564 	if (rdev->desc->n_voltages)
3565 		return rdev->desc->n_voltages;
3566 
3567 	if (!rdev->is_switch || !rdev->supply)
3568 		return -EINVAL;
3569 
3570 	return regulator_count_voltages(rdev->supply);
3571 }
3572 EXPORT_SYMBOL_GPL(regulator_count_voltages);
3573 
3574 /**
3575  * regulator_list_voltage - enumerate supported voltages
3576  * @regulator: regulator source
3577  * @selector: identify voltage to list
3578  * Context: can sleep
3579  *
3580  * Return: Voltage for @selector that can be passed to regulator_set_voltage(),
3581  *	   0 if @selector can't be used on this system, or a negative error
3582  *	   number on failure.
3583  */
3584 int regulator_list_voltage(struct regulator *regulator, unsigned selector)
3585 {
3586 	return _regulator_list_voltage(regulator->rdev, selector, 1);
3587 }
3588 EXPORT_SYMBOL_GPL(regulator_list_voltage);
3589 
3590 /**
3591  * regulator_get_regmap - get the regulator's register map
3592  * @regulator: regulator source
3593  *
3594  * Return: Pointer to the &struct regmap for @regulator, or ERR_PTR()
3595  *	   encoded -%EOPNOTSUPP if @regulator doesn't use regmap.
3596  */
3597 struct regmap *regulator_get_regmap(struct regulator *regulator)
3598 {
3599 	struct regmap *map = regulator->rdev->regmap;
3600 
3601 	return map ? map : ERR_PTR(-EOPNOTSUPP);
3602 }
3603 EXPORT_SYMBOL_GPL(regulator_get_regmap);
3604 
3605 /**
3606  * regulator_get_hardware_vsel_register - get the HW voltage selector register
3607  * @regulator: regulator source
3608  * @vsel_reg: voltage selector register, output parameter
3609  * @vsel_mask: mask for voltage selector bitfield, output parameter
3610  *
3611  * Returns the hardware register offset and bitmask used for setting the
3612  * regulator voltage. This might be useful when configuring voltage-scaling
3613  * hardware or firmware that can make I2C requests behind the kernel's back,
3614  * for example.
3615  *
3616  * Return: 0 on success, or -%EOPNOTSUPP if the regulator does not support
3617  *         voltage selectors.
3618  *
3619  * On success, the output parameters @vsel_reg and @vsel_mask are filled in
3620  * and 0 is returned, otherwise a negative error number is returned.
3621  */
3622 int regulator_get_hardware_vsel_register(struct regulator *regulator,
3623 					 unsigned *vsel_reg,
3624 					 unsigned *vsel_mask)
3625 {
3626 	struct regulator_dev *rdev = regulator->rdev;
3627 	const struct regulator_ops *ops = rdev->desc->ops;
3628 
3629 	if (ops->set_voltage_sel != regulator_set_voltage_sel_regmap)
3630 		return -EOPNOTSUPP;
3631 
3632 	*vsel_reg = rdev->desc->vsel_reg;
3633 	*vsel_mask = rdev->desc->vsel_mask;
3634 
3635 	return 0;
3636 }
3637 EXPORT_SYMBOL_GPL(regulator_get_hardware_vsel_register);
3638 
3639 /**
3640  * regulator_list_hardware_vsel - get the HW-specific register value for a selector
3641  * @regulator: regulator source
3642  * @selector: identify voltage to list
3643  *
3644  * Converts the selector to a hardware-specific voltage selector that can be
3645  * directly written to the regulator registers. The address of the voltage
3646  * register can be determined by calling @regulator_get_hardware_vsel_register.
3647  *
3648  * Return: 0 on success, -%EINVAL if the selector is outside the supported
3649  *	   range, or -%EOPNOTSUPP if the regulator does not support voltage
3650  *	   selectors.
3651  */
3652 int regulator_list_hardware_vsel(struct regulator *regulator,
3653 				 unsigned selector)
3654 {
3655 	struct regulator_dev *rdev = regulator->rdev;
3656 	const struct regulator_ops *ops = rdev->desc->ops;
3657 
3658 	if (selector >= rdev->desc->n_voltages)
3659 		return -EINVAL;
3660 	if (selector < rdev->desc->linear_min_sel)
3661 		return 0;
3662 	if (ops->set_voltage_sel != regulator_set_voltage_sel_regmap)
3663 		return -EOPNOTSUPP;
3664 
3665 	return selector;
3666 }
3667 EXPORT_SYMBOL_GPL(regulator_list_hardware_vsel);
3668 
3669 /**
3670  * regulator_hardware_enable - access the HW for enable/disable regulator
3671  * @regulator: regulator source
3672  * @enable: true for enable, false for disable
3673  *
3674  * Request that the regulator be enabled/disabled with the regulator output at
3675  * the predefined voltage or current value.
3676  *
3677  * Return: 0 on success or a negative error number on failure.
3678  */
3679 int regulator_hardware_enable(struct regulator *regulator, bool enable)
3680 {
3681 	struct regulator_dev *rdev = regulator->rdev;
3682 	const struct regulator_ops *ops = rdev->desc->ops;
3683 	int ret = -EOPNOTSUPP;
3684 
3685 	if (!rdev->exclusive || !ops || !ops->enable || !ops->disable)
3686 		return ret;
3687 
3688 	if (enable)
3689 		ret = ops->enable(rdev);
3690 	else
3691 		ret = ops->disable(rdev);
3692 
3693 	return ret;
3694 }
3695 EXPORT_SYMBOL_GPL(regulator_hardware_enable);
3696 
3697 /**
3698  * regulator_get_linear_step - return the voltage step size between VSEL values
3699  * @regulator: regulator source
3700  *
3701  * Return: The voltage step size between VSEL values for linear regulators,
3702  *	   or 0 if the regulator isn't a linear regulator.
3703  */
3704 unsigned int regulator_get_linear_step(struct regulator *regulator)
3705 {
3706 	struct regulator_dev *rdev = regulator->rdev;
3707 
3708 	return rdev->desc->uV_step;
3709 }
3710 EXPORT_SYMBOL_GPL(regulator_get_linear_step);
3711 
3712 /**
3713  * regulator_is_supported_voltage - check if a voltage range can be supported
3714  *
3715  * @regulator: Regulator to check.
3716  * @min_uV: Minimum required voltage in uV.
3717  * @max_uV: Maximum required voltage in uV.
3718  *
3719  * Return: 1 if the voltage range is supported, 0 if not, or a negative error
3720  *	   number if @regulator's voltage can't be changed and voltage readback
3721  *	   failed.
3722  */
3723 int regulator_is_supported_voltage(struct regulator *regulator,
3724 				   int min_uV, int max_uV)
3725 {
3726 	struct regulator_dev *rdev = regulator->rdev;
3727 	int i, voltages, ret;
3728 
3729 	/* If we can't change voltage check the current voltage */
3730 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_VOLTAGE)) {
3731 		ret = regulator_get_voltage(regulator);
3732 		if (ret >= 0)
3733 			return min_uV <= ret && ret <= max_uV;
3734 		else
3735 			return ret;
3736 	}
3737 
3738 	/* Any voltage within constrains range is fine? */
3739 	if (rdev->desc->continuous_voltage_range)
3740 		return min_uV >= rdev->constraints->min_uV &&
3741 				max_uV <= rdev->constraints->max_uV;
3742 
3743 	ret = regulator_count_voltages(regulator);
3744 	if (ret < 0)
3745 		return 0;
3746 	voltages = ret;
3747 
3748 	for (i = 0; i < voltages; i++) {
3749 		ret = regulator_list_voltage(regulator, i);
3750 
3751 		if (ret >= min_uV && ret <= max_uV)
3752 			return 1;
3753 	}
3754 
3755 	return 0;
3756 }
3757 EXPORT_SYMBOL_GPL(regulator_is_supported_voltage);
3758 
3759 static int regulator_map_voltage(struct regulator_dev *rdev, int min_uV,
3760 				 int max_uV)
3761 {
3762 	const struct regulator_desc *desc = rdev->desc;
3763 
3764 	if (desc->ops->map_voltage)
3765 		return desc->ops->map_voltage(rdev, min_uV, max_uV);
3766 
3767 	if (desc->ops->list_voltage == regulator_list_voltage_linear)
3768 		return regulator_map_voltage_linear(rdev, min_uV, max_uV);
3769 
3770 	if (desc->ops->list_voltage == regulator_list_voltage_linear_range)
3771 		return regulator_map_voltage_linear_range(rdev, min_uV, max_uV);
3772 
3773 	if (desc->ops->list_voltage ==
3774 		regulator_list_voltage_pickable_linear_range)
3775 		return regulator_map_voltage_pickable_linear_range(rdev,
3776 							min_uV, max_uV);
3777 
3778 	return regulator_map_voltage_iterate(rdev, min_uV, max_uV);
3779 }
3780 
3781 static int _regulator_call_set_voltage(struct regulator_dev *rdev,
3782 				       int min_uV, int max_uV,
3783 				       unsigned *selector)
3784 {
3785 	struct pre_voltage_change_data data;
3786 	int ret;
3787 
3788 	data.old_uV = regulator_get_voltage_rdev(rdev);
3789 	data.min_uV = min_uV;
3790 	data.max_uV = max_uV;
3791 	ret = _notifier_call_chain(rdev, REGULATOR_EVENT_PRE_VOLTAGE_CHANGE,
3792 				   &data);
3793 	if (ret & NOTIFY_STOP_MASK)
3794 		return -EINVAL;
3795 
3796 	ret = rdev->desc->ops->set_voltage(rdev, min_uV, max_uV, selector);
3797 	if (ret >= 0)
3798 		return ret;
3799 
3800 	_notifier_call_chain(rdev, REGULATOR_EVENT_ABORT_VOLTAGE_CHANGE,
3801 			     (void *)data.old_uV);
3802 
3803 	return ret;
3804 }
3805 
3806 static int _regulator_call_set_voltage_sel(struct regulator_dev *rdev,
3807 					   int uV, unsigned selector)
3808 {
3809 	struct pre_voltage_change_data data;
3810 	int ret;
3811 
3812 	data.old_uV = regulator_get_voltage_rdev(rdev);
3813 	data.min_uV = uV;
3814 	data.max_uV = uV;
3815 	ret = _notifier_call_chain(rdev, REGULATOR_EVENT_PRE_VOLTAGE_CHANGE,
3816 				   &data);
3817 	if (ret & NOTIFY_STOP_MASK)
3818 		return -EINVAL;
3819 
3820 	ret = rdev->desc->ops->set_voltage_sel(rdev, selector);
3821 	if (ret >= 0)
3822 		return ret;
3823 
3824 	_notifier_call_chain(rdev, REGULATOR_EVENT_ABORT_VOLTAGE_CHANGE,
3825 			     (void *)data.old_uV);
3826 
3827 	return ret;
3828 }
3829 
3830 static int _regulator_set_voltage_sel_step(struct regulator_dev *rdev,
3831 					   int uV, int new_selector)
3832 {
3833 	const struct regulator_ops *ops = rdev->desc->ops;
3834 	int diff, old_sel, curr_sel, ret;
3835 
3836 	/* Stepping is only needed if the regulator is enabled. */
3837 	if (!_regulator_is_enabled(rdev))
3838 		goto final_set;
3839 
3840 	if (!ops->get_voltage_sel)
3841 		return -EINVAL;
3842 
3843 	old_sel = ops->get_voltage_sel(rdev);
3844 	if (old_sel < 0)
3845 		return old_sel;
3846 
3847 	diff = new_selector - old_sel;
3848 	if (diff == 0)
3849 		return 0; /* No change needed. */
3850 
3851 	if (diff > 0) {
3852 		/* Stepping up. */
3853 		for (curr_sel = old_sel + rdev->desc->vsel_step;
3854 		     curr_sel < new_selector;
3855 		     curr_sel += rdev->desc->vsel_step) {
3856 			/*
3857 			 * Call the callback directly instead of using
3858 			 * _regulator_call_set_voltage_sel() as we don't
3859 			 * want to notify anyone yet. Same in the branch
3860 			 * below.
3861 			 */
3862 			ret = ops->set_voltage_sel(rdev, curr_sel);
3863 			if (ret)
3864 				goto try_revert;
3865 		}
3866 	} else {
3867 		/* Stepping down. */
3868 		for (curr_sel = old_sel - rdev->desc->vsel_step;
3869 		     curr_sel > new_selector;
3870 		     curr_sel -= rdev->desc->vsel_step) {
3871 			ret = ops->set_voltage_sel(rdev, curr_sel);
3872 			if (ret)
3873 				goto try_revert;
3874 		}
3875 	}
3876 
3877 final_set:
3878 	/* The final selector will trigger the notifiers. */
3879 	return _regulator_call_set_voltage_sel(rdev, uV, new_selector);
3880 
3881 try_revert:
3882 	/*
3883 	 * At least try to return to the previous voltage if setting a new
3884 	 * one failed.
3885 	 */
3886 	(void)ops->set_voltage_sel(rdev, old_sel);
3887 	return ret;
3888 }
3889 
3890 static int _regulator_set_voltage_time(struct regulator_dev *rdev,
3891 				       int old_uV, int new_uV)
3892 {
3893 	unsigned int ramp_delay = 0;
3894 
3895 	if (rdev->constraints->ramp_delay)
3896 		ramp_delay = rdev->constraints->ramp_delay;
3897 	else if (rdev->desc->ramp_delay)
3898 		ramp_delay = rdev->desc->ramp_delay;
3899 	else if (rdev->constraints->settling_time)
3900 		return rdev->constraints->settling_time;
3901 	else if (rdev->constraints->settling_time_up &&
3902 		 (new_uV > old_uV))
3903 		return rdev->constraints->settling_time_up;
3904 	else if (rdev->constraints->settling_time_down &&
3905 		 (new_uV < old_uV))
3906 		return rdev->constraints->settling_time_down;
3907 
3908 	if (ramp_delay == 0)
3909 		return 0;
3910 
3911 	return DIV_ROUND_UP(abs(new_uV - old_uV), ramp_delay);
3912 }
3913 
3914 static int _regulator_do_set_voltage(struct regulator_dev *rdev,
3915 				     int min_uV, int max_uV)
3916 {
3917 	int ret;
3918 	int delay = 0;
3919 	int best_val = 0;
3920 	unsigned int selector;
3921 	int old_selector = -1;
3922 	const struct regulator_ops *ops = rdev->desc->ops;
3923 	int old_uV = regulator_get_voltage_rdev(rdev);
3924 
3925 	trace_regulator_set_voltage(rdev_get_name(rdev), min_uV, max_uV);
3926 
3927 	min_uV += rdev->constraints->uV_offset;
3928 	max_uV += rdev->constraints->uV_offset;
3929 
3930 	/*
3931 	 * If we can't obtain the old selector there is not enough
3932 	 * info to call set_voltage_time_sel().
3933 	 */
3934 	if (_regulator_is_enabled(rdev) &&
3935 	    ops->set_voltage_time_sel && ops->get_voltage_sel) {
3936 		old_selector = ops->get_voltage_sel(rdev);
3937 		if (old_selector < 0)
3938 			return old_selector;
3939 	}
3940 
3941 	if (ops->set_voltage) {
3942 		ret = _regulator_call_set_voltage(rdev, min_uV, max_uV,
3943 						  &selector);
3944 
3945 		if (ret >= 0) {
3946 			if (ops->list_voltage)
3947 				best_val = ops->list_voltage(rdev,
3948 							     selector);
3949 			else
3950 				best_val = regulator_get_voltage_rdev(rdev);
3951 		}
3952 
3953 	} else if (ops->set_voltage_sel) {
3954 		ret = regulator_map_voltage(rdev, min_uV, max_uV);
3955 		if (ret >= 0) {
3956 			best_val = ops->list_voltage(rdev, ret);
3957 			if (min_uV <= best_val && max_uV >= best_val) {
3958 				selector = ret;
3959 				if (old_selector == selector)
3960 					ret = 0;
3961 				else if (rdev->desc->vsel_step)
3962 					ret = _regulator_set_voltage_sel_step(
3963 						rdev, best_val, selector);
3964 				else
3965 					ret = _regulator_call_set_voltage_sel(
3966 						rdev, best_val, selector);
3967 			} else {
3968 				ret = -EINVAL;
3969 			}
3970 		}
3971 	} else {
3972 		ret = -EINVAL;
3973 	}
3974 
3975 	if (ret)
3976 		goto out;
3977 
3978 	if (ops->set_voltage_time_sel) {
3979 		/*
3980 		 * Call set_voltage_time_sel if successfully obtained
3981 		 * old_selector
3982 		 */
3983 		if (old_selector >= 0 && old_selector != selector)
3984 			delay = ops->set_voltage_time_sel(rdev, old_selector,
3985 							  selector);
3986 	} else {
3987 		if (old_uV != best_val) {
3988 			if (ops->set_voltage_time)
3989 				delay = ops->set_voltage_time(rdev, old_uV,
3990 							      best_val);
3991 			else
3992 				delay = _regulator_set_voltage_time(rdev,
3993 								    old_uV,
3994 								    best_val);
3995 		}
3996 	}
3997 
3998 	if (delay < 0) {
3999 		rdev_warn(rdev, "failed to get delay: %pe\n", ERR_PTR(delay));
4000 		delay = 0;
4001 	}
4002 
4003 	/* Insert any necessary delays */
4004 	fsleep(delay);
4005 
4006 	if (best_val >= 0) {
4007 		unsigned long data = best_val;
4008 
4009 		_notifier_call_chain(rdev, REGULATOR_EVENT_VOLTAGE_CHANGE,
4010 				     (void *)data);
4011 	}
4012 
4013 out:
4014 	trace_regulator_set_voltage_complete(rdev_get_name(rdev), best_val);
4015 
4016 	return ret;
4017 }
4018 
4019 static int _regulator_do_set_suspend_voltage(struct regulator_dev *rdev,
4020 				  int min_uV, int max_uV, suspend_state_t state)
4021 {
4022 	struct regulator_state *rstate;
4023 	int uV, sel;
4024 
4025 	rstate = regulator_get_suspend_state(rdev, state);
4026 	if (rstate == NULL)
4027 		return -EINVAL;
4028 
4029 	if (min_uV < rstate->min_uV)
4030 		min_uV = rstate->min_uV;
4031 	if (max_uV > rstate->max_uV)
4032 		max_uV = rstate->max_uV;
4033 
4034 	sel = regulator_map_voltage(rdev, min_uV, max_uV);
4035 	if (sel < 0)
4036 		return sel;
4037 
4038 	uV = rdev->desc->ops->list_voltage(rdev, sel);
4039 	if (uV >= min_uV && uV <= max_uV)
4040 		rstate->uV = uV;
4041 
4042 	return 0;
4043 }
4044 
4045 static int regulator_get_voltage_delta(struct regulator_dev *rdev, int uV)
4046 {
4047 	int current_uV = regulator_get_voltage_rdev(rdev);
4048 
4049 	if (current_uV < 0)
4050 		return current_uV;
4051 
4052 	return abs(current_uV - uV);
4053 }
4054 
4055 static int regulator_set_voltage_unlocked(struct regulator *regulator,
4056 					  int min_uV, int max_uV,
4057 					  suspend_state_t state)
4058 {
4059 	struct regulator_dev *rdev = regulator->rdev;
4060 	struct regulator_voltage *voltage = &regulator->voltage[state];
4061 	int ret = 0;
4062 	int current_uV, delta, new_delta;
4063 	int old_min_uV, old_max_uV;
4064 
4065 	/* If we're setting the same range as last time the change
4066 	 * should be a noop (some cpufreq implementations use the same
4067 	 * voltage for multiple frequencies, for example).
4068 	 */
4069 	if (voltage->min_uV == min_uV && voltage->max_uV == max_uV)
4070 		goto out;
4071 
4072 	/* If we're trying to set a range that overlaps the current voltage,
4073 	 * return successfully even though the regulator does not support
4074 	 * changing the voltage.
4075 	 */
4076 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_VOLTAGE)) {
4077 		current_uV = regulator_get_voltage_rdev(rdev);
4078 		if (min_uV <= current_uV && current_uV <= max_uV) {
4079 			voltage->min_uV = min_uV;
4080 			voltage->max_uV = max_uV;
4081 			goto out;
4082 		}
4083 	}
4084 
4085 	/* sanity check */
4086 	if (!rdev->desc->ops->set_voltage &&
4087 	    !rdev->desc->ops->set_voltage_sel) {
4088 		ret = -EINVAL;
4089 		goto out;
4090 	}
4091 
4092 	/* constraints check */
4093 	ret = regulator_check_voltage(rdev, &min_uV, &max_uV);
4094 	if (ret < 0)
4095 		goto out;
4096 
4097 	/* restore original values in case of error */
4098 	old_min_uV = voltage->min_uV;
4099 	old_max_uV = voltage->max_uV;
4100 	voltage->min_uV = min_uV;
4101 	voltage->max_uV = max_uV;
4102 
4103 	/* for not coupled regulators this will just set the voltage */
4104 	ret = regulator_balance_voltage(rdev, state);
4105 	if (ret < 0) {
4106 		voltage->min_uV = old_min_uV;
4107 		voltage->max_uV = old_max_uV;
4108 	}
4109 
4110 	if (rdev->constraints->max_uV_step > 0) {
4111 		/* For regulators with a maximum voltage step, reaching the desired
4112 		 * voltage might take a few retries.
4113 		 */
4114 		ret = regulator_get_voltage_delta(rdev, min_uV);
4115 		if (ret < 0)
4116 			goto out;
4117 
4118 		delta = ret;
4119 
4120 		while (delta > 0) {
4121 			ret = regulator_balance_voltage(rdev, state);
4122 			if (ret < 0)
4123 				goto out;
4124 
4125 			ret = regulator_get_voltage_delta(rdev, min_uV);
4126 			if (ret < 0)
4127 				goto out;
4128 
4129 			new_delta = ret;
4130 
4131 			/* check that voltage is converging quickly enough */
4132 			if (delta - new_delta < rdev->constraints->max_uV_step) {
4133 				ret = -EWOULDBLOCK;
4134 				goto out;
4135 			}
4136 
4137 			delta = new_delta;
4138 		}
4139 	}
4140 
4141 out:
4142 	return ret;
4143 }
4144 
4145 int regulator_set_voltage_rdev(struct regulator_dev *rdev, int min_uV,
4146 			       int max_uV, suspend_state_t state)
4147 {
4148 	int best_supply_uV = 0;
4149 	int supply_change_uV = 0;
4150 	int ret;
4151 
4152 	if (rdev->supply &&
4153 	    regulator_ops_is_valid(rdev->supply->rdev,
4154 				   REGULATOR_CHANGE_VOLTAGE) &&
4155 	    (rdev->desc->min_dropout_uV || !(rdev->desc->ops->get_voltage ||
4156 					   rdev->desc->ops->get_voltage_sel))) {
4157 		int current_supply_uV;
4158 		int selector;
4159 
4160 		selector = regulator_map_voltage(rdev, min_uV, max_uV);
4161 		if (selector < 0) {
4162 			ret = selector;
4163 			goto out;
4164 		}
4165 
4166 		best_supply_uV = _regulator_list_voltage(rdev, selector, 0);
4167 		if (best_supply_uV < 0) {
4168 			ret = best_supply_uV;
4169 			goto out;
4170 		}
4171 
4172 		best_supply_uV += rdev->desc->min_dropout_uV;
4173 
4174 		current_supply_uV = regulator_get_voltage_rdev(rdev->supply->rdev);
4175 		if (current_supply_uV < 0) {
4176 			ret = current_supply_uV;
4177 			goto out;
4178 		}
4179 
4180 		supply_change_uV = best_supply_uV - current_supply_uV;
4181 	}
4182 
4183 	if (supply_change_uV > 0) {
4184 		ret = regulator_set_voltage_unlocked(rdev->supply,
4185 				best_supply_uV, INT_MAX, state);
4186 		if (ret) {
4187 			dev_err(&rdev->dev, "Failed to increase supply voltage: %pe\n",
4188 				ERR_PTR(ret));
4189 			goto out;
4190 		}
4191 	}
4192 
4193 	if (state == PM_SUSPEND_ON)
4194 		ret = _regulator_do_set_voltage(rdev, min_uV, max_uV);
4195 	else
4196 		ret = _regulator_do_set_suspend_voltage(rdev, min_uV,
4197 							max_uV, state);
4198 	if (ret < 0)
4199 		goto out;
4200 
4201 	if (supply_change_uV < 0) {
4202 		ret = regulator_set_voltage_unlocked(rdev->supply,
4203 				best_supply_uV, INT_MAX, state);
4204 		if (ret)
4205 			dev_warn(&rdev->dev, "Failed to decrease supply voltage: %pe\n",
4206 				 ERR_PTR(ret));
4207 		/* No need to fail here */
4208 		ret = 0;
4209 	}
4210 
4211 out:
4212 	return ret;
4213 }
4214 EXPORT_SYMBOL_GPL(regulator_set_voltage_rdev);
4215 
4216 static int regulator_limit_voltage_step(struct regulator_dev *rdev,
4217 					int *current_uV, int *min_uV)
4218 {
4219 	struct regulation_constraints *constraints = rdev->constraints;
4220 
4221 	/* Limit voltage change only if necessary */
4222 	if (!constraints->max_uV_step || !_regulator_is_enabled(rdev))
4223 		return 1;
4224 
4225 	if (*current_uV < 0) {
4226 		*current_uV = regulator_get_voltage_rdev(rdev);
4227 
4228 		if (*current_uV < 0)
4229 			return *current_uV;
4230 	}
4231 
4232 	if (abs(*current_uV - *min_uV) <= constraints->max_uV_step)
4233 		return 1;
4234 
4235 	/* Clamp target voltage within the given step */
4236 	if (*current_uV < *min_uV)
4237 		*min_uV = min(*current_uV + constraints->max_uV_step,
4238 			      *min_uV);
4239 	else
4240 		*min_uV = max(*current_uV - constraints->max_uV_step,
4241 			      *min_uV);
4242 
4243 	return 0;
4244 }
4245 
4246 static int regulator_get_optimal_voltage(struct regulator_dev *rdev,
4247 					 int *current_uV,
4248 					 int *min_uV, int *max_uV,
4249 					 suspend_state_t state,
4250 					 int n_coupled)
4251 {
4252 	struct coupling_desc *c_desc = &rdev->coupling_desc;
4253 	struct regulator_dev **c_rdevs = c_desc->coupled_rdevs;
4254 	struct regulation_constraints *constraints = rdev->constraints;
4255 	int desired_min_uV = 0, desired_max_uV = INT_MAX;
4256 	int max_current_uV = 0, min_current_uV = INT_MAX;
4257 	int highest_min_uV = 0, target_uV, possible_uV;
4258 	int i, ret, max_spread;
4259 	bool done;
4260 
4261 	*current_uV = -1;
4262 
4263 	/*
4264 	 * If there are no coupled regulators, simply set the voltage
4265 	 * demanded by consumers.
4266 	 */
4267 	if (n_coupled == 1) {
4268 		/*
4269 		 * If consumers don't provide any demands, set voltage
4270 		 * to min_uV
4271 		 */
4272 		desired_min_uV = constraints->min_uV;
4273 		desired_max_uV = constraints->max_uV;
4274 
4275 		ret = regulator_check_consumers(rdev,
4276 						&desired_min_uV,
4277 						&desired_max_uV, state);
4278 		if (ret < 0)
4279 			return ret;
4280 
4281 		done = true;
4282 
4283 		goto finish;
4284 	}
4285 
4286 	/* Find highest min desired voltage */
4287 	for (i = 0; i < n_coupled; i++) {
4288 		int tmp_min = 0;
4289 		int tmp_max = INT_MAX;
4290 
4291 		lockdep_assert_held_once(&c_rdevs[i]->mutex.base);
4292 
4293 		ret = regulator_check_consumers(c_rdevs[i],
4294 						&tmp_min,
4295 						&tmp_max, state);
4296 		if (ret < 0)
4297 			return ret;
4298 
4299 		ret = regulator_check_voltage(c_rdevs[i], &tmp_min, &tmp_max);
4300 		if (ret < 0)
4301 			return ret;
4302 
4303 		highest_min_uV = max(highest_min_uV, tmp_min);
4304 
4305 		if (i == 0) {
4306 			desired_min_uV = tmp_min;
4307 			desired_max_uV = tmp_max;
4308 		}
4309 	}
4310 
4311 	max_spread = constraints->max_spread[0];
4312 
4313 	/*
4314 	 * Let target_uV be equal to the desired one if possible.
4315 	 * If not, set it to minimum voltage, allowed by other coupled
4316 	 * regulators.
4317 	 */
4318 	target_uV = max(desired_min_uV, highest_min_uV - max_spread);
4319 
4320 	/*
4321 	 * Find min and max voltages, which currently aren't violating
4322 	 * max_spread.
4323 	 */
4324 	for (i = 1; i < n_coupled; i++) {
4325 		int tmp_act;
4326 
4327 		if (!_regulator_is_enabled(c_rdevs[i]))
4328 			continue;
4329 
4330 		tmp_act = regulator_get_voltage_rdev(c_rdevs[i]);
4331 		if (tmp_act < 0)
4332 			return tmp_act;
4333 
4334 		min_current_uV = min(tmp_act, min_current_uV);
4335 		max_current_uV = max(tmp_act, max_current_uV);
4336 	}
4337 
4338 	/* There aren't any other regulators enabled */
4339 	if (max_current_uV == 0) {
4340 		possible_uV = target_uV;
4341 	} else {
4342 		/*
4343 		 * Correct target voltage, so as it currently isn't
4344 		 * violating max_spread
4345 		 */
4346 		possible_uV = max(target_uV, max_current_uV - max_spread);
4347 		possible_uV = min(possible_uV, min_current_uV + max_spread);
4348 	}
4349 
4350 	if (possible_uV > desired_max_uV)
4351 		return -EINVAL;
4352 
4353 	done = (possible_uV == target_uV);
4354 	desired_min_uV = possible_uV;
4355 
4356 finish:
4357 	/* Apply max_uV_step constraint if necessary */
4358 	if (state == PM_SUSPEND_ON) {
4359 		ret = regulator_limit_voltage_step(rdev, current_uV,
4360 						   &desired_min_uV);
4361 		if (ret < 0)
4362 			return ret;
4363 
4364 		if (ret == 0)
4365 			done = false;
4366 	}
4367 
4368 	/* Set current_uV if wasn't done earlier in the code and if necessary */
4369 	if (n_coupled > 1 && *current_uV == -1) {
4370 
4371 		if (_regulator_is_enabled(rdev)) {
4372 			ret = regulator_get_voltage_rdev(rdev);
4373 			if (ret < 0)
4374 				return ret;
4375 
4376 			*current_uV = ret;
4377 		} else {
4378 			*current_uV = desired_min_uV;
4379 		}
4380 	}
4381 
4382 	*min_uV = desired_min_uV;
4383 	*max_uV = desired_max_uV;
4384 
4385 	return done;
4386 }
4387 
4388 int regulator_do_balance_voltage(struct regulator_dev *rdev,
4389 				 suspend_state_t state, bool skip_coupled)
4390 {
4391 	struct regulator_dev **c_rdevs;
4392 	struct regulator_dev *best_rdev;
4393 	struct coupling_desc *c_desc = &rdev->coupling_desc;
4394 	int i, ret, n_coupled, best_min_uV, best_max_uV, best_c_rdev;
4395 	unsigned int delta, best_delta;
4396 	unsigned long c_rdev_done = 0;
4397 	bool best_c_rdev_done;
4398 
4399 	c_rdevs = c_desc->coupled_rdevs;
4400 	n_coupled = skip_coupled ? 1 : c_desc->n_coupled;
4401 
4402 	/*
4403 	 * Find the best possible voltage change on each loop. Leave the loop
4404 	 * if there isn't any possible change.
4405 	 */
4406 	do {
4407 		best_c_rdev_done = false;
4408 		best_delta = 0;
4409 		best_min_uV = 0;
4410 		best_max_uV = 0;
4411 		best_c_rdev = 0;
4412 		best_rdev = NULL;
4413 
4414 		/*
4415 		 * Find highest difference between optimal voltage
4416 		 * and current voltage.
4417 		 */
4418 		for (i = 0; i < n_coupled; i++) {
4419 			/*
4420 			 * optimal_uV is the best voltage that can be set for
4421 			 * i-th regulator at the moment without violating
4422 			 * max_spread constraint in order to balance
4423 			 * the coupled voltages.
4424 			 */
4425 			int optimal_uV = 0, optimal_max_uV = 0, current_uV = 0;
4426 
4427 			if (test_bit(i, &c_rdev_done))
4428 				continue;
4429 
4430 			ret = regulator_get_optimal_voltage(c_rdevs[i],
4431 							    &current_uV,
4432 							    &optimal_uV,
4433 							    &optimal_max_uV,
4434 							    state, n_coupled);
4435 			if (ret < 0)
4436 				goto out;
4437 
4438 			delta = abs(optimal_uV - current_uV);
4439 
4440 			if (delta && best_delta <= delta) {
4441 				best_c_rdev_done = ret;
4442 				best_delta = delta;
4443 				best_rdev = c_rdevs[i];
4444 				best_min_uV = optimal_uV;
4445 				best_max_uV = optimal_max_uV;
4446 				best_c_rdev = i;
4447 			}
4448 		}
4449 
4450 		/* Nothing to change, return successfully */
4451 		if (!best_rdev) {
4452 			ret = 0;
4453 			goto out;
4454 		}
4455 
4456 		ret = regulator_set_voltage_rdev(best_rdev, best_min_uV,
4457 						 best_max_uV, state);
4458 
4459 		if (ret < 0)
4460 			goto out;
4461 
4462 		if (best_c_rdev_done)
4463 			set_bit(best_c_rdev, &c_rdev_done);
4464 
4465 	} while (n_coupled > 1);
4466 
4467 out:
4468 	return ret;
4469 }
4470 
4471 static int regulator_balance_voltage(struct regulator_dev *rdev,
4472 				     suspend_state_t state)
4473 {
4474 	struct coupling_desc *c_desc = &rdev->coupling_desc;
4475 	struct regulator_coupler *coupler = c_desc->coupler;
4476 	bool skip_coupled = false;
4477 
4478 	/*
4479 	 * If system is in a state other than PM_SUSPEND_ON, don't check
4480 	 * other coupled regulators.
4481 	 */
4482 	if (state != PM_SUSPEND_ON)
4483 		skip_coupled = true;
4484 
4485 	if (c_desc->n_resolved < c_desc->n_coupled) {
4486 		rdev_err(rdev, "Not all coupled regulators registered\n");
4487 		return -EPERM;
4488 	}
4489 
4490 	/* Invoke custom balancer for customized couplers */
4491 	if (coupler && coupler->balance_voltage)
4492 		return coupler->balance_voltage(coupler, rdev, state);
4493 
4494 	return regulator_do_balance_voltage(rdev, state, skip_coupled);
4495 }
4496 
4497 /**
4498  * regulator_set_voltage - set regulator output voltage
4499  * @regulator: regulator source
4500  * @min_uV: Minimum required voltage in uV
4501  * @max_uV: Maximum acceptable voltage in uV
4502  *
4503  * Sets a voltage regulator to the desired output voltage. This can be set
4504  * during any regulator state. IOW, regulator can be disabled or enabled.
4505  *
4506  * If the regulator is enabled then the voltage will change to the new value
4507  * immediately otherwise if the regulator is disabled the regulator will
4508  * output at the new voltage when enabled.
4509  *
4510  * NOTE: If the regulator is shared between several devices then the lowest
4511  * request voltage that meets the system constraints will be used.
4512  * Regulator system constraints must be set for this regulator before
4513  * calling this function otherwise this call will fail.
4514  *
4515  * Return: 0 on success or a negative error number on failure.
4516  */
4517 int regulator_set_voltage(struct regulator *regulator, int min_uV, int max_uV)
4518 {
4519 	struct ww_acquire_ctx ww_ctx;
4520 	int ret;
4521 
4522 	regulator_lock_dependent(regulator->rdev, &ww_ctx);
4523 
4524 	ret = regulator_set_voltage_unlocked(regulator, min_uV, max_uV,
4525 					     PM_SUSPEND_ON);
4526 
4527 	regulator_unlock_dependent(regulator->rdev, &ww_ctx);
4528 
4529 	return ret;
4530 }
4531 EXPORT_SYMBOL_GPL(regulator_set_voltage);
4532 
4533 static inline int regulator_suspend_toggle(struct regulator_dev *rdev,
4534 					   suspend_state_t state, bool en)
4535 {
4536 	struct regulator_state *rstate;
4537 
4538 	rstate = regulator_get_suspend_state(rdev, state);
4539 	if (rstate == NULL)
4540 		return -EINVAL;
4541 
4542 	if (!rstate->changeable)
4543 		return -EPERM;
4544 
4545 	rstate->enabled = (en) ? ENABLE_IN_SUSPEND : DISABLE_IN_SUSPEND;
4546 
4547 	return 0;
4548 }
4549 
4550 int regulator_suspend_enable(struct regulator_dev *rdev,
4551 				    suspend_state_t state)
4552 {
4553 	return regulator_suspend_toggle(rdev, state, true);
4554 }
4555 EXPORT_SYMBOL_GPL(regulator_suspend_enable);
4556 
4557 int regulator_suspend_disable(struct regulator_dev *rdev,
4558 				     suspend_state_t state)
4559 {
4560 	struct regulator *regulator;
4561 	struct regulator_voltage *voltage;
4562 
4563 	/*
4564 	 * if any consumer wants this regulator device keeping on in
4565 	 * suspend states, don't set it as disabled.
4566 	 */
4567 	list_for_each_entry(regulator, &rdev->consumer_list, list) {
4568 		voltage = &regulator->voltage[state];
4569 		if (voltage->min_uV || voltage->max_uV)
4570 			return 0;
4571 	}
4572 
4573 	return regulator_suspend_toggle(rdev, state, false);
4574 }
4575 EXPORT_SYMBOL_GPL(regulator_suspend_disable);
4576 
4577 static int _regulator_set_suspend_voltage(struct regulator *regulator,
4578 					  int min_uV, int max_uV,
4579 					  suspend_state_t state)
4580 {
4581 	struct regulator_dev *rdev = regulator->rdev;
4582 	struct regulator_state *rstate;
4583 
4584 	rstate = regulator_get_suspend_state(rdev, state);
4585 	if (rstate == NULL)
4586 		return -EINVAL;
4587 
4588 	if (rstate->min_uV == rstate->max_uV) {
4589 		rdev_err(rdev, "The suspend voltage can't be changed!\n");
4590 		return -EPERM;
4591 	}
4592 
4593 	return regulator_set_voltage_unlocked(regulator, min_uV, max_uV, state);
4594 }
4595 
4596 int regulator_set_suspend_voltage(struct regulator *regulator, int min_uV,
4597 				  int max_uV, suspend_state_t state)
4598 {
4599 	struct ww_acquire_ctx ww_ctx;
4600 	int ret;
4601 
4602 	/* PM_SUSPEND_ON is handled by regulator_set_voltage() */
4603 	if (regulator_check_states(state) || state == PM_SUSPEND_ON)
4604 		return -EINVAL;
4605 
4606 	regulator_lock_dependent(regulator->rdev, &ww_ctx);
4607 
4608 	ret = _regulator_set_suspend_voltage(regulator, min_uV,
4609 					     max_uV, state);
4610 
4611 	regulator_unlock_dependent(regulator->rdev, &ww_ctx);
4612 
4613 	return ret;
4614 }
4615 EXPORT_SYMBOL_GPL(regulator_set_suspend_voltage);
4616 
4617 /**
4618  * regulator_set_voltage_time - get raise/fall time
4619  * @regulator: regulator source
4620  * @old_uV: starting voltage in microvolts
4621  * @new_uV: target voltage in microvolts
4622  *
4623  * Provided with the starting and ending voltage, this function attempts to
4624  * calculate the time in microseconds required to rise or fall to this new
4625  * voltage.
4626  *
4627  * Return: ramp time in microseconds, or a negative error number if calculation failed.
4628  */
4629 int regulator_set_voltage_time(struct regulator *regulator,
4630 			       int old_uV, int new_uV)
4631 {
4632 	struct regulator_dev *rdev = regulator->rdev;
4633 	const struct regulator_ops *ops = rdev->desc->ops;
4634 	int old_sel = -1;
4635 	int new_sel = -1;
4636 	int voltage;
4637 	int i;
4638 
4639 	if (ops->set_voltage_time)
4640 		return ops->set_voltage_time(rdev, old_uV, new_uV);
4641 	else if (!ops->set_voltage_time_sel)
4642 		return _regulator_set_voltage_time(rdev, old_uV, new_uV);
4643 
4644 	/* Currently requires operations to do this */
4645 	if (!ops->list_voltage || !rdev->desc->n_voltages)
4646 		return -EINVAL;
4647 
4648 	for (i = 0; i < rdev->desc->n_voltages; i++) {
4649 		/* We only look for exact voltage matches here */
4650 		if (i < rdev->desc->linear_min_sel)
4651 			continue;
4652 
4653 		if (old_sel >= 0 && new_sel >= 0)
4654 			break;
4655 
4656 		voltage = regulator_list_voltage(regulator, i);
4657 		if (voltage < 0)
4658 			return -EINVAL;
4659 		if (voltage == 0)
4660 			continue;
4661 		if (voltage == old_uV)
4662 			old_sel = i;
4663 		if (voltage == new_uV)
4664 			new_sel = i;
4665 	}
4666 
4667 	if (old_sel < 0 || new_sel < 0)
4668 		return -EINVAL;
4669 
4670 	return ops->set_voltage_time_sel(rdev, old_sel, new_sel);
4671 }
4672 EXPORT_SYMBOL_GPL(regulator_set_voltage_time);
4673 
4674 /**
4675  * regulator_set_voltage_time_sel - get raise/fall time
4676  * @rdev: regulator source device
4677  * @old_selector: selector for starting voltage
4678  * @new_selector: selector for target voltage
4679  *
4680  * Provided with the starting and target voltage selectors, this function
4681  * returns time in microseconds required to rise or fall to this new voltage
4682  *
4683  * Drivers providing ramp_delay in regulation_constraints can use this as their
4684  * set_voltage_time_sel() operation.
4685  *
4686  * Return: ramp time in microseconds, or a negative error number if calculation failed.
4687  */
4688 int regulator_set_voltage_time_sel(struct regulator_dev *rdev,
4689 				   unsigned int old_selector,
4690 				   unsigned int new_selector)
4691 {
4692 	int old_volt, new_volt;
4693 
4694 	/* sanity check */
4695 	if (!rdev->desc->ops->list_voltage)
4696 		return -EINVAL;
4697 
4698 	old_volt = rdev->desc->ops->list_voltage(rdev, old_selector);
4699 	new_volt = rdev->desc->ops->list_voltage(rdev, new_selector);
4700 
4701 	if (rdev->desc->ops->set_voltage_time)
4702 		return rdev->desc->ops->set_voltage_time(rdev, old_volt,
4703 							 new_volt);
4704 	else
4705 		return _regulator_set_voltage_time(rdev, old_volt, new_volt);
4706 }
4707 EXPORT_SYMBOL_GPL(regulator_set_voltage_time_sel);
4708 
4709 int regulator_sync_voltage_rdev(struct regulator_dev *rdev)
4710 {
4711 	int ret;
4712 
4713 	regulator_lock(rdev);
4714 
4715 	if (!rdev->desc->ops->set_voltage &&
4716 	    !rdev->desc->ops->set_voltage_sel) {
4717 		ret = -EINVAL;
4718 		goto out;
4719 	}
4720 
4721 	/* balance only, if regulator is coupled */
4722 	if (rdev->coupling_desc.n_coupled > 1)
4723 		ret = regulator_balance_voltage(rdev, PM_SUSPEND_ON);
4724 	else
4725 		ret = -EOPNOTSUPP;
4726 
4727 out:
4728 	regulator_unlock(rdev);
4729 	return ret;
4730 }
4731 
4732 /**
4733  * regulator_sync_voltage - re-apply last regulator output voltage
4734  * @regulator: regulator source
4735  *
4736  * Re-apply the last configured voltage.  This is intended to be used
4737  * where some external control source the consumer is cooperating with
4738  * has caused the configured voltage to change.
4739  *
4740  * Return: 0 on success or a negative error number on failure.
4741  */
4742 int regulator_sync_voltage(struct regulator *regulator)
4743 {
4744 	struct regulator_dev *rdev = regulator->rdev;
4745 	struct regulator_voltage *voltage = &regulator->voltage[PM_SUSPEND_ON];
4746 	int ret, min_uV, max_uV;
4747 
4748 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_VOLTAGE))
4749 		return 0;
4750 
4751 	regulator_lock(rdev);
4752 
4753 	if (!rdev->desc->ops->set_voltage &&
4754 	    !rdev->desc->ops->set_voltage_sel) {
4755 		ret = -EINVAL;
4756 		goto out;
4757 	}
4758 
4759 	/* This is only going to work if we've had a voltage configured. */
4760 	if (!voltage->min_uV && !voltage->max_uV) {
4761 		ret = -EINVAL;
4762 		goto out;
4763 	}
4764 
4765 	min_uV = voltage->min_uV;
4766 	max_uV = voltage->max_uV;
4767 
4768 	/* This should be a paranoia check... */
4769 	ret = regulator_check_voltage(rdev, &min_uV, &max_uV);
4770 	if (ret < 0)
4771 		goto out;
4772 
4773 	ret = regulator_check_consumers(rdev, &min_uV, &max_uV, 0);
4774 	if (ret < 0)
4775 		goto out;
4776 
4777 	/* balance only, if regulator is coupled */
4778 	if (rdev->coupling_desc.n_coupled > 1)
4779 		ret = regulator_balance_voltage(rdev, PM_SUSPEND_ON);
4780 	else
4781 		ret = _regulator_do_set_voltage(rdev, min_uV, max_uV);
4782 
4783 out:
4784 	regulator_unlock(rdev);
4785 	return ret;
4786 }
4787 EXPORT_SYMBOL_GPL(regulator_sync_voltage);
4788 
4789 int regulator_get_voltage_rdev(struct regulator_dev *rdev)
4790 {
4791 	int sel, ret;
4792 	bool bypassed;
4793 
4794 	if (rdev->desc->ops->get_bypass) {
4795 		ret = rdev->desc->ops->get_bypass(rdev, &bypassed);
4796 		if (ret < 0)
4797 			return ret;
4798 		if (bypassed) {
4799 			/* if bypassed the regulator must have a supply */
4800 			if (!rdev->supply) {
4801 				rdev_err(rdev,
4802 					 "bypassed regulator has no supply!\n");
4803 				return -EPROBE_DEFER;
4804 			}
4805 
4806 			return regulator_get_voltage_rdev(rdev->supply->rdev);
4807 		}
4808 	}
4809 
4810 	if (rdev->desc->ops->get_voltage_sel) {
4811 		sel = rdev->desc->ops->get_voltage_sel(rdev);
4812 		if (sel < 0)
4813 			return sel;
4814 		ret = rdev->desc->ops->list_voltage(rdev, sel);
4815 	} else if (rdev->desc->ops->get_voltage) {
4816 		ret = rdev->desc->ops->get_voltage(rdev);
4817 	} else if (rdev->desc->ops->list_voltage) {
4818 		ret = rdev->desc->ops->list_voltage(rdev, 0);
4819 	} else if (rdev->desc->fixed_uV && (rdev->desc->n_voltages == 1)) {
4820 		ret = rdev->desc->fixed_uV;
4821 	} else if (rdev->supply) {
4822 		ret = regulator_get_voltage_rdev(rdev->supply->rdev);
4823 	} else if (rdev->supply_name) {
4824 		return -EPROBE_DEFER;
4825 	} else {
4826 		return -EINVAL;
4827 	}
4828 
4829 	if (ret < 0)
4830 		return ret;
4831 	return ret - rdev->constraints->uV_offset;
4832 }
4833 EXPORT_SYMBOL_GPL(regulator_get_voltage_rdev);
4834 
4835 /**
4836  * regulator_get_voltage - get regulator output voltage
4837  * @regulator: regulator source
4838  *
4839  * Return: Current regulator voltage in uV, or a negative error number on failure.
4840  *
4841  * NOTE: If the regulator is disabled it will return the voltage value. This
4842  * function should not be used to determine regulator state.
4843  */
4844 int regulator_get_voltage(struct regulator *regulator)
4845 {
4846 	struct ww_acquire_ctx ww_ctx;
4847 	int ret;
4848 
4849 	regulator_lock_dependent(regulator->rdev, &ww_ctx);
4850 	ret = regulator_get_voltage_rdev(regulator->rdev);
4851 	regulator_unlock_dependent(regulator->rdev, &ww_ctx);
4852 
4853 	return ret;
4854 }
4855 EXPORT_SYMBOL_GPL(regulator_get_voltage);
4856 
4857 /**
4858  * regulator_set_current_limit - set regulator output current limit
4859  * @regulator: regulator source
4860  * @min_uA: Minimum supported current in uA
4861  * @max_uA: Maximum supported current in uA
4862  *
4863  * Sets current sink to the desired output current. This can be set during
4864  * any regulator state. IOW, regulator can be disabled or enabled.
4865  *
4866  * If the regulator is enabled then the current will change to the new value
4867  * immediately otherwise if the regulator is disabled the regulator will
4868  * output at the new current when enabled.
4869  *
4870  * NOTE: Regulator system constraints must be set for this regulator before
4871  * calling this function otherwise this call will fail.
4872  *
4873  * Return: 0 on success or a negative error number on failure.
4874  */
4875 int regulator_set_current_limit(struct regulator *regulator,
4876 			       int min_uA, int max_uA)
4877 {
4878 	struct regulator_dev *rdev = regulator->rdev;
4879 	int ret;
4880 
4881 	regulator_lock(rdev);
4882 
4883 	/* sanity check */
4884 	if (!rdev->desc->ops->set_current_limit) {
4885 		ret = -EINVAL;
4886 		goto out;
4887 	}
4888 
4889 	/* constraints check */
4890 	ret = regulator_check_current_limit(rdev, &min_uA, &max_uA);
4891 	if (ret < 0)
4892 		goto out;
4893 
4894 	ret = rdev->desc->ops->set_current_limit(rdev, min_uA, max_uA);
4895 out:
4896 	regulator_unlock(rdev);
4897 	return ret;
4898 }
4899 EXPORT_SYMBOL_GPL(regulator_set_current_limit);
4900 
4901 static int _regulator_get_current_limit_unlocked(struct regulator_dev *rdev)
4902 {
4903 	/* sanity check */
4904 	if (!rdev->desc->ops->get_current_limit)
4905 		return -EINVAL;
4906 
4907 	return rdev->desc->ops->get_current_limit(rdev);
4908 }
4909 
4910 static int _regulator_get_current_limit(struct regulator_dev *rdev)
4911 {
4912 	int ret;
4913 
4914 	regulator_lock(rdev);
4915 	ret = _regulator_get_current_limit_unlocked(rdev);
4916 	regulator_unlock(rdev);
4917 
4918 	return ret;
4919 }
4920 
4921 /**
4922  * regulator_get_current_limit - get regulator output current
4923  * @regulator: regulator source
4924  *
4925  * Return: Current supplied by the specified current sink in uA,
4926  *	   or a negative error number on failure.
4927  *
4928  * NOTE: If the regulator is disabled it will return the current value. This
4929  * function should not be used to determine regulator state.
4930  */
4931 int regulator_get_current_limit(struct regulator *regulator)
4932 {
4933 	return _regulator_get_current_limit(regulator->rdev);
4934 }
4935 EXPORT_SYMBOL_GPL(regulator_get_current_limit);
4936 
4937 /**
4938  * regulator_get_unclaimed_power_budget - get regulator unclaimed power budget
4939  * @regulator: regulator source
4940  *
4941  * Return: Unclaimed power budget of the regulator in mW.
4942  */
4943 int regulator_get_unclaimed_power_budget(struct regulator *regulator)
4944 {
4945 	return regulator->rdev->constraints->pw_budget_mW -
4946 	       regulator->rdev->pw_requested_mW;
4947 }
4948 EXPORT_SYMBOL_GPL(regulator_get_unclaimed_power_budget);
4949 
4950 /**
4951  * regulator_request_power_budget - request power budget on a regulator
4952  * @regulator: regulator source
4953  * @pw_req: Power requested
4954  *
4955  * Return: 0 on success or a negative error number on failure.
4956  */
4957 int regulator_request_power_budget(struct regulator *regulator,
4958 				   unsigned int pw_req)
4959 {
4960 	struct regulator_dev *rdev = regulator->rdev;
4961 	int ret = 0, pw_tot_req;
4962 
4963 	regulator_lock(rdev);
4964 	if (rdev->supply) {
4965 		ret = regulator_request_power_budget(rdev->supply, pw_req);
4966 		if (ret < 0)
4967 			goto out;
4968 	}
4969 
4970 	pw_tot_req = rdev->pw_requested_mW + pw_req;
4971 	if (pw_tot_req > rdev->constraints->pw_budget_mW) {
4972 		rdev_warn(rdev, "power requested %d mW out of budget %d mW",
4973 			  pw_req,
4974 			  rdev->constraints->pw_budget_mW - rdev->pw_requested_mW);
4975 		regulator_notifier_call_chain(rdev,
4976 					      REGULATOR_EVENT_OVER_CURRENT_WARN,
4977 					      NULL);
4978 		ret = -ERANGE;
4979 		goto out;
4980 	}
4981 
4982 	rdev->pw_requested_mW = pw_tot_req;
4983 out:
4984 	regulator_unlock(rdev);
4985 	return ret;
4986 }
4987 EXPORT_SYMBOL_GPL(regulator_request_power_budget);
4988 
4989 /**
4990  * regulator_free_power_budget - free power budget on a regulator
4991  * @regulator: regulator source
4992  * @pw: Power to be released.
4993  *
4994  * Return: Power budget of the regulator in mW.
4995  */
4996 void regulator_free_power_budget(struct regulator *regulator,
4997 				 unsigned int pw)
4998 {
4999 	struct regulator_dev *rdev = regulator->rdev;
5000 	int pw_tot_req;
5001 
5002 	regulator_lock(rdev);
5003 	if (rdev->supply)
5004 		regulator_free_power_budget(rdev->supply, pw);
5005 
5006 	pw_tot_req = rdev->pw_requested_mW - pw;
5007 	if (pw_tot_req >= 0)
5008 		rdev->pw_requested_mW = pw_tot_req;
5009 	else
5010 		rdev_warn(rdev,
5011 			  "too much power freed %d mW (already requested %d mW)",
5012 			  pw, rdev->pw_requested_mW);
5013 
5014 	regulator_unlock(rdev);
5015 }
5016 EXPORT_SYMBOL_GPL(regulator_free_power_budget);
5017 
5018 /**
5019  * regulator_set_mode - set regulator operating mode
5020  * @regulator: regulator source
5021  * @mode: operating mode - one of the REGULATOR_MODE constants
5022  *
5023  * Set regulator operating mode to increase regulator efficiency or improve
5024  * regulation performance.
5025  *
5026  * NOTE: Regulator system constraints must be set for this regulator before
5027  * calling this function otherwise this call will fail.
5028  *
5029  * Return: 0 on success or a negative error number on failure.
5030  */
5031 int regulator_set_mode(struct regulator *regulator, unsigned int mode)
5032 {
5033 	struct regulator_dev *rdev = regulator->rdev;
5034 	int ret;
5035 	int regulator_curr_mode;
5036 
5037 	regulator_lock(rdev);
5038 
5039 	/* sanity check */
5040 	if (!rdev->desc->ops->set_mode) {
5041 		ret = -EINVAL;
5042 		goto out;
5043 	}
5044 
5045 	/* return if the same mode is requested */
5046 	if (rdev->desc->ops->get_mode) {
5047 		regulator_curr_mode = rdev->desc->ops->get_mode(rdev);
5048 		if (regulator_curr_mode == mode) {
5049 			ret = 0;
5050 			goto out;
5051 		}
5052 	}
5053 
5054 	/* constraints check */
5055 	ret = regulator_mode_constrain(rdev, &mode);
5056 	if (ret < 0)
5057 		goto out;
5058 
5059 	ret = rdev->desc->ops->set_mode(rdev, mode);
5060 out:
5061 	regulator_unlock(rdev);
5062 	return ret;
5063 }
5064 EXPORT_SYMBOL_GPL(regulator_set_mode);
5065 
5066 static unsigned int _regulator_get_mode_unlocked(struct regulator_dev *rdev)
5067 {
5068 	/* sanity check */
5069 	if (!rdev->desc->ops->get_mode)
5070 		return -EINVAL;
5071 
5072 	return rdev->desc->ops->get_mode(rdev);
5073 }
5074 
5075 static unsigned int _regulator_get_mode(struct regulator_dev *rdev)
5076 {
5077 	int ret;
5078 
5079 	regulator_lock(rdev);
5080 	ret = _regulator_get_mode_unlocked(rdev);
5081 	regulator_unlock(rdev);
5082 
5083 	return ret;
5084 }
5085 
5086 /**
5087  * regulator_get_mode - get regulator operating mode
5088  * @regulator: regulator source
5089  *
5090  * Get the current regulator operating mode.
5091  *
5092  * Return: Current operating mode as %REGULATOR_MODE_* values,
5093  *	   or a negative error number on failure.
5094  */
5095 unsigned int regulator_get_mode(struct regulator *regulator)
5096 {
5097 	return _regulator_get_mode(regulator->rdev);
5098 }
5099 EXPORT_SYMBOL_GPL(regulator_get_mode);
5100 
5101 static int rdev_get_cached_err_flags(struct regulator_dev *rdev)
5102 {
5103 	int ret = 0;
5104 
5105 	if (rdev->use_cached_err) {
5106 		spin_lock(&rdev->err_lock);
5107 		ret = rdev->cached_err;
5108 		spin_unlock(&rdev->err_lock);
5109 	}
5110 	return ret;
5111 }
5112 
5113 static int _regulator_get_error_flags(struct regulator_dev *rdev,
5114 					unsigned int *flags)
5115 {
5116 	int cached_flags, ret = 0;
5117 
5118 	regulator_lock(rdev);
5119 
5120 	cached_flags = rdev_get_cached_err_flags(rdev);
5121 
5122 	if (rdev->desc->ops->get_error_flags)
5123 		ret = rdev->desc->ops->get_error_flags(rdev, flags);
5124 	else if (!rdev->use_cached_err)
5125 		ret = -EINVAL;
5126 
5127 	*flags |= cached_flags;
5128 
5129 	regulator_unlock(rdev);
5130 
5131 	return ret;
5132 }
5133 
5134 /**
5135  * regulator_get_error_flags - get regulator error information
5136  * @regulator: regulator source
5137  * @flags: pointer to store error flags
5138  *
5139  * Get the current regulator error information.
5140  *
5141  * Return: 0 on success or a negative error number on failure.
5142  */
5143 int regulator_get_error_flags(struct regulator *regulator,
5144 				unsigned int *flags)
5145 {
5146 	return _regulator_get_error_flags(regulator->rdev, flags);
5147 }
5148 EXPORT_SYMBOL_GPL(regulator_get_error_flags);
5149 
5150 /**
5151  * regulator_set_load - set regulator load
5152  * @regulator: regulator source
5153  * @uA_load: load current
5154  *
5155  * Notifies the regulator core of a new device load. This is then used by
5156  * DRMS (if enabled by constraints) to set the most efficient regulator
5157  * operating mode for the new regulator loading.
5158  *
5159  * Consumer devices notify their supply regulator of the maximum power
5160  * they will require (can be taken from device datasheet in the power
5161  * consumption tables) when they change operational status and hence power
5162  * state. Examples of operational state changes that can affect power
5163  * consumption are :-
5164  *
5165  *    o Device is opened / closed.
5166  *    o Device I/O is about to begin or has just finished.
5167  *    o Device is idling in between work.
5168  *
5169  * This information is also exported via sysfs to userspace.
5170  *
5171  * DRMS will sum the total requested load on the regulator and change
5172  * to the most efficient operating mode if platform constraints allow.
5173  *
5174  * NOTE: when a regulator consumer requests to have a regulator
5175  * disabled then any load that consumer requested no longer counts
5176  * toward the total requested load.  If the regulator is re-enabled
5177  * then the previously requested load will start counting again.
5178  *
5179  * If a regulator is an always-on regulator then an individual consumer's
5180  * load will still be removed if that consumer is fully disabled.
5181  *
5182  * Return: 0 on success or a negative error number on failure.
5183  */
5184 int regulator_set_load(struct regulator *regulator, int uA_load)
5185 {
5186 	struct regulator_dev *rdev = regulator->rdev;
5187 	int old_uA_load;
5188 	int ret = 0;
5189 
5190 	regulator_lock(rdev);
5191 	old_uA_load = regulator->uA_load;
5192 	regulator->uA_load = uA_load;
5193 	if (regulator->enable_count && old_uA_load != uA_load) {
5194 		ret = drms_uA_update(rdev);
5195 		if (ret < 0)
5196 			regulator->uA_load = old_uA_load;
5197 	}
5198 	regulator_unlock(rdev);
5199 
5200 	return ret;
5201 }
5202 EXPORT_SYMBOL_GPL(regulator_set_load);
5203 
5204 /**
5205  * regulator_allow_bypass - allow the regulator to go into bypass mode
5206  *
5207  * @regulator: Regulator to configure
5208  * @enable: enable or disable bypass mode
5209  *
5210  * Allow the regulator to go into bypass mode if all other consumers
5211  * for the regulator also enable bypass mode and the machine
5212  * constraints allow this.  Bypass mode means that the regulator is
5213  * simply passing the input directly to the output with no regulation.
5214  *
5215  * Return: 0 on success or if changing bypass is not possible, or
5216  *	   a negative error number on failure.
5217  */
5218 int regulator_allow_bypass(struct regulator *regulator, bool enable)
5219 {
5220 	struct regulator_dev *rdev = regulator->rdev;
5221 	const char *name = rdev_get_name(rdev);
5222 	int ret = 0;
5223 
5224 	if (!rdev->desc->ops->set_bypass)
5225 		return 0;
5226 
5227 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_BYPASS))
5228 		return 0;
5229 
5230 	regulator_lock(rdev);
5231 
5232 	if (enable && !regulator->bypass) {
5233 		rdev->bypass_count++;
5234 
5235 		if (rdev->bypass_count == rdev->open_count) {
5236 			trace_regulator_bypass_enable(name);
5237 
5238 			ret = rdev->desc->ops->set_bypass(rdev, enable);
5239 			if (ret != 0)
5240 				rdev->bypass_count--;
5241 			else
5242 				trace_regulator_bypass_enable_complete(name);
5243 		}
5244 
5245 	} else if (!enable && regulator->bypass) {
5246 		rdev->bypass_count--;
5247 
5248 		if (rdev->bypass_count != rdev->open_count) {
5249 			trace_regulator_bypass_disable(name);
5250 
5251 			ret = rdev->desc->ops->set_bypass(rdev, enable);
5252 			if (ret != 0)
5253 				rdev->bypass_count++;
5254 			else
5255 				trace_regulator_bypass_disable_complete(name);
5256 		}
5257 	}
5258 
5259 	if (ret == 0)
5260 		regulator->bypass = enable;
5261 
5262 	regulator_unlock(rdev);
5263 
5264 	return ret;
5265 }
5266 EXPORT_SYMBOL_GPL(regulator_allow_bypass);
5267 
5268 /**
5269  * regulator_register_notifier - register regulator event notifier
5270  * @regulator: regulator source
5271  * @nb: notifier block
5272  *
5273  * Register notifier block to receive regulator events.
5274  *
5275  * Return: 0 on success or a negative error number on failure.
5276  */
5277 int regulator_register_notifier(struct regulator *regulator,
5278 			      struct notifier_block *nb)
5279 {
5280 	return blocking_notifier_chain_register(&regulator->rdev->notifier,
5281 						nb);
5282 }
5283 EXPORT_SYMBOL_GPL(regulator_register_notifier);
5284 
5285 /**
5286  * regulator_unregister_notifier - unregister regulator event notifier
5287  * @regulator: regulator source
5288  * @nb: notifier block
5289  *
5290  * Unregister regulator event notifier block.
5291  *
5292  * Return: 0 on success or a negative error number on failure.
5293  */
5294 int regulator_unregister_notifier(struct regulator *regulator,
5295 				struct notifier_block *nb)
5296 {
5297 	return blocking_notifier_chain_unregister(&regulator->rdev->notifier,
5298 						  nb);
5299 }
5300 EXPORT_SYMBOL_GPL(regulator_unregister_notifier);
5301 
5302 /* notify regulator consumers and downstream regulator consumers.
5303  * Note mutex must be held by caller.
5304  */
5305 static int _notifier_call_chain(struct regulator_dev *rdev,
5306 				  unsigned long event, void *data)
5307 {
5308 	/* call rdev chain first */
5309 	int ret =  blocking_notifier_call_chain(&rdev->notifier, event, data);
5310 
5311 	if (IS_REACHABLE(CONFIG_REGULATOR_NETLINK_EVENTS)) {
5312 		struct device *parent = rdev->dev.parent;
5313 		const char *rname = rdev_get_name(rdev);
5314 		char name[32];
5315 
5316 		/* Avoid duplicate debugfs directory names */
5317 		if (parent && rname == rdev->desc->name) {
5318 			snprintf(name, sizeof(name), "%s-%s", dev_name(parent),
5319 				 rname);
5320 			rname = name;
5321 		}
5322 		reg_generate_netlink_event(rname, event);
5323 	}
5324 
5325 	return ret;
5326 }
5327 
5328 int _regulator_bulk_get(struct device *dev, int num_consumers,
5329 			struct regulator_bulk_data *consumers, enum regulator_get_type get_type)
5330 {
5331 	int i;
5332 	int ret;
5333 
5334 	for (i = 0; i < num_consumers; i++)
5335 		consumers[i].consumer = NULL;
5336 
5337 	for (i = 0; i < num_consumers; i++) {
5338 		consumers[i].consumer = _regulator_get(dev,
5339 						       consumers[i].supply, get_type);
5340 		if (IS_ERR(consumers[i].consumer)) {
5341 			ret = dev_err_probe(dev, PTR_ERR(consumers[i].consumer),
5342 					    "Failed to get supply '%s'\n",
5343 					    consumers[i].supply);
5344 			consumers[i].consumer = NULL;
5345 			goto err;
5346 		}
5347 
5348 		if (consumers[i].init_load_uA > 0) {
5349 			ret = regulator_set_load(consumers[i].consumer,
5350 						 consumers[i].init_load_uA);
5351 			if (ret) {
5352 				i++;
5353 				goto err;
5354 			}
5355 		}
5356 	}
5357 
5358 	return 0;
5359 
5360 err:
5361 	while (--i >= 0)
5362 		regulator_put(consumers[i].consumer);
5363 
5364 	return ret;
5365 }
5366 
5367 /**
5368  * regulator_bulk_get - get multiple regulator consumers
5369  *
5370  * @dev:           Device to supply
5371  * @num_consumers: Number of consumers to register
5372  * @consumers:     Configuration of consumers; clients are stored here.
5373  *
5374  * This helper function allows drivers to get several regulator
5375  * consumers in one operation.  If any of the regulators cannot be
5376  * acquired then any regulators that were allocated will be freed
5377  * before returning to the caller.
5378  *
5379  * Return: 0 on success or a negative error number on failure.
5380  */
5381 int regulator_bulk_get(struct device *dev, int num_consumers,
5382 		       struct regulator_bulk_data *consumers)
5383 {
5384 	return _regulator_bulk_get(dev, num_consumers, consumers, NORMAL_GET);
5385 }
5386 EXPORT_SYMBOL_GPL(regulator_bulk_get);
5387 
5388 static void regulator_bulk_enable_async(void *data, async_cookie_t cookie)
5389 {
5390 	struct regulator_bulk_data *bulk = data;
5391 
5392 	bulk->ret = regulator_enable(bulk->consumer);
5393 }
5394 
5395 /**
5396  * regulator_bulk_enable - enable multiple regulator consumers
5397  *
5398  * @num_consumers: Number of consumers
5399  * @consumers:     Consumer data; clients are stored here.
5400  *
5401  * This convenience API allows consumers to enable multiple regulator
5402  * clients in a single API call.  If any consumers cannot be enabled
5403  * then any others that were enabled will be disabled again prior to
5404  * return.
5405  *
5406  * Return: 0 on success or a negative error number on failure.
5407  */
5408 int regulator_bulk_enable(int num_consumers,
5409 			  struct regulator_bulk_data *consumers)
5410 {
5411 	ASYNC_DOMAIN_EXCLUSIVE(async_domain);
5412 	int i;
5413 	int ret = 0;
5414 
5415 	for (i = 0; i < num_consumers; i++) {
5416 		async_schedule_domain(regulator_bulk_enable_async,
5417 				      &consumers[i], &async_domain);
5418 	}
5419 
5420 	async_synchronize_full_domain(&async_domain);
5421 
5422 	/* If any consumer failed we need to unwind any that succeeded */
5423 	for (i = 0; i < num_consumers; i++) {
5424 		if (consumers[i].ret != 0) {
5425 			ret = consumers[i].ret;
5426 			goto err;
5427 		}
5428 	}
5429 
5430 	return 0;
5431 
5432 err:
5433 	for (i = 0; i < num_consumers; i++) {
5434 		if (consumers[i].ret < 0)
5435 			pr_err("Failed to enable %s: %pe\n", consumers[i].supply,
5436 			       ERR_PTR(consumers[i].ret));
5437 		else
5438 			regulator_disable(consumers[i].consumer);
5439 	}
5440 
5441 	return ret;
5442 }
5443 EXPORT_SYMBOL_GPL(regulator_bulk_enable);
5444 
5445 /**
5446  * regulator_bulk_disable - disable multiple regulator consumers
5447  *
5448  * @num_consumers: Number of consumers
5449  * @consumers:     Consumer data; clients are stored here.
5450  *
5451  * This convenience API allows consumers to disable multiple regulator
5452  * clients in a single API call.  If any consumers cannot be disabled
5453  * then any others that were disabled will be enabled again prior to
5454  * return.
5455  *
5456  * Return: 0 on success or a negative error number on failure.
5457  */
5458 int regulator_bulk_disable(int num_consumers,
5459 			   struct regulator_bulk_data *consumers)
5460 {
5461 	int i;
5462 	int ret, r;
5463 
5464 	for (i = num_consumers - 1; i >= 0; --i) {
5465 		ret = regulator_disable(consumers[i].consumer);
5466 		if (ret != 0)
5467 			goto err;
5468 	}
5469 
5470 	return 0;
5471 
5472 err:
5473 	pr_err("Failed to disable %s: %pe\n", consumers[i].supply, ERR_PTR(ret));
5474 	for (++i; i < num_consumers; ++i) {
5475 		r = regulator_enable(consumers[i].consumer);
5476 		if (r != 0)
5477 			pr_err("Failed to re-enable %s: %pe\n",
5478 			       consumers[i].supply, ERR_PTR(r));
5479 	}
5480 
5481 	return ret;
5482 }
5483 EXPORT_SYMBOL_GPL(regulator_bulk_disable);
5484 
5485 /**
5486  * regulator_bulk_force_disable - force disable multiple regulator consumers
5487  *
5488  * @num_consumers: Number of consumers
5489  * @consumers:     Consumer data; clients are stored here.
5490  *
5491  * This convenience API allows consumers to forcibly disable multiple regulator
5492  * clients in a single API call.
5493  * NOTE: This should be used for situations when device damage will
5494  * likely occur if the regulators are not disabled (e.g. over temp).
5495  * Although regulator_force_disable function call for some consumers can
5496  * return error numbers, the function is called for all consumers.
5497  *
5498  * Return: 0 on success or a negative error number on failure.
5499  */
5500 int regulator_bulk_force_disable(int num_consumers,
5501 			   struct regulator_bulk_data *consumers)
5502 {
5503 	int i;
5504 	int ret = 0;
5505 
5506 	for (i = 0; i < num_consumers; i++) {
5507 		consumers[i].ret =
5508 			    regulator_force_disable(consumers[i].consumer);
5509 
5510 		/* Store first error for reporting */
5511 		if (consumers[i].ret && !ret)
5512 			ret = consumers[i].ret;
5513 	}
5514 
5515 	return ret;
5516 }
5517 EXPORT_SYMBOL_GPL(regulator_bulk_force_disable);
5518 
5519 /**
5520  * regulator_bulk_free - free multiple regulator consumers
5521  *
5522  * @num_consumers: Number of consumers
5523  * @consumers:     Consumer data; clients are stored here.
5524  *
5525  * This convenience API allows consumers to free multiple regulator
5526  * clients in a single API call.
5527  */
5528 void regulator_bulk_free(int num_consumers,
5529 			 struct regulator_bulk_data *consumers)
5530 {
5531 	int i;
5532 
5533 	for (i = 0; i < num_consumers; i++) {
5534 		regulator_put(consumers[i].consumer);
5535 		consumers[i].consumer = NULL;
5536 	}
5537 }
5538 EXPORT_SYMBOL_GPL(regulator_bulk_free);
5539 
5540 /**
5541  * regulator_handle_critical - Handle events for system-critical regulators.
5542  * @rdev: The regulator device.
5543  * @event: The event being handled.
5544  *
5545  * This function handles critical events such as under-voltage, over-current,
5546  * and unknown errors for regulators deemed system-critical. On detecting such
5547  * events, it triggers a hardware protection shutdown with a defined timeout.
5548  */
5549 static void regulator_handle_critical(struct regulator_dev *rdev,
5550 				      unsigned long event)
5551 {
5552 	const char *reason = NULL;
5553 
5554 	if (!rdev->constraints->system_critical)
5555 		return;
5556 
5557 	switch (event) {
5558 	case REGULATOR_EVENT_UNDER_VOLTAGE:
5559 		reason = "System critical regulator: voltage drop detected";
5560 		break;
5561 	case REGULATOR_EVENT_OVER_CURRENT:
5562 		reason = "System critical regulator: over-current detected";
5563 		break;
5564 	case REGULATOR_EVENT_FAIL:
5565 		reason = "System critical regulator: unknown error";
5566 	}
5567 
5568 	if (!reason)
5569 		return;
5570 
5571 	hw_protection_trigger(reason,
5572 			      rdev->constraints->uv_less_critical_window_ms);
5573 }
5574 
5575 /**
5576  * regulator_notifier_call_chain - call regulator event notifier
5577  * @rdev: regulator source
5578  * @event: notifier block
5579  * @data: callback-specific data.
5580  *
5581  * Called by regulator drivers to notify clients a regulator event has
5582  * occurred.
5583  *
5584  * Return: %NOTIFY_DONE.
5585  */
5586 int regulator_notifier_call_chain(struct regulator_dev *rdev,
5587 				  unsigned long event, void *data)
5588 {
5589 	regulator_handle_critical(rdev, event);
5590 
5591 	_notifier_call_chain(rdev, event, data);
5592 	return NOTIFY_DONE;
5593 
5594 }
5595 EXPORT_SYMBOL_GPL(regulator_notifier_call_chain);
5596 
5597 /**
5598  * regulator_mode_to_status - convert a regulator mode into a status
5599  *
5600  * @mode: Mode to convert
5601  *
5602  * Convert a regulator mode into a status.
5603  *
5604  * Return: %REGULATOR_STATUS_* value corresponding to given mode.
5605  */
5606 int regulator_mode_to_status(unsigned int mode)
5607 {
5608 	switch (mode) {
5609 	case REGULATOR_MODE_FAST:
5610 		return REGULATOR_STATUS_FAST;
5611 	case REGULATOR_MODE_NORMAL:
5612 		return REGULATOR_STATUS_NORMAL;
5613 	case REGULATOR_MODE_IDLE:
5614 		return REGULATOR_STATUS_IDLE;
5615 	case REGULATOR_MODE_STANDBY:
5616 		return REGULATOR_STATUS_STANDBY;
5617 	default:
5618 		return REGULATOR_STATUS_UNDEFINED;
5619 	}
5620 }
5621 EXPORT_SYMBOL_GPL(regulator_mode_to_status);
5622 
5623 static struct attribute *regulator_dev_attrs[] = {
5624 	&dev_attr_name.attr,
5625 	&dev_attr_num_users.attr,
5626 	&dev_attr_type.attr,
5627 	&dev_attr_microvolts.attr,
5628 	&dev_attr_microamps.attr,
5629 	&dev_attr_opmode.attr,
5630 	&dev_attr_state.attr,
5631 	&dev_attr_status.attr,
5632 	&dev_attr_bypass.attr,
5633 	&dev_attr_requested_microamps.attr,
5634 	&dev_attr_min_microvolts.attr,
5635 	&dev_attr_max_microvolts.attr,
5636 	&dev_attr_min_microamps.attr,
5637 	&dev_attr_max_microamps.attr,
5638 	&dev_attr_under_voltage.attr,
5639 	&dev_attr_over_current.attr,
5640 	&dev_attr_regulation_out.attr,
5641 	&dev_attr_fail.attr,
5642 	&dev_attr_over_temp.attr,
5643 	&dev_attr_under_voltage_warn.attr,
5644 	&dev_attr_over_current_warn.attr,
5645 	&dev_attr_over_voltage_warn.attr,
5646 	&dev_attr_over_temp_warn.attr,
5647 	&dev_attr_suspend_standby_state.attr,
5648 	&dev_attr_suspend_mem_state.attr,
5649 	&dev_attr_suspend_disk_state.attr,
5650 	&dev_attr_suspend_standby_microvolts.attr,
5651 	&dev_attr_suspend_mem_microvolts.attr,
5652 	&dev_attr_suspend_disk_microvolts.attr,
5653 	&dev_attr_suspend_standby_mode.attr,
5654 	&dev_attr_suspend_mem_mode.attr,
5655 	&dev_attr_suspend_disk_mode.attr,
5656 	&dev_attr_power_budget_milliwatt.attr,
5657 	&dev_attr_power_requested_milliwatt.attr,
5658 	NULL
5659 };
5660 
5661 /*
5662  * To avoid cluttering sysfs (and memory) with useless state, only
5663  * create attributes that can be meaningfully displayed.
5664  */
5665 static umode_t regulator_attr_is_visible(struct kobject *kobj,
5666 					 struct attribute *attr, int idx)
5667 {
5668 	struct device *dev = kobj_to_dev(kobj);
5669 	struct regulator_dev *rdev = dev_to_rdev(dev);
5670 	const struct regulator_ops *ops = rdev->desc->ops;
5671 	umode_t mode = attr->mode;
5672 
5673 	/* these three are always present */
5674 	if (attr == &dev_attr_name.attr ||
5675 	    attr == &dev_attr_num_users.attr ||
5676 	    attr == &dev_attr_type.attr)
5677 		return mode;
5678 
5679 	/* some attributes need specific methods to be displayed */
5680 	if (attr == &dev_attr_microvolts.attr) {
5681 		if ((ops->get_voltage && ops->get_voltage(rdev) >= 0) ||
5682 		    (ops->get_voltage_sel && ops->get_voltage_sel(rdev) >= 0) ||
5683 		    (ops->list_voltage && ops->list_voltage(rdev, 0) >= 0) ||
5684 		    (rdev->desc->fixed_uV && rdev->desc->n_voltages == 1))
5685 			return mode;
5686 		return 0;
5687 	}
5688 
5689 	if (attr == &dev_attr_microamps.attr)
5690 		return ops->get_current_limit ? mode : 0;
5691 
5692 	if (attr == &dev_attr_opmode.attr)
5693 		return ops->get_mode ? mode : 0;
5694 
5695 	if (attr == &dev_attr_state.attr)
5696 		return (rdev->ena_pin || ops->is_enabled) ? mode : 0;
5697 
5698 	if (attr == &dev_attr_status.attr)
5699 		return ops->get_status ? mode : 0;
5700 
5701 	if (attr == &dev_attr_bypass.attr)
5702 		return ops->get_bypass ? mode : 0;
5703 
5704 	if (attr == &dev_attr_under_voltage.attr ||
5705 	    attr == &dev_attr_over_current.attr ||
5706 	    attr == &dev_attr_regulation_out.attr ||
5707 	    attr == &dev_attr_fail.attr ||
5708 	    attr == &dev_attr_over_temp.attr ||
5709 	    attr == &dev_attr_under_voltage_warn.attr ||
5710 	    attr == &dev_attr_over_current_warn.attr ||
5711 	    attr == &dev_attr_over_voltage_warn.attr ||
5712 	    attr == &dev_attr_over_temp_warn.attr)
5713 		return ops->get_error_flags ? mode : 0;
5714 
5715 	/* constraints need specific supporting methods */
5716 	if (attr == &dev_attr_min_microvolts.attr ||
5717 	    attr == &dev_attr_max_microvolts.attr)
5718 		return (ops->set_voltage || ops->set_voltage_sel) ? mode : 0;
5719 
5720 	if (attr == &dev_attr_min_microamps.attr ||
5721 	    attr == &dev_attr_max_microamps.attr)
5722 		return ops->set_current_limit ? mode : 0;
5723 
5724 	if (attr == &dev_attr_suspend_standby_state.attr ||
5725 	    attr == &dev_attr_suspend_mem_state.attr ||
5726 	    attr == &dev_attr_suspend_disk_state.attr)
5727 		return mode;
5728 
5729 	if (attr == &dev_attr_suspend_standby_microvolts.attr ||
5730 	    attr == &dev_attr_suspend_mem_microvolts.attr ||
5731 	    attr == &dev_attr_suspend_disk_microvolts.attr)
5732 		return ops->set_suspend_voltage ? mode : 0;
5733 
5734 	if (attr == &dev_attr_suspend_standby_mode.attr ||
5735 	    attr == &dev_attr_suspend_mem_mode.attr ||
5736 	    attr == &dev_attr_suspend_disk_mode.attr)
5737 		return ops->set_suspend_mode ? mode : 0;
5738 
5739 	if (attr == &dev_attr_power_budget_milliwatt.attr ||
5740 	    attr == &dev_attr_power_requested_milliwatt.attr)
5741 		return rdev->constraints->pw_budget_mW != INT_MAX ? mode : 0;
5742 
5743 	return mode;
5744 }
5745 
5746 static const struct attribute_group regulator_dev_group = {
5747 	.attrs = regulator_dev_attrs,
5748 	.is_visible = regulator_attr_is_visible,
5749 };
5750 
5751 static const struct attribute_group *regulator_dev_groups[] = {
5752 	&regulator_dev_group,
5753 	NULL
5754 };
5755 
5756 static void regulator_dev_release(struct device *dev)
5757 {
5758 	struct regulator_dev *rdev = dev_get_drvdata(dev);
5759 
5760 	debugfs_remove_recursive(rdev->debugfs);
5761 	kfree(rdev->constraints);
5762 	of_node_put(rdev->dev.of_node);
5763 	kfree(rdev);
5764 }
5765 
5766 static void rdev_init_debugfs(struct regulator_dev *rdev)
5767 {
5768 	struct device *parent = rdev->dev.parent;
5769 	const char *rname = rdev_get_name(rdev);
5770 	char name[NAME_MAX];
5771 
5772 	/* Avoid duplicate debugfs directory names */
5773 	if (parent && rname == rdev->desc->name) {
5774 		snprintf(name, sizeof(name), "%s-%s", dev_name(parent),
5775 			 rname);
5776 		rname = name;
5777 	}
5778 
5779 	rdev->debugfs = debugfs_create_dir(rname, debugfs_root);
5780 	if (IS_ERR(rdev->debugfs))
5781 		rdev_dbg(rdev, "Failed to create debugfs directory\n");
5782 
5783 	debugfs_create_u32("use_count", 0444, rdev->debugfs,
5784 			   &rdev->use_count);
5785 	debugfs_create_u32("open_count", 0444, rdev->debugfs,
5786 			   &rdev->open_count);
5787 	debugfs_create_u32("bypass_count", 0444, rdev->debugfs,
5788 			   &rdev->bypass_count);
5789 }
5790 
5791 int regulator_coupler_register(struct regulator_coupler *coupler)
5792 {
5793 	mutex_lock(&regulator_list_mutex);
5794 	list_add_tail(&coupler->list, &regulator_coupler_list);
5795 	mutex_unlock(&regulator_list_mutex);
5796 
5797 	return 0;
5798 }
5799 
5800 static struct regulator_coupler *
5801 regulator_find_coupler(struct regulator_dev *rdev)
5802 {
5803 	struct regulator_coupler *coupler;
5804 	int err;
5805 
5806 	/*
5807 	 * Note that regulators are appended to the list and the generic
5808 	 * coupler is registered first, hence it will be attached at last
5809 	 * if nobody cared.
5810 	 */
5811 	list_for_each_entry_reverse(coupler, &regulator_coupler_list, list) {
5812 		err = coupler->attach_regulator(coupler, rdev);
5813 		if (!err) {
5814 			if (!coupler->balance_voltage &&
5815 			    rdev->coupling_desc.n_coupled > 2)
5816 				goto err_unsupported;
5817 
5818 			return coupler;
5819 		}
5820 
5821 		if (err < 0)
5822 			return ERR_PTR(err);
5823 
5824 		if (err == 1)
5825 			continue;
5826 
5827 		break;
5828 	}
5829 
5830 	return ERR_PTR(-EINVAL);
5831 
5832 err_unsupported:
5833 	if (coupler->detach_regulator)
5834 		coupler->detach_regulator(coupler, rdev);
5835 
5836 	rdev_err(rdev,
5837 		"Voltage balancing for multiple regulator couples is unimplemented\n");
5838 
5839 	return ERR_PTR(-EPERM);
5840 }
5841 
5842 static void regulator_resolve_coupling(struct regulator_dev *rdev)
5843 {
5844 	struct regulator_coupler *coupler = rdev->coupling_desc.coupler;
5845 	struct coupling_desc *c_desc = &rdev->coupling_desc;
5846 	int n_coupled = c_desc->n_coupled;
5847 	struct regulator_dev *c_rdev;
5848 	int i;
5849 
5850 	for (i = 1; i < n_coupled; i++) {
5851 		/* already resolved */
5852 		if (c_desc->coupled_rdevs[i])
5853 			continue;
5854 
5855 		c_rdev = of_parse_coupled_regulator(rdev, i - 1);
5856 
5857 		if (!c_rdev)
5858 			continue;
5859 
5860 		if (c_rdev->coupling_desc.coupler != coupler) {
5861 			rdev_err(rdev, "coupler mismatch with %s\n",
5862 				 rdev_get_name(c_rdev));
5863 			return;
5864 		}
5865 
5866 		c_desc->coupled_rdevs[i] = c_rdev;
5867 		c_desc->n_resolved++;
5868 
5869 		regulator_resolve_coupling(c_rdev);
5870 	}
5871 }
5872 
5873 static void regulator_remove_coupling(struct regulator_dev *rdev)
5874 {
5875 	struct regulator_coupler *coupler = rdev->coupling_desc.coupler;
5876 	struct coupling_desc *__c_desc, *c_desc = &rdev->coupling_desc;
5877 	struct regulator_dev *__c_rdev, *c_rdev;
5878 	unsigned int __n_coupled, n_coupled;
5879 	int i, k;
5880 	int err;
5881 
5882 	n_coupled = c_desc->n_coupled;
5883 
5884 	for (i = 1; i < n_coupled; i++) {
5885 		c_rdev = c_desc->coupled_rdevs[i];
5886 
5887 		if (!c_rdev)
5888 			continue;
5889 
5890 		regulator_lock(c_rdev);
5891 
5892 		__c_desc = &c_rdev->coupling_desc;
5893 		__n_coupled = __c_desc->n_coupled;
5894 
5895 		for (k = 1; k < __n_coupled; k++) {
5896 			__c_rdev = __c_desc->coupled_rdevs[k];
5897 
5898 			if (__c_rdev == rdev) {
5899 				__c_desc->coupled_rdevs[k] = NULL;
5900 				__c_desc->n_resolved--;
5901 				break;
5902 			}
5903 		}
5904 
5905 		regulator_unlock(c_rdev);
5906 
5907 		c_desc->coupled_rdevs[i] = NULL;
5908 		c_desc->n_resolved--;
5909 	}
5910 
5911 	if (coupler && coupler->detach_regulator) {
5912 		err = coupler->detach_regulator(coupler, rdev);
5913 		if (err)
5914 			rdev_err(rdev, "failed to detach from coupler: %pe\n",
5915 				 ERR_PTR(err));
5916 	}
5917 
5918 	rdev->coupling_desc.n_coupled = 0;
5919 	kfree(rdev->coupling_desc.coupled_rdevs);
5920 	rdev->coupling_desc.coupled_rdevs = NULL;
5921 }
5922 
5923 static int regulator_init_coupling(struct regulator_dev *rdev)
5924 {
5925 	struct regulator_dev **coupled;
5926 	int err, n_phandles;
5927 
5928 	if (!IS_ENABLED(CONFIG_OF))
5929 		n_phandles = 0;
5930 	else
5931 		n_phandles = of_get_n_coupled(rdev);
5932 
5933 	coupled = kzalloc_objs(*coupled, n_phandles + 1);
5934 	if (!coupled)
5935 		return -ENOMEM;
5936 
5937 	rdev->coupling_desc.coupled_rdevs = coupled;
5938 
5939 	/*
5940 	 * Every regulator should always have coupling descriptor filled with
5941 	 * at least pointer to itself.
5942 	 */
5943 	rdev->coupling_desc.coupled_rdevs[0] = rdev;
5944 	rdev->coupling_desc.n_coupled = n_phandles + 1;
5945 	rdev->coupling_desc.n_resolved++;
5946 
5947 	/* regulator isn't coupled */
5948 	if (n_phandles == 0)
5949 		return 0;
5950 
5951 	if (!of_check_coupling_data(rdev))
5952 		return -EPERM;
5953 
5954 	mutex_lock(&regulator_list_mutex);
5955 	rdev->coupling_desc.coupler = regulator_find_coupler(rdev);
5956 	mutex_unlock(&regulator_list_mutex);
5957 
5958 	if (IS_ERR(rdev->coupling_desc.coupler)) {
5959 		err = PTR_ERR(rdev->coupling_desc.coupler);
5960 		rdev_err(rdev, "failed to get coupler: %pe\n", ERR_PTR(err));
5961 		return err;
5962 	}
5963 
5964 	return 0;
5965 }
5966 
5967 static int generic_coupler_attach(struct regulator_coupler *coupler,
5968 				  struct regulator_dev *rdev)
5969 {
5970 	if (rdev->coupling_desc.n_coupled > 2) {
5971 		rdev_err(rdev,
5972 			 "Voltage balancing for multiple regulator couples is unimplemented\n");
5973 		return -EPERM;
5974 	}
5975 
5976 	if (!rdev->constraints->always_on) {
5977 		rdev_err(rdev,
5978 			 "Coupling of a non always-on regulator is unimplemented\n");
5979 		return -ENOTSUPP;
5980 	}
5981 
5982 	return 0;
5983 }
5984 
5985 static struct regulator_coupler generic_regulator_coupler = {
5986 	.attach_regulator = generic_coupler_attach,
5987 };
5988 
5989 /**
5990  * regulator_register - register regulator
5991  * @dev: the device that drive the regulator
5992  * @regulator_desc: regulator to register
5993  * @cfg: runtime configuration for regulator
5994  *
5995  * Called by regulator drivers to register a regulator.
5996  *
5997  * Return: Pointer to a valid &struct regulator_dev on success or
5998  *	   an ERR_PTR() encoded negative error number on failure.
5999  */
6000 struct regulator_dev *
6001 regulator_register(struct device *dev,
6002 		   const struct regulator_desc *regulator_desc,
6003 		   const struct regulator_config *cfg)
6004 {
6005 	const struct regulator_init_data *init_data;
6006 	struct regulator_config *config = NULL;
6007 	static atomic_t regulator_no = ATOMIC_INIT(-1);
6008 	struct regulator_dev *rdev;
6009 	bool tried_supply_resolve = false;
6010 	bool dangling_cfg_gpiod = false;
6011 	bool dangling_of_gpiod = false;
6012 	int ret, i;
6013 
6014 	if (cfg == NULL)
6015 		return ERR_PTR(-EINVAL);
6016 	if (cfg->ena_gpiod)
6017 		dangling_cfg_gpiod = true;
6018 	if (regulator_desc == NULL) {
6019 		ret = -EINVAL;
6020 		goto rinse;
6021 	}
6022 
6023 	WARN_ON(!dev || !cfg->dev);
6024 
6025 	if (regulator_desc->name == NULL || regulator_desc->ops == NULL) {
6026 		ret = -EINVAL;
6027 		goto rinse;
6028 	}
6029 
6030 	if (regulator_desc->type != REGULATOR_VOLTAGE &&
6031 	    regulator_desc->type != REGULATOR_CURRENT) {
6032 		ret = -EINVAL;
6033 		goto rinse;
6034 	}
6035 
6036 	/* Only one of each should be implemented */
6037 	WARN_ON(regulator_desc->ops->get_voltage &&
6038 		regulator_desc->ops->get_voltage_sel);
6039 	WARN_ON(regulator_desc->ops->set_voltage &&
6040 		regulator_desc->ops->set_voltage_sel);
6041 
6042 	/* If we're using selectors we must implement list_voltage. */
6043 	if (regulator_desc->ops->get_voltage_sel &&
6044 	    !regulator_desc->ops->list_voltage) {
6045 		ret = -EINVAL;
6046 		goto rinse;
6047 	}
6048 	if (regulator_desc->ops->set_voltage_sel &&
6049 	    !regulator_desc->ops->list_voltage) {
6050 		ret = -EINVAL;
6051 		goto rinse;
6052 	}
6053 
6054 	rdev = kzalloc_obj(struct regulator_dev);
6055 	if (rdev == NULL) {
6056 		ret = -ENOMEM;
6057 		goto rinse;
6058 	}
6059 	device_initialize(&rdev->dev);
6060 	dev_set_drvdata(&rdev->dev, rdev);
6061 	rdev->dev.class = &regulator_class;
6062 	spin_lock_init(&rdev->err_lock);
6063 
6064 	/*
6065 	 * Duplicate the config so the driver could override it after
6066 	 * parsing init data.
6067 	 */
6068 	config = kmemdup(cfg, sizeof(*cfg), GFP_KERNEL);
6069 	if (config == NULL) {
6070 		ret = -ENOMEM;
6071 		goto clean;
6072 	}
6073 
6074 	/*
6075 	 * DT may override the config->init_data provided if the platform
6076 	 * needs to do so. If so, config->init_data is completely ignored.
6077 	 */
6078 	init_data = regulator_of_get_init_data(dev, regulator_desc, config,
6079 					       &rdev->dev.of_node);
6080 
6081 	/*
6082 	 * Sometimes not all resources are probed already so we need to take
6083 	 * that into account. This happens most the time if the ena_gpiod comes
6084 	 * from a gpio extender or something else.
6085 	 */
6086 	if (PTR_ERR(init_data) == -EPROBE_DEFER) {
6087 		ret = -EPROBE_DEFER;
6088 		goto clean;
6089 	}
6090 
6091 	/*
6092 	 * We need to keep track of any GPIO descriptor coming from the
6093 	 * device tree until we have handled it over to the core. If the
6094 	 * config that was passed in to this function DOES NOT contain
6095 	 * a descriptor, and the config after this call DOES contain
6096 	 * a descriptor, we definitely got one from parsing the device
6097 	 * tree.
6098 	 */
6099 	if (!cfg->ena_gpiod && config->ena_gpiod)
6100 		dangling_of_gpiod = true;
6101 	if (!init_data) {
6102 		init_data = config->init_data;
6103 		rdev->dev.of_node = of_node_get(config->of_node);
6104 	}
6105 
6106 	ww_mutex_init(&rdev->mutex, &regulator_ww_class);
6107 	rdev->reg_data = config->driver_data;
6108 	rdev->owner = regulator_desc->owner;
6109 	rdev->desc = regulator_desc;
6110 	if (config->regmap)
6111 		rdev->regmap = config->regmap;
6112 	else if (dev_get_regmap(dev, NULL))
6113 		rdev->regmap = dev_get_regmap(dev, NULL);
6114 	else if (dev->parent)
6115 		rdev->regmap = dev_get_regmap(dev->parent, NULL);
6116 	INIT_LIST_HEAD(&rdev->consumer_list);
6117 	INIT_LIST_HEAD(&rdev->list);
6118 	BLOCKING_INIT_NOTIFIER_HEAD(&rdev->notifier);
6119 	INIT_DELAYED_WORK(&rdev->disable_work, regulator_disable_work);
6120 
6121 	if (init_data && init_data->supply_regulator)
6122 		rdev->supply_name = init_data->supply_regulator;
6123 	else if (regulator_desc->supply_name)
6124 		rdev->supply_name = regulator_desc->supply_name;
6125 
6126 	/* register with sysfs */
6127 	rdev->dev.parent = config->dev;
6128 	dev_set_name(&rdev->dev, "regulator.%lu",
6129 		    (unsigned long) atomic_inc_return(&regulator_no));
6130 
6131 	/* set regulator constraints */
6132 	if (init_data)
6133 		rdev->constraints = kmemdup(&init_data->constraints,
6134 					    sizeof(*rdev->constraints),
6135 					    GFP_KERNEL);
6136 	else
6137 		rdev->constraints = kzalloc_obj(*rdev->constraints);
6138 	if (!rdev->constraints) {
6139 		ret = -ENOMEM;
6140 		goto wash;
6141 	}
6142 
6143 	if (regulator_desc->init_cb) {
6144 		ret = regulator_desc->init_cb(rdev, config);
6145 		if (ret < 0)
6146 			goto wash;
6147 	}
6148 
6149 	if (config->ena_gpiod) {
6150 		ret = regulator_ena_gpio_request(rdev, config);
6151 		if (ret != 0) {
6152 			rdev_err(rdev, "Failed to request enable GPIO: %pe\n",
6153 				 ERR_PTR(ret));
6154 			goto wash;
6155 		}
6156 		/* The regulator core took over the GPIO descriptor */
6157 		dangling_cfg_gpiod = false;
6158 		dangling_of_gpiod = false;
6159 	}
6160 
6161 	ret = set_machine_constraints(rdev, false);
6162 	if (ret == -EPROBE_DEFER) {
6163 		/* Regulator might be in bypass mode or an always-on or boot-on
6164 		 * regulator and so needs its supply to set the constraints or
6165 		 * for enable.
6166 		 */
6167 		/* FIXME: this currently triggers a chicken-and-egg problem
6168 		 * when creating -SUPPLY symlink in sysfs to a regulator
6169 		 * that is just being created
6170 		 */
6171 		rdev_dbg(rdev, "will resolve supply early: %s\n",
6172 			 rdev->supply_name);
6173 		ret = regulator_resolve_supply(rdev);
6174 		if (!ret)
6175 			ret = set_machine_constraints(rdev, false);
6176 		else
6177 			rdev_dbg(rdev, "unable to resolve supply early: %pe\n",
6178 				 ERR_PTR(ret));
6179 		tried_supply_resolve = true;
6180 	}
6181 	if (ret < 0) {
6182 		if (ret != -EPROBE_DEFER)
6183 			goto wash;
6184 		rdev->constraints_pending = true;
6185 	}
6186 
6187 	ret = regulator_init_coupling(rdev);
6188 	if (ret < 0)
6189 		goto wash;
6190 
6191 	/* add consumers devices */
6192 	if (init_data) {
6193 		for (i = 0; i < init_data->num_consumer_supplies; i++) {
6194 			ret = set_consumer_device_supply(rdev,
6195 				init_data->consumer_supplies[i].dev_name,
6196 				init_data->consumer_supplies[i].supply);
6197 			if (ret < 0) {
6198 				dev_err(dev, "Failed to set supply %s\n",
6199 					init_data->consumer_supplies[i].supply);
6200 				goto unset_supplies;
6201 			}
6202 		}
6203 	}
6204 
6205 	if (!rdev->desc->ops->get_voltage &&
6206 	    !rdev->desc->ops->list_voltage &&
6207 	    !rdev->desc->fixed_uV)
6208 		rdev->is_switch = true;
6209 
6210 	ret = device_add(&rdev->dev);
6211 	if (ret != 0)
6212 		goto unset_supplies;
6213 
6214 	if (!tried_supply_resolve) {
6215 		/*
6216 		 * As an optimisation, try to resolve our supply (if any) now to
6217 		 * avoid adding the bus device. Errors are not fatal at this
6218 		 * stage, we'll simply try again later.
6219 		 */
6220 		ret = regulator_resolve_supply(rdev);
6221 		if (ret)
6222 			rdev_dbg(rdev,
6223 				 "unable to resolve supply (ignoring): %pe\n",
6224 				 ERR_PTR(ret));
6225 	}
6226 
6227 	/*
6228 	 * If we have a supply but couldn't resolve it yet, register a device
6229 	 * with our bus, so that the bus probe gets called whenever any new
6230 	 * driver binds, allowing us to retry matching supplies and which then
6231 	 * triggers (re)probe of consumers if successful.
6232 	 */
6233 	if (rdev->supply_name && !rdev->supply) {
6234 		device_initialize(&rdev->bdev);
6235 		rdev->bdev.bus = &regulator_bus;
6236 		rdev->bdev.parent = &rdev->dev;
6237 		device_set_pm_not_required(&rdev->dev);
6238 		dev_set_name(&rdev->bdev, "%s.bdev", dev_name(&rdev->dev));
6239 
6240 		ret = device_add(&rdev->bdev);
6241 		if (ret)
6242 			goto del_cdev_and_bdev;
6243 	}
6244 
6245 	rdev_init_debugfs(rdev);
6246 
6247 	/* try to resolve regulators coupling since a new one was registered */
6248 	mutex_lock(&regulator_list_mutex);
6249 	regulator_resolve_coupling(rdev);
6250 	mutex_unlock(&regulator_list_mutex);
6251 
6252 	kfree(config);
6253 	return rdev;
6254 
6255 del_cdev_and_bdev:
6256 	if (rdev->bdev.bus == &regulator_bus)
6257 		put_device(&rdev->bdev);
6258 	device_del(&rdev->dev);
6259 unset_supplies:
6260 	mutex_lock(&regulator_list_mutex);
6261 	unset_regulator_supplies(rdev);
6262 	regulator_remove_coupling(rdev);
6263 	mutex_unlock(&regulator_list_mutex);
6264 wash:
6265 	regulator_put(rdev->supply);
6266 	kfree(rdev->coupling_desc.coupled_rdevs);
6267 	mutex_lock(&regulator_list_mutex);
6268 	regulator_ena_gpio_free(rdev);
6269 	mutex_unlock(&regulator_list_mutex);
6270 clean:
6271 	if (dangling_of_gpiod)
6272 		gpiod_put(config->ena_gpiod);
6273 	kfree(config);
6274 	put_device(&rdev->dev);
6275 rinse:
6276 	if (dangling_cfg_gpiod)
6277 		gpiod_put(cfg->ena_gpiod);
6278 	return ERR_PTR(ret);
6279 }
6280 EXPORT_SYMBOL_GPL(regulator_register);
6281 
6282 /**
6283  * regulator_unregister - unregister regulator
6284  * @rdev: regulator to unregister
6285  *
6286  * Called by regulator drivers to unregister a regulator.
6287  */
6288 void regulator_unregister(struct regulator_dev *rdev)
6289 {
6290 	if (rdev == NULL)
6291 		return;
6292 
6293 	if (rdev->supply) {
6294 		regulator_unregister_notifier(rdev->supply,
6295 					      &rdev->supply_fwd_nb);
6296 
6297 		while (rdev->use_count--)
6298 			regulator_disable(rdev->supply);
6299 		regulator_put(rdev->supply);
6300 	}
6301 
6302 	flush_work(&rdev->disable_work.work);
6303 
6304 	mutex_lock(&regulator_list_mutex);
6305 
6306 	WARN_ON(rdev->open_count);
6307 	regulator_remove_coupling(rdev);
6308 	unset_regulator_supplies(rdev);
6309 	list_del(&rdev->list);
6310 	regulator_ena_gpio_free(rdev);
6311 	if (rdev->bdev.bus == &regulator_bus)
6312 		/* only if the device was added in the first place */
6313 		device_unregister(&rdev->bdev);
6314 	device_unregister(&rdev->dev);
6315 
6316 	mutex_unlock(&regulator_list_mutex);
6317 }
6318 EXPORT_SYMBOL_GPL(regulator_unregister);
6319 
6320 #ifdef CONFIG_SUSPEND
6321 /**
6322  * regulator_suspend - prepare regulators for system wide suspend
6323  * @dev: ``&struct device`` pointer that is passed to _regulator_suspend()
6324  *
6325  * Configure each regulator with it's suspend operating parameters for state.
6326  *
6327  * Return: 0 on success or a negative error number on failure.
6328  */
6329 static int regulator_suspend(struct device *dev)
6330 {
6331 	struct regulator_dev *rdev = dev_to_rdev(dev);
6332 	suspend_state_t state = pm_suspend_target_state;
6333 	int ret;
6334 	const struct regulator_state *rstate;
6335 
6336 	rstate = regulator_get_suspend_state_check(rdev, state);
6337 	if (!rstate)
6338 		return 0;
6339 
6340 	regulator_lock(rdev);
6341 	ret = __suspend_set_state(rdev, rstate);
6342 	regulator_unlock(rdev);
6343 
6344 	return ret;
6345 }
6346 
6347 static int regulator_resume(struct device *dev)
6348 {
6349 	suspend_state_t state = pm_suspend_target_state;
6350 	struct regulator_dev *rdev = dev_to_rdev(dev);
6351 	struct regulator_state *rstate;
6352 	int ret = 0;
6353 
6354 	rstate = regulator_get_suspend_state(rdev, state);
6355 	if (rstate == NULL)
6356 		return 0;
6357 
6358 	/* Avoid grabbing the lock if we don't need to */
6359 	if (!rdev->desc->ops->resume)
6360 		return 0;
6361 
6362 	regulator_lock(rdev);
6363 
6364 	if (rstate->enabled == ENABLE_IN_SUSPEND ||
6365 	    rstate->enabled == DISABLE_IN_SUSPEND)
6366 		ret = rdev->desc->ops->resume(rdev);
6367 
6368 	regulator_unlock(rdev);
6369 
6370 	return ret;
6371 }
6372 #else /* !CONFIG_SUSPEND */
6373 
6374 #define regulator_suspend	NULL
6375 #define regulator_resume	NULL
6376 
6377 #endif /* !CONFIG_SUSPEND */
6378 
6379 #ifdef CONFIG_PM
6380 static const struct dev_pm_ops __maybe_unused regulator_pm_ops = {
6381 	.suspend	= regulator_suspend,
6382 	.resume		= regulator_resume,
6383 };
6384 #endif
6385 
6386 const struct class regulator_class = {
6387 	.name = "regulator",
6388 	.dev_release = regulator_dev_release,
6389 	.dev_groups = regulator_dev_groups,
6390 #ifdef CONFIG_PM
6391 	.pm = &regulator_pm_ops,
6392 #endif
6393 };
6394 
6395 #define bdev_to_rdev(__bdev) container_of_const(__bdev, struct regulator_dev, bdev)
6396 
6397 static int regulator_bus_match(struct device *bdev,
6398 			       const struct device_driver *drv)
6399 {
6400 	/* Match always succeeds, we only have one driver */
6401 	return 1;
6402 }
6403 
6404 static int regulator_bus_probe(struct device *bdev)
6405 {
6406 	struct regulator_dev *rdev = bdev_to_rdev(bdev);
6407 	int ret;
6408 
6409 	ret = regulator_resolve_supply(rdev);
6410 	if (ret)
6411 		rdev_dbg(rdev,
6412 			 "unable to resolve supply or constraints '%s': %pe\n",
6413 			 rdev->supply_name, ERR_PTR(ret));
6414 	else
6415 		rdev_dbg(rdev, "resolved supply '%s'\n", rdev->supply_name);
6416 
6417 	return ret;
6418 }
6419 
6420 static const struct bus_type regulator_bus = {
6421 	.name = "regulator",
6422 	.match = regulator_bus_match,
6423 	.probe = regulator_bus_probe,
6424 };
6425 
6426 static struct device_driver regulator_bus_driver = {
6427 	.name = "regulator-bus-drv",
6428 	.bus = &regulator_bus,
6429 	.suppress_bind_attrs = true,
6430 	.probe_type = PROBE_PREFER_ASYNCHRONOUS,
6431 };
6432 
6433 /**
6434  * regulator_has_full_constraints - the system has fully specified constraints
6435  *
6436  * Calling this function will cause the regulator API to disable all
6437  * regulators which have a zero use count and don't have an always_on
6438  * constraint in a late_initcall.
6439  *
6440  * The intention is that this will become the default behaviour in a
6441  * future kernel release so users are encouraged to use this facility
6442  * now.
6443  */
6444 void regulator_has_full_constraints(void)
6445 {
6446 	has_full_constraints = 1;
6447 }
6448 EXPORT_SYMBOL_GPL(regulator_has_full_constraints);
6449 
6450 /**
6451  * rdev_get_drvdata - get rdev regulator driver data
6452  * @rdev: regulator
6453  *
6454  * Get rdev regulator driver private data. This call can be used in the
6455  * regulator driver context.
6456  *
6457  * Return: Pointer to regulator driver private data.
6458  */
6459 void *rdev_get_drvdata(struct regulator_dev *rdev)
6460 {
6461 	return rdev->reg_data;
6462 }
6463 EXPORT_SYMBOL_GPL(rdev_get_drvdata);
6464 
6465 /**
6466  * regulator_get_drvdata - get regulator driver data
6467  * @regulator: regulator
6468  *
6469  * Get regulator driver private data. This call can be used in the consumer
6470  * driver context when non API regulator specific functions need to be called.
6471  *
6472  * Return: Pointer to regulator driver private data.
6473  */
6474 void *regulator_get_drvdata(struct regulator *regulator)
6475 {
6476 	return regulator->rdev->reg_data;
6477 }
6478 EXPORT_SYMBOL_GPL(regulator_get_drvdata);
6479 
6480 /**
6481  * regulator_set_drvdata - set regulator driver data
6482  * @regulator: regulator
6483  * @data: data
6484  */
6485 void regulator_set_drvdata(struct regulator *regulator, void *data)
6486 {
6487 	regulator->rdev->reg_data = data;
6488 }
6489 EXPORT_SYMBOL_GPL(regulator_set_drvdata);
6490 
6491 /**
6492  * rdev_get_id - get regulator ID
6493  * @rdev: regulator
6494  *
6495  * Return: Regulator ID for @rdev.
6496  */
6497 int rdev_get_id(struct regulator_dev *rdev)
6498 {
6499 	return rdev->desc->id;
6500 }
6501 EXPORT_SYMBOL_GPL(rdev_get_id);
6502 
6503 struct device *rdev_get_dev(struct regulator_dev *rdev)
6504 {
6505 	return &rdev->dev;
6506 }
6507 EXPORT_SYMBOL_GPL(rdev_get_dev);
6508 
6509 struct regmap *rdev_get_regmap(struct regulator_dev *rdev)
6510 {
6511 	return rdev->regmap;
6512 }
6513 EXPORT_SYMBOL_GPL(rdev_get_regmap);
6514 
6515 void *regulator_get_init_drvdata(struct regulator_init_data *reg_init_data)
6516 {
6517 	return reg_init_data->driver_data;
6518 }
6519 EXPORT_SYMBOL_GPL(regulator_get_init_drvdata);
6520 
6521 #ifdef CONFIG_DEBUG_FS
6522 static int supply_map_show(struct seq_file *sf, void *data)
6523 {
6524 	struct regulator_map *map;
6525 
6526 	list_for_each_entry(map, &regulator_map_list, list) {
6527 		seq_printf(sf, "%s -> %s.%s\n",
6528 				rdev_get_name(map->regulator), map->dev_name,
6529 				map->supply);
6530 	}
6531 
6532 	return 0;
6533 }
6534 DEFINE_SHOW_ATTRIBUTE(supply_map);
6535 
6536 struct summary_data {
6537 	struct seq_file *s;
6538 	struct regulator_dev *parent;
6539 	int level;
6540 };
6541 
6542 static void regulator_summary_show_subtree(struct seq_file *s,
6543 					   struct regulator_dev *rdev,
6544 					   int level);
6545 
6546 static int regulator_summary_show_children(struct device *dev, void *data)
6547 {
6548 	struct regulator_dev *rdev = dev_to_rdev(dev);
6549 	struct summary_data *summary_data = data;
6550 
6551 	if (rdev->supply && rdev->supply->rdev == summary_data->parent)
6552 		regulator_summary_show_subtree(summary_data->s, rdev,
6553 					       summary_data->level + 1);
6554 
6555 	return 0;
6556 }
6557 
6558 static void regulator_summary_show_subtree(struct seq_file *s,
6559 					   struct regulator_dev *rdev,
6560 					   int level)
6561 {
6562 	struct regulation_constraints *c;
6563 	struct regulator *consumer;
6564 	struct summary_data summary_data;
6565 	unsigned int opmode;
6566 
6567 	if (!rdev)
6568 		return;
6569 
6570 	opmode = _regulator_get_mode_unlocked(rdev);
6571 	seq_printf(s, "%*s%-*s %3d %4d %6d %7s ",
6572 		   level * 3 + 1, "",
6573 		   30 - level * 3, rdev_get_name(rdev),
6574 		   rdev->use_count, rdev->open_count, rdev->bypass_count,
6575 		   regulator_opmode_to_str(opmode));
6576 
6577 	seq_printf(s, "%5dmV ", regulator_get_voltage_rdev(rdev) / 1000);
6578 	seq_printf(s, "%5dmA ",
6579 		   _regulator_get_current_limit_unlocked(rdev) / 1000);
6580 
6581 	c = rdev->constraints;
6582 	if (c) {
6583 		switch (rdev->desc->type) {
6584 		case REGULATOR_VOLTAGE:
6585 			seq_printf(s, "%5dmV %5dmV ",
6586 				   c->min_uV / 1000, c->max_uV / 1000);
6587 			break;
6588 		case REGULATOR_CURRENT:
6589 			seq_printf(s, "%5dmA %5dmA ",
6590 				   c->min_uA / 1000, c->max_uA / 1000);
6591 			break;
6592 		}
6593 	}
6594 
6595 	seq_puts(s, "\n");
6596 
6597 	list_for_each_entry(consumer, &rdev->consumer_list, list) {
6598 		if (consumer->dev && consumer->dev->class == &regulator_class)
6599 			continue;
6600 
6601 		seq_printf(s, "%*s%-*s ",
6602 			   (level + 1) * 3 + 1, "",
6603 			   30 - (level + 1) * 3,
6604 			   consumer->supply_name ? consumer->supply_name :
6605 			   consumer->dev ? dev_name(consumer->dev) : "deviceless");
6606 
6607 		switch (rdev->desc->type) {
6608 		case REGULATOR_VOLTAGE:
6609 			seq_printf(s, "%3d %33dmA%c%5dmV %5dmV",
6610 				   consumer->enable_count,
6611 				   consumer->uA_load / 1000,
6612 				   consumer->uA_load && !consumer->enable_count ?
6613 				   '*' : ' ',
6614 				   consumer->voltage[PM_SUSPEND_ON].min_uV / 1000,
6615 				   consumer->voltage[PM_SUSPEND_ON].max_uV / 1000);
6616 			break;
6617 		case REGULATOR_CURRENT:
6618 			break;
6619 		}
6620 
6621 		seq_puts(s, "\n");
6622 	}
6623 
6624 	summary_data.s = s;
6625 	summary_data.level = level;
6626 	summary_data.parent = rdev;
6627 
6628 	class_for_each_device(&regulator_class, NULL, &summary_data,
6629 			      regulator_summary_show_children);
6630 }
6631 
6632 struct summary_lock_data {
6633 	struct ww_acquire_ctx *ww_ctx;
6634 	struct regulator_dev **new_contended_rdev;
6635 	struct regulator_dev **old_contended_rdev;
6636 };
6637 
6638 static int regulator_summary_lock_one(struct device *dev, void *data)
6639 {
6640 	struct regulator_dev *rdev = dev_to_rdev(dev);
6641 	struct summary_lock_data *lock_data = data;
6642 	int ret = 0;
6643 
6644 	if (rdev != *lock_data->old_contended_rdev) {
6645 		ret = regulator_lock_nested(rdev, lock_data->ww_ctx);
6646 
6647 		if (ret == -EDEADLK)
6648 			*lock_data->new_contended_rdev = rdev;
6649 		else
6650 			WARN_ON_ONCE(ret);
6651 	} else {
6652 		*lock_data->old_contended_rdev = NULL;
6653 	}
6654 
6655 	return ret;
6656 }
6657 
6658 static int regulator_summary_unlock_one(struct device *dev, void *data)
6659 {
6660 	struct regulator_dev *rdev = dev_to_rdev(dev);
6661 	struct summary_lock_data *lock_data = data;
6662 
6663 	if (lock_data) {
6664 		if (rdev == *lock_data->new_contended_rdev)
6665 			return -EDEADLK;
6666 	}
6667 
6668 	regulator_unlock(rdev);
6669 
6670 	return 0;
6671 }
6672 
6673 static int regulator_summary_lock_all(struct ww_acquire_ctx *ww_ctx,
6674 				      struct regulator_dev **new_contended_rdev,
6675 				      struct regulator_dev **old_contended_rdev)
6676 {
6677 	struct summary_lock_data lock_data;
6678 	int ret;
6679 
6680 	lock_data.ww_ctx = ww_ctx;
6681 	lock_data.new_contended_rdev = new_contended_rdev;
6682 	lock_data.old_contended_rdev = old_contended_rdev;
6683 
6684 	ret = class_for_each_device(&regulator_class, NULL, &lock_data,
6685 				    regulator_summary_lock_one);
6686 	if (ret)
6687 		class_for_each_device(&regulator_class, NULL, &lock_data,
6688 				      regulator_summary_unlock_one);
6689 
6690 	return ret;
6691 }
6692 
6693 static void regulator_summary_lock(struct ww_acquire_ctx *ww_ctx)
6694 {
6695 	struct regulator_dev *new_contended_rdev = NULL;
6696 	struct regulator_dev *old_contended_rdev = NULL;
6697 	int err;
6698 
6699 	mutex_lock(&regulator_list_mutex);
6700 
6701 	ww_acquire_init(ww_ctx, &regulator_ww_class);
6702 
6703 	do {
6704 		if (new_contended_rdev) {
6705 			ww_mutex_lock_slow(&new_contended_rdev->mutex, ww_ctx);
6706 			old_contended_rdev = new_contended_rdev;
6707 			old_contended_rdev->ref_cnt++;
6708 			old_contended_rdev->mutex_owner = current;
6709 		}
6710 
6711 		err = regulator_summary_lock_all(ww_ctx,
6712 						 &new_contended_rdev,
6713 						 &old_contended_rdev);
6714 
6715 		if (old_contended_rdev)
6716 			regulator_unlock(old_contended_rdev);
6717 
6718 	} while (err == -EDEADLK);
6719 
6720 	ww_acquire_done(ww_ctx);
6721 }
6722 
6723 static void regulator_summary_unlock(struct ww_acquire_ctx *ww_ctx)
6724 {
6725 	class_for_each_device(&regulator_class, NULL, NULL,
6726 			      regulator_summary_unlock_one);
6727 	ww_acquire_fini(ww_ctx);
6728 
6729 	mutex_unlock(&regulator_list_mutex);
6730 }
6731 
6732 static int regulator_summary_show_roots(struct device *dev, void *data)
6733 {
6734 	struct regulator_dev *rdev = dev_to_rdev(dev);
6735 	struct seq_file *s = data;
6736 
6737 	if (!rdev->supply)
6738 		regulator_summary_show_subtree(s, rdev, 0);
6739 
6740 	return 0;
6741 }
6742 
6743 static int regulator_summary_show(struct seq_file *s, void *data)
6744 {
6745 	struct ww_acquire_ctx ww_ctx;
6746 
6747 	seq_puts(s, " regulator                      use open bypass  opmode voltage current     min     max\n");
6748 	seq_puts(s, "---------------------------------------------------------------------------------------\n");
6749 
6750 	regulator_summary_lock(&ww_ctx);
6751 
6752 	class_for_each_device(&regulator_class, NULL, s,
6753 			      regulator_summary_show_roots);
6754 
6755 	regulator_summary_unlock(&ww_ctx);
6756 
6757 	return 0;
6758 }
6759 DEFINE_SHOW_ATTRIBUTE(regulator_summary);
6760 #endif /* CONFIG_DEBUG_FS */
6761 
6762 static int __init regulator_init(void)
6763 {
6764 	int ret;
6765 
6766 	ret = bus_register(&regulator_bus);
6767 	if (ret)
6768 		return ret;
6769 
6770 	ret = class_register(&regulator_class);
6771 	if (ret)
6772 		goto err_class;
6773 
6774 	ret = driver_register(&regulator_bus_driver);
6775 	if (ret)
6776 		goto err_driver;
6777 
6778 	debugfs_root = debugfs_create_dir("regulator", NULL);
6779 	if (IS_ERR(debugfs_root))
6780 		pr_debug("regulator: Failed to create debugfs directory\n");
6781 
6782 #ifdef CONFIG_DEBUG_FS
6783 	debugfs_create_file("supply_map", 0444, debugfs_root, NULL,
6784 			    &supply_map_fops);
6785 
6786 	debugfs_create_file("regulator_summary", 0444, debugfs_root,
6787 			    NULL, &regulator_summary_fops);
6788 #endif
6789 	regulator_dummy_init();
6790 
6791 	regulator_coupler_register(&generic_regulator_coupler);
6792 
6793 	return 0;
6794 
6795 err_driver:
6796 	class_unregister(&regulator_class);
6797 err_class:
6798 	bus_unregister(&regulator_bus);
6799 	return ret;
6800 }
6801 
6802 /* init early to allow our consumers to complete system booting */
6803 core_initcall(regulator_init);
6804 
6805 static int regulator_late_cleanup(struct device *dev, void *data)
6806 {
6807 	struct regulator_dev *rdev = dev_to_rdev(dev);
6808 	struct regulation_constraints *c = rdev->constraints;
6809 	int ret;
6810 
6811 	if (c && c->always_on)
6812 		return 0;
6813 
6814 	if (!regulator_ops_is_valid(rdev, REGULATOR_CHANGE_STATUS))
6815 		return 0;
6816 
6817 	regulator_lock(rdev);
6818 
6819 	if (rdev->use_count)
6820 		goto unlock;
6821 
6822 	/* If reading the status failed, assume that it's off. */
6823 	if (_regulator_is_enabled(rdev) <= 0)
6824 		goto unlock;
6825 
6826 	if (have_full_constraints()) {
6827 		/* We log since this may kill the system if it goes
6828 		 * wrong.
6829 		 */
6830 		rdev_info(rdev, "disabling\n");
6831 		ret = _regulator_do_disable(rdev);
6832 		if (ret != 0)
6833 			rdev_err(rdev, "couldn't disable: %pe\n", ERR_PTR(ret));
6834 	} else {
6835 		/* The intention is that in future we will
6836 		 * assume that full constraints are provided
6837 		 * so warn even if we aren't going to do
6838 		 * anything here.
6839 		 */
6840 		rdev_warn(rdev, "incomplete constraints, leaving on\n");
6841 	}
6842 
6843 unlock:
6844 	regulator_unlock(rdev);
6845 
6846 	return 0;
6847 }
6848 
6849 static bool regulator_ignore_unused;
6850 static int __init regulator_ignore_unused_setup(char *__unused)
6851 {
6852 	regulator_ignore_unused = true;
6853 	return 1;
6854 }
6855 __setup("regulator_ignore_unused", regulator_ignore_unused_setup);
6856 
6857 static void regulator_init_complete_work_function(struct work_struct *work)
6858 {
6859 	/*
6860 	 * For debugging purposes, it may be useful to prevent unused
6861 	 * regulators from being disabled.
6862 	 */
6863 	if (regulator_ignore_unused) {
6864 		pr_warn("regulator: Not disabling unused regulators\n");
6865 		return;
6866 	}
6867 
6868 	/* If we have a full configuration then disable any regulators
6869 	 * we have permission to change the status for and which are
6870 	 * not in use or always_on.  This is effectively the default
6871 	 * for DT and ACPI as they have full constraints.
6872 	 */
6873 	class_for_each_device(&regulator_class, NULL, NULL,
6874 			      regulator_late_cleanup);
6875 }
6876 
6877 static DECLARE_DELAYED_WORK(regulator_init_complete_work,
6878 			    regulator_init_complete_work_function);
6879 
6880 static int __init regulator_init_complete(void)
6881 {
6882 	/*
6883 	 * Since DT doesn't provide an idiomatic mechanism for
6884 	 * enabling full constraints and since it's much more natural
6885 	 * with DT to provide them just assume that a DT enabled
6886 	 * system has full constraints.
6887 	 */
6888 	if (of_have_populated_dt())
6889 		has_full_constraints = true;
6890 
6891 	/*
6892 	 * We punt completion for an arbitrary amount of time since
6893 	 * systems like distros will load many drivers from userspace
6894 	 * so consumers might not always be ready yet, this is
6895 	 * particularly an issue with laptops where this might bounce
6896 	 * the display off then on.  Ideally we'd get a notification
6897 	 * from userspace when this happens but we don't so just wait
6898 	 * a bit and hope we waited long enough.  It'd be better if
6899 	 * we'd only do this on systems that need it, and a kernel
6900 	 * command line option might be useful.
6901 	 */
6902 	schedule_delayed_work(&regulator_init_complete_work,
6903 			      msecs_to_jiffies(30000));
6904 
6905 	return 0;
6906 }
6907 late_initcall_sync(regulator_init_complete);
6908