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