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