1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2016 - Beniamino Galvani <b.galvani@gmail.com>
4  */
5 
6 #include <asm/gpio.h>
7 #include <common.h>
8 #include <dm.h>
9 #include <dm/pinctrl.h>
10 #include <linux/io.h>
11 #include "pinctrl-meson-gx.h"
12 
13 static void meson_gx_pinmux_disable_other_groups(struct meson_pinctrl *priv,
14 						 unsigned int pin,
15 						 int sel_group)
16 {
17 	struct meson_pmx_group *group;
18 	struct meson_gx_pmx_data *pmx_data;
19 	void __iomem *addr;
20 	int i, j;
21 
22 	for (i = 0; i < priv->data->num_groups; i++) {
23 		group = &priv->data->groups[i];
24 		pmx_data = (struct meson_gx_pmx_data *)group->data;
25 		if (pmx_data->is_gpio || i == sel_group)
26 			continue;
27 
28 		for (j = 0; j < group->num_pins; j++) {
29 			if (group->pins[j] == pin) {
30 				/* We have found a group using the pin */
31 				debug("pinmux: disabling %s\n", group->name);
32 				addr = priv->reg_mux + pmx_data->reg * 4;
33 				writel(readl(addr) & ~BIT(pmx_data->bit), addr);
34 			}
35 		}
36 	}
37 }
38 
39 static int meson_gx_pinmux_group_set(struct udevice *dev,
40 				     unsigned int group_selector,
41 				     unsigned int func_selector)
42 {
43 	struct meson_pinctrl *priv = dev_get_priv(dev);
44 	const struct meson_pmx_group *group;
45 	const struct meson_pmx_func *func;
46 	struct meson_gx_pmx_data *pmx_data;
47 	void __iomem *addr;
48 	int i;
49 
50 	group = &priv->data->groups[group_selector];
51 	pmx_data = (struct meson_gx_pmx_data *)group->data;
52 	func = &priv->data->funcs[func_selector];
53 
54 	debug("pinmux: set group %s func %s\n", group->name, func->name);
55 
56 	/*
57 	 * Disable groups using the same pins.
58 	 * The selected group is not disabled to avoid glitches.
59 	 */
60 	for (i = 0; i < group->num_pins; i++) {
61 		meson_gx_pinmux_disable_other_groups(priv,
62 						     group->pins[i],
63 						     group_selector);
64 	}
65 
66 	/* Function 0 (GPIO) doesn't need any additional setting */
67 	if (func_selector) {
68 		addr = priv->reg_mux + pmx_data->reg * 4;
69 		writel(readl(addr) | BIT(pmx_data->bit), addr);
70 	}
71 
72 	return 0;
73 }
74 
75 const struct pinctrl_ops meson_gx_pinctrl_ops = {
76 	.get_groups_count = meson_pinctrl_get_groups_count,
77 	.get_group_name = meson_pinctrl_get_group_name,
78 	.get_functions_count = meson_pinmux_get_functions_count,
79 	.get_function_name = meson_pinmux_get_function_name,
80 	.pinmux_group_set = meson_gx_pinmux_group_set,
81 	.set_state = pinctrl_generic_set_state,
82 };
83 
84 static const struct dm_gpio_ops meson_gx_gpio_ops = {
85 	.set_value = meson_gpio_set,
86 	.get_value = meson_gpio_get,
87 	.get_function = meson_gpio_get_direction,
88 	.direction_input = meson_gpio_direction_input,
89 	.direction_output = meson_gpio_direction_output,
90 };
91 
92 const struct driver meson_gx_gpio_driver = {
93 	.name	= "meson-gx-gpio",
94 	.id	= UCLASS_GPIO,
95 	.probe	= meson_gpio_probe,
96 	.ops	= &meson_gx_gpio_ops,
97 };
98