1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2016 Atmel Corporation
4  *               Wenyou.Yang <wenyou.yang@atmel.com>
5  */
6 
7 #include <common.h>
8 #include <clk-uclass.h>
9 #include <dm.h>
10 #include <linux/io.h>
11 #include <mach/at91_pmc.h>
12 #include "pmc.h"
13 
14 #define PERIPHERAL_ID_MIN	2
15 #define PERIPHERAL_ID_MAX	31
16 #define PERIPHERAL_MASK(id)	(1 << ((id) & PERIPHERAL_ID_MAX))
17 
18 enum periph_clk_type {
19 	CLK_PERIPH_AT91RM9200 = 0,
20 	CLK_PERIPH_AT91SAM9X5,
21 };
22 /**
23  * sam9x5_periph_clk_bind() - for the periph clock driver
24  * Recursively bind its children as clk devices.
25  *
26  * @return: 0 on success, or negative error code on failure
27  */
28 static int sam9x5_periph_clk_bind(struct udevice *dev)
29 {
30 	return at91_clk_sub_device_bind(dev, "periph-clk");
31 }
32 
33 static const struct udevice_id sam9x5_periph_clk_match[] = {
34 	{
35 		.compatible = "atmel,at91rm9200-clk-peripheral",
36 		.data = CLK_PERIPH_AT91RM9200,
37 	},
38 	{
39 		.compatible = "atmel,at91sam9x5-clk-peripheral",
40 		.data = CLK_PERIPH_AT91SAM9X5,
41 	},
42 	{}
43 };
44 
45 U_BOOT_DRIVER(sam9x5_periph_clk) = {
46 	.name = "sam9x5-periph-clk",
47 	.id = UCLASS_MISC,
48 	.of_match = sam9x5_periph_clk_match,
49 	.bind = sam9x5_periph_clk_bind,
50 };
51 
52 /*---------------------------------------------------------*/
53 
54 static int periph_clk_enable(struct clk *clk)
55 {
56 	struct pmc_platdata *plat = dev_get_platdata(clk->dev);
57 	struct at91_pmc *pmc = plat->reg_base;
58 	enum periph_clk_type clk_type;
59 	void *addr;
60 
61 	if (clk->id < PERIPHERAL_ID_MIN)
62 		return -1;
63 
64 	clk_type = dev_get_driver_data(dev_get_parent(clk->dev));
65 	if (clk_type == CLK_PERIPH_AT91RM9200) {
66 		addr = &pmc->pcer;
67 		if (clk->id > PERIPHERAL_ID_MAX)
68 			addr = &pmc->pcer1;
69 
70 		setbits_le32(addr, PERIPHERAL_MASK(clk->id));
71 	} else {
72 		writel(clk->id & AT91_PMC_PCR_PID_MASK, &pmc->pcr);
73 		setbits_le32(&pmc->pcr,
74 			     AT91_PMC_PCR_CMD_WRITE | AT91_PMC_PCR_EN);
75 	}
76 
77 	return 0;
78 }
79 
80 static ulong periph_get_rate(struct clk *clk)
81 {
82 	struct udevice *dev;
83 	struct clk clk_dev;
84 	ulong clk_rate;
85 	int ret;
86 
87 	dev = dev_get_parent(clk->dev);
88 
89 	ret = clk_get_by_index(dev, 0, &clk_dev);
90 	if (ret)
91 		return ret;
92 
93 	clk_rate = clk_get_rate(&clk_dev);
94 
95 	clk_free(&clk_dev);
96 
97 	return clk_rate;
98 }
99 
100 static struct clk_ops periph_clk_ops = {
101 	.of_xlate = at91_clk_of_xlate,
102 	.enable = periph_clk_enable,
103 	.get_rate = periph_get_rate,
104 };
105 
106 U_BOOT_DRIVER(clk_periph) = {
107 	.name	= "periph-clk",
108 	.id	= UCLASS_CLK,
109 	.platdata_auto_alloc_size = sizeof(struct pmc_platdata),
110 	.probe = at91_clk_probe,
111 	.ops	= &periph_clk_ops,
112 };
113