xref: /optee_os/core/drivers/gpio/gpio.c (revision 32b3180828fa15a49ccc86ecb4be9d274c140c89)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2022, Microchip
4  */
5 
6 #include <drivers/gpio.h>
7 #include <libfdt.h>
8 #include <stdio.h>
9 #include <tee_api_defines.h>
10 #include <tee_api_defines_extensions.h>
11 #include <tee_api_types.h>
12 #include <util.h>
13 
14 TEE_Result gpio_dt_alloc_pin(struct dt_pargs *pargs, struct gpio **out_gpio)
15 {
16 	struct gpio *gpio = NULL;
17 
18 	if (pargs->args_count != 2)
19 		return TEE_ERROR_BAD_PARAMETERS;
20 
21 	gpio = calloc(1, sizeof(struct gpio));
22 	if (!gpio)
23 		return TEE_ERROR_OUT_OF_MEMORY;
24 
25 	gpio->pin = pargs->args[0];
26 	gpio->dt_flags = pargs->args[1];
27 
28 	*out_gpio = gpio;
29 
30 	return TEE_SUCCESS;
31 }
32 
33 static char *gpio_get_dt_prop_name(const char *gpio_name)
34 {
35 	char *prop_name = NULL;
36 	int max_len = strlen(gpio_name) + strlen("-gpios") + 1;
37 
38 	prop_name = calloc(1, max_len);
39 	if (!prop_name)
40 		return NULL;
41 
42 	snprintf(prop_name, max_len, "%s-gpios", gpio_name);
43 
44 	return prop_name;
45 }
46 
47 TEE_Result gpio_dt_get_by_index(const void *fdt, int nodeoffset,
48 				unsigned int index, const char *gpio_name,
49 				struct gpio **gpio)
50 {
51 	TEE_Result res = TEE_ERROR_GENERIC;
52 	char *prop_name = NULL;
53 	void *out_gpio = NULL;
54 
55 	prop_name = gpio_get_dt_prop_name(gpio_name);
56 	if (!prop_name)
57 		return TEE_ERROR_OUT_OF_MEMORY;
58 
59 	res = dt_driver_device_from_node_idx_prop(prop_name, fdt, nodeoffset,
60 						  index, DT_DRIVER_GPIO,
61 						  &out_gpio);
62 	free(prop_name);
63 	if (!res)
64 		*gpio = out_gpio;
65 
66 	return res;
67 }
68