1 /*
2  * Copyright (c) 2020, MediaTek Inc. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <mt_lp_rm.h>
8 #include <stddef.h>
9 
10 struct platform_mt_resource_manager {
11 	unsigned int count;
12 	struct mt_resource_manager *plat_rm;
13 };
14 
15 static struct platform_mt_resource_manager plat_mt_rm;
16 
mt_lp_rm_register(struct mt_resource_manager * rm)17 int mt_lp_rm_register(struct mt_resource_manager *rm)
18 {
19 	unsigned int i;
20 	struct mt_resource_constraint *const *rc;
21 
22 	if ((rm == NULL) || (rm->consts == NULL) ||
23 	    (plat_mt_rm.plat_rm != NULL)) {
24 		return MT_RM_STATUS_BAD;
25 	}
26 
27 	for (i = 0U, rc = rm->consts; *rc != NULL; i++, rc++) {
28 		if ((*rc)->init != NULL) {
29 			(*rc)->init();
30 		}
31 	}
32 
33 	plat_mt_rm.plat_rm = rm;
34 	plat_mt_rm.count = i;
35 
36 	return MT_RM_STATUS_OK;
37 }
38 
mt_lp_rm_reset_constraint(int idx,unsigned int cpuid,int stateid)39 int mt_lp_rm_reset_constraint(int idx, unsigned int cpuid, int stateid)
40 {
41 	struct mt_resource_constraint const *rc = NULL;
42 
43 	if ((plat_mt_rm.plat_rm == NULL) || (idx < 0) ||
44 	    (idx >= plat_mt_rm.count)) {
45 		return MT_RM_STATUS_BAD;
46 	}
47 
48 	rc = plat_mt_rm.plat_rm->consts[idx];
49 
50 	if ((rc == NULL) || (rc->reset == NULL)) {
51 		return MT_RM_STATUS_BAD;
52 	}
53 
54 	return rc->reset(cpuid, stateid);
55 }
56 
mt_lp_rm_find_and_run_constraint(int idx,unsigned int cpuid,int stateid,void * priv)57 int mt_lp_rm_find_and_run_constraint(int idx, unsigned int cpuid,
58 				     int stateid, void *priv)
59 {
60 	int i, res = MT_RM_STATUS_BAD;
61 	struct mt_resource_constraint *const *rc;
62 	struct mt_resource_manager *rm = plat_mt_rm.plat_rm;
63 
64 	if ((rm == NULL) || (idx < 0) || (idx >= plat_mt_rm.count)) {
65 		return res;
66 	}
67 
68 	/* If subsys clk/mtcmos is on, add block-resource-off flag */
69 	if (rm->update != NULL) {
70 		res = rm->update(rm->consts, stateid, priv);
71 		if (res != 0) {
72 			return res;
73 		}
74 	}
75 
76 	for (i = idx, rc = (rm->consts + idx); *rc != NULL; i++, rc++) {
77 		if (((*rc)->is_valid != NULL) &&
78 		    ((*rc)->is_valid(cpuid, stateid))) {
79 			if (((*rc)->run != NULL) &&
80 			    ((*rc)->run(cpuid, stateid) == 0)) {
81 				res = i;
82 				break;
83 			}
84 		}
85 	}
86 
87 	return res;
88 }
89 
mt_lp_rm_do_update(int stateid,int type,void const * p)90 int mt_lp_rm_do_update(int stateid, int type, void const *p)
91 {
92 	int res = MT_RM_STATUS_BAD;
93 	struct mt_resource_constraint *const *rc;
94 	struct mt_resource_manager *rm = plat_mt_rm.plat_rm;
95 
96 	if (rm == NULL) {
97 		return res;
98 	}
99 
100 	for (rc = rm->consts; *rc != NULL; rc++) {
101 		if ((*rc)->update != NULL) {
102 			res = (*rc)->update(stateid, type, p);
103 			if (res != MT_RM_STATUS_OK) {
104 				break;
105 			}
106 		}
107 	}
108 
109 	return res;
110 }
111