xref: /freebsd/sys/dev/regulator/regulator.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*-
2  * Copyright 2016 Michal Meloun <mmel@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 #include "opt_platform.h"
29 #include <sys/param.h>
30 #include <sys/conf.h>
31 #include <sys/bus.h>
32 #include <sys/kernel.h>
33 #include <sys/queue.h>
34 #include <sys/kobj.h>
35 #include <sys/malloc.h>
36 #include <sys/mutex.h>
37 #include <sys/limits.h>
38 #include <sys/lock.h>
39 #include <sys/sysctl.h>
40 #include <sys/systm.h>
41 #include <sys/sx.h>
42 
43 #ifdef FDT
44 #include <dev/fdt/fdt_common.h>
45 #include <dev/ofw/ofw_bus.h>
46 #include <dev/ofw/ofw_bus_subr.h>
47 #endif
48 #include <dev/regulator/regulator.h>
49 
50 #ifdef FDT
51 #include "regdev_if.h"
52 #endif
53 
54 SYSCTL_NODE(_hw, OID_AUTO, regulator, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
55     "Regulators");
56 
57 MALLOC_DEFINE(M_REGULATOR, "regulator", "Regulator framework");
58 
59 #define	DIV_ROUND_UP(n,d) howmany(n, d)
60 
61 /* Forward declarations. */
62 struct regulator;
63 struct regnode;
64 
65 typedef TAILQ_HEAD(regnode_list, regnode) regnode_list_t;
66 typedef TAILQ_HEAD(regulator_list, regulator) regulator_list_t;
67 
68 /* Default regulator methods. */
69 static int regnode_method_init(struct regnode *regnode);
70 static int regnode_method_enable(struct regnode *regnode, bool enable,
71     int *udelay);
72 static int regnode_method_status(struct regnode *regnode, int *status);
73 static int regnode_method_set_voltage(struct regnode *regnode, int min_uvolt,
74     int max_uvolt, int *udelay);
75 static int regnode_method_get_voltage(struct regnode *regnode, int *uvolt);
76 static void regulator_constraint(void *dummy);
77 static void regulator_shutdown(void *dummy);
78 
79 /*
80  * Regulator controller methods.
81  */
82 static regnode_method_t regnode_methods[] = {
83 	REGNODEMETHOD(regnode_init,		regnode_method_init),
84 	REGNODEMETHOD(regnode_enable,		regnode_method_enable),
85 	REGNODEMETHOD(regnode_status,		regnode_method_status),
86 	REGNODEMETHOD(regnode_set_voltage,	regnode_method_set_voltage),
87 	REGNODEMETHOD(regnode_get_voltage,	regnode_method_get_voltage),
88 	REGNODEMETHOD(regnode_check_voltage,	regnode_method_check_voltage),
89 
90 	REGNODEMETHOD_END
91 };
92 DEFINE_CLASS_0(regnode, regnode_class, regnode_methods, 0);
93 
94 /*
95  * Regulator node - basic element for modelling SOC and bard power supply
96  * chains. Its contains producer data.
97  */
98 struct regnode {
99 	KOBJ_FIELDS;
100 
101 	TAILQ_ENTRY(regnode)	reglist_link;	/* Global list entry */
102 	regulator_list_t	consumers_list;	/* Consumers list */
103 
104 	/* Cache for already resolved names */
105 	struct regnode		*parent;	/* Resolved parent */
106 
107 	/* Details of this device. */
108 	const char		*name;		/* Globally unique name */
109 	const char		*parent_name;	/* Parent name */
110 
111 	device_t		pdev;		/* Producer device_t */
112 	void			*softc;		/* Producer softc */
113 	intptr_t		id;		/* Per producer unique id */
114 #ifdef FDT
115 	 phandle_t 		ofw_node;	/* OFW node of regulator */
116 #endif
117 	int			flags;		/* REGULATOR_FLAGS_ */
118 	struct sx		lock;		/* Lock for this regulator */
119 	int			ref_cnt;	/* Reference counter */
120 	int			enable_cnt;	/* Enabled counter */
121 
122 	struct regnode_std_param std_param;	/* Standard parameters */
123 
124 	struct sysctl_ctx_list	sysctl_ctx;
125 };
126 
127 /*
128  * Per consumer data, information about how a consumer is using a regulator
129  * node.
130  * A pointer to this structure is used as a handle in the consumer interface.
131  */
132 struct regulator {
133 	device_t		cdev;		/* Consumer device */
134 	struct regnode		*regnode;
135 	TAILQ_ENTRY(regulator)	link;		/* Consumers list entry */
136 
137 	int			enable_cnt;
138 	int 			min_uvolt;	/* Requested uvolt range */
139 	int 			max_uvolt;
140 };
141 
142 /*
143  * Regulator names must be system wide unique.
144  */
145 static regnode_list_t regnode_list = TAILQ_HEAD_INITIALIZER(regnode_list);
146 
147 static struct sx		regnode_topo_lock;
148 SX_SYSINIT(regulator_topology, &regnode_topo_lock, "Regulator topology lock");
149 
150 #define REG_TOPO_SLOCK()	sx_slock(&regnode_topo_lock)
151 #define REG_TOPO_XLOCK()	sx_xlock(&regnode_topo_lock)
152 #define REG_TOPO_UNLOCK()	sx_unlock(&regnode_topo_lock)
153 #define REG_TOPO_ASSERT()	sx_assert(&regnode_topo_lock, SA_LOCKED)
154 #define REG_TOPO_XASSERT() 	sx_assert(&regnode_topo_lock, SA_XLOCKED)
155 
156 #define REGNODE_SLOCK(_sc)	sx_slock(&((_sc)->lock))
157 #define REGNODE_XLOCK(_sc)	sx_xlock(&((_sc)->lock))
158 #define REGNODE_UNLOCK(_sc)	sx_unlock(&((_sc)->lock))
159 
160 SYSINIT(regulator_constraint, SI_SUB_LAST, SI_ORDER_ANY, regulator_constraint,
161     NULL);
162 SYSINIT(regulator_shutdown, SI_SUB_LAST, SI_ORDER_ANY, regulator_shutdown,
163     NULL);
164 
165 static void
166 regulator_constraint(void *dummy)
167 {
168 	struct regnode *entry;
169 	int rv;
170 
171 	REG_TOPO_SLOCK();
172 	TAILQ_FOREACH(entry, &regnode_list, reglist_link) {
173 		rv = regnode_set_constraint(entry);
174 		if (rv != 0 && bootverbose)
175 			printf("regulator: setting constraint on %s failed (%d)\n",
176 			    entry->name, rv);
177 	}
178 	REG_TOPO_UNLOCK();
179 }
180 
181 /*
182  * Disable unused regulator
183  * We run this function at SI_SUB_LAST which mean that every driver that needs
184  * regulator should have already enable them.
185  * All the remaining regulators should be those left enabled by the bootloader
186  * or enable by default by the PMIC.
187  */
188 static void
189 regulator_shutdown(void *dummy)
190 {
191 	struct regnode *entry;
192 	int status, ret;
193 	int disable = 1;
194 
195 	TUNABLE_INT_FETCH("hw.regulator.disable_unused", &disable);
196 	if (!disable)
197 		return;
198 	REG_TOPO_SLOCK();
199 
200 	if (bootverbose)
201 		printf("regulator: shutting down unused regulators\n");
202 	TAILQ_FOREACH(entry, &regnode_list, reglist_link) {
203 		if (!entry->std_param.always_on) {
204 			ret = regnode_status(entry, &status);
205 			if (ret == 0 && status == REGULATOR_STATUS_ENABLED) {
206 				if (bootverbose)
207 					printf("regulator: shutting down %s... ",
208 					    entry->name);
209 				ret = regnode_stop(entry, 0);
210 				if (bootverbose) {
211 					/*
212 					 * Call out busy in particular, here,
213 					 * because it's not unexpected to fail
214 					 * shutdown if the regulator is simply
215 					 * in-use.
216 					 */
217 					if (ret == EBUSY)
218 						printf("busy\n");
219 					else if (ret != 0)
220 						printf("error (%d)\n", ret);
221 					else
222 						printf("ok\n");
223 				}
224 			}
225 		}
226 	}
227 	REG_TOPO_UNLOCK();
228 }
229 
230 /*
231  * sysctl handler
232  */
233 static int
234 regnode_uvolt_sysctl(SYSCTL_HANDLER_ARGS)
235 {
236 	struct regnode *regnode = arg1;
237 	int rv, uvolt;
238 
239 	if (regnode->std_param.min_uvolt == regnode->std_param.max_uvolt) {
240 		uvolt = regnode->std_param.min_uvolt;
241 	} else {
242 		REG_TOPO_SLOCK();
243 		if ((rv = regnode_get_voltage(regnode, &uvolt)) != 0) {
244 			REG_TOPO_UNLOCK();
245 			return (rv);
246 		}
247 		REG_TOPO_UNLOCK();
248 	}
249 
250 	return sysctl_handle_int(oidp, &uvolt, sizeof(uvolt), req);
251 }
252 
253 /* ----------------------------------------------------------------------------
254  *
255  * Default regulator methods for base class.
256  *
257  */
258 static int
259 regnode_method_init(struct regnode *regnode)
260 {
261 
262 	return (0);
263 }
264 
265 static int
266 regnode_method_enable(struct regnode *regnode, bool enable, int *udelay)
267 {
268 
269 	if (!enable)
270 		return (ENXIO);
271 
272 	*udelay = 0;
273 	return (0);
274 }
275 
276 static int
277 regnode_method_status(struct regnode *regnode, int *status)
278 {
279 	*status = REGULATOR_STATUS_ENABLED;
280 	return (0);
281 }
282 
283 static int
284 regnode_method_set_voltage(struct regnode *regnode, int min_uvolt, int max_uvolt,
285     int *udelay)
286 {
287 
288 	if ((min_uvolt > regnode->std_param.max_uvolt) ||
289 	    (max_uvolt < regnode->std_param.min_uvolt))
290 		return (ERANGE);
291 	*udelay = 0;
292 	return (0);
293 }
294 
295 static int
296 regnode_method_get_voltage(struct regnode *regnode, int *uvolt)
297 {
298 
299 	*uvolt = regnode->std_param.min_uvolt +
300 	    (regnode->std_param.max_uvolt - regnode->std_param.min_uvolt) / 2;
301 	return (0);
302 }
303 
304 int
305 regnode_method_check_voltage(struct regnode *regnode, int uvolt)
306 {
307 
308 	if ((uvolt > regnode->std_param.max_uvolt) ||
309 	    (uvolt < regnode->std_param.min_uvolt))
310 		return (ERANGE);
311 	return (0);
312 }
313 
314 /* ----------------------------------------------------------------------------
315  *
316  * Internal functions.
317  *
318  */
319 
320 static struct regnode *
321 regnode_find_by_name(const char *name)
322 {
323 	struct regnode *entry;
324 
325 	REG_TOPO_ASSERT();
326 
327 	TAILQ_FOREACH(entry, &regnode_list, reglist_link) {
328 		if (strcmp(entry->name, name) == 0)
329 			return (entry);
330 	}
331 	return (NULL);
332 }
333 
334 static struct regnode *
335 regnode_find_by_id(device_t dev, intptr_t id)
336 {
337 	struct regnode *entry;
338 
339 	REG_TOPO_ASSERT();
340 
341 	TAILQ_FOREACH(entry, &regnode_list, reglist_link) {
342 		if ((entry->pdev == dev) && (entry->id ==  id))
343 			return (entry);
344 	}
345 
346 	return (NULL);
347 }
348 
349 /*
350  * Create and initialize regulator object, but do not register it.
351  */
352 struct regnode *
353 regnode_create(device_t pdev, regnode_class_t regnode_class,
354     struct regnode_init_def *def)
355 {
356 	struct regnode *regnode;
357 	struct sysctl_oid *regnode_oid;
358 
359 	KASSERT(def->name != NULL, ("regulator name is NULL"));
360 	KASSERT(def->name[0] != '\0', ("regulator name is empty"));
361 
362 	REG_TOPO_SLOCK();
363 	if (regnode_find_by_name(def->name) != NULL)
364 		panic("Duplicated regulator registration: %s\n", def->name);
365 	REG_TOPO_UNLOCK();
366 
367 	/* Create object and initialize it. */
368 	regnode = malloc(sizeof(struct regnode), M_REGULATOR,
369 	    M_WAITOK | M_ZERO);
370 	kobj_init((kobj_t)regnode, (kobj_class_t)regnode_class);
371 	sx_init(&regnode->lock, "Regulator node lock");
372 
373 	/* Allocate softc if required. */
374 	if (regnode_class->size > 0) {
375 		regnode->softc = malloc(regnode_class->size, M_REGULATOR,
376 		    M_WAITOK | M_ZERO);
377 	}
378 
379 
380 	/* Copy all strings unless they're flagged as static. */
381 	if (def->flags & REGULATOR_FLAGS_STATIC) {
382 		regnode->name = def->name;
383 		regnode->parent_name = def->parent_name;
384 	} else {
385 		regnode->name = strdup(def->name, M_REGULATOR);
386 		if (def->parent_name != NULL)
387 			regnode->parent_name = strdup(def->parent_name,
388 			    M_REGULATOR);
389 	}
390 
391 	/* Rest of init. */
392 	TAILQ_INIT(&regnode->consumers_list);
393 	regnode->id = def->id;
394 	regnode->pdev = pdev;
395 	regnode->flags = def->flags;
396 	regnode->parent = NULL;
397 	regnode->std_param = def->std_param;
398 #ifdef FDT
399 	regnode->ofw_node = def->ofw_node;
400 #endif
401 
402 	sysctl_ctx_init(&regnode->sysctl_ctx);
403 	regnode_oid = SYSCTL_ADD_NODE(&regnode->sysctl_ctx,
404 	    SYSCTL_STATIC_CHILDREN(_hw_regulator),
405 	    OID_AUTO, regnode->name,
406 	    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "A regulator node");
407 
408 	SYSCTL_ADD_INT(&regnode->sysctl_ctx,
409 	    SYSCTL_CHILDREN(regnode_oid),
410 	    OID_AUTO, "min_uvolt",
411 	    CTLFLAG_RD, &regnode->std_param.min_uvolt, 0,
412 	    "Minimal voltage (in uV)");
413 	SYSCTL_ADD_INT(&regnode->sysctl_ctx,
414 	    SYSCTL_CHILDREN(regnode_oid),
415 	    OID_AUTO, "max_uvolt",
416 	    CTLFLAG_RD, &regnode->std_param.max_uvolt, 0,
417 	    "Maximal voltage (in uV)");
418 	SYSCTL_ADD_INT(&regnode->sysctl_ctx,
419 	    SYSCTL_CHILDREN(regnode_oid),
420 	    OID_AUTO, "min_uamp",
421 	    CTLFLAG_RD, &regnode->std_param.min_uamp, 0,
422 	    "Minimal amperage (in uA)");
423 	SYSCTL_ADD_INT(&regnode->sysctl_ctx,
424 	    SYSCTL_CHILDREN(regnode_oid),
425 	    OID_AUTO, "max_uamp",
426 	    CTLFLAG_RD, &regnode->std_param.max_uamp, 0,
427 	    "Maximal amperage (in uA)");
428 	SYSCTL_ADD_INT(&regnode->sysctl_ctx,
429 	    SYSCTL_CHILDREN(regnode_oid),
430 	    OID_AUTO, "ramp_delay",
431 	    CTLFLAG_RD, &regnode->std_param.ramp_delay, 0,
432 	    "Ramp delay (in uV/us)");
433 	SYSCTL_ADD_INT(&regnode->sysctl_ctx,
434 	    SYSCTL_CHILDREN(regnode_oid),
435 	    OID_AUTO, "enable_delay",
436 	    CTLFLAG_RD, &regnode->std_param.enable_delay, 0,
437 	    "Enable delay (in us)");
438 	SYSCTL_ADD_INT(&regnode->sysctl_ctx,
439 	    SYSCTL_CHILDREN(regnode_oid),
440 	    OID_AUTO, "enable_cnt",
441 	    CTLFLAG_RD, &regnode->enable_cnt, 0,
442 	    "The regulator enable counter");
443 	SYSCTL_ADD_U8(&regnode->sysctl_ctx,
444 	    SYSCTL_CHILDREN(regnode_oid),
445 	    OID_AUTO, "boot_on",
446 	    CTLFLAG_RD, (uint8_t *) &regnode->std_param.boot_on, 0,
447 	    "Is enabled on boot");
448 	SYSCTL_ADD_U8(&regnode->sysctl_ctx,
449 	    SYSCTL_CHILDREN(regnode_oid),
450 	    OID_AUTO, "always_on",
451 	    CTLFLAG_RD, (uint8_t *)&regnode->std_param.always_on, 0,
452 	    "Is always enabled");
453 
454 	SYSCTL_ADD_PROC(&regnode->sysctl_ctx,
455 	    SYSCTL_CHILDREN(regnode_oid),
456 	    OID_AUTO, "uvolt",
457 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
458 	    regnode, 0, regnode_uvolt_sysctl,
459 	    "I",
460 	    "Current voltage (in uV)");
461 
462 	return (regnode);
463 }
464 
465 /* Register regulator object. */
466 struct regnode *
467 regnode_register(struct regnode *regnode)
468 {
469 	int rv;
470 
471 #ifdef FDT
472 	if (regnode->ofw_node <= 0)
473 		regnode->ofw_node = ofw_bus_get_node(regnode->pdev);
474 	if (regnode->ofw_node <= 0)
475 		return (NULL);
476 #endif
477 
478 	rv = REGNODE_INIT(regnode);
479 	if (rv != 0) {
480 		printf("REGNODE_INIT failed: %d\n", rv);
481 		return (NULL);
482 	}
483 
484 	REG_TOPO_XLOCK();
485 	TAILQ_INSERT_TAIL(&regnode_list, regnode, reglist_link);
486 	REG_TOPO_UNLOCK();
487 #ifdef FDT
488 	OF_device_register_xref(OF_xref_from_node(regnode->ofw_node),
489 	    regnode->pdev);
490 #endif
491 	return (regnode);
492 }
493 
494 static int
495 regnode_resolve_parent(struct regnode *regnode)
496 {
497 
498 	/* All ready resolved or no parent? */
499 	if ((regnode->parent != NULL) ||
500 	    (regnode->parent_name == NULL))
501 		return (0);
502 
503 	regnode->parent = regnode_find_by_name(regnode->parent_name);
504 	if (regnode->parent == NULL)
505 		return (ENODEV);
506 	return (0);
507 }
508 
509 static void
510 regnode_delay(int usec)
511 {
512 	int ticks;
513 
514 	if (usec == 0)
515 		return;
516 	ticks = (usec * hz + 999999) / 1000000;
517 
518 	if (cold || ticks < 2)
519 		DELAY(usec);
520 	else
521 		pause("REGULATOR", ticks);
522 }
523 
524 /* --------------------------------------------------------------------------
525  *
526  * Regulator providers interface
527  *
528  */
529 
530 const char *
531 regnode_get_name(struct regnode *regnode)
532 {
533 
534 	return (regnode->name);
535 }
536 
537 const char *
538 regnode_get_parent_name(struct regnode *regnode)
539 {
540 
541 	return (regnode->parent_name);
542 }
543 
544 int
545 regnode_get_flags(struct regnode *regnode)
546 {
547 
548 	return (regnode->flags);
549 }
550 
551 void *
552 regnode_get_softc(struct regnode *regnode)
553 {
554 
555 	return (regnode->softc);
556 }
557 
558 device_t
559 regnode_get_device(struct regnode *regnode)
560 {
561 
562 	return (regnode->pdev);
563 }
564 
565 struct regnode_std_param *regnode_get_stdparam(struct regnode *regnode)
566 {
567 
568 	return (&regnode->std_param);
569 }
570 
571 void regnode_topo_unlock(void)
572 {
573 
574 	REG_TOPO_UNLOCK();
575 }
576 
577 void regnode_topo_xlock(void)
578 {
579 
580 	REG_TOPO_XLOCK();
581 }
582 
583 void regnode_topo_slock(void)
584 {
585 
586 	REG_TOPO_SLOCK();
587 }
588 
589 
590 /* --------------------------------------------------------------------------
591  *
592  * Real consumers executive
593  *
594  */
595 struct regnode *
596 regnode_get_parent(struct regnode *regnode)
597 {
598 	int rv;
599 
600 	REG_TOPO_ASSERT();
601 
602 	rv = regnode_resolve_parent(regnode);
603 	if (rv != 0)
604 		return (NULL);
605 
606 	return (regnode->parent);
607 }
608 
609 /*
610  * Enable regulator.
611  */
612 int
613 regnode_enable(struct regnode *regnode)
614 {
615 	int udelay;
616 	int rv;
617 
618 	REG_TOPO_ASSERT();
619 
620 	/* Enable regulator for each node in chain, starting from source. */
621 	rv = regnode_resolve_parent(regnode);
622 	if (rv != 0)
623 		return (rv);
624 	if (regnode->parent != NULL) {
625 		rv = regnode_enable(regnode->parent);
626 		if (rv != 0)
627 			return (rv);
628 	}
629 
630 	/* Handle this node. */
631 	REGNODE_XLOCK(regnode);
632 	if (regnode->enable_cnt == 0) {
633 		rv = REGNODE_ENABLE(regnode, true, &udelay);
634 		if (rv != 0) {
635 			REGNODE_UNLOCK(regnode);
636 			return (rv);
637 		}
638 		regnode_delay(udelay);
639 	}
640 	regnode->enable_cnt++;
641 	REGNODE_UNLOCK(regnode);
642 	return (0);
643 }
644 
645 /*
646  * Disable regulator.
647  */
648 int
649 regnode_disable(struct regnode *regnode)
650 {
651 	int udelay;
652 	int rv;
653 
654 	REG_TOPO_ASSERT();
655 	rv = 0;
656 
657 	REGNODE_XLOCK(regnode);
658 	/* Disable regulator for each node in chain, starting from consumer. */
659 	if (regnode->enable_cnt == 1 &&
660 	    (regnode->flags & REGULATOR_FLAGS_NOT_DISABLE) == 0 &&
661 	    !regnode->std_param.always_on) {
662 		rv = REGNODE_ENABLE(regnode, false, &udelay);
663 		if (rv != 0) {
664 			REGNODE_UNLOCK(regnode);
665 			return (rv);
666 		}
667 		regnode_delay(udelay);
668 	}
669 	regnode->enable_cnt--;
670 	REGNODE_UNLOCK(regnode);
671 
672 	rv = regnode_resolve_parent(regnode);
673 	if (rv != 0)
674 		return (rv);
675 	if (regnode->parent != NULL)
676 		rv = regnode_disable(regnode->parent);
677 	return (rv);
678 }
679 
680 /*
681  * Stop regulator.
682  */
683 int
684 regnode_stop(struct regnode *regnode, int depth)
685 {
686 	int udelay;
687 	int rv;
688 
689 	REG_TOPO_ASSERT();
690 	rv = 0;
691 
692 	REGNODE_XLOCK(regnode);
693 	/* The first node must not be enabled. */
694 	if ((regnode->enable_cnt != 0) && (depth == 0)) {
695 		REGNODE_UNLOCK(regnode);
696 		return (EBUSY);
697 	}
698 	/* Disable regulator for each node in chain, starting from consumer */
699 	if ((regnode->enable_cnt == 0) &&
700 	    ((regnode->flags & REGULATOR_FLAGS_NOT_DISABLE) == 0)) {
701 		rv = REGNODE_STOP(regnode, &udelay);
702 		if (rv != 0) {
703 			REGNODE_UNLOCK(regnode);
704 			return (rv);
705 		}
706 		regnode_delay(udelay);
707 	}
708 	REGNODE_UNLOCK(regnode);
709 
710 	rv = regnode_resolve_parent(regnode);
711 	if (rv != 0)
712 		return (rv);
713 	if (regnode->parent != NULL && regnode->parent->enable_cnt == 0)
714 		rv = regnode_stop(regnode->parent, depth + 1);
715 	return (rv);
716 }
717 
718 /*
719  * Get regulator status. (REGULATOR_STATUS_*)
720  */
721 int
722 regnode_status(struct regnode *regnode, int *status)
723 {
724 	int rv;
725 
726 	REG_TOPO_ASSERT();
727 
728 	REGNODE_XLOCK(regnode);
729 	rv = REGNODE_STATUS(regnode, status);
730 	REGNODE_UNLOCK(regnode);
731 	return (rv);
732 }
733 
734 /*
735  * Get actual regulator voltage.
736  */
737 int
738 regnode_get_voltage(struct regnode *regnode, int *uvolt)
739 {
740 	int rv;
741 
742 	REG_TOPO_ASSERT();
743 
744 	REGNODE_XLOCK(regnode);
745 	rv = REGNODE_GET_VOLTAGE(regnode, uvolt);
746 	REGNODE_UNLOCK(regnode);
747 
748 	/* Pass call into parent, if regulator is in bypass mode. */
749 	if (rv == ENOENT) {
750 		rv = regnode_resolve_parent(regnode);
751 		if (rv != 0)
752 			return (rv);
753 		if (regnode->parent != NULL)
754 			rv = regnode_get_voltage(regnode->parent, uvolt);
755 
756 	}
757 	return (rv);
758 }
759 
760 /*
761  * Set regulator voltage.
762  */
763 int
764 regnode_set_voltage(struct regnode *regnode, int min_uvolt, int max_uvolt)
765 {
766 	int udelay;
767 	int rv;
768 
769 	REG_TOPO_ASSERT();
770 
771 	REGNODE_XLOCK(regnode);
772 
773 	rv = REGNODE_SET_VOLTAGE(regnode, min_uvolt, max_uvolt, &udelay);
774 	if (rv == 0)
775 		regnode_delay(udelay);
776 	REGNODE_UNLOCK(regnode);
777 	return (rv);
778 }
779 
780 /*
781  * Consumer variant of regnode_set_voltage().
782  */
783 static int
784 regnode_set_voltage_checked(struct regnode *regnode, struct regulator *reg,
785     int min_uvolt, int max_uvolt)
786 {
787 	int udelay;
788 	int all_max_uvolt;
789 	int all_min_uvolt;
790 	struct regulator *tmp;
791 	int rv;
792 
793 	REG_TOPO_ASSERT();
794 
795 	REGNODE_XLOCK(regnode);
796 	/* Return error if requested range is outside of regulator range. */
797 	if ((min_uvolt > regnode->std_param.max_uvolt) ||
798 	    (max_uvolt < regnode->std_param.min_uvolt)) {
799 		REGNODE_UNLOCK(regnode);
800 		return (ERANGE);
801 	}
802 
803 	/* Get actual voltage range for all consumers. */
804 	all_min_uvolt = regnode->std_param.min_uvolt;
805 	all_max_uvolt = regnode->std_param.max_uvolt;
806 	TAILQ_FOREACH(tmp, &regnode->consumers_list, link) {
807 		/* Don't take requestor in account. */
808 		if (tmp == reg)
809 			continue;
810 		if (all_min_uvolt < tmp->min_uvolt)
811 			all_min_uvolt = tmp->min_uvolt;
812 		if (all_max_uvolt > tmp->max_uvolt)
813 			all_max_uvolt = tmp->max_uvolt;
814 	}
815 
816 	/* Test if request fits to actual contract. */
817 	if ((min_uvolt > all_max_uvolt) ||
818 	    (max_uvolt < all_min_uvolt)) {
819 		REGNODE_UNLOCK(regnode);
820 		return (ERANGE);
821 	}
822 
823 	/* Adjust new range.*/
824 	if (min_uvolt < all_min_uvolt)
825 		min_uvolt = all_min_uvolt;
826 	if (max_uvolt > all_max_uvolt)
827 		max_uvolt = all_max_uvolt;
828 
829 	rv = REGNODE_SET_VOLTAGE(regnode, min_uvolt, max_uvolt, &udelay);
830 	regnode_delay(udelay);
831 	REGNODE_UNLOCK(regnode);
832 	return (rv);
833 }
834 
835 int
836 regnode_set_constraint(struct regnode *regnode)
837 {
838 	int status, rv, uvolt;
839 
840 	if (regnode->std_param.boot_on != true &&
841 	    regnode->std_param.always_on != true)
842 		return (0);
843 
844 	rv = regnode_status(regnode, &status);
845 	if (rv != 0) {
846 		if (bootverbose)
847 			printf("Cannot get regulator status for %s\n",
848 			    regnode_get_name(regnode));
849 		return (rv);
850 	}
851 
852 	if (status == REGULATOR_STATUS_ENABLED)
853 		return (0);
854 
855 	rv = regnode_get_voltage(regnode, &uvolt);
856 	if (rv != 0) {
857 		if (bootverbose)
858 			printf("Cannot get regulator voltage for %s\n",
859 			    regnode_get_name(regnode));
860 		return (rv);
861 	}
862 
863 	if (uvolt < regnode->std_param.min_uvolt ||
864 	  uvolt > regnode->std_param.max_uvolt) {
865 		if (bootverbose)
866 			printf("Regulator %s current voltage %d is not in the"
867 			    " acceptable range : %d<->%d\n",
868 			    regnode_get_name(regnode),
869 			    uvolt, regnode->std_param.min_uvolt,
870 			    regnode->std_param.max_uvolt);
871 		return (ERANGE);
872 	}
873 
874 	rv = regnode_enable(regnode);
875 	if (rv != 0) {
876 		if (bootverbose)
877 			printf("Cannot enable regulator %s\n",
878 			    regnode_get_name(regnode));
879 		return (rv);
880 	}
881 
882 	return (0);
883 }
884 
885 #ifdef FDT
886 phandle_t
887 regnode_get_ofw_node(struct regnode *regnode)
888 {
889 
890 	return (regnode->ofw_node);
891 }
892 #endif
893 
894 /* --------------------------------------------------------------------------
895  *
896  * Regulator consumers interface.
897  *
898  */
899 /* Helper function for regulator_get*() */
900 static regulator_t
901 regulator_create(struct regnode *regnode, device_t cdev)
902 {
903 	struct regulator *reg;
904 
905 	REG_TOPO_ASSERT();
906 
907 	reg =  malloc(sizeof(struct regulator), M_REGULATOR,
908 	    M_WAITOK | M_ZERO);
909 	reg->cdev = cdev;
910 	reg->regnode = regnode;
911 	reg->enable_cnt = 0;
912 
913 	REGNODE_XLOCK(regnode);
914 	regnode->ref_cnt++;
915 	TAILQ_INSERT_TAIL(&regnode->consumers_list, reg, link);
916 	reg ->min_uvolt = regnode->std_param.min_uvolt;
917 	reg ->max_uvolt = regnode->std_param.max_uvolt;
918 	REGNODE_UNLOCK(regnode);
919 
920 	return (reg);
921 }
922 
923 int
924 regulator_enable(regulator_t reg)
925 {
926 	int rv;
927 	struct regnode *regnode;
928 
929 	regnode = reg->regnode;
930 	KASSERT(regnode->ref_cnt > 0,
931 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
932 	REG_TOPO_SLOCK();
933 	rv = regnode_enable(regnode);
934 	if (rv == 0)
935 		reg->enable_cnt++;
936 	REG_TOPO_UNLOCK();
937 	return (rv);
938 }
939 
940 int
941 regulator_disable(regulator_t reg)
942 {
943 	int rv;
944 	struct regnode *regnode;
945 
946 	regnode = reg->regnode;
947 	KASSERT(regnode->ref_cnt > 0,
948 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
949 	KASSERT(reg->enable_cnt > 0,
950 	   ("Attempt to disable already disabled regulator: %s\n",
951 	   regnode->name));
952 	REG_TOPO_SLOCK();
953 	rv = regnode_disable(regnode);
954 	if (rv == 0)
955 		reg->enable_cnt--;
956 	REG_TOPO_UNLOCK();
957 	return (rv);
958 }
959 
960 int
961 regulator_stop(regulator_t reg)
962 {
963 	int rv;
964 	struct regnode *regnode;
965 
966 	regnode = reg->regnode;
967 	KASSERT(regnode->ref_cnt > 0,
968 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
969 	KASSERT(reg->enable_cnt == 0,
970 	   ("Attempt to stop already enabled regulator: %s\n", regnode->name));
971 
972 	REG_TOPO_SLOCK();
973 	rv = regnode_stop(regnode, 0);
974 	REG_TOPO_UNLOCK();
975 	return (rv);
976 }
977 
978 int
979 regulator_status(regulator_t reg, int *status)
980 {
981 	int rv;
982 	struct regnode *regnode;
983 
984 	regnode = reg->regnode;
985 	KASSERT(regnode->ref_cnt > 0,
986 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
987 
988 	if (reg->enable_cnt == 0) {
989 		*status = 0;
990 		return (0);
991 	}
992 	REG_TOPO_SLOCK();
993 	rv = regnode_status(regnode, status);
994 	REG_TOPO_UNLOCK();
995 	return (rv);
996 }
997 
998 int
999 regulator_get_voltage(regulator_t reg, int *uvolt)
1000 {
1001 	int rv;
1002 	struct regnode *regnode;
1003 
1004 	regnode = reg->regnode;
1005 	KASSERT(regnode->ref_cnt > 0,
1006 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
1007 
1008 	REG_TOPO_SLOCK();
1009 	rv = regnode_get_voltage(regnode, uvolt);
1010 	REG_TOPO_UNLOCK();
1011 	return (rv);
1012 }
1013 
1014 int
1015 regulator_set_voltage(regulator_t reg, int min_uvolt, int max_uvolt)
1016 {
1017 	struct regnode *regnode;
1018 	int rv;
1019 
1020 	regnode = reg->regnode;
1021 	KASSERT(regnode->ref_cnt > 0,
1022 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
1023 
1024 	REG_TOPO_SLOCK();
1025 
1026 	rv = regnode_set_voltage_checked(regnode, reg, min_uvolt, max_uvolt);
1027 	if (rv == 0) {
1028 		reg->min_uvolt = min_uvolt;
1029 		reg->max_uvolt = max_uvolt;
1030 	}
1031 	REG_TOPO_UNLOCK();
1032 	return (rv);
1033 }
1034 
1035 int
1036 regulator_check_voltage(regulator_t reg, int uvolt)
1037 {
1038 	int rv;
1039 	struct regnode *regnode;
1040 
1041 	regnode = reg->regnode;
1042 	KASSERT(regnode->ref_cnt > 0,
1043 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
1044 
1045 	REG_TOPO_SLOCK();
1046 	rv = REGNODE_CHECK_VOLTAGE(regnode, uvolt);
1047 	REG_TOPO_UNLOCK();
1048 	return (rv);
1049 }
1050 
1051 const char *
1052 regulator_get_name(regulator_t reg)
1053 {
1054 	struct regnode *regnode;
1055 
1056 	regnode = reg->regnode;
1057 	KASSERT(regnode->ref_cnt > 0,
1058 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
1059 	return (regnode->name);
1060 }
1061 
1062 int
1063 regulator_get_by_name(device_t cdev, const char *name, regulator_t *reg)
1064 {
1065 	struct regnode *regnode;
1066 
1067 	REG_TOPO_SLOCK();
1068 	regnode = regnode_find_by_name(name);
1069 	if (regnode == NULL) {
1070 		REG_TOPO_UNLOCK();
1071 		return (ENODEV);
1072 	}
1073 	*reg = regulator_create(regnode, cdev);
1074 	REG_TOPO_UNLOCK();
1075 	return (0);
1076 }
1077 
1078 int
1079 regulator_get_by_id(device_t cdev, device_t pdev, intptr_t id, regulator_t *reg)
1080 {
1081 	struct regnode *regnode;
1082 
1083 	REG_TOPO_SLOCK();
1084 
1085 	regnode = regnode_find_by_id(pdev, id);
1086 	if (regnode == NULL) {
1087 		REG_TOPO_UNLOCK();
1088 		return (ENODEV);
1089 	}
1090 	*reg = regulator_create(regnode, cdev);
1091 	REG_TOPO_UNLOCK();
1092 
1093 	return (0);
1094 }
1095 
1096 int
1097 regulator_release(regulator_t reg)
1098 {
1099 	struct regnode *regnode;
1100 
1101 	regnode = reg->regnode;
1102 	KASSERT(regnode->ref_cnt > 0,
1103 	   ("Attempt to access unreferenced regulator: %s\n", regnode->name));
1104 	REG_TOPO_SLOCK();
1105 	while (reg->enable_cnt > 0) {
1106 		regnode_disable(regnode);
1107 		reg->enable_cnt--;
1108 	}
1109 	REGNODE_XLOCK(regnode);
1110 	TAILQ_REMOVE(&regnode->consumers_list, reg, link);
1111 	regnode->ref_cnt--;
1112 	REGNODE_UNLOCK(regnode);
1113 	REG_TOPO_UNLOCK();
1114 
1115 	free(reg, M_REGULATOR);
1116 	return (0);
1117 }
1118 
1119 #ifdef FDT
1120 /* Default DT mapper. */
1121 int
1122 regdev_default_ofw_map(device_t dev, phandle_t 	xref, int ncells,
1123     pcell_t *cells, intptr_t *id)
1124 {
1125 	if (ncells == 0)
1126 		*id = 1;
1127 	else if (ncells == 1)
1128 		*id = cells[0];
1129 	else
1130 		return  (ERANGE);
1131 
1132 	return (0);
1133 }
1134 
1135 int
1136 regulator_parse_ofw_stdparam(device_t pdev, phandle_t node,
1137     struct regnode_init_def *def)
1138 {
1139 	phandle_t supply_xref;
1140 	struct regnode_std_param *par;
1141 	int rv;
1142 
1143 	par = &def->std_param;
1144 	rv = OF_getprop_alloc(node, "regulator-name",
1145 	    (void **)&def->name);
1146 	if (rv <= 0) {
1147 		device_printf(pdev, "%s: Missing regulator name\n",
1148 		 __func__);
1149 		return (ENXIO);
1150 	}
1151 
1152 	rv = OF_getencprop(node, "regulator-min-microvolt", &par->min_uvolt,
1153 	    sizeof(par->min_uvolt));
1154 	if (rv <= 0)
1155 		par->min_uvolt = 0;
1156 
1157 	rv = OF_getencprop(node, "regulator-max-microvolt", &par->max_uvolt,
1158 	    sizeof(par->max_uvolt));
1159 	if (rv <= 0)
1160 		par->max_uvolt = 0;
1161 
1162 	rv = OF_getencprop(node, "regulator-min-microamp", &par->min_uamp,
1163 	    sizeof(par->min_uamp));
1164 	if (rv <= 0)
1165 		par->min_uamp = 0;
1166 
1167 	rv = OF_getencprop(node, "regulator-max-microamp", &par->max_uamp,
1168 	    sizeof(par->max_uamp));
1169 	if (rv <= 0)
1170 		par->max_uamp = 0;
1171 
1172 	rv = OF_getencprop(node, "regulator-ramp-delay", &par->ramp_delay,
1173 	    sizeof(par->ramp_delay));
1174 	if (rv <= 0)
1175 		par->ramp_delay = 0;
1176 
1177 	rv = OF_getencprop(node, "regulator-enable-ramp-delay",
1178 	    &par->enable_delay, sizeof(par->enable_delay));
1179 	if (rv <= 0)
1180 		par->enable_delay = 0;
1181 
1182 	if (OF_hasprop(node, "regulator-boot-on"))
1183 		par->boot_on = true;
1184 
1185 	if (OF_hasprop(node, "regulator-always-on"))
1186 		par->always_on = true;
1187 
1188 	if (OF_hasprop(node, "enable-active-high"))
1189 		par->enable_active_high = 1;
1190 
1191 	rv = OF_getencprop(node, "vin-supply", &supply_xref,
1192 	    sizeof(supply_xref));
1193 	if (rv >=  0) {
1194 		rv = OF_getprop_alloc(supply_xref, "regulator-name",
1195 		    (void **)&def->parent_name);
1196 		if (rv <= 0)
1197 			def->parent_name = NULL;
1198 	}
1199 	return (0);
1200 }
1201 
1202 int
1203 regulator_get_by_ofw_property(device_t cdev, phandle_t cnode, char *name,
1204     regulator_t *reg)
1205 {
1206 	phandle_t *cells;
1207 	device_t regdev;
1208 	int ncells, rv;
1209 	intptr_t id;
1210 
1211 	*reg = NULL;
1212 
1213 	if (cnode <= 0)
1214 		cnode = ofw_bus_get_node(cdev);
1215 	if (cnode <= 0) {
1216 		device_printf(cdev, "%s called on not ofw based device\n",
1217 		 __func__);
1218 		return (ENXIO);
1219 	}
1220 
1221 	cells = NULL;
1222 	ncells = OF_getencprop_alloc_multi(cnode, name, sizeof(*cells),
1223 	    (void **)&cells);
1224 	if (ncells <= 0)
1225 		return (ENOENT);
1226 
1227 	/* Translate xref to device */
1228 	regdev = OF_device_from_xref(cells[0]);
1229 	if (regdev == NULL) {
1230 		OF_prop_free(cells);
1231 		return (ENODEV);
1232 	}
1233 
1234 	/* Map regulator to number */
1235 	rv = REGDEV_MAP(regdev, cells[0], ncells - 1, cells + 1, &id);
1236 	OF_prop_free(cells);
1237 	if (rv != 0)
1238 		return (rv);
1239 	return (regulator_get_by_id(cdev, regdev, id, reg));
1240 }
1241 #endif
1242 
1243 /* --------------------------------------------------------------------------
1244  *
1245  * Regulator utility functions.
1246  *
1247  */
1248 
1249 /* Convert raw selector value to real voltage */
1250 int
1251 regulator_range_sel8_to_volt(struct regulator_range *ranges, int nranges,
1252    uint8_t sel, int *volt)
1253 {
1254 	struct regulator_range *range;
1255 	int i;
1256 
1257 	if (nranges == 0)
1258 		panic("Voltage regulator have zero ranges\n");
1259 
1260 	for (i = 0; i < nranges ; i++) {
1261 		range = ranges  + i;
1262 
1263 		if (!(sel >= range->min_sel &&
1264 		      sel <= range->max_sel))
1265 			continue;
1266 
1267 		sel -= range->min_sel;
1268 
1269 		*volt = range->min_uvolt + sel * range->step_uvolt;
1270 		return (0);
1271 	}
1272 
1273 	return (ERANGE);
1274 }
1275 
1276 int
1277 regulator_range_volt_to_sel8(struct regulator_range *ranges, int nranges,
1278     int min_uvolt, int max_uvolt, uint8_t *out_sel)
1279 {
1280 	struct regulator_range *range;
1281 	uint8_t sel;
1282 	int uvolt;
1283 	int rv, i;
1284 
1285 	if (nranges == 0)
1286 		panic("Voltage regulator have zero ranges\n");
1287 
1288 	for (i = 0; i < nranges; i++) {
1289 		range = ranges  + i;
1290 		uvolt = range->min_uvolt +
1291 		    (range->max_sel - range->min_sel) * range->step_uvolt;
1292 
1293 		if ((min_uvolt > uvolt) ||
1294 		    (max_uvolt < range->min_uvolt))
1295 			continue;
1296 
1297 		if (min_uvolt <= range->min_uvolt)
1298 			min_uvolt = range->min_uvolt;
1299 
1300 		/* if step == 0 -> fixed voltage range. */
1301 		if (range->step_uvolt == 0)
1302 			sel = 0;
1303 		else
1304 			sel = DIV_ROUND_UP(min_uvolt - range->min_uvolt,
1305 			   range->step_uvolt);
1306 
1307 
1308 		sel += range->min_sel;
1309 
1310 		break;
1311 	}
1312 
1313 	if (i >= nranges)
1314 		return (ERANGE);
1315 
1316 	/* Verify new settings. */
1317 	rv = regulator_range_sel8_to_volt(ranges, nranges, sel, &uvolt);
1318 	if (rv != 0)
1319 		return (rv);
1320 	if ((uvolt < min_uvolt) || (uvolt > max_uvolt))
1321 		return (ERANGE);
1322 
1323 	*out_sel = sel;
1324 	return (0);
1325 }
1326