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 <log.h>
9 #include <malloc.h>
10 #include <dm/device.h>
11
12 #include "clk-lib.h"
13
14 #define HZ_IN_MHZ 1000000
15 #define ceil(x, y) ({ ulong __x = (x), __y = (y); (__x + __y - 1) / __y; })
16
soc_clk_ctl(const char * name,ulong * rate,enum clk_ctl_ops ctl)17 int soc_clk_ctl(const char *name, ulong *rate, enum clk_ctl_ops ctl)
18 {
19 int ret;
20 ulong mhz_rate, priv_rate;
21 struct clk clk;
22
23 /* Dummy fmeas device, just to be able to use standard clk_* api */
24 struct udevice fmeas = {
25 .name = "clk-fmeas",
26 };
27 dev_set_ofnode(&fmeas, ofnode_path("/clk-fmeas"));
28
29 ret = clk_get_by_name(&fmeas, name, &clk);
30 if (ret) {
31 pr_err("clock '%s' not found, err=%d\n", name, ret);
32 return ret;
33 }
34
35 if (ctl & CLK_ON) {
36 ret = clk_enable(&clk);
37 if (ret && ret != -ENOSYS && ret != -ENOTSUPP)
38 return ret;
39 }
40
41 if ((ctl & CLK_SET) && rate) {
42 priv_rate = ctl & CLK_MHZ ? (*rate) * HZ_IN_MHZ : *rate;
43 ret = clk_set_rate(&clk, priv_rate);
44 if (ret)
45 return ret;
46 }
47
48 if (ctl & CLK_OFF) {
49 ret = clk_disable(&clk);
50 if (ret) {
51 pr_err("clock '%s' can't be disabled, err=%d\n", name, ret);
52 return ret;
53 }
54 }
55
56 priv_rate = clk_get_rate(&clk);
57
58 clk_free(&clk);
59
60 mhz_rate = ceil(priv_rate, HZ_IN_MHZ);
61
62 if (ctl & CLK_MHZ)
63 priv_rate = mhz_rate;
64
65 if ((ctl & CLK_GET) && rate)
66 *rate = priv_rate;
67
68 if ((ctl & CLK_PRINT) && (ctl & CLK_MHZ))
69 printf("HSDK: clock '%s' rate %lu MHz\n", name, priv_rate);
70 else if (ctl & CLK_PRINT)
71 printf("HSDK: clock '%s' rate %lu Hz\n", name, priv_rate);
72 else
73 debug("HSDK: clock '%s' rate %lu MHz\n", name, mhz_rate);
74
75 return 0;
76 }
77