clk-cpu.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (c) 2014 Lucas Stach <l.stach@pengutronix.de>, Pengutronix
  4. */
  5. #include <linux/clk.h>
  6. #include <linux/clk-provider.h>
  7. #include <linux/export.h>
  8. #include <linux/slab.h>
  9. #include "clk.h"
  10. struct clk_cpu {
  11. struct clk_hw hw;
  12. struct clk *div;
  13. struct clk *mux;
  14. struct clk *pll;
  15. struct clk *step;
  16. };
  17. static inline struct clk_cpu *to_clk_cpu(struct clk_hw *hw)
  18. {
  19. return container_of(hw, struct clk_cpu, hw);
  20. }
  21. static unsigned long clk_cpu_recalc_rate(struct clk_hw *hw,
  22. unsigned long parent_rate)
  23. {
  24. struct clk_cpu *cpu = to_clk_cpu(hw);
  25. return clk_get_rate(cpu->div);
  26. }
  27. static long clk_cpu_round_rate(struct clk_hw *hw, unsigned long rate,
  28. unsigned long *prate)
  29. {
  30. struct clk_cpu *cpu = to_clk_cpu(hw);
  31. return clk_round_rate(cpu->pll, rate);
  32. }
  33. static int clk_cpu_set_rate(struct clk_hw *hw, unsigned long rate,
  34. unsigned long parent_rate)
  35. {
  36. struct clk_cpu *cpu = to_clk_cpu(hw);
  37. int ret;
  38. /* switch to PLL bypass clock */
  39. ret = clk_set_parent(cpu->mux, cpu->step);
  40. if (ret)
  41. return ret;
  42. /* reprogram PLL */
  43. ret = clk_set_rate(cpu->pll, rate);
  44. if (ret) {
  45. clk_set_parent(cpu->mux, cpu->pll);
  46. return ret;
  47. }
  48. /* switch back to PLL clock */
  49. clk_set_parent(cpu->mux, cpu->pll);
  50. /* Ensure the divider is what we expect */
  51. clk_set_rate(cpu->div, rate);
  52. return 0;
  53. }
  54. static const struct clk_ops clk_cpu_ops = {
  55. .recalc_rate = clk_cpu_recalc_rate,
  56. .round_rate = clk_cpu_round_rate,
  57. .set_rate = clk_cpu_set_rate,
  58. };
  59. struct clk_hw *imx_clk_hw_cpu(const char *name, const char *parent_name,
  60. struct clk *div, struct clk *mux, struct clk *pll,
  61. struct clk *step)
  62. {
  63. struct clk_cpu *cpu;
  64. struct clk_hw *hw;
  65. struct clk_init_data init;
  66. int ret;
  67. cpu = kzalloc(sizeof(*cpu), GFP_KERNEL);
  68. if (!cpu)
  69. return ERR_PTR(-ENOMEM);
  70. cpu->div = div;
  71. cpu->mux = mux;
  72. cpu->pll = pll;
  73. cpu->step = step;
  74. init.name = name;
  75. init.ops = &clk_cpu_ops;
  76. init.flags = CLK_IS_CRITICAL;
  77. init.parent_names = &parent_name;
  78. init.num_parents = 1;
  79. cpu->hw.init = &init;
  80. hw = &cpu->hw;
  81. ret = clk_hw_register(NULL, hw);
  82. if (ret) {
  83. kfree(cpu);
  84. return ERR_PTR(ret);
  85. }
  86. return hw;
  87. }
  88. EXPORT_SYMBOL_GPL(imx_clk_hw_cpu);