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