1 /*
2  * Copyright (c) 2016, NVIDIA CORPORATION.
3  *
4  * SPDX-License-Identifier: GPL-2.0
5  */
6 
7 #include <common.h>
8 #include <dm.h>
9 #include <fdtdec.h>
10 #include <power-domain.h>
11 #include <power-domain-uclass.h>
12 
13 DECLARE_GLOBAL_DATA_PTR;
14 
15 static inline struct power_domain_ops *power_domain_dev_ops(struct udevice *dev)
16 {
17 	return (struct power_domain_ops *)dev->driver->ops;
18 }
19 
20 static int power_domain_of_xlate_default(struct power_domain *power_domain,
21 				       struct fdtdec_phandle_args *args)
22 {
23 	debug("%s(power_domain=%p)\n", __func__, power_domain);
24 
25 	if (args->args_count != 1) {
26 		debug("Invalid args_count: %d\n", args->args_count);
27 		return -EINVAL;
28 	}
29 
30 	power_domain->id = args->args[0];
31 
32 	return 0;
33 }
34 
35 int power_domain_get(struct udevice *dev, struct power_domain *power_domain)
36 {
37 	struct fdtdec_phandle_args args;
38 	int ret;
39 	struct udevice *dev_power_domain;
40 	struct power_domain_ops *ops;
41 
42 	debug("%s(dev=%p, power_domain=%p)\n", __func__, dev, power_domain);
43 
44 	ret = fdtdec_parse_phandle_with_args(gd->fdt_blob, dev->of_offset,
45 					     "power-domains",
46 					     "#power-domain-cells", 0, 0,
47 					     &args);
48 	if (ret) {
49 		debug("%s: fdtdec_parse_phandle_with_args failed: %d\n",
50 		      __func__, ret);
51 		return ret;
52 	}
53 
54 	ret = uclass_get_device_by_of_offset(UCLASS_POWER_DOMAIN, args.node,
55 					     &dev_power_domain);
56 	if (ret) {
57 		debug("%s: uclass_get_device_by_of_offset failed: %d\n",
58 		      __func__, ret);
59 		return ret;
60 	}
61 	ops = power_domain_dev_ops(dev_power_domain);
62 
63 	power_domain->dev = dev_power_domain;
64 	if (ops->of_xlate)
65 		ret = ops->of_xlate(power_domain, &args);
66 	else
67 		ret = power_domain_of_xlate_default(power_domain, &args);
68 	if (ret) {
69 		debug("of_xlate() failed: %d\n", ret);
70 		return ret;
71 	}
72 
73 	ret = ops->request(power_domain);
74 	if (ret) {
75 		debug("ops->request() failed: %d\n", ret);
76 		return ret;
77 	}
78 
79 	return 0;
80 }
81 
82 int power_domain_free(struct power_domain *power_domain)
83 {
84 	struct power_domain_ops *ops = power_domain_dev_ops(power_domain->dev);
85 
86 	debug("%s(power_domain=%p)\n", __func__, power_domain);
87 
88 	return ops->free(power_domain);
89 }
90 
91 int power_domain_on(struct power_domain *power_domain)
92 {
93 	struct power_domain_ops *ops = power_domain_dev_ops(power_domain->dev);
94 
95 	debug("%s(power_domain=%p)\n", __func__, power_domain);
96 
97 	return ops->on(power_domain);
98 }
99 
100 int power_domain_off(struct power_domain *power_domain)
101 {
102 	struct power_domain_ops *ops = power_domain_dev_ops(power_domain->dev);
103 
104 	debug("%s(power_domain=%p)\n", __func__, power_domain);
105 
106 	return ops->off(power_domain);
107 }
108 
109 UCLASS_DRIVER(power_domain) = {
110 	.id		= UCLASS_POWER_DOMAIN,
111 	.name		= "power_domain",
112 };
113