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