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