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