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