xref: /openbmc/u-boot/board/synopsys/hsdk/clk-lib.c (revision f77d4410)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2018 Synopsys, Inc. All rights reserved.
4  * Author: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
5  */
6 
7 #include <clk.h>
8 #include <dm/device.h>
9 
10 #include "clk-lib.h"
11 
12 #define HZ_IN_MHZ	1000000
13 #define ceil(x, y)	({ ulong __x = (x), __y = (y); (__x + __y - 1) / __y; })
14 
15 int soc_clk_ctl(const char *name, ulong *rate, enum clk_ctl_ops ctl)
16 {
17 	int ret;
18 	ulong mhz_rate, priv_rate;
19 	struct clk clk;
20 
21 	/* Dummy fmeas device, just to be able to use standard clk_* api */
22 	struct udevice fmeas = {
23 		.name = "clk-fmeas",
24 		.node = ofnode_path("/clk-fmeas"),
25 	};
26 
27 	ret = clk_get_by_name(&fmeas, name, &clk);
28 	if (ret) {
29 		pr_err("clock '%s' not found, err=%d\n", name, ret);
30 		return ret;
31 	}
32 
33 	if (ctl & CLK_ON) {
34 		ret = clk_enable(&clk);
35 		if (ret && ret != -ENOSYS && ret != -ENOTSUPP)
36 			return ret;
37 	}
38 
39 	if ((ctl & CLK_SET) && rate) {
40 		priv_rate = ctl & CLK_MHZ ? (*rate) * HZ_IN_MHZ : *rate;
41 		ret = clk_set_rate(&clk, priv_rate);
42 		if (ret)
43 			return ret;
44 	}
45 
46 	if (ctl & CLK_OFF) {
47 		ret = clk_disable(&clk);
48 		if (ret) {
49 			pr_err("clock '%s' can't be disabled, err=%d\n", name, ret);
50 			return ret;
51 		}
52 	}
53 
54 	priv_rate = clk_get_rate(&clk);
55 
56 	clk_free(&clk);
57 
58 	mhz_rate = ceil(priv_rate, HZ_IN_MHZ);
59 
60 	if (ctl & CLK_MHZ)
61 		priv_rate = mhz_rate;
62 
63 	if ((ctl & CLK_GET) && rate)
64 		*rate = priv_rate;
65 
66 	if ((ctl & CLK_PRINT) && (ctl & CLK_MHZ))
67 		printf("HSDK: clock '%s' rate %lu MHz\n", name, priv_rate);
68 	else if (ctl & CLK_PRINT)
69 		printf("HSDK: clock '%s' rate %lu Hz\n", name, priv_rate);
70 	else
71 		debug("HSDK: clock '%s' rate %lu MHz\n", name, mhz_rate);
72 
73 	return 0;
74 }
75