2 * Copyright (C) 2014 Intel Corporation
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
8 * Adjustable fractional divider clock implementation.
9 * Output rate = (m / n) * parent_rate.
12 #include <linux/clk-provider.h>
13 #include <linux/module.h>
14 #include <linux/device.h>
15 #include <linux/slab.h>
16 #include <linux/gcd.h>
18 #define to_clk_fd(_hw) container_of(_hw, struct clk_fractional_divider, hw)
20 static unsigned long clk_fd_recalc_rate(struct clk_hw *hw,
21 unsigned long parent_rate)
23 struct clk_fractional_divider *fd = to_clk_fd(hw);
24 unsigned long flags = 0;
29 spin_lock_irqsave(fd->lock, flags);
31 val = clk_readl(fd->reg);
34 spin_unlock_irqrestore(fd->lock, flags);
36 m = (val & fd->mmask) >> fd->mshift;
37 n = (val & fd->nmask) >> fd->nshift;
39 ret = parent_rate * m;
45 static long clk_fd_round_rate(struct clk_hw *hw, unsigned long rate,
48 struct clk_fractional_divider *fd = to_clk_fd(hw);
49 unsigned maxn = (fd->nmask >> fd->nshift) + 1;
52 if (!rate || rate >= *prate)
55 div = gcd(*prate, rate);
57 while ((*prate / div) > maxn) {
65 static int clk_fd_set_rate(struct clk_hw *hw, unsigned long rate,
66 unsigned long parent_rate)
68 struct clk_fractional_divider *fd = to_clk_fd(hw);
69 unsigned long flags = 0;
74 div = gcd(parent_rate, rate);
76 n = parent_rate / div;
79 spin_lock_irqsave(fd->lock, flags);
81 val = clk_readl(fd->reg);
82 val &= ~(fd->mmask | fd->nmask);
83 val |= (m << fd->mshift) | (n << fd->nshift);
84 clk_writel(val, fd->reg);
87 spin_unlock_irqrestore(fd->lock, flags);
92 const struct clk_ops clk_fractional_divider_ops = {
93 .recalc_rate = clk_fd_recalc_rate,
94 .round_rate = clk_fd_round_rate,
95 .set_rate = clk_fd_set_rate,
97 EXPORT_SYMBOL_GPL(clk_fractional_divider_ops);
99 struct clk *clk_register_fractional_divider(struct device *dev,
100 const char *name, const char *parent_name, unsigned long flags,
101 void __iomem *reg, u8 mshift, u8 mwidth, u8 nshift, u8 nwidth,
102 u8 clk_divider_flags, spinlock_t *lock)
104 struct clk_fractional_divider *fd;
105 struct clk_init_data init;
108 fd = kzalloc(sizeof(*fd), GFP_KERNEL);
110 dev_err(dev, "could not allocate fractional divider clk\n");
111 return ERR_PTR(-ENOMEM);
115 init.ops = &clk_fractional_divider_ops;
116 init.flags = flags | CLK_IS_BASIC;
117 init.parent_names = parent_name ? &parent_name : NULL;
118 init.num_parents = parent_name ? 1 : 0;
122 fd->mmask = (BIT(mwidth) - 1) << mshift;
124 fd->nmask = (BIT(nwidth) - 1) << nshift;
125 fd->flags = clk_divider_flags;
129 clk = clk_register(dev, &fd->hw);
135 EXPORT_SYMBOL_GPL(clk_register_fractional_divider);