summaryrefslogtreecommitdiff
path: root/board/synopsys/hsdk/clk-lib.c
blob: 6b6bb70e3cb6071e53c8a03e98a51b59dc013447 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// SPDX-License-Identifier: GPL-2.0+
/*
 * Copyright (C) 2018 Synopsys, Inc. All rights reserved.
 * Author: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
 */

#include <clk.h>
#include <malloc.h>
#include <dm/device.h>

#include "clk-lib.h"

#define HZ_IN_MHZ	1000000
#define ceil(x, y)	({ ulong __x = (x), __y = (y); (__x + __y - 1) / __y; })

int soc_clk_ctl(const char *name, ulong *rate, enum clk_ctl_ops ctl)
{
	int ret;
	ulong mhz_rate, priv_rate;
	struct clk clk;

	/* Dummy fmeas device, just to be able to use standard clk_* api */
	struct udevice fmeas = {
		.name = "clk-fmeas",
		.node = ofnode_path("/clk-fmeas"),
	};

	ret = clk_get_by_name(&fmeas, name, &clk);
	if (ret) {
		pr_err("clock '%s' not found, err=%d\n", name, ret);
		return ret;
	}

	if (ctl & CLK_ON) {
		ret = clk_enable(&clk);
		if (ret && ret != -ENOSYS && ret != -ENOTSUPP)
			return ret;
	}

	if ((ctl & CLK_SET) && rate) {
		priv_rate = ctl & CLK_MHZ ? (*rate) * HZ_IN_MHZ : *rate;
		ret = clk_set_rate(&clk, priv_rate);
		if (ret)
			return ret;
	}

	if (ctl & CLK_OFF) {
		ret = clk_disable(&clk);
		if (ret) {
			pr_err("clock '%s' can't be disabled, err=%d\n", name, ret);
			return ret;
		}
	}

	priv_rate = clk_get_rate(&clk);

	clk_free(&clk);

	mhz_rate = ceil(priv_rate, HZ_IN_MHZ);

	if (ctl & CLK_MHZ)
		priv_rate = mhz_rate;

	if ((ctl & CLK_GET) && rate)
		*rate = priv_rate;

	if ((ctl & CLK_PRINT) && (ctl & CLK_MHZ))
		printf("HSDK: clock '%s' rate %lu MHz\n", name, priv_rate);
	else if (ctl & CLK_PRINT)
		printf("HSDK: clock '%s' rate %lu Hz\n", name, priv_rate);
	else
		debug("HSDK: clock '%s' rate %lu MHz\n", name, mhz_rate);

	return 0;
}