clk-cpu.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 int clk_cpu_determine_rate(struct clk_hw *hw,
  28. struct clk_rate_request *req)
  29. {
  30. struct clk_cpu *cpu = to_clk_cpu(hw);
  31. req->rate = clk_round_rate(cpu->pll, req->rate);
  32. return 0;
  33. }
  34. static int clk_cpu_set_rate(struct clk_hw *hw, unsigned long rate,
  35. unsigned long parent_rate)
  36. {
  37. struct clk_cpu *cpu = to_clk_cpu(hw);
  38. int ret;
  39. /* switch to PLL bypass clock */
  40. ret = clk_set_parent(cpu->mux, cpu->step);
  41. if (ret)
  42. return ret;
  43. /* reprogram PLL */
  44. ret = clk_set_rate(cpu->pll, rate);
  45. if (ret) {
  46. clk_set_parent(cpu->mux, cpu->pll);
  47. return ret;
  48. }
  49. /* switch back to PLL clock */
  50. clk_set_parent(cpu->mux, cpu->pll);
  51. /* Ensure the divider is what we expect */
  52. clk_set_rate(cpu->div, rate);
  53. return 0;
  54. }
  55. static const struct clk_ops clk_cpu_ops = {
  56. .recalc_rate = clk_cpu_recalc_rate,
  57. .determine_rate = clk_cpu_determine_rate,
  58. .set_rate = clk_cpu_set_rate,
  59. };
  60. struct clk_hw *imx_clk_hw_cpu(const char *name, const char *parent_name,
  61. struct clk *div, struct clk *mux, struct clk *pll,
  62. struct clk *step)
  63. {
  64. struct clk_cpu *cpu;
  65. struct clk_hw *hw;
  66. struct clk_init_data init;
  67. int ret;
  68. cpu = kzalloc_obj(*cpu);
  69. if (!cpu)
  70. return ERR_PTR(-ENOMEM);
  71. cpu->div = div;
  72. cpu->mux = mux;
  73. cpu->pll = pll;
  74. cpu->step = step;
  75. init.name = name;
  76. init.ops = &clk_cpu_ops;
  77. init.flags = CLK_IS_CRITICAL;
  78. init.parent_names = &parent_name;
  79. init.num_parents = 1;
  80. cpu->hw.init = &init;
  81. hw = &cpu->hw;
  82. ret = clk_hw_register(NULL, hw);
  83. if (ret) {
  84. kfree(cpu);
  85. return ERR_PTR(ret);
  86. }
  87. return hw;
  88. }
  89. EXPORT_SYMBOL_GPL(imx_clk_hw_cpu);