xref: /openbmc/linux/drivers/gpio/gpiolib-of.c (revision 4c5a116a)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * OF helpers for the GPIO API
4  *
5  * Copyright (c) 2007-2008  MontaVista Software, Inc.
6  *
7  * Author: Anton Vorontsov <avorontsov@ru.mvista.com>
8  */
9 
10 #include <linux/device.h>
11 #include <linux/err.h>
12 #include <linux/errno.h>
13 #include <linux/module.h>
14 #include <linux/io.h>
15 #include <linux/gpio/consumer.h>
16 #include <linux/of.h>
17 #include <linux/of_address.h>
18 #include <linux/of_gpio.h>
19 #include <linux/pinctrl/pinctrl.h>
20 #include <linux/slab.h>
21 #include <linux/gpio/machine.h>
22 
23 #include "gpiolib.h"
24 #include "gpiolib-of.h"
25 
26 /**
27  * of_gpio_spi_cs_get_count() - special GPIO counting for SPI
28  * Some elder GPIO controllers need special quirks. Currently we handle
29  * the Freescale and PPC GPIO controller with bindings that doesn't use the
30  * established "cs-gpios" for chip selects but instead rely on
31  * "gpios" for the chip select lines. If we detect this, we redirect
32  * the counting of "cs-gpios" to count "gpios" transparent to the
33  * driver.
34  */
35 static int of_gpio_spi_cs_get_count(struct device *dev, const char *con_id)
36 {
37 	struct device_node *np = dev->of_node;
38 
39 	if (!IS_ENABLED(CONFIG_SPI_MASTER))
40 		return 0;
41 	if (!con_id || strcmp(con_id, "cs"))
42 		return 0;
43 	if (!of_device_is_compatible(np, "fsl,spi") &&
44 	    !of_device_is_compatible(np, "aeroflexgaisler,spictrl") &&
45 	    !of_device_is_compatible(np, "ibm,ppc4xx-spi"))
46 		return 0;
47 	return of_gpio_named_count(np, "gpios");
48 }
49 
50 /*
51  * This is used by external users of of_gpio_count() from <linux/of_gpio.h>
52  *
53  * FIXME: get rid of those external users by converting them to GPIO
54  * descriptors and let them all use gpiod_count()
55  */
56 int of_gpio_get_count(struct device *dev, const char *con_id)
57 {
58 	int ret;
59 	char propname[32];
60 	unsigned int i;
61 
62 	ret = of_gpio_spi_cs_get_count(dev, con_id);
63 	if (ret > 0)
64 		return ret;
65 
66 	for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
67 		if (con_id)
68 			snprintf(propname, sizeof(propname), "%s-%s",
69 				 con_id, gpio_suffixes[i]);
70 		else
71 			snprintf(propname, sizeof(propname), "%s",
72 				 gpio_suffixes[i]);
73 
74 		ret = of_gpio_named_count(dev->of_node, propname);
75 		if (ret > 0)
76 			break;
77 	}
78 	return ret ? ret : -ENOENT;
79 }
80 
81 static int of_gpiochip_match_node_and_xlate(struct gpio_chip *chip, void *data)
82 {
83 	struct of_phandle_args *gpiospec = data;
84 
85 	return chip->gpiodev->dev.of_node == gpiospec->np &&
86 				chip->of_xlate &&
87 				chip->of_xlate(chip, gpiospec, NULL) >= 0;
88 }
89 
90 static struct gpio_chip *of_find_gpiochip_by_xlate(
91 					struct of_phandle_args *gpiospec)
92 {
93 	return gpiochip_find(gpiospec, of_gpiochip_match_node_and_xlate);
94 }
95 
96 static struct gpio_desc *of_xlate_and_get_gpiod_flags(struct gpio_chip *chip,
97 					struct of_phandle_args *gpiospec,
98 					enum of_gpio_flags *flags)
99 {
100 	int ret;
101 
102 	if (chip->of_gpio_n_cells != gpiospec->args_count)
103 		return ERR_PTR(-EINVAL);
104 
105 	ret = chip->of_xlate(chip, gpiospec, flags);
106 	if (ret < 0)
107 		return ERR_PTR(ret);
108 
109 	return gpiochip_get_desc(chip, ret);
110 }
111 
112 /**
113  * of_gpio_need_valid_mask() - figure out if the OF GPIO driver needs
114  * to set the .valid_mask
115  * @gc: the target gpio_chip
116  *
117  * Return: true if the valid mask needs to be set
118  */
119 bool of_gpio_need_valid_mask(const struct gpio_chip *gc)
120 {
121 	int size;
122 	struct device_node *np = gc->of_node;
123 
124 	size = of_property_count_u32_elems(np,  "gpio-reserved-ranges");
125 	if (size > 0 && size % 2 == 0)
126 		return true;
127 	return false;
128 }
129 
130 static void of_gpio_flags_quirks(struct device_node *np,
131 				 const char *propname,
132 				 enum of_gpio_flags *flags,
133 				 int index)
134 {
135 	/*
136 	 * Some GPIO fixed regulator quirks.
137 	 * Note that active low is the default.
138 	 */
139 	if (IS_ENABLED(CONFIG_REGULATOR) &&
140 	    (of_device_is_compatible(np, "regulator-fixed") ||
141 	     of_device_is_compatible(np, "reg-fixed-voltage") ||
142 	     (!(strcmp(propname, "enable-gpio") &&
143 		strcmp(propname, "enable-gpios")) &&
144 	      of_device_is_compatible(np, "regulator-gpio")))) {
145 		bool active_low = !of_property_read_bool(np,
146 							 "enable-active-high");
147 		/*
148 		 * The regulator GPIO handles are specified such that the
149 		 * presence or absence of "enable-active-high" solely controls
150 		 * the polarity of the GPIO line. Any phandle flags must
151 		 * be actively ignored.
152 		 */
153 		if ((*flags & OF_GPIO_ACTIVE_LOW) && !active_low) {
154 			pr_warn("%s GPIO handle specifies active low - ignored\n",
155 				of_node_full_name(np));
156 			*flags &= ~OF_GPIO_ACTIVE_LOW;
157 		}
158 		if (active_low)
159 			*flags |= OF_GPIO_ACTIVE_LOW;
160 	}
161 	/*
162 	 * Legacy open drain handling for fixed voltage regulators.
163 	 */
164 	if (IS_ENABLED(CONFIG_REGULATOR) &&
165 	    of_device_is_compatible(np, "reg-fixed-voltage") &&
166 	    of_property_read_bool(np, "gpio-open-drain")) {
167 		*flags |= (OF_GPIO_SINGLE_ENDED | OF_GPIO_OPEN_DRAIN);
168 		pr_info("%s uses legacy open drain flag - update the DTS if you can\n",
169 			of_node_full_name(np));
170 	}
171 
172 	/*
173 	 * Legacy handling of SPI active high chip select. If we have a
174 	 * property named "cs-gpios" we need to inspect the child node
175 	 * to determine if the flags should have inverted semantics.
176 	 */
177 	if (IS_ENABLED(CONFIG_SPI_MASTER) && !strcmp(propname, "cs-gpios") &&
178 	    of_property_read_bool(np, "cs-gpios")) {
179 		struct device_node *child;
180 		u32 cs;
181 		int ret;
182 
183 		for_each_child_of_node(np, child) {
184 			ret = of_property_read_u32(child, "reg", &cs);
185 			if (ret)
186 				continue;
187 			if (cs == index) {
188 				/*
189 				 * SPI children have active low chip selects
190 				 * by default. This can be specified negatively
191 				 * by just omitting "spi-cs-high" in the
192 				 * device node, or actively by tagging on
193 				 * GPIO_ACTIVE_LOW as flag in the device
194 				 * tree. If the line is simultaneously
195 				 * tagged as active low in the device tree
196 				 * and has the "spi-cs-high" set, we get a
197 				 * conflict and the "spi-cs-high" flag will
198 				 * take precedence.
199 				 */
200 				if (of_property_read_bool(child, "spi-cs-high")) {
201 					if (*flags & OF_GPIO_ACTIVE_LOW) {
202 						pr_warn("%s GPIO handle specifies active low - ignored\n",
203 							of_node_full_name(child));
204 						*flags &= ~OF_GPIO_ACTIVE_LOW;
205 					}
206 				} else {
207 					if (!(*flags & OF_GPIO_ACTIVE_LOW))
208 						pr_info("%s enforce active low on chipselect handle\n",
209 							of_node_full_name(child));
210 					*flags |= OF_GPIO_ACTIVE_LOW;
211 				}
212 				of_node_put(child);
213 				break;
214 			}
215 		}
216 	}
217 
218 	/* Legacy handling of stmmac's active-low PHY reset line */
219 	if (IS_ENABLED(CONFIG_STMMAC_ETH) &&
220 	    !strcmp(propname, "snps,reset-gpio") &&
221 	    of_property_read_bool(np, "snps,reset-active-low"))
222 		*flags |= OF_GPIO_ACTIVE_LOW;
223 }
224 
225 /**
226  * of_get_named_gpiod_flags() - Get a GPIO descriptor and flags for GPIO API
227  * @np:		device node to get GPIO from
228  * @propname:	property name containing gpio specifier(s)
229  * @index:	index of the GPIO
230  * @flags:	a flags pointer to fill in
231  *
232  * Returns GPIO descriptor to use with Linux GPIO API, or one of the errno
233  * value on the error condition. If @flags is not NULL the function also fills
234  * in flags for the GPIO.
235  */
236 static struct gpio_desc *of_get_named_gpiod_flags(struct device_node *np,
237 		     const char *propname, int index, enum of_gpio_flags *flags)
238 {
239 	struct of_phandle_args gpiospec;
240 	struct gpio_chip *chip;
241 	struct gpio_desc *desc;
242 	int ret;
243 
244 	ret = of_parse_phandle_with_args_map(np, propname, "gpio", index,
245 					     &gpiospec);
246 	if (ret) {
247 		pr_debug("%s: can't parse '%s' property of node '%pOF[%d]'\n",
248 			__func__, propname, np, index);
249 		return ERR_PTR(ret);
250 	}
251 
252 	chip = of_find_gpiochip_by_xlate(&gpiospec);
253 	if (!chip) {
254 		desc = ERR_PTR(-EPROBE_DEFER);
255 		goto out;
256 	}
257 
258 	desc = of_xlate_and_get_gpiod_flags(chip, &gpiospec, flags);
259 	if (IS_ERR(desc))
260 		goto out;
261 
262 	if (flags)
263 		of_gpio_flags_quirks(np, propname, flags, index);
264 
265 	pr_debug("%s: parsed '%s' property of node '%pOF[%d]' - status (%d)\n",
266 		 __func__, propname, np, index,
267 		 PTR_ERR_OR_ZERO(desc));
268 
269 out:
270 	of_node_put(gpiospec.np);
271 
272 	return desc;
273 }
274 
275 int of_get_named_gpio_flags(struct device_node *np, const char *list_name,
276 			    int index, enum of_gpio_flags *flags)
277 {
278 	struct gpio_desc *desc;
279 
280 	desc = of_get_named_gpiod_flags(np, list_name, index, flags);
281 
282 	if (IS_ERR(desc))
283 		return PTR_ERR(desc);
284 	else
285 		return desc_to_gpio(desc);
286 }
287 EXPORT_SYMBOL_GPL(of_get_named_gpio_flags);
288 
289 /**
290  * gpiod_get_from_of_node() - obtain a GPIO from an OF node
291  * @node:	handle of the OF node
292  * @propname:	name of the DT property representing the GPIO
293  * @index:	index of the GPIO to obtain for the consumer
294  * @dflags:	GPIO initialization flags
295  * @label:	label to attach to the requested GPIO
296  *
297  * Returns:
298  * On successful request the GPIO pin is configured in accordance with
299  * provided @dflags.
300  *
301  * In case of error an ERR_PTR() is returned.
302  */
303 struct gpio_desc *gpiod_get_from_of_node(struct device_node *node,
304 					 const char *propname, int index,
305 					 enum gpiod_flags dflags,
306 					 const char *label)
307 {
308 	unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
309 	struct gpio_desc *desc;
310 	enum of_gpio_flags flags;
311 	bool active_low = false;
312 	bool single_ended = false;
313 	bool open_drain = false;
314 	bool transitory = false;
315 	int ret;
316 
317 	desc = of_get_named_gpiod_flags(node, propname,
318 					index, &flags);
319 
320 	if (!desc || IS_ERR(desc)) {
321 		return desc;
322 	}
323 
324 	active_low = flags & OF_GPIO_ACTIVE_LOW;
325 	single_ended = flags & OF_GPIO_SINGLE_ENDED;
326 	open_drain = flags & OF_GPIO_OPEN_DRAIN;
327 	transitory = flags & OF_GPIO_TRANSITORY;
328 
329 	ret = gpiod_request(desc, label);
330 	if (ret == -EBUSY && (dflags & GPIOD_FLAGS_BIT_NONEXCLUSIVE))
331 		return desc;
332 	if (ret)
333 		return ERR_PTR(ret);
334 
335 	if (active_low)
336 		lflags |= GPIO_ACTIVE_LOW;
337 
338 	if (single_ended) {
339 		if (open_drain)
340 			lflags |= GPIO_OPEN_DRAIN;
341 		else
342 			lflags |= GPIO_OPEN_SOURCE;
343 	}
344 
345 	if (transitory)
346 		lflags |= GPIO_TRANSITORY;
347 
348 	if (flags & OF_GPIO_PULL_UP)
349 		lflags |= GPIO_PULL_UP;
350 
351 	if (flags & OF_GPIO_PULL_DOWN)
352 		lflags |= GPIO_PULL_DOWN;
353 
354 	ret = gpiod_configure_flags(desc, propname, lflags, dflags);
355 	if (ret < 0) {
356 		gpiod_put(desc);
357 		return ERR_PTR(ret);
358 	}
359 
360 	return desc;
361 }
362 EXPORT_SYMBOL_GPL(gpiod_get_from_of_node);
363 
364 /*
365  * The SPI GPIO bindings happened before we managed to establish that GPIO
366  * properties should be named "foo-gpios" so we have this special kludge for
367  * them.
368  */
369 static struct gpio_desc *of_find_spi_gpio(struct device *dev, const char *con_id,
370 					  enum of_gpio_flags *of_flags)
371 {
372 	char prop_name[32]; /* 32 is max size of property name */
373 	struct device_node *np = dev->of_node;
374 	struct gpio_desc *desc;
375 
376 	/*
377 	 * Hopefully the compiler stubs the rest of the function if this
378 	 * is false.
379 	 */
380 	if (!IS_ENABLED(CONFIG_SPI_MASTER))
381 		return ERR_PTR(-ENOENT);
382 
383 	/* Allow this specifically for "spi-gpio" devices */
384 	if (!of_device_is_compatible(np, "spi-gpio") || !con_id)
385 		return ERR_PTR(-ENOENT);
386 
387 	/* Will be "gpio-sck", "gpio-mosi" or "gpio-miso" */
388 	snprintf(prop_name, sizeof(prop_name), "%s-%s", "gpio", con_id);
389 
390 	desc = of_get_named_gpiod_flags(np, prop_name, 0, of_flags);
391 	return desc;
392 }
393 
394 /*
395  * The old Freescale bindings use simply "gpios" as name for the chip select
396  * lines rather than "cs-gpios" like all other SPI hardware. Account for this
397  * with a special quirk.
398  */
399 static struct gpio_desc *of_find_spi_cs_gpio(struct device *dev,
400 					     const char *con_id,
401 					     unsigned int idx,
402 					     unsigned long *flags)
403 {
404 	struct device_node *np = dev->of_node;
405 
406 	if (!IS_ENABLED(CONFIG_SPI_MASTER))
407 		return ERR_PTR(-ENOENT);
408 
409 	/* Allow this specifically for Freescale and PPC devices */
410 	if (!of_device_is_compatible(np, "fsl,spi") &&
411 	    !of_device_is_compatible(np, "aeroflexgaisler,spictrl") &&
412 	    !of_device_is_compatible(np, "ibm,ppc4xx-spi"))
413 		return ERR_PTR(-ENOENT);
414 	/* Allow only if asking for "cs-gpios" */
415 	if (!con_id || strcmp(con_id, "cs"))
416 		return ERR_PTR(-ENOENT);
417 
418 	/*
419 	 * While all other SPI controllers use "cs-gpios" the Freescale
420 	 * uses just "gpios" so translate to that when "cs-gpios" is
421 	 * requested.
422 	 */
423 	return of_find_gpio(dev, NULL, idx, flags);
424 }
425 
426 /*
427  * Some regulator bindings happened before we managed to establish that GPIO
428  * properties should be named "foo-gpios" so we have this special kludge for
429  * them.
430  */
431 static struct gpio_desc *of_find_regulator_gpio(struct device *dev, const char *con_id,
432 						enum of_gpio_flags *of_flags)
433 {
434 	/* These are the connection IDs we accept as legacy GPIO phandles */
435 	const char *whitelist[] = {
436 		"wlf,ldoena", /* Arizona */
437 		"wlf,ldo1ena", /* WM8994 */
438 		"wlf,ldo2ena", /* WM8994 */
439 	};
440 	struct device_node *np = dev->of_node;
441 	struct gpio_desc *desc;
442 	int i;
443 
444 	if (!IS_ENABLED(CONFIG_REGULATOR))
445 		return ERR_PTR(-ENOENT);
446 
447 	if (!con_id)
448 		return ERR_PTR(-ENOENT);
449 
450 	i = match_string(whitelist, ARRAY_SIZE(whitelist), con_id);
451 	if (i < 0)
452 		return ERR_PTR(-ENOENT);
453 
454 	desc = of_get_named_gpiod_flags(np, con_id, 0, of_flags);
455 	return desc;
456 }
457 
458 static struct gpio_desc *of_find_arizona_gpio(struct device *dev,
459 					      const char *con_id,
460 					      enum of_gpio_flags *of_flags)
461 {
462 	if (!IS_ENABLED(CONFIG_MFD_ARIZONA))
463 		return ERR_PTR(-ENOENT);
464 
465 	if (!con_id || strcmp(con_id, "wlf,reset"))
466 		return ERR_PTR(-ENOENT);
467 
468 	return of_get_named_gpiod_flags(dev->of_node, con_id, 0, of_flags);
469 }
470 
471 static struct gpio_desc *of_find_usb_gpio(struct device *dev,
472 					  const char *con_id,
473 					  enum of_gpio_flags *of_flags)
474 {
475 	/*
476 	 * Currently this USB quirk is only for the Fairchild FUSB302 host which is using
477 	 * an undocumented DT GPIO line named "fcs,int_n" without the compulsory "-gpios"
478 	 * suffix.
479 	 */
480 	if (!IS_ENABLED(CONFIG_TYPEC_FUSB302))
481 		return ERR_PTR(-ENOENT);
482 
483 	if (!con_id || strcmp(con_id, "fcs,int_n"))
484 		return ERR_PTR(-ENOENT);
485 
486 	return of_get_named_gpiod_flags(dev->of_node, con_id, 0, of_flags);
487 }
488 
489 struct gpio_desc *of_find_gpio(struct device *dev, const char *con_id,
490 			       unsigned int idx, unsigned long *flags)
491 {
492 	char prop_name[32]; /* 32 is max size of property name */
493 	enum of_gpio_flags of_flags;
494 	struct gpio_desc *desc;
495 	unsigned int i;
496 
497 	/* Try GPIO property "foo-gpios" and "foo-gpio" */
498 	for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
499 		if (con_id)
500 			snprintf(prop_name, sizeof(prop_name), "%s-%s", con_id,
501 				 gpio_suffixes[i]);
502 		else
503 			snprintf(prop_name, sizeof(prop_name), "%s",
504 				 gpio_suffixes[i]);
505 
506 		desc = of_get_named_gpiod_flags(dev->of_node, prop_name, idx,
507 						&of_flags);
508 
509 		if (!IS_ERR(desc) || PTR_ERR(desc) != -ENOENT)
510 			break;
511 	}
512 
513 	if (PTR_ERR(desc) == -ENOENT) {
514 		/* Special handling for SPI GPIOs if used */
515 		desc = of_find_spi_gpio(dev, con_id, &of_flags);
516 	}
517 
518 	if (PTR_ERR(desc) == -ENOENT) {
519 		/* This quirk looks up flags and all */
520 		desc = of_find_spi_cs_gpio(dev, con_id, idx, flags);
521 		if (!IS_ERR(desc))
522 			return desc;
523 	}
524 
525 	if (PTR_ERR(desc) == -ENOENT) {
526 		/* Special handling for regulator GPIOs if used */
527 		desc = of_find_regulator_gpio(dev, con_id, &of_flags);
528 	}
529 
530 	if (PTR_ERR(desc) == -ENOENT)
531 		desc = of_find_arizona_gpio(dev, con_id, &of_flags);
532 
533 	if (PTR_ERR(desc) == -ENOENT)
534 		desc = of_find_usb_gpio(dev, con_id, &of_flags);
535 
536 	if (IS_ERR(desc))
537 		return desc;
538 
539 	if (of_flags & OF_GPIO_ACTIVE_LOW)
540 		*flags |= GPIO_ACTIVE_LOW;
541 
542 	if (of_flags & OF_GPIO_SINGLE_ENDED) {
543 		if (of_flags & OF_GPIO_OPEN_DRAIN)
544 			*flags |= GPIO_OPEN_DRAIN;
545 		else
546 			*flags |= GPIO_OPEN_SOURCE;
547 	}
548 
549 	if (of_flags & OF_GPIO_TRANSITORY)
550 		*flags |= GPIO_TRANSITORY;
551 
552 	if (of_flags & OF_GPIO_PULL_UP)
553 		*flags |= GPIO_PULL_UP;
554 	if (of_flags & OF_GPIO_PULL_DOWN)
555 		*flags |= GPIO_PULL_DOWN;
556 
557 	return desc;
558 }
559 
560 /**
561  * of_parse_own_gpio() - Get a GPIO hog descriptor, names and flags for GPIO API
562  * @np:		device node to get GPIO from
563  * @chip:	GPIO chip whose hog is parsed
564  * @idx:	Index of the GPIO to parse
565  * @name:	GPIO line name
566  * @lflags:	bitmask of gpio_lookup_flags GPIO_* values - returned from
567  *		of_find_gpio() or of_parse_own_gpio()
568  * @dflags:	gpiod_flags - optional GPIO initialization flags
569  *
570  * Returns GPIO descriptor to use with Linux GPIO API, or one of the errno
571  * value on the error condition.
572  */
573 static struct gpio_desc *of_parse_own_gpio(struct device_node *np,
574 					   struct gpio_chip *chip,
575 					   unsigned int idx, const char **name,
576 					   unsigned long *lflags,
577 					   enum gpiod_flags *dflags)
578 {
579 	struct device_node *chip_np;
580 	enum of_gpio_flags xlate_flags;
581 	struct of_phandle_args gpiospec;
582 	struct gpio_desc *desc;
583 	unsigned int i;
584 	u32 tmp;
585 	int ret;
586 
587 	chip_np = chip->of_node;
588 	if (!chip_np)
589 		return ERR_PTR(-EINVAL);
590 
591 	xlate_flags = 0;
592 	*lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
593 	*dflags = 0;
594 
595 	ret = of_property_read_u32(chip_np, "#gpio-cells", &tmp);
596 	if (ret)
597 		return ERR_PTR(ret);
598 
599 	gpiospec.np = chip_np;
600 	gpiospec.args_count = tmp;
601 
602 	for (i = 0; i < tmp; i++) {
603 		ret = of_property_read_u32_index(np, "gpios", idx * tmp + i,
604 						 &gpiospec.args[i]);
605 		if (ret)
606 			return ERR_PTR(ret);
607 	}
608 
609 	desc = of_xlate_and_get_gpiod_flags(chip, &gpiospec, &xlate_flags);
610 	if (IS_ERR(desc))
611 		return desc;
612 
613 	if (xlate_flags & OF_GPIO_ACTIVE_LOW)
614 		*lflags |= GPIO_ACTIVE_LOW;
615 	if (xlate_flags & OF_GPIO_TRANSITORY)
616 		*lflags |= GPIO_TRANSITORY;
617 	if (xlate_flags & OF_GPIO_PULL_UP)
618 		*lflags |= GPIO_PULL_UP;
619 	if (xlate_flags & OF_GPIO_PULL_DOWN)
620 		*lflags |= GPIO_PULL_DOWN;
621 
622 	if (of_property_read_bool(np, "input"))
623 		*dflags |= GPIOD_IN;
624 	else if (of_property_read_bool(np, "output-low"))
625 		*dflags |= GPIOD_OUT_LOW;
626 	else if (of_property_read_bool(np, "output-high"))
627 		*dflags |= GPIOD_OUT_HIGH;
628 	else {
629 		pr_warn("GPIO line %d (%pOFn): no hogging state specified, bailing out\n",
630 			desc_to_gpio(desc), np);
631 		return ERR_PTR(-EINVAL);
632 	}
633 
634 	if (name && of_property_read_string(np, "line-name", name))
635 		*name = np->name;
636 
637 	return desc;
638 }
639 
640 /**
641  * of_gpiochip_add_hog - Add all hogs in a hog device node
642  * @chip:	gpio chip to act on
643  * @hog:	device node describing the hogs
644  *
645  * Returns error if it fails otherwise 0 on success.
646  */
647 static int of_gpiochip_add_hog(struct gpio_chip *chip, struct device_node *hog)
648 {
649 	enum gpiod_flags dflags;
650 	struct gpio_desc *desc;
651 	unsigned long lflags;
652 	const char *name;
653 	unsigned int i;
654 	int ret;
655 
656 	for (i = 0;; i++) {
657 		desc = of_parse_own_gpio(hog, chip, i, &name, &lflags, &dflags);
658 		if (IS_ERR(desc))
659 			break;
660 
661 		ret = gpiod_hog(desc, name, lflags, dflags);
662 		if (ret < 0)
663 			return ret;
664 
665 #ifdef CONFIG_OF_DYNAMIC
666 		desc->hog = hog;
667 #endif
668 	}
669 
670 	return 0;
671 }
672 
673 /**
674  * of_gpiochip_scan_gpios - Scan gpio-controller for gpio definitions
675  * @chip:	gpio chip to act on
676  *
677  * This is only used by of_gpiochip_add to request/set GPIO initial
678  * configuration.
679  * It returns error if it fails otherwise 0 on success.
680  */
681 static int of_gpiochip_scan_gpios(struct gpio_chip *chip)
682 {
683 	struct device_node *np;
684 	int ret;
685 
686 	for_each_available_child_of_node(chip->of_node, np) {
687 		if (!of_property_read_bool(np, "gpio-hog"))
688 			continue;
689 
690 		ret = of_gpiochip_add_hog(chip, np);
691 		if (ret < 0) {
692 			of_node_put(np);
693 			return ret;
694 		}
695 
696 		of_node_set_flag(np, OF_POPULATED);
697 	}
698 
699 	return 0;
700 }
701 
702 #ifdef CONFIG_OF_DYNAMIC
703 /**
704  * of_gpiochip_remove_hog - Remove all hogs in a hog device node
705  * @chip:	gpio chip to act on
706  * @hog:	device node describing the hogs
707  */
708 static void of_gpiochip_remove_hog(struct gpio_chip *chip,
709 				   struct device_node *hog)
710 {
711 	struct gpio_desc *descs = chip->gpiodev->descs;
712 	unsigned int i;
713 
714 	for (i = 0; i < chip->ngpio; i++) {
715 		if (test_bit(FLAG_IS_HOGGED, &descs[i].flags) &&
716 		    descs[i].hog == hog)
717 			gpiochip_free_own_desc(&descs[i]);
718 	}
719 }
720 
721 static int of_gpiochip_match_node(struct gpio_chip *chip, void *data)
722 {
723 	return chip->gpiodev->dev.of_node == data;
724 }
725 
726 static struct gpio_chip *of_find_gpiochip_by_node(struct device_node *np)
727 {
728 	return gpiochip_find(np, of_gpiochip_match_node);
729 }
730 
731 static int of_gpio_notify(struct notifier_block *nb, unsigned long action,
732 			  void *arg)
733 {
734 	struct of_reconfig_data *rd = arg;
735 	struct gpio_chip *chip;
736 	int ret;
737 
738 	/*
739 	 * This only supports adding and removing complete gpio-hog nodes.
740 	 * Modifying an existing gpio-hog node is not supported (except for
741 	 * changing its "status" property, which is treated the same as
742 	 * addition/removal).
743 	 */
744 	switch (of_reconfig_get_state_change(action, arg)) {
745 	case OF_RECONFIG_CHANGE_ADD:
746 		if (!of_property_read_bool(rd->dn, "gpio-hog"))
747 			return NOTIFY_OK;	/* not for us */
748 
749 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED))
750 			return NOTIFY_OK;
751 
752 		chip = of_find_gpiochip_by_node(rd->dn->parent);
753 		if (chip == NULL)
754 			return NOTIFY_OK;	/* not for us */
755 
756 		ret = of_gpiochip_add_hog(chip, rd->dn);
757 		if (ret < 0) {
758 			pr_err("%s: failed to add hogs for %pOF\n", __func__,
759 			       rd->dn);
760 			of_node_clear_flag(rd->dn, OF_POPULATED);
761 			return notifier_from_errno(ret);
762 		}
763 		break;
764 
765 	case OF_RECONFIG_CHANGE_REMOVE:
766 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
767 			return NOTIFY_OK;	/* already depopulated */
768 
769 		chip = of_find_gpiochip_by_node(rd->dn->parent);
770 		if (chip == NULL)
771 			return NOTIFY_OK;	/* not for us */
772 
773 		of_gpiochip_remove_hog(chip, rd->dn);
774 		of_node_clear_flag(rd->dn, OF_POPULATED);
775 		break;
776 	}
777 
778 	return NOTIFY_OK;
779 }
780 
781 struct notifier_block gpio_of_notifier = {
782 	.notifier_call = of_gpio_notify,
783 };
784 #endif /* CONFIG_OF_DYNAMIC */
785 
786 /**
787  * of_gpio_simple_xlate - translate gpiospec to the GPIO number and flags
788  * @gc:		pointer to the gpio_chip structure
789  * @gpiospec:	GPIO specifier as found in the device tree
790  * @flags:	a flags pointer to fill in
791  *
792  * This is simple translation function, suitable for the most 1:1 mapped
793  * GPIO chips. This function performs only one sanity check: whether GPIO
794  * is less than ngpios (that is specified in the gpio_chip).
795  */
796 static int of_gpio_simple_xlate(struct gpio_chip *gc,
797 				const struct of_phandle_args *gpiospec,
798 				u32 *flags)
799 {
800 	/*
801 	 * We're discouraging gpio_cells < 2, since that way you'll have to
802 	 * write your own xlate function (that will have to retrieve the GPIO
803 	 * number and the flags from a single gpio cell -- this is possible,
804 	 * but not recommended).
805 	 */
806 	if (gc->of_gpio_n_cells < 2) {
807 		WARN_ON(1);
808 		return -EINVAL;
809 	}
810 
811 	if (WARN_ON(gpiospec->args_count < gc->of_gpio_n_cells))
812 		return -EINVAL;
813 
814 	if (gpiospec->args[0] >= gc->ngpio)
815 		return -EINVAL;
816 
817 	if (flags)
818 		*flags = gpiospec->args[1];
819 
820 	return gpiospec->args[0];
821 }
822 
823 /**
824  * of_mm_gpiochip_add_data - Add memory mapped GPIO chip (bank)
825  * @np:		device node of the GPIO chip
826  * @mm_gc:	pointer to the of_mm_gpio_chip allocated structure
827  * @data:	driver data to store in the struct gpio_chip
828  *
829  * To use this function you should allocate and fill mm_gc with:
830  *
831  * 1) In the gpio_chip structure:
832  *    - all the callbacks
833  *    - of_gpio_n_cells
834  *    - of_xlate callback (optional)
835  *
836  * 3) In the of_mm_gpio_chip structure:
837  *    - save_regs callback (optional)
838  *
839  * If succeeded, this function will map bank's memory and will
840  * do all necessary work for you. Then you'll able to use .regs
841  * to manage GPIOs from the callbacks.
842  */
843 int of_mm_gpiochip_add_data(struct device_node *np,
844 			    struct of_mm_gpio_chip *mm_gc,
845 			    void *data)
846 {
847 	int ret = -ENOMEM;
848 	struct gpio_chip *gc = &mm_gc->gc;
849 
850 	gc->label = kasprintf(GFP_KERNEL, "%pOF", np);
851 	if (!gc->label)
852 		goto err0;
853 
854 	mm_gc->regs = of_iomap(np, 0);
855 	if (!mm_gc->regs)
856 		goto err1;
857 
858 	gc->base = -1;
859 
860 	if (mm_gc->save_regs)
861 		mm_gc->save_regs(mm_gc);
862 
863 	mm_gc->gc.of_node = np;
864 
865 	ret = gpiochip_add_data(gc, data);
866 	if (ret)
867 		goto err2;
868 
869 	return 0;
870 err2:
871 	iounmap(mm_gc->regs);
872 err1:
873 	kfree(gc->label);
874 err0:
875 	pr_err("%pOF: GPIO chip registration failed with status %d\n", np, ret);
876 	return ret;
877 }
878 EXPORT_SYMBOL_GPL(of_mm_gpiochip_add_data);
879 
880 /**
881  * of_mm_gpiochip_remove - Remove memory mapped GPIO chip (bank)
882  * @mm_gc:	pointer to the of_mm_gpio_chip allocated structure
883  */
884 void of_mm_gpiochip_remove(struct of_mm_gpio_chip *mm_gc)
885 {
886 	struct gpio_chip *gc = &mm_gc->gc;
887 
888 	if (!mm_gc)
889 		return;
890 
891 	gpiochip_remove(gc);
892 	iounmap(mm_gc->regs);
893 	kfree(gc->label);
894 }
895 EXPORT_SYMBOL_GPL(of_mm_gpiochip_remove);
896 
897 static void of_gpiochip_init_valid_mask(struct gpio_chip *chip)
898 {
899 	int len, i;
900 	u32 start, count;
901 	struct device_node *np = chip->of_node;
902 
903 	len = of_property_count_u32_elems(np,  "gpio-reserved-ranges");
904 	if (len < 0 || len % 2 != 0)
905 		return;
906 
907 	for (i = 0; i < len; i += 2) {
908 		of_property_read_u32_index(np, "gpio-reserved-ranges",
909 					   i, &start);
910 		of_property_read_u32_index(np, "gpio-reserved-ranges",
911 					   i + 1, &count);
912 		if (start >= chip->ngpio || start + count >= chip->ngpio)
913 			continue;
914 
915 		bitmap_clear(chip->valid_mask, start, count);
916 	}
917 };
918 
919 #ifdef CONFIG_PINCTRL
920 static int of_gpiochip_add_pin_range(struct gpio_chip *chip)
921 {
922 	struct device_node *np = chip->of_node;
923 	struct of_phandle_args pinspec;
924 	struct pinctrl_dev *pctldev;
925 	int index = 0, ret;
926 	const char *name;
927 	static const char group_names_propname[] = "gpio-ranges-group-names";
928 	struct property *group_names;
929 
930 	if (!np)
931 		return 0;
932 
933 	group_names = of_find_property(np, group_names_propname, NULL);
934 
935 	for (;; index++) {
936 		ret = of_parse_phandle_with_fixed_args(np, "gpio-ranges", 3,
937 				index, &pinspec);
938 		if (ret)
939 			break;
940 
941 		pctldev = of_pinctrl_get(pinspec.np);
942 		of_node_put(pinspec.np);
943 		if (!pctldev)
944 			return -EPROBE_DEFER;
945 
946 		if (pinspec.args[2]) {
947 			if (group_names) {
948 				of_property_read_string_index(np,
949 						group_names_propname,
950 						index, &name);
951 				if (strlen(name)) {
952 					pr_err("%pOF: Group name of numeric GPIO ranges must be the empty string.\n",
953 						np);
954 					break;
955 				}
956 			}
957 			/* npins != 0: linear range */
958 			ret = gpiochip_add_pin_range(chip,
959 					pinctrl_dev_get_devname(pctldev),
960 					pinspec.args[0],
961 					pinspec.args[1],
962 					pinspec.args[2]);
963 			if (ret)
964 				return ret;
965 		} else {
966 			/* npins == 0: special range */
967 			if (pinspec.args[1]) {
968 				pr_err("%pOF: Illegal gpio-range format.\n",
969 					np);
970 				break;
971 			}
972 
973 			if (!group_names) {
974 				pr_err("%pOF: GPIO group range requested but no %s property.\n",
975 					np, group_names_propname);
976 				break;
977 			}
978 
979 			ret = of_property_read_string_index(np,
980 						group_names_propname,
981 						index, &name);
982 			if (ret)
983 				break;
984 
985 			if (!strlen(name)) {
986 				pr_err("%pOF: Group name of GPIO group range cannot be the empty string.\n",
987 				np);
988 				break;
989 			}
990 
991 			ret = gpiochip_add_pingroup_range(chip, pctldev,
992 						pinspec.args[0], name);
993 			if (ret)
994 				return ret;
995 		}
996 	}
997 
998 	return 0;
999 }
1000 
1001 #else
1002 static int of_gpiochip_add_pin_range(struct gpio_chip *chip) { return 0; }
1003 #endif
1004 
1005 int of_gpiochip_add(struct gpio_chip *chip)
1006 {
1007 	int ret;
1008 
1009 	if (!chip->of_node)
1010 		return 0;
1011 
1012 	if (!chip->of_xlate) {
1013 		chip->of_gpio_n_cells = 2;
1014 		chip->of_xlate = of_gpio_simple_xlate;
1015 	}
1016 
1017 	if (chip->of_gpio_n_cells > MAX_PHANDLE_ARGS)
1018 		return -EINVAL;
1019 
1020 	of_gpiochip_init_valid_mask(chip);
1021 
1022 	ret = of_gpiochip_add_pin_range(chip);
1023 	if (ret)
1024 		return ret;
1025 
1026 	/* If the chip defines names itself, these take precedence */
1027 	if (!chip->names)
1028 		devprop_gpiochip_set_names(chip,
1029 					   of_fwnode_handle(chip->of_node));
1030 
1031 	of_node_get(chip->of_node);
1032 
1033 	ret = of_gpiochip_scan_gpios(chip);
1034 	if (ret)
1035 		of_node_put(chip->of_node);
1036 
1037 	return ret;
1038 }
1039 
1040 void of_gpiochip_remove(struct gpio_chip *chip)
1041 {
1042 	of_node_put(chip->of_node);
1043 }
1044