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