OSDN Git Service

treewide: Fix code issues detected using GCC 8
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / drivers / regulator / cpr3-regulator.c
1 /*
2  * Copyright (c) 2015-2017, The Linux Foundation. All rights reserved.
3  *
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 and
6  * only version 2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  */
13
14 #define pr_fmt(fmt) "%s: " fmt, __func__
15
16 #include <linux/bitops.h>
17 #include <linux/debugfs.h>
18 #include <linux/delay.h>
19 #include <linux/err.h>
20 #include <linux/init.h>
21 #include <linux/interrupt.h>
22 #include <linux/io.h>
23 #include <linux/kernel.h>
24 #include <linux/ktime.h>
25 #include <linux/list.h>
26 #include <linux/module.h>
27 #include <linux/of.h>
28 #include <linux/of_device.h>
29 #include <linux/platform_device.h>
30 #include <linux/pm_opp.h>
31 #include <linux/slab.h>
32 #include <linux/sort.h>
33 #include <linux/string.h>
34 #include <linux/uaccess.h>
35 #include <linux/regulator/driver.h>
36 #include <linux/regulator/machine.h>
37 #include <linux/regulator/of_regulator.h>
38 #include <linux/regulator/msm-ldo-regulator.h>
39
40 #include <soc/qcom/spm.h>
41
42 #include "cpr3-regulator.h"
43
44 #define CPR3_REGULATOR_CORNER_INVALID   (-1)
45 #define CPR3_RO_MASK                    GENMASK(CPR3_RO_COUNT - 1, 0)
46
47 /* CPR3 registers */
48 #define CPR3_REG_CPR_CTL                        0x4
49 #define CPR3_CPR_CTL_LOOP_EN_MASK               BIT(0)
50 #define CPR3_CPR_CTL_LOOP_ENABLE                BIT(0)
51 #define CPR3_CPR_CTL_LOOP_DISABLE               0
52 #define CPR3_CPR_CTL_IDLE_CLOCKS_MASK           GENMASK(5, 1)
53 #define CPR3_CPR_CTL_IDLE_CLOCKS_SHIFT          1
54 #define CPR3_CPR_CTL_COUNT_MODE_MASK            GENMASK(7, 6)
55 #define CPR3_CPR_CTL_COUNT_MODE_SHIFT           6
56 #define CPR3_CPR_CTL_COUNT_MODE_ALL_AT_ONCE_MIN 0
57 #define CPR3_CPR_CTL_COUNT_MODE_ALL_AT_ONCE_MAX 1
58 #define CPR3_CPR_CTL_COUNT_MODE_STAGGERED       2
59 #define CPR3_CPR_CTL_COUNT_MODE_ALL_AT_ONCE_AGE 3
60 #define CPR3_CPR_CTL_COUNT_REPEAT_MASK          GENMASK(31, 9)
61 #define CPR3_CPR_CTL_COUNT_REPEAT_SHIFT         9
62
63 #define CPR3_REG_CPR_STATUS                     0x8
64 #define CPR3_CPR_STATUS_BUSY_MASK               BIT(0)
65 #define CPR3_CPR_STATUS_AGING_MEASUREMENT_MASK  BIT(1)
66
67 /*
68  * This register is not present on controllers that support HW closed-loop
69  * except CPR4 APSS controller.
70  */
71 #define CPR3_REG_CPR_TIMER_AUTO_CONT            0xC
72
73 #define CPR3_REG_CPR_STEP_QUOT                  0x14
74 #define CPR3_CPR_STEP_QUOT_MIN_MASK             GENMASK(5, 0)
75 #define CPR3_CPR_STEP_QUOT_MIN_SHIFT            0
76 #define CPR3_CPR_STEP_QUOT_MAX_MASK             GENMASK(11, 6)
77 #define CPR3_CPR_STEP_QUOT_MAX_SHIFT            6
78
79 #define CPR3_REG_GCNT(ro)                       (0xA0 + 0x4 * (ro))
80
81 #define CPR3_REG_SENSOR_BYPASS_WRITE(sensor)    (0xE0 + 0x4 * ((sensor) / 32))
82 #define CPR3_REG_SENSOR_BYPASS_WRITE_BANK(bank) (0xE0 + 0x4 * (bank))
83
84 #define CPR3_REG_SENSOR_MASK_WRITE(sensor)      (0x120 + 0x4 * ((sensor) / 32))
85 #define CPR3_REG_SENSOR_MASK_WRITE_BANK(bank)   (0x120 + 0x4 * (bank))
86 #define CPR3_REG_SENSOR_MASK_READ(sensor)       (0x140 + 0x4 * ((sensor) / 32))
87
88 #define CPR3_REG_SENSOR_OWNER(sensor)   (0x200 + 0x4 * (sensor))
89
90 #define CPR3_REG_CONT_CMD               0x800
91 #define CPR3_CONT_CMD_ACK               0x1
92 #define CPR3_CONT_CMD_NACK              0x0
93
94 #define CPR3_REG_THRESH(thread)         (0x808 + 0x440 * (thread))
95 #define CPR3_THRESH_CONS_DOWN_MASK      GENMASK(3, 0)
96 #define CPR3_THRESH_CONS_DOWN_SHIFT     0
97 #define CPR3_THRESH_CONS_UP_MASK        GENMASK(7, 4)
98 #define CPR3_THRESH_CONS_UP_SHIFT       4
99 #define CPR3_THRESH_DOWN_THRESH_MASK    GENMASK(12, 8)
100 #define CPR3_THRESH_DOWN_THRESH_SHIFT   8
101 #define CPR3_THRESH_UP_THRESH_MASK      GENMASK(17, 13)
102 #define CPR3_THRESH_UP_THRESH_SHIFT     13
103
104 #define CPR3_REG_RO_MASK(thread)        (0x80C + 0x440 * (thread))
105
106 #define CPR3_REG_RESULT0(thread)        (0x810 + 0x440 * (thread))
107 #define CPR3_RESULT0_BUSY_MASK          BIT(0)
108 #define CPR3_RESULT0_STEP_DN_MASK       BIT(1)
109 #define CPR3_RESULT0_STEP_UP_MASK       BIT(2)
110 #define CPR3_RESULT0_ERROR_STEPS_MASK   GENMASK(7, 3)
111 #define CPR3_RESULT0_ERROR_STEPS_SHIFT  3
112 #define CPR3_RESULT0_ERROR_MASK         GENMASK(19, 8)
113 #define CPR3_RESULT0_ERROR_SHIFT        8
114 #define CPR3_RESULT0_NEGATIVE_MASK      BIT(20)
115
116 #define CPR3_REG_RESULT1(thread)        (0x814 + 0x440 * (thread))
117 #define CPR3_RESULT1_QUOT_MIN_MASK      GENMASK(11, 0)
118 #define CPR3_RESULT1_QUOT_MIN_SHIFT     0
119 #define CPR3_RESULT1_QUOT_MAX_MASK      GENMASK(23, 12)
120 #define CPR3_RESULT1_QUOT_MAX_SHIFT     12
121 #define CPR3_RESULT1_RO_MIN_MASK        GENMASK(27, 24)
122 #define CPR3_RESULT1_RO_MIN_SHIFT       24
123 #define CPR3_RESULT1_RO_MAX_MASK        GENMASK(31, 28)
124 #define CPR3_RESULT1_RO_MAX_SHIFT       28
125
126 #define CPR3_REG_RESULT2(thread)                (0x818 + 0x440 * (thread))
127 #define CPR3_RESULT2_STEP_QUOT_MIN_MASK         GENMASK(5, 0)
128 #define CPR3_RESULT2_STEP_QUOT_MIN_SHIFT        0
129 #define CPR3_RESULT2_STEP_QUOT_MAX_MASK         GENMASK(11, 6)
130 #define CPR3_RESULT2_STEP_QUOT_MAX_SHIFT        6
131 #define CPR3_RESULT2_SENSOR_MIN_MASK            GENMASK(23, 16)
132 #define CPR3_RESULT2_SENSOR_MIN_SHIFT           16
133 #define CPR3_RESULT2_SENSOR_MAX_MASK            GENMASK(31, 24)
134 #define CPR3_RESULT2_SENSOR_MAX_SHIFT           24
135
136 #define CPR3_REG_IRQ_EN                 0x81C
137 #define CPR3_REG_IRQ_CLEAR              0x820
138 #define CPR3_REG_IRQ_STATUS             0x824
139 #define CPR3_IRQ_UP                     BIT(3)
140 #define CPR3_IRQ_MID                    BIT(2)
141 #define CPR3_IRQ_DOWN                   BIT(1)
142
143 #define CPR3_REG_TARGET_QUOT(thread, ro) \
144                                         (0x840 + 0x440 * (thread) + 0x4 * (ro))
145
146 /* Registers found only on controllers that support HW closed-loop. */
147 #define CPR3_REG_PD_THROTTLE            0xE8
148 #define CPR3_PD_THROTTLE_DISABLE        0x0
149
150 #define CPR3_REG_HW_CLOSED_LOOP         0x3000
151 #define CPR3_HW_CLOSED_LOOP_ENABLE      0x0
152 #define CPR3_HW_CLOSED_LOOP_DISABLE     0x1
153
154 #define CPR3_REG_CPR_TIMER_MID_CONT     0x3004
155 #define CPR3_REG_CPR_TIMER_UP_DN_CONT   0x3008
156
157 #define CPR3_REG_LAST_MEASUREMENT               0x7F8
158 #define CPR3_LAST_MEASUREMENT_THREAD_DN_SHIFT   0
159 #define CPR3_LAST_MEASUREMENT_THREAD_UP_SHIFT   4
160 #define CPR3_LAST_MEASUREMENT_THREAD_DN(thread) \
161                 (BIT(thread) << CPR3_LAST_MEASUREMENT_THREAD_DN_SHIFT)
162 #define CPR3_LAST_MEASUREMENT_THREAD_UP(thread) \
163                 (BIT(thread) << CPR3_LAST_MEASUREMENT_THREAD_UP_SHIFT)
164 #define CPR3_LAST_MEASUREMENT_AGGR_DN           BIT(8)
165 #define CPR3_LAST_MEASUREMENT_AGGR_MID          BIT(9)
166 #define CPR3_LAST_MEASUREMENT_AGGR_UP           BIT(10)
167 #define CPR3_LAST_MEASUREMENT_VALID             BIT(11)
168 #define CPR3_LAST_MEASUREMENT_SAW_ERROR         BIT(12)
169 #define CPR3_LAST_MEASUREMENT_PD_BYPASS_MASK    GENMASK(23, 16)
170 #define CPR3_LAST_MEASUREMENT_PD_BYPASS_SHIFT   16
171
172 /* CPR4 controller specific registers and bit definitions */
173 #define CPR4_REG_CPR_TIMER_CLAMP                        0x10
174 #define CPR4_CPR_TIMER_CLAMP_THREAD_AGGREGATION_EN      BIT(27)
175
176 #define CPR4_REG_MISC                           0x700
177 #define CPR4_MISC_RESET_STEP_QUOT_LOOP_EN       BIT(2)
178 #define CPR4_MISC_MARGIN_TABLE_ROW_SELECT_MASK  GENMASK(23, 20)
179 #define CPR4_MISC_MARGIN_TABLE_ROW_SELECT_SHIFT 20
180 #define CPR4_MISC_TEMP_SENSOR_ID_START_MASK     GENMASK(27, 24)
181 #define CPR4_MISC_TEMP_SENSOR_ID_START_SHIFT    24
182 #define CPR4_MISC_TEMP_SENSOR_ID_END_MASK       GENMASK(31, 28)
183 #define CPR4_MISC_TEMP_SENSOR_ID_END_SHIFT      28
184
185 #define CPR4_REG_SAW_ERROR_STEP_LIMIT           0x7A4
186 #define CPR4_SAW_ERROR_STEP_LIMIT_UP_MASK       GENMASK(4, 0)
187 #define CPR4_SAW_ERROR_STEP_LIMIT_UP_SHIFT      0
188 #define CPR4_SAW_ERROR_STEP_LIMIT_DN_MASK       GENMASK(9, 5)
189 #define CPR4_SAW_ERROR_STEP_LIMIT_DN_SHIFT      5
190
191 #define CPR4_REG_MARGIN_TEMP_CORE_TIMERS                        0x7A8
192 #define CPR4_MARGIN_TEMP_CORE_TIMERS_SETTLE_VOLTAGE_COUNT_MASK  GENMASK(28, 18)
193 #define CPR4_MARGIN_TEMP_CORE_TIMERS_SETTLE_VOLTAGE_COUNT_SHIFT 18
194
195 #define CPR4_REG_MARGIN_TEMP_CORE(core)         (0x7AC + 0x4 * (core))
196 #define CPR4_MARGIN_TEMP_CORE_ADJ_MASK          GENMASK(7, 0)
197 #define CPR4_MARGIN_TEMP_CORE_ADJ_SHIFT         8
198
199 #define CPR4_REG_MARGIN_TEMP_POINT0N1           0x7F0
200 #define CPR4_MARGIN_TEMP_POINT0_MASK            GENMASK(11, 0)
201 #define CPR4_MARGIN_TEMP_POINT0_SHIFT           0
202 #define CPR4_MARGIN_TEMP_POINT1_MASK            GENMASK(23, 12)
203 #define CPR4_MARGIN_TEMP_POINT1_SHIFT           12
204 #define CPR4_REG_MARGIN_TEMP_POINT2             0x7F4
205 #define CPR4_MARGIN_TEMP_POINT2_MASK            GENMASK(11, 0)
206 #define CPR4_MARGIN_TEMP_POINT2_SHIFT           0
207
208 #define CPR4_REG_MARGIN_ADJ_CTL                                 0x7F8
209 #define CPR4_MARGIN_ADJ_CTL_BOOST_EN                            BIT(0)
210 #define CPR4_MARGIN_ADJ_CTL_CORE_ADJ_EN                         BIT(1)
211 #define CPR4_MARGIN_ADJ_CTL_TEMP_ADJ_EN                         BIT(2)
212 #define CPR4_MARGIN_ADJ_CTL_TIMER_SETTLE_VOLTAGE_EN             BIT(3)
213 #define CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK              BIT(4)
214 #define CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE               BIT(4)
215 #define CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_DISABLE              0
216 #define CPR4_MARGIN_ADJ_CTL_PER_RO_KV_MARGIN_EN                 BIT(7)
217 #define CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_EN                    BIT(8)
218 #define CPR4_MARGIN_ADJ_CTL_PMIC_STEP_SIZE_MASK                 GENMASK(16, 12)
219 #define CPR4_MARGIN_ADJ_CTL_PMIC_STEP_SIZE_SHIFT                12
220 #define CPR4_MARGIN_ADJ_CTL_INITIAL_TEMP_BAND_MASK              GENMASK(21, 19)
221 #define CPR4_MARGIN_ADJ_CTL_INITIAL_TEMP_BAND_SHIFT             19
222 #define CPR4_MARGIN_ADJ_CTL_MAX_NUM_CORES_MASK                  GENMASK(25, 22)
223 #define CPR4_MARGIN_ADJ_CTL_MAX_NUM_CORES_SHIFT                 22
224 #define CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_STEP_QUOT_MASK        GENMASK(31, 26)
225 #define CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_STEP_QUOT_SHIFT       26
226
227 #define CPR4_REG_CPR_MASK_THREAD(thread)        (0x80C + 0x440 * (thread))
228 #define CPR4_CPR_MASK_THREAD_DISABLE_THREAD             BIT(31)
229 #define CPR4_CPR_MASK_THREAD_RO_MASK4THREAD_MASK        GENMASK(15, 0)
230
231 /* CPRh controller specific registers and bit definitions */
232 #define CPRH_REG_CORNER(corner) (0x3A00 + 0x4 * (corner))
233 #define CPRH_CORNER_INIT_VOLTAGE_MASK           GENMASK(7, 0)
234 #define CPRH_CORNER_INIT_VOLTAGE_SHIFT          0
235 #define CPRH_CORNER_FLOOR_VOLTAGE_MASK          GENMASK(15, 8)
236 #define CPRH_CORNER_FLOOR_VOLTAGE_SHIFT         8
237 #define CPRH_CORNER_QUOT_DELTA_MASK             GENMASK(24, 16)
238 #define CPRH_CORNER_QUOT_DELTA_SHIFT            16
239 #define CPRH_CORNER_RO_SEL_MASK                 GENMASK(28, 25)
240 #define CPRH_CORNER_RO_SEL_SHIFT                25
241 #define CPRH_CORNER_CPR_CL_DISABLE      BIT(29)
242 #define CPRH_CORNER_CORE_TEMP_MARGIN_DISABLE    BIT(30)
243 #define CPRH_CORNER_LAST_KNOWN_VOLTAGE_ENABLE   BIT(31)
244 #define CPRH_CORNER_INIT_VOLTAGE_MAX_VALUE      255
245 #define CPRH_CORNER_FLOOR_VOLTAGE_MAX_VALUE     255
246 #define CPRH_CORNER_QUOT_DELTA_MAX_VALUE        511
247
248 #define CPRH_REG_CTL                            0x3AA0
249 #define CPRH_CTL_OSM_ENABLED                    BIT(0)
250 #define CPRH_CTL_BASE_VOLTAGE_MASK              GENMASK(10, 1)
251 #define CPRH_CTL_BASE_VOLTAGE_SHIFT             1
252 #define CPRH_CTL_INIT_MODE_MASK         GENMASK(16, 11)
253 #define CPRH_CTL_INIT_MODE_SHIFT                11
254 #define CPRH_CTL_MODE_SWITCH_DELAY_MASK         GENMASK(24, 17)
255 #define CPRH_CTL_MODE_SWITCH_DELAY_SHIFT        17
256 #define CPRH_CTL_VOLTAGE_MULTIPLIER_MASK        GENMASK(28, 25)
257 #define CPRH_CTL_VOLTAGE_MULTIPLIER_SHIFT       25
258 #define CPRH_CTL_LAST_KNOWN_VOLTAGE_MARGIN_MASK         GENMASK(31, 29)
259 #define CPRH_CTL_LAST_KNOWN_VOLTAGE_MARGIN_SHIFT        29
260
261 #define CPRH_REG_STATUS                 0x3AA4
262 #define CPRH_STATUS_CORNER                      GENMASK(5, 0)
263 #define CPRH_STATUS_CORNER_LAST_VOLT_MASK       GENMASK(17, 6)
264 #define CPRH_STATUS_CORNER_LAST_VOLT_SHIFT      6
265
266 #define CPRH_REG_CORNER_BAND    0x3AA8
267 #define CPRH_CORNER_BAND_MASK           GENMASK(5, 0)
268 #define CPRH_CORNER_BAND_SHIFT          6
269 #define CPRH_CORNER_BAND_MAX_COUNT              4
270
271 #define CPRH_MARGIN_TEMP_CORE_VBAND(core, vband) \
272         ((vband) == 0 ? CPR4_REG_MARGIN_TEMP_CORE(core) \
273                         : 0x3AB0 + 0x40 * ((vband) - 1) + 0x4 * (core))
274
275 /*
276  * The amount of time to wait for the CPR controller to become idle when
277  * performing an aging measurement.
278  */
279 #define CPR3_AGING_MEASUREMENT_TIMEOUT_NS       5000000
280
281 /*
282  * The number of individual aging measurements to perform which are then
283  * averaged together in order to determine the final aging adjustment value.
284  */
285 #define CPR3_AGING_MEASUREMENT_ITERATIONS       16
286
287 /*
288  * Aging measurements for the aged and unaged ring oscillators take place a few
289  * microseconds apart.  If the vdd-supply voltage fluctuates between the two
290  * measurements, then the difference between them will be incorrect.  The
291  * difference could end up too high or too low.  This constant defines the
292  * number of lowest and highest measurements to ignore when averaging.
293  */
294 #define CPR3_AGING_MEASUREMENT_FILTER           3
295
296 /*
297  * The number of times to attempt the full aging measurement sequence before
298  * declaring a measurement failure.
299  */
300 #define CPR3_AGING_RETRY_COUNT                  5
301
302 /*
303  * The maximum time to wait in microseconds for a CPR register write to
304  * complete.
305  */
306 #define CPR3_REGISTER_WRITE_DELAY_US            200
307
308 /*
309  * The number of times the CPRh controller multiplies the mode switch
310  * delay before utilizing it.
311  */
312 #define CPRH_MODE_SWITCH_DELAY_FACTOR 4
313
314 /*
315  * The number of times the CPRh controller multiplies the delta quotient
316  * steps before utilizing it.
317  */
318 #define CPRH_DELTA_QUOT_STEP_FACTOR 4
319
320 /*
321  * The multiplier applied to scaling factor value used to derive GCNT
322  * for aging measurements.
323  */
324 #define CPR3_AGING_GCNT_SCALING_UNITY   1000
325
326 static DEFINE_MUTEX(cpr3_controller_list_mutex);
327 static LIST_HEAD(cpr3_controller_list);
328 static struct dentry *cpr3_debugfs_base;
329
330 /**
331  * cpr3_read() - read four bytes from the memory address specified
332  * @ctrl:               Pointer to the CPR3 controller
333  * @offset:             Offset in bytes from the CPR3 controller's base address
334  *
335  * Return: memory address value
336  */
337 static inline u32 cpr3_read(struct cpr3_controller *ctrl, u32 offset)
338 {
339         if (!ctrl->cpr_enabled) {
340                 cpr3_err(ctrl, "CPR register reads are not possible when CPR clocks are disabled\n");
341                 return 0;
342         }
343
344         return readl_relaxed(ctrl->cpr_ctrl_base + offset);
345 }
346
347 /**
348  * cpr3_write() - write four bytes to the memory address specified
349  * @ctrl:               Pointer to the CPR3 controller
350  * @offset:             Offset in bytes from the CPR3 controller's base address
351  * @value:              Value to write to the memory address
352  *
353  * Return: none
354  */
355 static inline void cpr3_write(struct cpr3_controller *ctrl, u32 offset,
356                                 u32 value)
357 {
358         if (!ctrl->cpr_enabled) {
359                 cpr3_err(ctrl, "CPR register writes are not possible when CPR clocks are disabled\n");
360                 return;
361         }
362
363         writel_relaxed(value, ctrl->cpr_ctrl_base + offset);
364 }
365
366 /**
367  * cpr3_masked_write() - perform a read-modify-write sequence so that only
368  *              masked bits are modified
369  * @ctrl:               Pointer to the CPR3 controller
370  * @offset:             Offset in bytes from the CPR3 controller's base address
371  * @mask:               Mask identifying the bits that should be modified
372  * @value:              Value to write to the memory address
373  *
374  * Return: none
375  */
376 static inline void cpr3_masked_write(struct cpr3_controller *ctrl, u32 offset,
377                                 u32 mask, u32 value)
378 {
379         u32 reg_val, orig_val;
380
381         if (!ctrl->cpr_enabled) {
382                 cpr3_err(ctrl, "CPR register writes are not possible when CPR clocks are disabled\n");
383                 return;
384         }
385
386         reg_val = orig_val = readl_relaxed(ctrl->cpr_ctrl_base + offset);
387         reg_val &= ~mask;
388         reg_val |= value & mask;
389
390         if (reg_val != orig_val)
391                 writel_relaxed(reg_val, ctrl->cpr_ctrl_base + offset);
392 }
393
394 /**
395  * cpr3_ctrl_loop_enable() - enable the CPR sensing loop for a given controller
396  * @ctrl:               Pointer to the CPR3 controller
397  *
398  * Return: none
399  */
400 static inline void cpr3_ctrl_loop_enable(struct cpr3_controller *ctrl)
401 {
402         if (ctrl->cpr_enabled && !(ctrl->aggr_corner.sdelta
403                 && ctrl->aggr_corner.sdelta->allow_boost))
404                 cpr3_masked_write(ctrl, CPR3_REG_CPR_CTL,
405                         CPR3_CPR_CTL_LOOP_EN_MASK, CPR3_CPR_CTL_LOOP_ENABLE);
406 }
407
408 /**
409  * cpr3_ctrl_loop_disable() - disable the CPR sensing loop for a given
410  *              controller
411  * @ctrl:               Pointer to the CPR3 controller
412  *
413  * Return: none
414  */
415 static inline void cpr3_ctrl_loop_disable(struct cpr3_controller *ctrl)
416 {
417         if (ctrl->cpr_enabled)
418                 cpr3_masked_write(ctrl, CPR3_REG_CPR_CTL,
419                         CPR3_CPR_CTL_LOOP_EN_MASK, CPR3_CPR_CTL_LOOP_DISABLE);
420 }
421
422 /**
423  * cpr3_clock_enable() - prepare and enable all clocks used by this CPR3
424  *              controller
425  * @ctrl:               Pointer to the CPR3 controller
426  *
427  * Return: 0 on success, errno on failure
428  */
429 static int cpr3_clock_enable(struct cpr3_controller *ctrl)
430 {
431         int rc;
432
433         rc = clk_prepare_enable(ctrl->bus_clk);
434         if (rc) {
435                 cpr3_err(ctrl, "failed to enable bus clock, rc=%d\n", rc);
436                 return rc;
437         }
438
439         rc = clk_prepare_enable(ctrl->iface_clk);
440         if (rc) {
441                 cpr3_err(ctrl, "failed to enable interface clock, rc=%d\n", rc);
442                 clk_disable_unprepare(ctrl->bus_clk);
443                 return rc;
444         }
445
446         rc = clk_prepare_enable(ctrl->core_clk);
447         if (rc) {
448                 cpr3_err(ctrl, "failed to enable core clock, rc=%d\n", rc);
449                 clk_disable_unprepare(ctrl->iface_clk);
450                 clk_disable_unprepare(ctrl->bus_clk);
451                 return rc;
452         }
453
454         return 0;
455 }
456
457 /**
458  * cpr3_clock_disable() - disable and unprepare all clocks used by this CPR3
459  *              controller
460  * @ctrl:               Pointer to the CPR3 controller
461  *
462  * Return: none
463  */
464 static void cpr3_clock_disable(struct cpr3_controller *ctrl)
465 {
466         clk_disable_unprepare(ctrl->core_clk);
467         clk_disable_unprepare(ctrl->iface_clk);
468         clk_disable_unprepare(ctrl->bus_clk);
469 }
470
471 /**
472  * cpr3_ctrl_clear_cpr4_config() - clear the CPR4 register configuration
473  *              programmed for current aggregated corner of a given controller
474  * @ctrl:               Pointer to the CPR3 controller
475  *
476  * Return: 0 on success, errno on failure
477  */
478 static inline int cpr3_ctrl_clear_cpr4_config(struct cpr3_controller *ctrl)
479 {
480         struct cpr4_sdelta *aggr_sdelta = ctrl->aggr_corner.sdelta;
481         bool cpr_enabled = ctrl->cpr_enabled;
482         int i, rc = 0;
483
484         if (!aggr_sdelta || !(aggr_sdelta->allow_core_count_adj
485                 || aggr_sdelta->allow_temp_adj || aggr_sdelta->allow_boost))
486                 /* cpr4 features are not enabled */
487                 return 0;
488
489         /* Ensure that CPR clocks are enabled before writing to registers. */
490         if (!cpr_enabled) {
491                 rc = cpr3_clock_enable(ctrl);
492                 if (rc) {
493                         cpr3_err(ctrl, "clock enable failed, rc=%d\n", rc);
494                         return rc;
495                 }
496                 ctrl->cpr_enabled = true;
497         }
498
499         /*
500          * Clear feature enable configuration made for current
501          * aggregated corner.
502          */
503         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
504                 CPR4_MARGIN_ADJ_CTL_MAX_NUM_CORES_MASK
505                 | CPR4_MARGIN_ADJ_CTL_CORE_ADJ_EN
506                 | CPR4_MARGIN_ADJ_CTL_TEMP_ADJ_EN
507                 | CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_EN
508                 | CPR4_MARGIN_ADJ_CTL_BOOST_EN
509                 | CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK, 0);
510
511         cpr3_masked_write(ctrl, CPR4_REG_MISC,
512                         CPR4_MISC_MARGIN_TABLE_ROW_SELECT_MASK,
513                         0 << CPR4_MISC_MARGIN_TABLE_ROW_SELECT_SHIFT);
514
515         for (i = 0; i <= aggr_sdelta->max_core_count; i++) {
516                 /* Clear voltage margin adjustments programmed in TEMP_COREi */
517                 cpr3_write(ctrl, CPR4_REG_MARGIN_TEMP_CORE(i), 0);
518         }
519
520         /* Turn off CPR clocks if they were off before this function call. */
521         if (!cpr_enabled) {
522                 cpr3_clock_disable(ctrl);
523                 ctrl->cpr_enabled = false;
524         }
525
526         return 0;
527 }
528
529 /**
530  * cpr3_closed_loop_enable() - enable logical CPR closed-loop operation
531  * @ctrl:               Pointer to the CPR3 controller
532  *
533  * Return: 0 on success, errno on failure
534  */
535 static int cpr3_closed_loop_enable(struct cpr3_controller *ctrl)
536 {
537         int rc;
538
539         if (!ctrl->cpr_allowed_hw || !ctrl->cpr_allowed_sw) {
540                 cpr3_err(ctrl, "cannot enable closed-loop CPR operation because it is disallowed\n");
541                 return -EPERM;
542         } else if (ctrl->cpr_enabled) {
543                 /* Already enabled */
544                 return 0;
545         } else if (ctrl->cpr_suspended) {
546                 /*
547                  * CPR must remain disabled as the system is entering suspend.
548                  */
549                 return 0;
550         }
551
552         rc = cpr3_clock_enable(ctrl);
553         if (rc) {
554                 cpr3_err(ctrl, "unable to enable CPR clocks, rc=%d\n", rc);
555                 return rc;
556         }
557
558         ctrl->cpr_enabled = true;
559         cpr3_debug(ctrl, "CPR closed-loop operation enabled\n");
560
561         return 0;
562 }
563
564 /**
565  * cpr3_closed_loop_disable() - disable logical CPR closed-loop operation
566  * @ctrl:               Pointer to the CPR3 controller
567  *
568  * Return: 0 on success, errno on failure
569  */
570 static inline int cpr3_closed_loop_disable(struct cpr3_controller *ctrl)
571 {
572         if (!ctrl->cpr_enabled) {
573                 /* Already disabled */
574                 return 0;
575         }
576
577         cpr3_clock_disable(ctrl);
578         ctrl->cpr_enabled = false;
579         cpr3_debug(ctrl, "CPR closed-loop operation disabled\n");
580
581         return 0;
582 }
583
584 /**
585  * cpr3_regulator_get_gcnt() - returns the GCNT register value corresponding
586  *              to the clock rate and sensor time of the CPR3 controller
587  * @ctrl:               Pointer to the CPR3 controller
588  *
589  * Return: GCNT value
590  */
591 static u32 cpr3_regulator_get_gcnt(struct cpr3_controller *ctrl)
592 {
593         u64 temp;
594         unsigned int remainder;
595         u32 gcnt;
596
597         temp = (u64)ctrl->cpr_clock_rate * (u64)ctrl->sensor_time;
598         remainder = do_div(temp, 1000000000);
599         if (remainder)
600                 temp++;
601         /*
602          * GCNT == 0 corresponds to a single ref clock measurement interval so
603          * offset GCNT values by 1.
604          */
605         gcnt = temp - 1;
606
607         return gcnt;
608 }
609
610 /**
611  * cpr3_regulator_init_thread() - performs hardware initialization of CPR
612  *              thread registers
613  * @thread:             Pointer to the CPR3 thread
614  *
615  * CPR interface/bus clocks must be enabled before calling this function.
616  *
617  * Return: 0 on success, errno on failure
618  */
619 static int cpr3_regulator_init_thread(struct cpr3_thread *thread)
620 {
621         u32 reg;
622
623         reg = (thread->consecutive_up << CPR3_THRESH_CONS_UP_SHIFT)
624                 & CPR3_THRESH_CONS_UP_MASK;
625         reg |= (thread->consecutive_down << CPR3_THRESH_CONS_DOWN_SHIFT)
626                 & CPR3_THRESH_CONS_DOWN_MASK;
627         reg |= (thread->up_threshold << CPR3_THRESH_UP_THRESH_SHIFT)
628                 & CPR3_THRESH_UP_THRESH_MASK;
629         reg |= (thread->down_threshold << CPR3_THRESH_DOWN_THRESH_SHIFT)
630                 & CPR3_THRESH_DOWN_THRESH_MASK;
631
632         cpr3_write(thread->ctrl, CPR3_REG_THRESH(thread->thread_id), reg);
633
634         /*
635          * Mask all RO's initially so that unused thread doesn't contribute
636          * to closed-loop voltage.
637          */
638         cpr3_write(thread->ctrl, CPR3_REG_RO_MASK(thread->thread_id),
639                 CPR3_RO_MASK);
640
641         return 0;
642 }
643
644 /**
645  * cpr4_regulator_init_temp_points() - performs hardware initialization of CPR4
646  *              registers to track tsen temperature data and also specify the
647  *              temperature band range values to apply different voltage margins
648  * @ctrl:               Pointer to the CPR3 controller
649  *
650  * CPR interface/bus clocks must be enabled before calling this function.
651  *
652  * Return: 0 on success, errno on failure
653  */
654 static int cpr4_regulator_init_temp_points(struct cpr3_controller *ctrl)
655 {
656         if (!ctrl->allow_temp_adj)
657                 return 0;
658
659         cpr3_masked_write(ctrl, CPR4_REG_MISC,
660                                 CPR4_MISC_TEMP_SENSOR_ID_START_MASK,
661                                 ctrl->temp_sensor_id_start
662                                 << CPR4_MISC_TEMP_SENSOR_ID_START_SHIFT);
663
664         cpr3_masked_write(ctrl, CPR4_REG_MISC,
665                                 CPR4_MISC_TEMP_SENSOR_ID_END_MASK,
666                                 ctrl->temp_sensor_id_end
667                                 << CPR4_MISC_TEMP_SENSOR_ID_END_SHIFT);
668
669         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_TEMP_POINT2,
670                 CPR4_MARGIN_TEMP_POINT2_MASK,
671                 (ctrl->temp_band_count == 4 ? ctrl->temp_points[2] : 0x7FF)
672                 << CPR4_MARGIN_TEMP_POINT2_SHIFT);
673
674         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_TEMP_POINT0N1,
675                 CPR4_MARGIN_TEMP_POINT1_MASK,
676                 (ctrl->temp_band_count >= 3 ? ctrl->temp_points[1] : 0x7FF)
677                 << CPR4_MARGIN_TEMP_POINT1_SHIFT);
678
679         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_TEMP_POINT0N1,
680                 CPR4_MARGIN_TEMP_POINT0_MASK,
681                 (ctrl->temp_band_count >= 2 ? ctrl->temp_points[0] : 0x7FF)
682                 << CPR4_MARGIN_TEMP_POINT0_SHIFT);
683         return 0;
684 }
685
686 /**
687  * cpr3_regulator_init_cpr4() - performs hardware initialization at the
688  *              controller and thread level required for CPR4 operation.
689  * @ctrl:               Pointer to the CPR3 controller
690  *
691  * CPR interface/bus clocks must be enabled before calling this function.
692  * This function allocates sdelta structures and sdelta tables for aggregated
693  * corners of the controller and its threads.
694  *
695  * Return: 0 on success, errno on failure
696  */
697 static int cpr3_regulator_init_cpr4(struct cpr3_controller *ctrl)
698 {
699         struct cpr3_thread *thread;
700         struct cpr3_regulator *vreg;
701         struct cpr4_sdelta *sdelta;
702         int i, j, ctrl_max_core_count, thread_max_core_count, rc = 0;
703         bool ctrl_valid_sdelta, thread_valid_sdelta;
704         u32 pmic_step_size = 1;
705         int thread_id = 0;
706         u64 temp;
707
708         if (ctrl->reset_step_quot_loop_en)
709                 cpr3_masked_write(ctrl, CPR4_REG_MISC,
710                                 CPR4_MISC_RESET_STEP_QUOT_LOOP_EN,
711                                 CPR4_MISC_RESET_STEP_QUOT_LOOP_EN);
712
713         if (ctrl->supports_hw_closed_loop) {
714                 if (ctrl->saw_use_unit_mV)
715                         pmic_step_size = ctrl->step_volt / 1000;
716                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
717                                   CPR4_MARGIN_ADJ_CTL_PMIC_STEP_SIZE_MASK,
718                                   (pmic_step_size
719                                   << CPR4_MARGIN_ADJ_CTL_PMIC_STEP_SIZE_SHIFT));
720
721                 cpr3_masked_write(ctrl, CPR4_REG_SAW_ERROR_STEP_LIMIT,
722                                   CPR4_SAW_ERROR_STEP_LIMIT_DN_MASK,
723                                   (ctrl->down_error_step_limit
724                                         << CPR4_SAW_ERROR_STEP_LIMIT_DN_SHIFT));
725
726                 cpr3_masked_write(ctrl, CPR4_REG_SAW_ERROR_STEP_LIMIT,
727                                   CPR4_SAW_ERROR_STEP_LIMIT_UP_MASK,
728                                   (ctrl->up_error_step_limit
729                                         << CPR4_SAW_ERROR_STEP_LIMIT_UP_SHIFT));
730
731                 /*
732                  * Enable thread aggregation regardless of which threads are
733                  * enabled or disabled.
734                  */
735                 cpr3_masked_write(ctrl, CPR4_REG_CPR_TIMER_CLAMP,
736                                   CPR4_CPR_TIMER_CLAMP_THREAD_AGGREGATION_EN,
737                                   CPR4_CPR_TIMER_CLAMP_THREAD_AGGREGATION_EN);
738
739                 switch (ctrl->thread_count) {
740                 case 0:
741                         /* Disable both threads */
742                         cpr3_masked_write(ctrl, CPR4_REG_CPR_MASK_THREAD(0),
743                                 CPR4_CPR_MASK_THREAD_DISABLE_THREAD
744                                     | CPR4_CPR_MASK_THREAD_RO_MASK4THREAD_MASK,
745                                 CPR4_CPR_MASK_THREAD_DISABLE_THREAD
746                                     | CPR4_CPR_MASK_THREAD_RO_MASK4THREAD_MASK);
747
748                         cpr3_masked_write(ctrl, CPR4_REG_CPR_MASK_THREAD(1),
749                                 CPR4_CPR_MASK_THREAD_DISABLE_THREAD
750                                     | CPR4_CPR_MASK_THREAD_RO_MASK4THREAD_MASK,
751                                 CPR4_CPR_MASK_THREAD_DISABLE_THREAD
752                                     | CPR4_CPR_MASK_THREAD_RO_MASK4THREAD_MASK);
753                         break;
754                 case 1:
755                         /* Disable unused thread */
756                         thread_id = ctrl->thread[0].thread_id ? 0 : 1;
757                         cpr3_masked_write(ctrl,
758                                 CPR4_REG_CPR_MASK_THREAD(thread_id),
759                                 CPR4_CPR_MASK_THREAD_DISABLE_THREAD
760                                     | CPR4_CPR_MASK_THREAD_RO_MASK4THREAD_MASK,
761                                 CPR4_CPR_MASK_THREAD_DISABLE_THREAD
762                                     | CPR4_CPR_MASK_THREAD_RO_MASK4THREAD_MASK);
763                         break;
764                 }
765         }
766
767         if (!ctrl->allow_core_count_adj && !ctrl->allow_temp_adj
768                 && !ctrl->allow_boost) {
769                 /*
770                  * Skip below configuration as none of the features
771                  * are enabled.
772                  */
773                 return rc;
774         }
775
776         if (ctrl->supports_hw_closed_loop)
777                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
778                                   CPR4_MARGIN_ADJ_CTL_TIMER_SETTLE_VOLTAGE_EN,
779                                   CPR4_MARGIN_ADJ_CTL_TIMER_SETTLE_VOLTAGE_EN);
780
781         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
782                         CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_STEP_QUOT_MASK,
783                         ctrl->step_quot_fixed
784                         << CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_STEP_QUOT_SHIFT);
785
786         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
787                         CPR4_MARGIN_ADJ_CTL_PER_RO_KV_MARGIN_EN,
788                         (ctrl->use_dynamic_step_quot
789                         ? CPR4_MARGIN_ADJ_CTL_PER_RO_KV_MARGIN_EN : 0));
790
791         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
792                         CPR4_MARGIN_ADJ_CTL_INITIAL_TEMP_BAND_MASK,
793                         ctrl->initial_temp_band
794                         << CPR4_MARGIN_ADJ_CTL_INITIAL_TEMP_BAND_SHIFT);
795
796         rc = cpr4_regulator_init_temp_points(ctrl);
797         if (rc) {
798                 cpr3_err(ctrl, "initialize temp points failed, rc=%d\n", rc);
799                 return rc;
800         }
801
802         if (ctrl->voltage_settling_time) {
803                 /*
804                  * Configure the settling timer used to account for
805                  * one VDD supply step.
806                  */
807                 temp = (u64)ctrl->cpr_clock_rate
808                                 * (u64)ctrl->voltage_settling_time;
809                 do_div(temp, 1000000000);
810                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_TEMP_CORE_TIMERS,
811                         CPR4_MARGIN_TEMP_CORE_TIMERS_SETTLE_VOLTAGE_COUNT_MASK,
812                         temp
813                     << CPR4_MARGIN_TEMP_CORE_TIMERS_SETTLE_VOLTAGE_COUNT_SHIFT);
814         }
815
816         /*
817          * Allocate memory for cpr4_sdelta structure and sdelta table for
818          * controller aggregated corner by finding the maximum core count
819          * used by any cpr3 regulators.
820          */
821         ctrl_max_core_count = 1;
822         ctrl_valid_sdelta = false;
823         for (i = 0; i < ctrl->thread_count; i++) {
824                 thread = &ctrl->thread[i];
825
826                 /*
827                  * Allocate memory for cpr4_sdelta structure and sdelta table
828                  * for thread aggregated corner by finding the maximum core
829                  * count used by any cpr3 regulators of the thread.
830                  */
831                 thread_max_core_count = 1;
832                 thread_valid_sdelta = false;
833                 for (j = 0; j < thread->vreg_count; j++) {
834                         vreg = &thread->vreg[j];
835                         thread_max_core_count = max(thread_max_core_count,
836                                                         vreg->max_core_count);
837                         thread_valid_sdelta |= (vreg->allow_core_count_adj
838                                                         | vreg->allow_temp_adj
839                                                         | vreg->allow_boost);
840                 }
841                 if (thread_valid_sdelta) {
842                         sdelta = devm_kzalloc(ctrl->dev, sizeof(*sdelta),
843                                         GFP_KERNEL);
844                         if (!sdelta)
845                                 return -ENOMEM;
846
847                         sdelta->table = devm_kcalloc(ctrl->dev,
848                                                 thread_max_core_count
849                                                 * ctrl->temp_band_count,
850                                                 sizeof(*sdelta->table),
851                                                 GFP_KERNEL);
852                         if (!sdelta->table)
853                                 return -ENOMEM;
854
855                         sdelta->boost_table = devm_kcalloc(ctrl->dev,
856                                                 ctrl->temp_band_count,
857                                                 sizeof(*sdelta->boost_table),
858                                                 GFP_KERNEL);
859                         if (!sdelta->boost_table)
860                                 return -ENOMEM;
861
862                         thread->aggr_corner.sdelta = sdelta;
863                 }
864
865                 ctrl_valid_sdelta |= thread_valid_sdelta;
866                 ctrl_max_core_count = max(ctrl_max_core_count,
867                                                 thread_max_core_count);
868         }
869
870         if (ctrl_valid_sdelta) {
871                 sdelta = devm_kzalloc(ctrl->dev, sizeof(*sdelta), GFP_KERNEL);
872                 if (!sdelta)
873                         return -ENOMEM;
874
875                 sdelta->table = devm_kcalloc(ctrl->dev, ctrl_max_core_count
876                                         * ctrl->temp_band_count,
877                                         sizeof(*sdelta->table), GFP_KERNEL);
878                 if (!sdelta->table)
879                         return -ENOMEM;
880
881                 sdelta->boost_table = devm_kcalloc(ctrl->dev,
882                                         ctrl->temp_band_count,
883                                         sizeof(*sdelta->boost_table),
884                                         GFP_KERNEL);
885                 if (!sdelta->boost_table)
886                         return -ENOMEM;
887
888                 ctrl->aggr_corner.sdelta = sdelta;
889         }
890
891         return 0;
892 }
893
894 /**
895  * cpr3_write_temp_core_margin() - programs hardware SDELTA registers with
896  *              the voltage margin adjustments that need to be applied for
897  *              different online core-count and temperature bands.
898  * @ctrl:               Pointer to the CPR3 controller
899  * @addr:               SDELTA register address
900  * @temp_core_adj:      Array of voltage margin values for different temperature
901  *                      bands.
902  *
903  * CPR interface/bus clocks must be enabled before calling this function.
904  *
905  * Return: none
906  */
907 static void cpr3_write_temp_core_margin(struct cpr3_controller *ctrl,
908                                  int addr, int *temp_core_adj)
909 {
910         int i, margin_steps;
911         u32 reg = 0;
912
913         for (i = 0; i < ctrl->temp_band_count; i++) {
914                 margin_steps = max(min(temp_core_adj[i], 127), -128);
915                 reg |= (margin_steps & CPR4_MARGIN_TEMP_CORE_ADJ_MASK) <<
916                         (i * CPR4_MARGIN_TEMP_CORE_ADJ_SHIFT);
917         }
918
919         cpr3_write(ctrl, addr, reg);
920         cpr3_debug(ctrl, "sdelta offset=0x%08x, val=0x%08x\n", addr, reg);
921 }
922
923 /**
924  * cpr3_controller_program_sdelta() - programs hardware SDELTA registers with
925  *              the voltage margin adjustments that need to be applied at
926  *              different online core-count and temperature bands. Also,
927  *              programs hardware register configuration for per-online-core
928  *              and per-temperature based adjustments.
929  * @ctrl:               Pointer to the CPR3 controller
930  *
931  * CPR interface/bus clocks must be enabled before calling this function.
932  *
933  * Return: 0 on success, errno on failure
934  */
935 static int cpr3_controller_program_sdelta(struct cpr3_controller *ctrl)
936 {
937         struct cpr3_corner *corner = &ctrl->aggr_corner;
938         struct cpr4_sdelta *sdelta = corner->sdelta;
939         int i, index, max_core_count, rc = 0;
940         bool cpr_enabled = ctrl->cpr_enabled;
941
942         if (!sdelta)
943                 /* cpr4_sdelta not defined for current aggregated corner */
944                 return 0;
945
946         if (ctrl->supports_hw_closed_loop && ctrl->cpr_enabled) {
947                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
948                         CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
949                         (ctrl->use_hw_closed_loop && !sdelta->allow_boost)
950                         ? CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE : 0);
951         }
952
953         if (!sdelta->allow_core_count_adj && !sdelta->allow_temp_adj
954                 && !sdelta->allow_boost) {
955                 /*
956                  * Per-online-core, per-temperature and voltage boost
957                  * adjustments are disabled for this aggregation corner.
958                  */
959                 return 0;
960         }
961
962         /* Ensure that CPR clocks are enabled before writing to registers. */
963         if (!cpr_enabled) {
964                 rc = cpr3_clock_enable(ctrl);
965                 if (rc) {
966                         cpr3_err(ctrl, "clock enable failed, rc=%d\n", rc);
967                         return rc;
968                 }
969                 ctrl->cpr_enabled = true;
970         }
971
972         max_core_count = sdelta->max_core_count;
973
974         if (sdelta->allow_core_count_adj || sdelta->allow_temp_adj) {
975                 if (sdelta->allow_core_count_adj) {
976                         /* Program TEMP_CORE0 to same margins as TEMP_CORE1 */
977                         cpr3_write_temp_core_margin(ctrl,
978                                 CPR4_REG_MARGIN_TEMP_CORE(0),
979                                 &sdelta->table[0]);
980                 }
981
982                 for (i = 0; i < max_core_count; i++) {
983                         index = i * sdelta->temp_band_count;
984                         /*
985                          * Program TEMP_COREi with voltage margin adjustments
986                          * that need to be applied when the number of cores
987                          * becomes i.
988                          */
989                         cpr3_write_temp_core_margin(ctrl,
990                                 CPR4_REG_MARGIN_TEMP_CORE(
991                                                 sdelta->allow_core_count_adj
992                                                 ? i + 1 : max_core_count),
993                                                 &sdelta->table[index]);
994                 }
995         }
996
997         if (sdelta->allow_boost) {
998                 /* Program only boost_num_cores row of SDELTA */
999                 cpr3_write_temp_core_margin(ctrl,
1000                         CPR4_REG_MARGIN_TEMP_CORE(sdelta->boost_num_cores),
1001                                         &sdelta->boost_table[0]);
1002         }
1003
1004         if (!sdelta->allow_core_count_adj && !sdelta->allow_boost) {
1005                 cpr3_masked_write(ctrl, CPR4_REG_MISC,
1006                         CPR4_MISC_MARGIN_TABLE_ROW_SELECT_MASK,
1007                         max_core_count
1008                         << CPR4_MISC_MARGIN_TABLE_ROW_SELECT_SHIFT);
1009         }
1010
1011         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
1012                 CPR4_MARGIN_ADJ_CTL_MAX_NUM_CORES_MASK
1013                 | CPR4_MARGIN_ADJ_CTL_CORE_ADJ_EN
1014                 | CPR4_MARGIN_ADJ_CTL_TEMP_ADJ_EN
1015                 | CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_EN
1016                 | CPR4_MARGIN_ADJ_CTL_BOOST_EN,
1017                 max_core_count << CPR4_MARGIN_ADJ_CTL_MAX_NUM_CORES_SHIFT
1018                 | ((sdelta->allow_core_count_adj || sdelta->allow_boost)
1019                         ? CPR4_MARGIN_ADJ_CTL_CORE_ADJ_EN : 0)
1020                 | ((sdelta->allow_temp_adj && ctrl->supports_hw_closed_loop
1021                         && sdelta->allow_core_count_adj)
1022                         ? CPR4_MARGIN_ADJ_CTL_TEMP_ADJ_EN : 0)
1023                 | (((ctrl->use_hw_closed_loop && !sdelta->allow_boost)
1024                     || !ctrl->supports_hw_closed_loop)
1025                         ? CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_EN : 0)
1026                 | (sdelta->allow_boost
1027                         ?  CPR4_MARGIN_ADJ_CTL_BOOST_EN : 0));
1028
1029         /*
1030          * Ensure that all previous CPR register writes have completed before
1031          * continuing.
1032          */
1033         mb();
1034
1035         /* Turn off CPR clocks if they were off before this function call. */
1036         if (!cpr_enabled) {
1037                 cpr3_clock_disable(ctrl);
1038                 ctrl->cpr_enabled = false;
1039         }
1040
1041         return 0;
1042 }
1043
1044 /**
1045  * cpr3_regulator_set_base_target_quot() - configure the target quotient
1046  *              for each RO of the CPR3 regulator for CPRh operation.
1047  *              In particular, the quotient of the RO selected for operation
1048  *              should correspond to the lowest target quotient across the
1049  *              corners supported by the single regulator of the CPR3 thread.
1050  * @vreg:               Pointer to the CPR3 regulator
1051  * @base_quots:         Pointer to the base quotient array. The array must be
1052  *                      of size CPR3_RO_COUNT and it is populated with the
1053  *                      base quotient per-RO.
1054  *
1055  * Return: none
1056  */
1057 static void cpr3_regulator_set_base_target_quot(struct cpr3_regulator *vreg,
1058                                                 u32 *base_quots)
1059 {
1060         struct cpr3_controller *ctrl = vreg->thread->ctrl;
1061         int i, j, ro_mask = CPR3_RO_MASK;
1062         u32 min_quot;
1063
1064         for (i = 0; i < vreg->corner_count; i++)
1065                 ro_mask &= vreg->corner[i].ro_mask;
1066
1067         /* Unmask the ROs selected for active use. */
1068         cpr3_write(ctrl, CPR3_REG_RO_MASK(vreg->thread->thread_id),
1069                    ro_mask);
1070
1071         for (i = 0; i < CPR3_RO_COUNT; i++) {
1072                 for (j = 0, min_quot = INT_MAX; j < vreg->corner_count; j++)
1073                         if (vreg->corner[j].target_quot[i])
1074                                 min_quot = min(min_quot,
1075                                        vreg->corner[j].target_quot[i]);
1076
1077                 if (min_quot == INT_MAX)
1078                         min_quot = 0;
1079
1080                 cpr3_write(ctrl,
1081                            CPR3_REG_TARGET_QUOT(vreg->thread->thread_id, i),
1082                            min_quot);
1083
1084                 base_quots[i] = min_quot;
1085         }
1086 }
1087
1088 /**
1089  * cpr3_regulator_init_cprh_corners() - configure the per-corner CPRh registers
1090  * @vreg:               Pointer to the CPR3 regulator
1091  *
1092  * This function programs the controller registers which contain all information
1093  * necessary to resolve the closed-loop voltage per-corner at runtime such as
1094  * open-loop and floor voltages, target quotient delta, and RO select value.
1095  * These registers also provide a means to disable closed-loop operation, core
1096  * and temperature adjustments.
1097  *
1098  * Return: 0 on success, errno on failure
1099  */
1100 static int cpr3_regulator_init_cprh_corners(struct cpr3_regulator *vreg)
1101 {
1102         struct cpr3_controller *ctrl = vreg->thread->ctrl;
1103         struct cpr3_corner *corner;
1104         u32 reg, delta_quot_steps, ro_sel;
1105         u32 *base_quots;
1106         int open_loop_volt_steps, floor_volt_steps, i, j, rc = 0;
1107
1108         base_quots = kcalloc(CPR3_RO_COUNT, sizeof(*base_quots),
1109                              GFP_KERNEL);
1110         if (!base_quots)
1111                 return -ENOMEM;
1112
1113         cpr3_regulator_set_base_target_quot(vreg, base_quots);
1114
1115         for (i = 0; i < vreg->corner_count; i++) {
1116                 corner = &vreg->corner[i];
1117                 for (j = 0, ro_sel = INT_MAX; j < CPR3_RO_COUNT; j++) {
1118                         if (corner->target_quot[j]) {
1119                                 ro_sel = j;
1120                                 break;
1121                         }
1122                 }
1123
1124                 if (ro_sel == INT_MAX) {
1125                         if (!corner->proc_freq) {
1126                                 /*
1127                                  * Corner is not used as active DCVS set point
1128                                  * select RO 0 arbitrarily.
1129                                  */
1130                                 ro_sel = 0;
1131                         } else {
1132                                 cpr3_err(vreg, "corner=%d has invalid RO select value\n",
1133                                          i);
1134                                 rc = -EINVAL;
1135                                 goto free_base_quots;
1136                         }
1137                 }
1138
1139                 open_loop_volt_steps = DIV_ROUND_UP(corner->open_loop_volt -
1140                                                     ctrl->base_volt,
1141                                                     ctrl->step_volt);
1142                 floor_volt_steps = DIV_ROUND_UP(corner->floor_volt -
1143                                                 ctrl->base_volt,
1144                                                 ctrl->step_volt);
1145                 delta_quot_steps = corner->proc_freq ?
1146                         DIV_ROUND_UP(corner->target_quot[ro_sel] -
1147                                      base_quots[ro_sel],
1148                                      CPRH_DELTA_QUOT_STEP_FACTOR) :
1149                         0;
1150
1151                 if (open_loop_volt_steps > CPRH_CORNER_INIT_VOLTAGE_MAX_VALUE ||
1152                     floor_volt_steps > CPRH_CORNER_FLOOR_VOLTAGE_MAX_VALUE ||
1153                     delta_quot_steps > CPRH_CORNER_QUOT_DELTA_MAX_VALUE) {
1154                         cpr3_err(ctrl, "invalid CPRh corner configuration: open_loop_volt_steps=%d (%d max.), floor_volt_steps=%d (%d max), delta_quot_steps=%d (%d max)\n",
1155                                  open_loop_volt_steps,
1156                                  CPRH_CORNER_INIT_VOLTAGE_MAX_VALUE,
1157                                  floor_volt_steps,
1158                                  CPRH_CORNER_FLOOR_VOLTAGE_MAX_VALUE,
1159                                  delta_quot_steps,
1160                                  CPRH_CORNER_QUOT_DELTA_MAX_VALUE);
1161                         rc = -EINVAL;
1162                         goto free_base_quots;
1163                 }
1164
1165                 reg = (open_loop_volt_steps << CPRH_CORNER_INIT_VOLTAGE_SHIFT)
1166                         & CPRH_CORNER_INIT_VOLTAGE_MASK;
1167                 reg |= (floor_volt_steps << CPRH_CORNER_FLOOR_VOLTAGE_SHIFT)
1168                         & CPRH_CORNER_FLOOR_VOLTAGE_MASK;
1169                 reg |= (delta_quot_steps << CPRH_CORNER_QUOT_DELTA_SHIFT)
1170                         & CPRH_CORNER_QUOT_DELTA_MASK;
1171                 reg |= (ro_sel << CPRH_CORNER_RO_SEL_SHIFT)
1172                         & CPRH_CORNER_RO_SEL_MASK;
1173
1174                 if (corner->use_open_loop)
1175                         reg |= CPRH_CORNER_CPR_CL_DISABLE;
1176
1177                 cpr3_debug(ctrl, "corner=%d open_loop_volt_steps=%d, floor_volt_steps=%d, delta_quot_steps=%d, base_volt=%d, step_volt=%d, base_quot=%d\n",
1178                            i, open_loop_volt_steps, floor_volt_steps,
1179                            delta_quot_steps, ctrl->base_volt,
1180                            ctrl->step_volt, base_quots[ro_sel]);
1181                 cpr3_write(ctrl, CPRH_REG_CORNER(i), reg);
1182         }
1183
1184 free_base_quots:
1185         kfree(base_quots);
1186         return rc;
1187 }
1188
1189 /**
1190  * cprh_controller_program_sdelta() - programs hardware SDELTA registers with
1191  *              the margins that need to be applied at different online
1192  *              core-count and temperature bands for each corner band. Also,
1193  *              programs hardware register configuration for core-count and
1194  *              temp-based adjustments
1195  *
1196  * @ctrl:               Pointer to the CPR3 controller
1197  *
1198  * CPR interface/bus clocks must be enabled before calling this function.
1199  *
1200  * Return: none
1201  */
1202 static void cprh_controller_program_sdelta(
1203                 struct cpr3_controller *ctrl)
1204 {
1205         struct cpr3_regulator *vreg = &ctrl->thread[0].vreg[0];
1206         struct cprh_corner_band *corner_band;
1207         struct cpr4_sdelta *sdelta;
1208         int i, j, index;
1209         u32 reg = 0;
1210
1211         if (!vreg->allow_core_count_adj && !vreg->allow_temp_adj)
1212                 return;
1213
1214         cpr4_regulator_init_temp_points(ctrl);
1215
1216         for (i = 0; i < CPRH_CORNER_BAND_MAX_COUNT; i++) {
1217                 reg |= (i < vreg->corner_band_count ?
1218                         vreg->corner_band[i].corner
1219                         & CPRH_CORNER_BAND_MASK :
1220                         vreg->corner_count + 1)
1221                         << (i * CPRH_CORNER_BAND_SHIFT);
1222         }
1223
1224         cpr3_write(ctrl, CPRH_REG_CORNER_BAND, reg);
1225
1226         for (i = 0; i < vreg->corner_band_count; i++) {
1227                 corner_band = &vreg->corner_band[i];
1228                 sdelta = corner_band->sdelta;
1229
1230                 if (!sdelta->allow_core_count_adj && !sdelta->allow_temp_adj) {
1231                         /*
1232                          * Per-online-core and per-temperature margin
1233                          * adjustments are disabled for this corner band.
1234                          */
1235                         continue;
1236                 }
1237
1238                 if (vreg->allow_core_count_adj)
1239                         cpr3_write_temp_core_margin(ctrl,
1240                                     CPRH_MARGIN_TEMP_CORE_VBAND(0, i),
1241                                     &sdelta->table[0]);
1242
1243                 for (j = 0; j < sdelta->max_core_count; j++) {
1244                         index = j * sdelta->temp_band_count;
1245
1246                         cpr3_write_temp_core_margin(ctrl,
1247                                     CPRH_MARGIN_TEMP_CORE_VBAND(
1248                                     sdelta->allow_core_count_adj
1249                                     ? j + 1 : vreg->max_core_count, i),
1250                                     &sdelta->table[index]);
1251                 }
1252         }
1253
1254         if (!vreg->allow_core_count_adj) {
1255                 cpr3_masked_write(ctrl, CPR4_REG_MISC,
1256                         CPR4_MISC_MARGIN_TABLE_ROW_SELECT_MASK,
1257                         vreg->max_core_count
1258                         << CPR4_MISC_MARGIN_TABLE_ROW_SELECT_SHIFT);
1259         }
1260
1261         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
1262                 CPR4_MARGIN_ADJ_CTL_MAX_NUM_CORES_MASK
1263                 | CPR4_MARGIN_ADJ_CTL_CORE_ADJ_EN
1264                 | CPR4_MARGIN_ADJ_CTL_TEMP_ADJ_EN
1265                 | CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_EN
1266                 | CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
1267                 vreg->max_core_count << CPR4_MARGIN_ADJ_CTL_MAX_NUM_CORES_SHIFT
1268                 | ((vreg->allow_core_count_adj)
1269                    ? CPR4_MARGIN_ADJ_CTL_CORE_ADJ_EN : 0)
1270                 | (vreg->allow_temp_adj ? CPR4_MARGIN_ADJ_CTL_TEMP_ADJ_EN : 0)
1271                 | ((ctrl->use_hw_closed_loop)
1272                 ? CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_EN : 0)
1273                 | (ctrl->use_hw_closed_loop
1274                 ? CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE : 0));
1275
1276         /* Ensure that previous CPR register writes complete */
1277         mb();
1278 }
1279
1280 static int cprh_regulator_aging_adjust(struct cpr3_controller *ctrl);
1281
1282 /**
1283  * cpr3_regulator_init_cprh() - performs hardware initialization at the
1284  *              controller and thread level required for CPRh operation.
1285  * @ctrl:               Pointer to the CPR3 controller
1286  *
1287  * CPR interface/bus clocks must be enabled before calling this function.
1288  *
1289  * Return: 0 on success, errno on failure
1290  */
1291 static int cpr3_regulator_init_cprh(struct cpr3_controller *ctrl)
1292 {
1293         u32 reg, pmic_step_size = 1;
1294         u64 temp;
1295         int rc;
1296
1297         /* Single thread, single regulator supported */
1298         if (ctrl->thread_count != 1) {
1299                 cpr3_err(ctrl, "expected 1 thread but found %d\n",
1300                         ctrl->thread_count);
1301                 return -EINVAL;
1302         } else if (ctrl->thread[0].vreg_count != 1) {
1303                 cpr3_err(ctrl, "expected 1 regulator but found %d\n",
1304                         ctrl->thread[0].vreg_count);
1305                 return -EINVAL;
1306         }
1307
1308         rc = cprh_regulator_aging_adjust(ctrl);
1309         if (rc && rc != -ETIMEDOUT) {
1310                 /*
1311                  * Don't fail initialization if the CPR aging measurement
1312                  * timed out due to sensors not being available.
1313                  */
1314                 cpr3_err(ctrl, "CPR aging adjustment failed, rc=%d\n", rc);
1315                 return rc;
1316         }
1317
1318         cprh_controller_program_sdelta(ctrl);
1319
1320         rc = cpr3_regulator_init_cprh_corners(&ctrl->thread[0].vreg[0]);
1321         if (rc) {
1322                 cpr3_err(ctrl, "failed to initialize CPRh corner registers\n");
1323                 return rc;
1324         }
1325
1326         if (ctrl->reset_step_quot_loop_en)
1327                 cpr3_masked_write(ctrl, CPR4_REG_MISC,
1328                                 CPR4_MISC_RESET_STEP_QUOT_LOOP_EN,
1329                                 CPR4_MISC_RESET_STEP_QUOT_LOOP_EN);
1330
1331         if (ctrl->saw_use_unit_mV)
1332                 pmic_step_size = ctrl->step_volt / 1000;
1333         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
1334                                 CPR4_MARGIN_ADJ_CTL_PMIC_STEP_SIZE_MASK,
1335                                 (pmic_step_size
1336                                 << CPR4_MARGIN_ADJ_CTL_PMIC_STEP_SIZE_SHIFT));
1337
1338         cpr3_masked_write(ctrl, CPR4_REG_SAW_ERROR_STEP_LIMIT,
1339                                 CPR4_SAW_ERROR_STEP_LIMIT_DN_MASK,
1340                                 (ctrl->down_error_step_limit
1341                                 << CPR4_SAW_ERROR_STEP_LIMIT_DN_SHIFT));
1342
1343         cpr3_masked_write(ctrl, CPR4_REG_SAW_ERROR_STEP_LIMIT,
1344                                 CPR4_SAW_ERROR_STEP_LIMIT_UP_MASK,
1345                                 (ctrl->up_error_step_limit
1346                                 << CPR4_SAW_ERROR_STEP_LIMIT_UP_SHIFT));
1347
1348         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
1349                         CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_STEP_QUOT_MASK,
1350                         ctrl->step_quot_fixed
1351                         << CPR4_MARGIN_ADJ_CTL_KV_MARGIN_ADJ_STEP_QUOT_SHIFT);
1352
1353         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
1354                         CPR4_MARGIN_ADJ_CTL_PER_RO_KV_MARGIN_EN,
1355                         (ctrl->use_dynamic_step_quot
1356                         ? CPR4_MARGIN_ADJ_CTL_PER_RO_KV_MARGIN_EN : 0));
1357
1358         if (ctrl->voltage_settling_time) {
1359                 /*
1360                  * Configure the settling timer used to account for
1361                  * one VDD supply step.
1362                  */
1363                 temp = (u64)ctrl->cpr_clock_rate
1364                                 * (u64)ctrl->voltage_settling_time;
1365                 do_div(temp, 1000000000);
1366                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_TEMP_CORE_TIMERS,
1367                         CPR4_MARGIN_TEMP_CORE_TIMERS_SETTLE_VOLTAGE_COUNT_MASK,
1368                         temp
1369                   << CPR4_MARGIN_TEMP_CORE_TIMERS_SETTLE_VOLTAGE_COUNT_SHIFT);
1370         }
1371
1372         if (ctrl->corner_switch_delay_time) {
1373                 /*
1374                  * Configure the settling timer used to delay
1375                  * following SAW requests
1376                  */
1377                 temp = (u64)ctrl->cpr_clock_rate
1378                         * (u64)ctrl->corner_switch_delay_time;
1379                 do_div(temp, 1000000000);
1380                 do_div(temp, CPRH_MODE_SWITCH_DELAY_FACTOR);
1381                 cpr3_masked_write(ctrl, CPRH_REG_CTL,
1382                                   CPRH_CTL_MODE_SWITCH_DELAY_MASK,
1383                                   temp << CPRH_CTL_MODE_SWITCH_DELAY_SHIFT);
1384         }
1385
1386         /*
1387          * Program base voltage and voltage multiplier values which
1388          * are used for floor and initial voltage calculations by the
1389          * CPRh controller.
1390          */
1391         reg = (DIV_ROUND_UP(ctrl->base_volt, ctrl->step_volt)
1392                << CPRH_CTL_BASE_VOLTAGE_SHIFT)
1393                 & CPRH_CTL_BASE_VOLTAGE_MASK;
1394         reg |= (DIV_ROUND_UP(ctrl->step_volt, 1000)
1395                 << CPRH_CTL_VOLTAGE_MULTIPLIER_SHIFT)
1396                 & CPRH_CTL_VOLTAGE_MULTIPLIER_MASK;
1397         /* Enable OSM block interface with CPR */
1398         reg |= CPRH_CTL_OSM_ENABLED;
1399         cpr3_masked_write(ctrl, CPRH_REG_CTL, CPRH_CTL_BASE_VOLTAGE_MASK
1400                           | CPRH_CTL_VOLTAGE_MULTIPLIER_MASK
1401                           | CPRH_CTL_OSM_ENABLED, reg);
1402
1403         /* Enable loop_en */
1404         cpr3_ctrl_loop_enable(ctrl);
1405
1406         return 0;
1407 }
1408
1409 /**
1410  * cpr3_regulator_init_ctrl() - performs hardware initialization of CPR
1411  *              controller registers
1412  * @ctrl:               Pointer to the CPR3 controller
1413  *
1414  * Return: 0 on success, errno on failure
1415  */
1416 static int cpr3_regulator_init_ctrl(struct cpr3_controller *ctrl)
1417 {
1418         int i, j, k, m, rc;
1419         u32 ro_used = 0;
1420         u32 gcnt, cont_dly, up_down_dly, val;
1421         u64 temp;
1422         char *mode;
1423
1424         if (ctrl->core_clk) {
1425                 rc = clk_set_rate(ctrl->core_clk, ctrl->cpr_clock_rate);
1426                 if (rc) {
1427                         cpr3_err(ctrl, "clk_set_rate(core_clk, %u) failed, rc=%d\n",
1428                                 ctrl->cpr_clock_rate, rc);
1429                         return rc;
1430                 }
1431         }
1432
1433         rc = cpr3_clock_enable(ctrl);
1434         if (rc) {
1435                 cpr3_err(ctrl, "clock enable failed, rc=%d\n", rc);
1436                 return rc;
1437         }
1438         ctrl->cpr_enabled = true;
1439
1440         /* Find all RO's used by any corner of any regulator. */
1441         for (i = 0; i < ctrl->thread_count; i++)
1442                 for (j = 0; j < ctrl->thread[i].vreg_count; j++)
1443                         for (k = 0; k < ctrl->thread[i].vreg[j].corner_count;
1444                              k++)
1445                                 for (m = 0; m < CPR3_RO_COUNT; m++)
1446                                         if (ctrl->thread[i].vreg[j].corner[k].
1447                                             target_quot[m])
1448                                                 ro_used |= BIT(m);
1449
1450         /* Configure the GCNT of the RO's that will be used */
1451         gcnt = cpr3_regulator_get_gcnt(ctrl);
1452         for (i = 0; i < CPR3_RO_COUNT; i++)
1453                 if (ro_used & BIT(i))
1454                         cpr3_write(ctrl, CPR3_REG_GCNT(i), gcnt);
1455
1456         /* Configure the loop delay time */
1457         temp = (u64)ctrl->cpr_clock_rate * (u64)ctrl->loop_time;
1458         do_div(temp, 1000000000);
1459         cont_dly = temp;
1460         if (ctrl->supports_hw_closed_loop
1461                 && ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3)
1462                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_MID_CONT, cont_dly);
1463         else
1464                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_AUTO_CONT, cont_dly);
1465
1466         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
1467                 temp = (u64)ctrl->cpr_clock_rate *
1468                                 (u64)ctrl->up_down_delay_time;
1469                 do_div(temp, 1000000000);
1470                 up_down_dly = temp;
1471                 if (ctrl->supports_hw_closed_loop)
1472                         cpr3_write(ctrl, CPR3_REG_CPR_TIMER_UP_DN_CONT,
1473                                 up_down_dly);
1474                 cpr3_debug(ctrl, "up_down_dly=%u, up_down_delay_time=%u ns\n",
1475                         up_down_dly, ctrl->up_down_delay_time);
1476         }
1477
1478         cpr3_debug(ctrl, "cpr_clock_rate=%u HZ, sensor_time=%u ns, loop_time=%u ns, gcnt=%u, cont_dly=%u\n",
1479                 ctrl->cpr_clock_rate, ctrl->sensor_time, ctrl->loop_time,
1480                 gcnt, cont_dly);
1481
1482         /* Configure CPR sensor operation */
1483         val = (ctrl->idle_clocks << CPR3_CPR_CTL_IDLE_CLOCKS_SHIFT)
1484                 & CPR3_CPR_CTL_IDLE_CLOCKS_MASK;
1485         val |= (ctrl->count_mode << CPR3_CPR_CTL_COUNT_MODE_SHIFT)
1486                 & CPR3_CPR_CTL_COUNT_MODE_MASK;
1487         val |= (ctrl->count_repeat << CPR3_CPR_CTL_COUNT_REPEAT_SHIFT)
1488                 & CPR3_CPR_CTL_COUNT_REPEAT_MASK;
1489         cpr3_write(ctrl, CPR3_REG_CPR_CTL, val);
1490
1491         cpr3_debug(ctrl, "idle_clocks=%u, count_mode=%u, count_repeat=%u; CPR_CTL=0x%08X\n",
1492                 ctrl->idle_clocks, ctrl->count_mode, ctrl->count_repeat, val);
1493
1494         /* Configure CPR default step quotients */
1495         val = (ctrl->step_quot_init_min << CPR3_CPR_STEP_QUOT_MIN_SHIFT)
1496                 & CPR3_CPR_STEP_QUOT_MIN_MASK;
1497         val |= (ctrl->step_quot_init_max << CPR3_CPR_STEP_QUOT_MAX_SHIFT)
1498                 & CPR3_CPR_STEP_QUOT_MAX_MASK;
1499         cpr3_write(ctrl, CPR3_REG_CPR_STEP_QUOT, val);
1500
1501         cpr3_debug(ctrl, "step_quot_min=%u, step_quot_max=%u; STEP_QUOT=0x%08X\n",
1502                 ctrl->step_quot_init_min, ctrl->step_quot_init_max, val);
1503
1504         /* Configure the CPR sensor ownership */
1505         for (i = 0; i < ctrl->sensor_count; i++)
1506                 cpr3_write(ctrl, CPR3_REG_SENSOR_OWNER(i),
1507                            ctrl->sensor_owner[i]);
1508
1509         /* Configure per-thread registers */
1510         for (i = 0; i < ctrl->thread_count; i++) {
1511                 rc = cpr3_regulator_init_thread(&ctrl->thread[i]);
1512                 if (rc) {
1513                         cpr3_err(ctrl, "CPR thread register initialization failed, rc=%d\n",
1514                                 rc);
1515                         return rc;
1516                 }
1517         }
1518
1519         if (ctrl->supports_hw_closed_loop) {
1520                 if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4 ||
1521                     ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH) {
1522                         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
1523                                 CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
1524                                 ctrl->use_hw_closed_loop
1525                                 ? CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE
1526                                 : CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_DISABLE);
1527                 } else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
1528                         cpr3_write(ctrl, CPR3_REG_HW_CLOSED_LOOP,
1529                                 ctrl->use_hw_closed_loop
1530                                 ? CPR3_HW_CLOSED_LOOP_ENABLE
1531                                 : CPR3_HW_CLOSED_LOOP_DISABLE);
1532
1533                         cpr3_debug(ctrl, "PD_THROTTLE=0x%08X\n",
1534                                 ctrl->proc_clock_throttle);
1535                 }
1536
1537                 if ((ctrl->use_hw_closed_loop ||
1538                      ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) &&
1539                     ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
1540                         rc = regulator_enable(ctrl->vdd_limit_regulator);
1541                         if (rc) {
1542                                 cpr3_err(ctrl, "CPR limit regulator enable failed, rc=%d\n",
1543                                         rc);
1544                                 return rc;
1545                         }
1546
1547                         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
1548                                 rc = msm_spm_avs_enable_irq(0,
1549                                                            MSM_SPM_AVS_IRQ_MAX);
1550                                 if (rc) {
1551                                         cpr3_err(ctrl, "could not enable max IRQ, rc=%d\n",
1552                                                 rc);
1553                                         return rc;
1554                                 }
1555                         }
1556                 }
1557         }
1558
1559         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
1560                 rc = cpr3_regulator_init_cpr4(ctrl);
1561                 if (rc) {
1562                         cpr3_err(ctrl, "CPR4-specific controller initialization failed, rc=%d\n",
1563                                 rc);
1564                         return rc;
1565                 }
1566         } else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH) {
1567                 rc = cpr3_regulator_init_cprh(ctrl);
1568                 if (rc) {
1569                         cpr3_err(ctrl, "CPRh-specific controller initialization failed, rc=%d\n",
1570                                  rc);
1571                         return rc;
1572                 }
1573         }
1574
1575         /* Ensure that all register writes complete before disabling clocks. */
1576         wmb();
1577
1578         /* Keep CPR clocks on for CPRh full HW closed-loop operation */
1579         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
1580                 cpr3_clock_disable(ctrl);
1581                 ctrl->cpr_enabled = false;
1582         }
1583
1584         if (!ctrl->cpr_allowed_sw || !ctrl->cpr_allowed_hw)
1585                 mode = "open-loop";
1586         else if (ctrl->supports_hw_closed_loop &&
1587                  ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH)
1588                 mode = ctrl->use_hw_closed_loop
1589                         ? "HW closed-loop" : "SW closed-loop";
1590         else if (ctrl->supports_hw_closed_loop &&
1591                  ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH)
1592                 mode = ctrl->use_hw_closed_loop
1593                         ? "full HW closed-loop" : "open-loop";
1594         else
1595                 mode = "closed-loop";
1596
1597         cpr3_info(ctrl, "Default CPR mode = %s", mode);
1598
1599         return 0;
1600 }
1601
1602 /**
1603  * cpr3_regulator_set_target_quot() - configure the target quotient for each
1604  *              RO of the CPR3 thread and set the RO mask
1605  * @thread:             Pointer to the CPR3 thread
1606  *
1607  * Return: none
1608  */
1609 static void cpr3_regulator_set_target_quot(struct cpr3_thread *thread)
1610 {
1611         u32 new_quot, last_quot;
1612         int i;
1613
1614         if (thread->aggr_corner.ro_mask == CPR3_RO_MASK
1615             && thread->last_closed_loop_aggr_corner.ro_mask == CPR3_RO_MASK) {
1616                 /* Avoid writing target quotients since all RO's are masked. */
1617                 return;
1618         } else if (thread->aggr_corner.ro_mask == CPR3_RO_MASK) {
1619                 cpr3_write(thread->ctrl, CPR3_REG_RO_MASK(thread->thread_id),
1620                         CPR3_RO_MASK);
1621                 thread->last_closed_loop_aggr_corner.ro_mask = CPR3_RO_MASK;
1622                 /*
1623                  * Only the RO_MASK register needs to be written since all
1624                  * RO's are masked.
1625                  */
1626                 return;
1627         } else if (thread->aggr_corner.ro_mask
1628                         != thread->last_closed_loop_aggr_corner.ro_mask) {
1629                 cpr3_write(thread->ctrl, CPR3_REG_RO_MASK(thread->thread_id),
1630                         thread->aggr_corner.ro_mask);
1631         }
1632
1633         for (i = 0; i < CPR3_RO_COUNT; i++) {
1634                 new_quot = thread->aggr_corner.target_quot[i];
1635                 last_quot = thread->last_closed_loop_aggr_corner.target_quot[i];
1636                 if (new_quot != last_quot)
1637                         cpr3_write(thread->ctrl,
1638                                 CPR3_REG_TARGET_QUOT(thread->thread_id, i),
1639                                 new_quot);
1640         }
1641
1642         thread->last_closed_loop_aggr_corner = thread->aggr_corner;
1643 }
1644
1645 /**
1646  * cpr3_update_vreg_closed_loop_volt() - update the last known settled
1647  *              closed loop voltage for a CPR3 regulator
1648  * @vreg:               Pointer to the CPR3 regulator
1649  * @vdd_volt:           Last known settled voltage in microvolts for the
1650  *                      VDD supply
1651  * @reg_last_measurement: Value read from the LAST_MEASUREMENT register
1652  *
1653  * Return: none
1654  */
1655 static void cpr3_update_vreg_closed_loop_volt(struct cpr3_regulator *vreg,
1656                                 int vdd_volt, u32 reg_last_measurement)
1657 {
1658         bool step_dn, step_up, aggr_step_up, aggr_step_dn, aggr_step_mid;
1659         bool valid, pd_valid, saw_error;
1660         struct cpr3_controller *ctrl = vreg->thread->ctrl;
1661         struct cpr3_corner *corner;
1662         u32 id;
1663
1664         if (vreg->last_closed_loop_corner == CPR3_REGULATOR_CORNER_INVALID)
1665                 return;
1666
1667         corner = &vreg->corner[vreg->last_closed_loop_corner];
1668
1669         if (vreg->thread->last_closed_loop_aggr_corner.ro_mask
1670             == CPR3_RO_MASK  || !vreg->aggregated) {
1671                 return;
1672         } else if (!ctrl->cpr_enabled || !ctrl->last_corner_was_closed_loop) {
1673                 return;
1674         } else if (ctrl->thread_count == 1
1675                  && vdd_volt >= corner->floor_volt
1676                  && vdd_volt <= corner->ceiling_volt) {
1677                 corner->last_volt = vdd_volt;
1678                 cpr3_debug(vreg, "last_volt updated: last_volt[%d]=%d, ceiling_volt[%d]=%d, floor_volt[%d]=%d\n",
1679                            vreg->last_closed_loop_corner, corner->last_volt,
1680                            vreg->last_closed_loop_corner,
1681                            corner->ceiling_volt,
1682                            vreg->last_closed_loop_corner,
1683                            corner->floor_volt);
1684                 return;
1685         } else if (!ctrl->supports_hw_closed_loop) {
1686                 return;
1687         } else if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPR3) {
1688                 corner->last_volt = vdd_volt;
1689                 cpr3_debug(vreg, "last_volt updated: last_volt[%d]=%d, ceiling_volt[%d]=%d, floor_volt[%d]=%d\n",
1690                            vreg->last_closed_loop_corner, corner->last_volt,
1691                            vreg->last_closed_loop_corner,
1692                            corner->ceiling_volt,
1693                            vreg->last_closed_loop_corner,
1694                            corner->floor_volt);
1695                 return;
1696         }
1697
1698         /* CPR clocks are on and HW closed loop is supported */
1699         valid = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_VALID);
1700         if (!valid) {
1701                 cpr3_debug(vreg, "CPR_LAST_VALID_MEASUREMENT=0x%X valid bit not set\n",
1702                            reg_last_measurement);
1703                 return;
1704         }
1705
1706         id = vreg->thread->thread_id;
1707
1708         step_dn
1709                = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_THREAD_DN(id));
1710         step_up
1711                = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_THREAD_UP(id));
1712         aggr_step_dn = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_AGGR_DN);
1713         aggr_step_mid
1714                 = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_AGGR_MID);
1715         aggr_step_up = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_AGGR_UP);
1716         saw_error = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_SAW_ERROR);
1717         pd_valid
1718              = !((((reg_last_measurement & CPR3_LAST_MEASUREMENT_PD_BYPASS_MASK)
1719                        >> CPR3_LAST_MEASUREMENT_PD_BYPASS_SHIFT)
1720                       & vreg->pd_bypass_mask) == vreg->pd_bypass_mask);
1721
1722         if (!pd_valid) {
1723                 cpr3_debug(vreg, "CPR_LAST_VALID_MEASUREMENT=0x%X, all power domains bypassed\n",
1724                            reg_last_measurement);
1725                 return;
1726         } else if (step_dn && step_up) {
1727                 cpr3_err(vreg, "both up and down status bits set, CPR_LAST_VALID_MEASUREMENT=0x%X\n",
1728                          reg_last_measurement);
1729                 return;
1730         } else if (aggr_step_dn && step_dn && vdd_volt < corner->last_volt
1731                    && vdd_volt >= corner->floor_volt) {
1732                 corner->last_volt = vdd_volt;
1733         } else if (aggr_step_up && step_up && vdd_volt > corner->last_volt
1734                    && vdd_volt <= corner->ceiling_volt) {
1735                 corner->last_volt = vdd_volt;
1736         } else if (aggr_step_mid
1737                    && vdd_volt >= corner->floor_volt
1738                    && vdd_volt <= corner->ceiling_volt) {
1739                 corner->last_volt = vdd_volt;
1740         } else if (saw_error && (vdd_volt == corner->ceiling_volt
1741                                  || vdd_volt == corner->floor_volt)) {
1742                 corner->last_volt = vdd_volt;
1743         } else {
1744                 cpr3_debug(vreg, "last_volt not updated: last_volt[%d]=%d, ceiling_volt[%d]=%d, floor_volt[%d]=%d, vdd_volt=%d, CPR_LAST_VALID_MEASUREMENT=0x%X\n",
1745                            vreg->last_closed_loop_corner, corner->last_volt,
1746                            vreg->last_closed_loop_corner,
1747                            corner->ceiling_volt,
1748                            vreg->last_closed_loop_corner, corner->floor_volt,
1749                            vdd_volt, reg_last_measurement);
1750                 return;
1751         }
1752
1753         cpr3_debug(vreg, "last_volt updated: last_volt[%d]=%d, ceiling_volt[%d]=%d, floor_volt[%d]=%d, CPR_LAST_VALID_MEASUREMENT=0x%X\n",
1754                    vreg->last_closed_loop_corner, corner->last_volt,
1755                    vreg->last_closed_loop_corner, corner->ceiling_volt,
1756                    vreg->last_closed_loop_corner, corner->floor_volt,
1757                    reg_last_measurement);
1758 }
1759
1760 /**
1761  * cpr3_regulator_config_ldo_retention() - configure per-regulator LDO retention
1762  *              mode
1763  * @vreg:               Pointer to the CPR3 regulator to configure
1764  * @ref_volt:           Reference voltage used to determine if LDO retention
1765  *                      mode can be allowed. It corresponds either to the
1766  *                      aggregated floor voltage or the next VDD supply setpoint
1767  *
1768  * This function determines if a CPR3 regulator's configuration satisfies safe
1769  * operating voltages for LDO retention and uses the regulator_allow_bypass()
1770  * interface on the LDO retention regulator to enable or disable such feature
1771  * accordingly.
1772  *
1773  * Return: 0 on success, errno on failure
1774  */
1775 static int cpr3_regulator_config_ldo_retention(struct cpr3_regulator *vreg,
1776                                         int ref_volt)
1777 {
1778         struct regulator *ldo_ret_reg = vreg->ldo_ret_regulator;
1779         int retention_volt, rc;
1780         enum msm_ldo_supply_mode mode;
1781
1782         if (!ldo_ret_reg) {
1783                 /* LDO retention regulator is not defined */
1784                 return 0;
1785         }
1786
1787         retention_volt = regulator_get_voltage(ldo_ret_reg);
1788         if (retention_volt < 0) {
1789                 cpr3_err(vreg, "regulator_get_voltage(ldo_ret) failed, rc=%d\n",
1790                          retention_volt);
1791                 return retention_volt;
1792
1793         }
1794
1795         mode = ref_volt >= retention_volt + vreg->ldo_min_headroom_volt
1796                 ? LDO_MODE : BHS_MODE;
1797
1798         rc = regulator_allow_bypass(ldo_ret_reg, mode);
1799         if (rc)
1800                 cpr3_err(vreg, "regulator_allow_bypass(ldo_ret) == %s failed, rc=%d\n",
1801                          mode ? "true" : "false", rc);
1802
1803         return rc;
1804 }
1805
1806 /**
1807  * cpr3_regulator_config_kryo_ldo_mem_acc() - configure the mem-acc regulator
1808  *              corner based upon a future Kryo LDO regulator voltage setpoint
1809  * @vreg:               Pointer to the CPR3 regulator
1810  * @new_volt:           New voltage in microvolts that the LDO regulator needs
1811  *                      to end up at
1812  *
1813  * This function determines if a new LDO regulator set point will result
1814  * in crossing the voltage threshold that requires reconfiguration of
1815  * the mem-acc regulator associated with a CPR3 regulator and if so, performs
1816  * the correct sequence to select the correct mem-acc corner.
1817  *
1818  * Return: 0 on success, errno on failure
1819  */
1820 static int cpr3_regulator_config_kryo_ldo_mem_acc(struct cpr3_regulator *vreg,
1821                                              int new_volt)
1822 {
1823         struct cpr3_controller *ctrl = vreg->thread->ctrl;
1824         struct regulator *ldo_reg = vreg->ldo_regulator;
1825         struct regulator *mem_acc_reg = vreg->mem_acc_regulator;
1826         int mem_acc_volt = ctrl->mem_acc_threshold_volt;
1827         int last_volt, safe_volt, mem_acc_corn, rc;
1828         enum msm_apm_supply apm_mode;
1829
1830         if (!mem_acc_reg || !mem_acc_volt || !ldo_reg)
1831                 return 0;
1832
1833         apm_mode = msm_apm_get_supply(ctrl->apm);
1834         if (apm_mode < 0) {
1835                 cpr3_err(ctrl, "APM get supply failed, rc=%d\n",
1836                          apm_mode);
1837                 return apm_mode;
1838         }
1839
1840         last_volt = regulator_get_voltage(ldo_reg);
1841         if (last_volt < 0) {
1842                 cpr3_err(vreg, "regulator_get_voltage(ldo) failed, rc=%d\n",
1843                          last_volt);
1844                 return last_volt;
1845         }
1846
1847         if (((last_volt < mem_acc_volt && mem_acc_volt <= new_volt)
1848              || (last_volt >= mem_acc_volt && mem_acc_volt > new_volt))) {
1849
1850                 if (apm_mode == ctrl->apm_high_supply)
1851                         safe_volt = min(vreg->ldo_max_volt, mem_acc_volt);
1852                 else
1853                         safe_volt = min(max(ctrl->system_supply_max_volt -
1854                                             vreg->ldo_max_headroom_volt,
1855                                             mem_acc_volt), vreg->ldo_max_volt);
1856
1857                 rc = regulator_set_voltage(ldo_reg, safe_volt,
1858                                            max(new_volt, last_volt));
1859                 if (rc) {
1860                         cpr3_err(ctrl, "regulator_set_voltage(ldo) == %d failed, rc=%d\n",
1861                                  mem_acc_volt, rc);
1862                         return rc;
1863                 }
1864
1865                 mem_acc_corn = new_volt < mem_acc_volt ?
1866                         ctrl->mem_acc_corner_map[CPR3_MEM_ACC_LOW_CORNER] :
1867                         ctrl->mem_acc_corner_map[CPR3_MEM_ACC_HIGH_CORNER];
1868
1869                 rc = regulator_set_voltage(mem_acc_reg, mem_acc_corn,
1870                                            mem_acc_corn);
1871                 if (rc) {
1872                         cpr3_err(ctrl, "regulator_set_voltage(mem_acc) == %d failed, rc=%d\n",
1873                                  0, rc);
1874                         return rc;
1875                 }
1876         }
1877
1878         return 0;
1879 }
1880
1881 /**
1882  * cpr3_regulator_kryo_bhs_prepare() - configure the Kryo LDO regulator
1883  *              associated with a CPR3 regulator in preparation for BHS
1884  *              mode switch.
1885  * @vreg:               Pointer to the CPR3 regulator
1886  * @vdd_volt:           Last known settled voltage in microvolts for the VDD
1887  *                      supply
1888  * @vdd_ceiling_volt:   Last known aggregated ceiling voltage in microvolts for
1889  *                      the VDD supply
1890  *
1891  * This function performs the necessary steps prior to switching a Kryo LDO
1892  * regulator to BHS mode (LDO bypassed mode).
1893  *
1894  * Return: 0 on success, errno on failure
1895  */
1896 static int cpr3_regulator_kryo_bhs_prepare(struct cpr3_regulator *vreg,
1897                                int vdd_volt, int vdd_ceiling_volt)
1898 {
1899         struct regulator *ldo_reg = vreg->ldo_regulator;
1900         int bhs_volt, rc;
1901
1902         bhs_volt = vdd_volt - vreg->ldo_min_headroom_volt;
1903         if (bhs_volt > vreg->ldo_max_volt) {
1904                 cpr3_debug(vreg, "limited to LDO output of %d uV when switching to BHS mode\n",
1905                            vreg->ldo_max_volt);
1906                 bhs_volt = vreg->ldo_max_volt;
1907         }
1908
1909         rc = cpr3_regulator_config_kryo_ldo_mem_acc(vreg, bhs_volt);
1910         if (rc) {
1911                 cpr3_err(vreg, "failed to configure mem-acc settings\n");
1912                 return rc;
1913         }
1914
1915         rc = regulator_set_voltage(ldo_reg, bhs_volt, min(vdd_ceiling_volt,
1916                                                           vreg->ldo_max_volt));
1917         if (rc) {
1918                 cpr3_err(vreg, "regulator_set_voltage(ldo) == %d failed, rc=%d\n",
1919                          bhs_volt, rc);
1920                 return rc;
1921         }
1922
1923         return rc;
1924 }
1925
1926 /**
1927  * cpr3_regulator_set_bhs_mode() - configure the LDO regulator associated with
1928  *              a CPR3 regulator to BHS mode
1929  * @vreg:               Pointer to the CPR3 regulator
1930  * @vdd_volt:           Last known settled voltage in microvolts for the VDD
1931  *                      supply
1932  * @vdd_ceiling_volt:   Last known aggregated ceiling voltage in microvolts for
1933  *                      the VDD supply
1934  *
1935  * This function performs the necessary steps to switch an LDO regulator
1936  * to BHS mode (LDO bypassed mode).
1937  */
1938 static int cpr3_regulator_set_bhs_mode(struct cpr3_regulator *vreg,
1939                                int vdd_volt, int vdd_ceiling_volt)
1940 {
1941         struct regulator *ldo_reg = vreg->ldo_regulator;
1942         int rc;
1943
1944         if (vreg->ldo_type == CPR3_LDO_KRYO) {
1945                 rc = cpr3_regulator_kryo_bhs_prepare(vreg, vdd_volt,
1946                                 vdd_ceiling_volt);
1947                 if (rc) {
1948                         cpr3_err(vreg, "cpr3 regulator bhs mode prepare failed, rc=%d\n",
1949                                 rc);
1950                         return rc;
1951                 }
1952         }
1953
1954         rc = regulator_allow_bypass(ldo_reg, BHS_MODE);
1955         if (rc) {
1956                 cpr3_err(vreg, "regulator_allow_bypass(bhs) == %s failed, rc=%d\n",
1957                          BHS_MODE ? "true" : "false", rc);
1958                 return rc;
1959         }
1960         vreg->ldo_regulator_bypass = BHS_MODE;
1961
1962         return rc;
1963 }
1964
1965 /**
1966  * cpr3_regulator_ldo_apm_prepare() - configure LDO regulators associated
1967  *              with each CPR3 regulator of a CPR3 controller in preparation
1968  *              for an APM switch.
1969  * @ctrl:               Pointer to the CPR3 controller
1970  * @new_volt:           New voltage in microvolts that the VDD supply
1971  *                      needs to end up at
1972  * @last_volt:          Last known voltage in microvolts for the VDD supply
1973  * @aggr_corner:        Pointer to the CPR3 corner which corresponds to the max
1974  *                      corner aggregated from all CPR3 threads managed by the
1975  *                      CPR3 controller
1976  *
1977  * This function ensures LDO regulator hardware requirements are met before
1978  * an APM switch is requested. The function must be called as the last step
1979  * before switching the APM mode.
1980  *
1981  * Return: 0 on success, errno on failure
1982  */
1983 static int cpr3_regulator_ldo_apm_prepare(struct cpr3_controller *ctrl,
1984                                 int new_volt, int last_volt,
1985                                 struct cpr3_corner *aggr_corner)
1986 {
1987         struct cpr3_regulator *vreg;
1988         struct cpr3_corner *current_corner;
1989         enum msm_apm_supply apm_mode;
1990         int i, j, safe_volt, max_volt, ldo_volt, ref_volt, rc;
1991
1992         apm_mode = msm_apm_get_supply(ctrl->apm);
1993         if (apm_mode < 0) {
1994                 cpr3_err(ctrl, "APM get supply failed, rc=%d\n", apm_mode);
1995                 return apm_mode;
1996         }
1997
1998         if (apm_mode == ctrl->apm_low_supply ||
1999             new_volt >= ctrl->apm_threshold_volt)
2000                 return 0;
2001
2002         /*
2003          * Guarantee LDO maximum headroom is not violated when the APM is
2004          * switched to the system-supply source.
2005          */
2006         for (i = 0; i < ctrl->thread_count; i++) {
2007                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
2008                         vreg = &ctrl->thread[i].vreg[j];
2009
2010                         if (!vreg->vreg_enabled || vreg->current_corner
2011                             == CPR3_REGULATOR_CORNER_INVALID)
2012                                 continue;
2013
2014                         if (!vreg->ldo_regulator || !vreg->ldo_mode_allowed ||
2015                             vreg->ldo_regulator_bypass == BHS_MODE)
2016                                 continue;
2017
2018                         /*
2019                          * If the new VDD configuration does not satisfy
2020                          * requirements for LDO usage, switch the regulator
2021                          * to BHS mode. By doing so, the LDO maximum headroom
2022                          * does not need to be enforced.
2023                          */
2024                         current_corner = &vreg->corner[vreg->current_corner];
2025                         ldo_volt = current_corner->open_loop_volt
2026                                 - vreg->ldo_adjust_volt;
2027                         ref_volt = ctrl->use_hw_closed_loop ?
2028                                 aggr_corner->floor_volt :
2029                                 new_volt;
2030
2031                         if (ref_volt < ldo_volt + vreg->ldo_min_headroom_volt
2032                             || ldo_volt < ctrl->system_supply_max_volt -
2033                             vreg->ldo_max_headroom_volt ||
2034                             ldo_volt > vreg->ldo_max_volt) {
2035                                 rc = cpr3_regulator_set_bhs_mode(vreg,
2036                                          last_volt, aggr_corner->ceiling_volt);
2037                                 if (rc)
2038                                         return rc;
2039                                 /*
2040                                  * Do not enforce LDO maximum headroom since the
2041                                  * regulator is now configured to BHS mode.
2042                                  */
2043                                 continue;
2044                         }
2045
2046                         safe_volt = min(max(ldo_volt,
2047                                             ctrl->system_supply_max_volt
2048                                             - vreg->ldo_max_headroom_volt),
2049                                         vreg->ldo_max_volt);
2050                         max_volt = min(ctrl->system_supply_max_volt,
2051                                        vreg->ldo_max_volt);
2052
2053                         rc = regulator_set_voltage(vreg->ldo_regulator,
2054                                                    safe_volt, max_volt);
2055                         if (rc) {
2056                                 cpr3_err(vreg, "regulator_set_voltage(ldo) == %d failed, rc=%d\n",
2057                                          safe_volt, rc);
2058                                 return rc;
2059                         }
2060                 }
2061         }
2062
2063         return 0;
2064 }
2065
2066 /**
2067  * cpr3_regulator_config_vreg_kryo_ldo() - configure the voltage and bypass
2068  *              state for the Kryo LDO regulator associated with a single CPR3
2069  *              regulator.
2070  *
2071  * @vreg:               Pointer to the CPR3 regulator
2072  * @vdd_floor_volt:     Last known aggregated floor voltage in microvolts for
2073  *                      the VDD supply
2074  * @vdd_ceiling_volt:   Last known aggregated ceiling voltage in microvolts for
2075  *                      the VDD supply
2076  * @ref_volt:           Reference voltage in microvolts corresponds either to
2077  *                      the aggregated floor voltage or the next VDD supply
2078  *                      setpoint.
2079  * @last_volt:          Last known voltage in microvolts for the VDD supply
2080  *
2081  * This function performs all relevant LDO or BHS configurations if a Kryo LDO
2082  * regulator is specified.
2083  *
2084  * Return: 0 on success, errno on failure
2085  */
2086 static int cpr3_regulator_config_vreg_kryo_ldo(struct cpr3_regulator *vreg,
2087                           int vdd_floor_volt, int vdd_ceiling_volt,
2088                           int ref_volt, int last_volt)
2089 {
2090         struct cpr3_controller *ctrl = vreg->thread->ctrl;
2091         struct regulator *ldo_reg = vreg->ldo_regulator;
2092         struct cpr3_corner *current_corner;
2093         enum msm_apm_supply apm_mode;
2094         int rc, ldo_volt, final_ldo_volt, bhs_volt, max_volt, safe_volt;
2095
2096         current_corner = &vreg->corner[vreg->current_corner];
2097         ldo_volt = current_corner->open_loop_volt
2098                 - vreg->ldo_adjust_volt;
2099         bhs_volt = last_volt - vreg->ldo_min_headroom_volt;
2100         max_volt = min(vdd_ceiling_volt, vreg->ldo_max_volt);
2101
2102         if (ref_volt >= ldo_volt + vreg->ldo_min_headroom_volt &&
2103             ldo_volt >= ctrl->system_supply_max_volt -
2104             vreg->ldo_max_headroom_volt &&
2105             bhs_volt >= ctrl->system_supply_max_volt -
2106             vreg->ldo_max_headroom_volt &&
2107             ldo_volt <= vreg->ldo_max_volt) {
2108                 /* LDO minimum and maximum headrooms satisfied */
2109                 apm_mode = msm_apm_get_supply(ctrl->apm);
2110                 if (apm_mode < 0) {
2111                         cpr3_err(ctrl, "APM get supply failed, rc=%d\n",
2112                                  apm_mode);
2113                         return apm_mode;
2114                 }
2115
2116                 if (vreg->ldo_regulator_bypass == BHS_MODE) {
2117                         /*
2118                          * BHS to LDO transition. Configure LDO output
2119                          * to min(max LDO output, VDD - LDO headroom)
2120                          * voltage if APM is on high supply source or
2121                          * min(max(system-supply ceiling - LDO max headroom,
2122                          * VDD - LDO headroom), max LDO output) if
2123                          * APM is on low supply source, then switch
2124                          * regulator mode.
2125                          */
2126                         if (apm_mode == ctrl->apm_high_supply)
2127                                 safe_volt = min(vreg->ldo_max_volt, bhs_volt);
2128                         else
2129                                 safe_volt =
2130                                         min(max(ctrl->system_supply_max_volt -
2131                                                 vreg->ldo_max_headroom_volt,
2132                                                 bhs_volt),
2133                                             vreg->ldo_max_volt);
2134
2135                         rc = cpr3_regulator_config_kryo_ldo_mem_acc(vreg,
2136                                                                safe_volt);
2137                         if (rc) {
2138                                 cpr3_err(vreg, "failed to configure mem-acc settings\n");
2139                                 return rc;
2140                         }
2141
2142                         rc = regulator_set_voltage(ldo_reg, safe_volt,
2143                                                    max_volt);
2144                         if (rc) {
2145                                 cpr3_err(vreg, "regulator_set_voltage(ldo) == %d failed, rc=%d\n",
2146                                          safe_volt, rc);
2147                                 return rc;
2148                         }
2149
2150                         rc = regulator_allow_bypass(ldo_reg, LDO_MODE);
2151                         if (rc) {
2152                                 cpr3_err(vreg, "regulator_allow_bypass(ldo) == %s failed, rc=%d\n",
2153                                          LDO_MODE ? "true" : "false", rc);
2154                                 return rc;
2155                         }
2156                         vreg->ldo_regulator_bypass = LDO_MODE;
2157                 }
2158
2159                 /* Configure final LDO output voltage */
2160                 if (apm_mode == ctrl->apm_high_supply)
2161                         final_ldo_volt = max(ldo_volt,
2162                                              vdd_ceiling_volt -
2163                                              vreg->ldo_max_headroom_volt);
2164                 else
2165                         final_ldo_volt = ldo_volt;
2166
2167                 rc = cpr3_regulator_config_kryo_ldo_mem_acc(vreg,
2168                                                        final_ldo_volt);
2169                 if (rc) {
2170                         cpr3_err(vreg, "failed to configure mem-acc settings\n");
2171                         return rc;
2172                 }
2173
2174                 rc = regulator_set_voltage(ldo_reg, final_ldo_volt, max_volt);
2175                 if (rc) {
2176                         cpr3_err(vreg, "regulator_set_voltage(ldo) == %d failed, rc=%d\n",
2177                                  final_ldo_volt, rc);
2178                         return rc;
2179                 }
2180         } else {
2181                 if (vreg->ldo_regulator_bypass == LDO_MODE) {
2182                         /* LDO to BHS transition */
2183                         rc = cpr3_regulator_set_bhs_mode(vreg, last_volt,
2184                                                          vdd_ceiling_volt);
2185                         if (rc)
2186                                 return rc;
2187                 }
2188         }
2189
2190         return 0;
2191 }
2192
2193 /**
2194  * cpr3_regulator_config_vreg_ldo300() - configure the voltage and bypass state
2195  *              for the LDO300 regulator associated with a single CPR3
2196  *              regulator.
2197  *
2198  * @vreg:               Pointer to the CPR3 regulator
2199  * @new_volt:           New voltage in microvolts that VDD supply needs to
2200  *                      end up at
2201  * @vdd_ceiling_volt:   Last known aggregated ceiling voltage in microvolts for
2202  *                      the VDD supply
2203  *
2204  * This function performs all relevant LDO or BHS configurations for an LDO300
2205  * type regulator.
2206  *
2207  * Return: 0 on success, errno on failure
2208  */
2209 static int cpr3_regulator_config_vreg_ldo300(struct cpr3_regulator *vreg,
2210                 int new_volt, int vdd_ceiling_volt)
2211 {
2212         struct regulator *ldo_reg = vreg->ldo_regulator;
2213         struct cpr3_corner *corner;
2214         bool mode;
2215         int rc = 0;
2216
2217         corner = &vreg->corner[vreg->current_corner];
2218         mode = corner->ldo_mode_allowed ? LDO_MODE : BHS_MODE;
2219
2220         if (mode == LDO_MODE) {
2221                 rc = regulator_set_voltage(ldo_reg, new_volt, vdd_ceiling_volt);
2222                 if (rc) {
2223                         cpr3_err(vreg, "regulator_set_voltage(ldo) == %d failed, rc=%d\n",
2224                                  new_volt, rc);
2225                         return rc;
2226                 }
2227         }
2228
2229         if (vreg->ldo_regulator_bypass != mode) {
2230                 rc = regulator_allow_bypass(ldo_reg, mode);
2231                 if (rc) {
2232                         cpr3_err(vreg, "regulator_allow_bypass(%s) is failed, rc=%d\n",
2233                                  mode == LDO_MODE ? "ldo" : "bhs", rc);
2234                         return rc;
2235                 }
2236                 vreg->ldo_regulator_bypass = mode;
2237         }
2238
2239         return rc;
2240 }
2241
2242 /**
2243  * cpr3_regulator_config_vreg_ldo() - configure the voltage and bypass state for
2244  *              the LDO regulator associated with a single CPR3 regulator.
2245  *
2246  * @vreg:               Pointer to the CPR3 regulator
2247  * @vdd_floor_volt:     Last known aggregated floor voltage in microvolts for
2248  *                      the VDD supply
2249  * @vdd_ceiling_volt:   Last known aggregated ceiling voltage in microvolts for
2250  *                      the VDD supply
2251  * @new_volt:           New voltage in microvolts that VDD supply needs to
2252  *                      end up at
2253  * @last_volt:          Last known voltage in microvolts for the VDD supply
2254  *
2255  * This function identifies the type of LDO regulator associated with a CPR3
2256  * regulator and invokes the LDO specific configuration functions.
2257  *
2258  * Return: 0 on success, errno on failure
2259  */
2260 static int cpr3_regulator_config_vreg_ldo(struct cpr3_regulator *vreg,
2261                           int vdd_floor_volt, int vdd_ceiling_volt,
2262                           int new_volt, int last_volt)
2263 {
2264         struct cpr3_controller *ctrl = vreg->thread->ctrl;
2265         int ref_volt, rc;
2266
2267         ref_volt = ctrl->use_hw_closed_loop ? vdd_floor_volt :
2268                 new_volt;
2269
2270         rc = cpr3_regulator_config_ldo_retention(vreg, ref_volt);
2271         if (rc)
2272                 return rc;
2273
2274         if (!vreg->vreg_enabled ||
2275                 vreg->current_corner == CPR3_REGULATOR_CORNER_INVALID)
2276                 return 0;
2277
2278         switch (vreg->ldo_type) {
2279         case CPR3_LDO_KRYO:
2280                 rc = cpr3_regulator_config_vreg_kryo_ldo(vreg, vdd_floor_volt,
2281                                 vdd_ceiling_volt, ref_volt, last_volt);
2282                 if (rc)
2283                         cpr3_err(vreg, "kryo ldo regulator config failed, rc=%d\n",
2284                                 rc);
2285                 break;
2286         case CPR3_LDO300:
2287                 rc = cpr3_regulator_config_vreg_ldo300(vreg, new_volt,
2288                                 vdd_ceiling_volt);
2289                 if (rc)
2290                         cpr3_err(vreg, "ldo300 regulator config failed, rc=%d\n",
2291                                 rc);
2292                 break;
2293         default:
2294                 cpr3_err(vreg, "invalid ldo regulator type = %d\n",
2295                                 vreg->ldo_type);
2296                 rc = -EINVAL;
2297         }
2298
2299         return rc;
2300 }
2301
2302 /**
2303  * cpr3_regulator_config_ldo() - configure the voltage and bypass state for the
2304  *              LDO regulator associated with each CPR3 regulator of a CPR3
2305  *              controller
2306  * @ctrl:               Pointer to the CPR3 controller
2307  * @vdd_floor_volt:     Last known aggregated floor voltage in microvolts for
2308  *                      the VDD supply
2309  * @vdd_ceiling_volt:   Last known aggregated ceiling voltage in microvolts for
2310  *                      the VDD supply
2311  * @new_volt:           New voltage in microvolts that VDD supply needs to
2312  *                      end up at
2313  * @last_volt:          Last known voltage in microvolts for the VDD supply
2314  *
2315  * Return: 0 on success, errno on failure
2316  */
2317 static int cpr3_regulator_config_ldo(struct cpr3_controller *ctrl,
2318                                 int vdd_floor_volt, int vdd_ceiling_volt,
2319                                 int new_volt, int last_volt)
2320 {
2321         struct cpr3_regulator *vreg;
2322         int i, j, rc;
2323
2324         for (i = 0; i < ctrl->thread_count; i++) {
2325                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
2326                         vreg = &ctrl->thread[i].vreg[j];
2327
2328                         if (!vreg->ldo_regulator || !vreg->ldo_mode_allowed)
2329                                 continue;
2330
2331                         rc = cpr3_regulator_config_vreg_ldo(vreg,
2332                                         vdd_floor_volt, vdd_ceiling_volt,
2333                                         new_volt, last_volt);
2334                         if (rc)
2335                                 return rc;
2336                 }
2337         }
2338
2339         return 0;
2340 }
2341
2342 /**
2343  * cpr3_regulator_mem_acc_bhs_used() - determines if mem-acc regulators powered
2344  *              through a BHS are associated with the CPR3 controller or any of
2345  *              the CPR3 regulators it controls.
2346  * @ctrl:               Pointer to the CPR3 controller
2347  *
2348  * This function determines if the CPR3 controller or any of its CPR3 regulators
2349  * need to manage mem-acc regulators that are currently powered through a BHS
2350  * and whose corner selection is based upon a particular voltage threshold.
2351  *
2352  * Return: true or false
2353  */
2354 static bool cpr3_regulator_mem_acc_bhs_used(struct cpr3_controller *ctrl)
2355 {
2356         struct cpr3_regulator *vreg;
2357         int i, j;
2358
2359         if (!ctrl->mem_acc_threshold_volt)
2360                 return false;
2361
2362         if (ctrl->mem_acc_regulator)
2363                 return true;
2364
2365         for (i = 0; i < ctrl->thread_count; i++) {
2366                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
2367                         vreg = &ctrl->thread[i].vreg[j];
2368
2369                         if (vreg->mem_acc_regulator &&
2370                             (!vreg->ldo_regulator ||
2371                              vreg->ldo_regulator_bypass
2372                              == BHS_MODE))
2373                                 return true;
2374                 }
2375         }
2376
2377         return false;
2378 }
2379
2380 /**
2381  * cpr3_regulator_config_bhs_mem_acc() - configure the mem-acc regulator
2382  *              settings for hardware blocks currently powered through the BHS.
2383  * @ctrl:               Pointer to the CPR3 controller
2384  * @new_volt:           New voltage in microvolts that VDD supply needs to
2385  *                      end up at
2386  * @last_volt:          Pointer to the last known voltage in microvolts for the
2387  *                      VDD supply
2388  * @aggr_corner:        Pointer to the CPR3 corner which corresponds to the max
2389  *                      corner aggregated from all CPR3 threads managed by the
2390  *                      CPR3 controller
2391  *
2392  * This function programs the mem-acc regulator corners for CPR3 regulators
2393  * whose LDO regulators are in bypassed state. The function also handles
2394  * CPR3 controllers which utilize mem-acc regulators that operate independently
2395  * from the LDO hardware and that must be programmed when the VDD supply
2396  * crosses a particular voltage threshold.
2397  *
2398  * Return: 0 on success, errno on failure. If the VDD supply voltage is
2399  * modified, last_volt is updated to reflect the new voltage setpoint.
2400  */
2401 static int cpr3_regulator_config_bhs_mem_acc(struct cpr3_controller *ctrl,
2402                                      int new_volt, int *last_volt,
2403                                      struct cpr3_corner *aggr_corner)
2404 {
2405         struct cpr3_regulator *vreg;
2406         int i, j, rc, mem_acc_corn, safe_volt;
2407         int mem_acc_volt = ctrl->mem_acc_threshold_volt;
2408         int ref_volt;
2409
2410         if (!cpr3_regulator_mem_acc_bhs_used(ctrl))
2411                 return 0;
2412
2413         ref_volt = ctrl->use_hw_closed_loop ? aggr_corner->floor_volt :
2414                 new_volt;
2415
2416         if (((*last_volt < mem_acc_volt && mem_acc_volt <= ref_volt) ||
2417              (*last_volt >= mem_acc_volt && mem_acc_volt > ref_volt))) {
2418                 if (ref_volt < *last_volt)
2419                         safe_volt = max(mem_acc_volt, aggr_corner->last_volt);
2420                 else
2421                         safe_volt = max(mem_acc_volt, *last_volt);
2422
2423                 rc = regulator_set_voltage(ctrl->vdd_regulator, safe_volt,
2424                                            new_volt < *last_volt ?
2425                                            ctrl->aggr_corner.ceiling_volt :
2426                                            new_volt);
2427                 if (rc) {
2428                         cpr3_err(ctrl, "regulator_set_voltage(vdd) == %d failed, rc=%d\n",
2429                                  safe_volt, rc);
2430                         return rc;
2431                 }
2432
2433                 *last_volt = safe_volt;
2434
2435                 mem_acc_corn = ref_volt < mem_acc_volt ?
2436                         ctrl->mem_acc_corner_map[CPR3_MEM_ACC_LOW_CORNER] :
2437                         ctrl->mem_acc_corner_map[CPR3_MEM_ACC_HIGH_CORNER];
2438
2439                 if (ctrl->mem_acc_regulator) {
2440                         rc = regulator_set_voltage(ctrl->mem_acc_regulator,
2441                                                    mem_acc_corn, mem_acc_corn);
2442                         if (rc) {
2443                                 cpr3_err(ctrl, "regulator_set_voltage(mem_acc) == %d failed, rc=%d\n",
2444                                          mem_acc_corn, rc);
2445                                 return rc;
2446                         }
2447                 }
2448
2449                 for (i = 0; i < ctrl->thread_count; i++) {
2450                         for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
2451                                 vreg = &ctrl->thread[i].vreg[j];
2452
2453                                 if (!vreg->mem_acc_regulator ||
2454                                     (vreg->ldo_regulator &&
2455                                      vreg->ldo_regulator_bypass
2456                                      == LDO_MODE))
2457                                         continue;
2458
2459                                 rc = regulator_set_voltage(
2460                                         vreg->mem_acc_regulator, mem_acc_corn,
2461                                         mem_acc_corn);
2462                                 if (rc) {
2463                                         cpr3_err(vreg, "regulator_set_voltage(mem_acc) == %d failed, rc=%d\n",
2464                                                  mem_acc_corn, rc);
2465                                         return rc;
2466                                 }
2467                         }
2468                 }
2469         }
2470
2471         return 0;
2472 }
2473
2474 /**
2475  * cpr3_regulator_switch_apm_mode() - switch the mode of the APM controller
2476  *              associated with a given CPR3 controller
2477  * @ctrl:               Pointer to the CPR3 controller
2478  * @new_volt:           New voltage in microvolts that VDD supply needs to
2479  *                      end up at
2480  * @last_volt:          Pointer to the last known voltage in microvolts for the
2481  *                      VDD supply
2482  * @aggr_corner:        Pointer to the CPR3 corner which corresponds to the max
2483  *                      corner aggregated from all CPR3 threads managed by the
2484  *                      CPR3 controller
2485  *
2486  * This function requests a switch of the APM mode while guaranteeing
2487  * any LDO regulator hardware requirements are satisfied. The function must
2488  * be called once it is known a new VDD supply setpoint crosses the APM
2489  * voltage threshold.
2490  *
2491  * Return: 0 on success, errno on failure. If the VDD supply voltage is
2492  * modified, last_volt is updated to reflect the new voltage setpoint.
2493  */
2494 static int cpr3_regulator_switch_apm_mode(struct cpr3_controller *ctrl,
2495                                           int new_volt, int *last_volt,
2496                                           struct cpr3_corner *aggr_corner)
2497 {
2498         struct regulator *vdd = ctrl->vdd_regulator;
2499         int apm_volt = ctrl->apm_threshold_volt;
2500         int orig_last_volt = *last_volt;
2501         int rc;
2502
2503         rc = regulator_set_voltage(vdd, apm_volt, apm_volt);
2504         if (rc) {
2505                 cpr3_err(ctrl, "regulator_set_voltage(vdd) == %d failed, rc=%d\n",
2506                          apm_volt, rc);
2507                 return rc;
2508         }
2509
2510         *last_volt = apm_volt;
2511
2512         rc = cpr3_regulator_ldo_apm_prepare(ctrl, new_volt, *last_volt,
2513                                             aggr_corner);
2514         if (rc) {
2515                 cpr3_err(ctrl, "unable to prepare LDO state for APM switch, rc=%d\n",
2516                          rc);
2517                 return rc;
2518         }
2519
2520         rc = msm_apm_set_supply(ctrl->apm, new_volt >= apm_volt
2521                                 ? ctrl->apm_high_supply : ctrl->apm_low_supply);
2522         if (rc) {
2523                 cpr3_err(ctrl, "APM switch failed, rc=%d\n", rc);
2524                 /* Roll back the voltage. */
2525                 regulator_set_voltage(vdd, orig_last_volt, INT_MAX);
2526                 *last_volt = orig_last_volt;
2527                 return rc;
2528         }
2529         return 0;
2530 }
2531
2532 /**
2533  * cpr3_regulator_config_voltage_crossings() - configure APM and mem-acc
2534  *              settings depending upon a new VDD supply setpoint
2535  *
2536  * @ctrl:               Pointer to the CPR3 controller
2537  * @new_volt:           New voltage in microvolts that VDD supply needs to
2538  *                      end up at
2539  * @last_volt:          Pointer to the last known voltage in microvolts for the
2540  *                      VDD supply
2541  * @aggr_corner:        Pointer to the CPR3 corner which corresponds to the max
2542  *                      corner aggregated from all CPR3 threads managed by the
2543  *                      CPR3 controller
2544  *
2545  * This function handles the APM and mem-acc regulator reconfiguration if
2546  * the new VDD supply voltage will result in crossing their respective voltage
2547  * thresholds.
2548  *
2549  * Return: 0 on success, errno on failure. If the VDD supply voltage is
2550  * modified, last_volt is updated to reflect the new voltage setpoint.
2551  */
2552 static int cpr3_regulator_config_voltage_crossings(struct cpr3_controller *ctrl,
2553                                    int new_volt, int *last_volt,
2554                                    struct cpr3_corner *aggr_corner)
2555 {
2556         bool apm_crossing = false, mem_acc_crossing = false;
2557         bool mem_acc_bhs_used;
2558         int apm_volt = ctrl->apm_threshold_volt;
2559         int mem_acc_volt = ctrl->mem_acc_threshold_volt;
2560         int ref_volt, rc;
2561
2562         if (ctrl->apm && apm_volt > 0
2563             && ((*last_volt < apm_volt && apm_volt <= new_volt)
2564                 || (*last_volt >= apm_volt && apm_volt > new_volt)))
2565                 apm_crossing = true;
2566
2567         mem_acc_bhs_used = cpr3_regulator_mem_acc_bhs_used(ctrl);
2568
2569         ref_volt = ctrl->use_hw_closed_loop ? aggr_corner->floor_volt :
2570                 new_volt;
2571
2572         if (mem_acc_bhs_used &&
2573             (((*last_volt < mem_acc_volt && mem_acc_volt <= ref_volt) ||
2574               (*last_volt >= mem_acc_volt && mem_acc_volt > ref_volt))))
2575                 mem_acc_crossing = true;
2576
2577         if (apm_crossing && mem_acc_crossing) {
2578                 if ((new_volt < *last_volt && apm_volt >= mem_acc_volt) ||
2579                     (new_volt >= *last_volt && apm_volt < mem_acc_volt)) {
2580                         rc = cpr3_regulator_switch_apm_mode(ctrl, new_volt,
2581                                                             last_volt,
2582                                                             aggr_corner);
2583                         if (rc) {
2584                                 cpr3_err(ctrl, "unable to switch APM mode\n");
2585                                 return rc;
2586                         }
2587
2588                         rc = cpr3_regulator_config_bhs_mem_acc(ctrl, new_volt,
2589                                                        last_volt, aggr_corner);
2590                         if (rc) {
2591                                 cpr3_err(ctrl, "unable to configure BHS mem-acc settings\n");
2592                                 return rc;
2593                         }
2594                 } else {
2595                         rc = cpr3_regulator_config_bhs_mem_acc(ctrl, new_volt,
2596                                                        last_volt, aggr_corner);
2597                         if (rc) {
2598                                 cpr3_err(ctrl, "unable to configure BHS mem-acc settings\n");
2599                                 return rc;
2600                         }
2601
2602                         rc = cpr3_regulator_switch_apm_mode(ctrl, new_volt,
2603                                                             last_volt,
2604                                                             aggr_corner);
2605                         if (rc) {
2606                                 cpr3_err(ctrl, "unable to switch APM mode\n");
2607                                 return rc;
2608                         }
2609                 }
2610         } else if (apm_crossing) {
2611                 rc = cpr3_regulator_switch_apm_mode(ctrl, new_volt, last_volt,
2612                                                     aggr_corner);
2613                 if (rc) {
2614                         cpr3_err(ctrl, "unable to switch APM mode\n");
2615                         return rc;
2616                 }
2617         } else if (mem_acc_crossing) {
2618                 rc = cpr3_regulator_config_bhs_mem_acc(ctrl, new_volt,
2619                                                        last_volt, aggr_corner);
2620                 if (rc) {
2621                         cpr3_err(ctrl, "unable to configure BHS mem-acc settings\n");
2622                         return rc;
2623                 }
2624         }
2625
2626         return 0;
2627 }
2628
2629 /**
2630  * cpr3_regulator_config_mem_acc() - configure the corner of the mem-acc
2631  *                      regulator associated with the CPR3 controller
2632  * @ctrl:               Pointer to the CPR3 controller
2633  * @aggr_corner:        Pointer to the CPR3 corner which corresponds to the max
2634  *                      corner aggregated from all CPR3 threads managed by the
2635  *                      CPR3 controller
2636  *
2637  * Return: 0 on success, errno on failure
2638  */
2639 static int cpr3_regulator_config_mem_acc(struct cpr3_controller *ctrl,
2640                                          struct cpr3_corner *aggr_corner)
2641 {
2642         int rc;
2643
2644         if (ctrl->mem_acc_regulator && aggr_corner->mem_acc_volt) {
2645                 rc = regulator_set_voltage(ctrl->mem_acc_regulator,
2646                                            aggr_corner->mem_acc_volt,
2647                                            aggr_corner->mem_acc_volt);
2648                 if (rc) {
2649                         cpr3_err(ctrl, "regulator_set_voltage(mem_acc) == %d failed, rc=%d\n",
2650                                  aggr_corner->mem_acc_volt, rc);
2651                         return rc;
2652                 }
2653         }
2654
2655         return 0;
2656 }
2657
2658 /**
2659  * cpr3_regulator_scale_vdd_voltage() - scale the CPR controlled VDD supply
2660  *              voltage to the new level while satisfying any other hardware
2661  *              requirements
2662  * @ctrl:               Pointer to the CPR3 controller
2663  * @new_volt:           New voltage in microvolts that VDD supply needs to end
2664  *                      up at
2665  * @last_volt:          Last known voltage in microvolts for the VDD supply
2666  * @aggr_corner:        Pointer to the CPR3 corner which corresponds to the max
2667  *                      corner aggregated from all CPR3 threads managed by the
2668  *                      CPR3 controller
2669  *
2670  * This function scales the CPR controlled VDD supply voltage from its
2671  * current level to the new voltage that is specified.  If the supply is
2672  * configured to use the APM and the APM threshold is crossed as a result of
2673  * the voltage scaling, then this function also stops at the APM threshold,
2674  * switches the APM source, and finally sets the final new voltage.
2675  *
2676  * Return: 0 on success, errno on failure
2677  */
2678 static int cpr3_regulator_scale_vdd_voltage(struct cpr3_controller *ctrl,
2679                                 int new_volt, int last_volt,
2680                                 struct cpr3_corner *aggr_corner)
2681 {
2682         struct regulator *vdd = ctrl->vdd_regulator;
2683         int rc;
2684
2685         if (new_volt < last_volt) {
2686                 if (ctrl->support_ldo300_vreg) {
2687                         rc = cpr3_regulator_config_mem_acc(ctrl, aggr_corner);
2688                         if (rc)
2689                                 return rc;
2690                 }
2691
2692                 /* Decreasing VDD voltage */
2693                 rc = cpr3_regulator_config_ldo(ctrl, aggr_corner->floor_volt,
2694                                                ctrl->aggr_corner.ceiling_volt,
2695                                                new_volt, last_volt);
2696                 if (rc) {
2697                         cpr3_err(ctrl, "unable to configure LDO state, rc=%d\n",
2698                                  rc);
2699                         return rc;
2700                 }
2701
2702                 if (!ctrl->support_ldo300_vreg) {
2703                         rc = cpr3_regulator_config_mem_acc(ctrl, aggr_corner);
2704                         if (rc)
2705                                 return rc;
2706                 }
2707         } else {
2708                 /* Increasing VDD voltage */
2709                 if (ctrl->system_regulator) {
2710                         rc = regulator_set_voltage(ctrl->system_regulator,
2711                                 aggr_corner->system_volt, INT_MAX);
2712                         if (rc) {
2713                                 cpr3_err(ctrl, "regulator_set_voltage(system) == %d failed, rc=%d\n",
2714                                         aggr_corner->system_volt, rc);
2715                                 return rc;
2716                         }
2717                 }
2718         }
2719
2720         rc = cpr3_regulator_config_voltage_crossings(ctrl, new_volt, &last_volt,
2721                                                      aggr_corner);
2722         if (rc) {
2723                 cpr3_err(ctrl, "unable to handle voltage threshold crossing configurations, rc=%d\n",
2724                          rc);
2725                 return rc;
2726         }
2727
2728         /*
2729          * Subtract a small amount from the min_uV parameter so that the
2730          * set voltage request is not dropped by the framework due to being
2731          * duplicate.  This is needed in order to switch from hardware
2732          * closed-loop to open-loop successfully.
2733          */
2734         rc = regulator_set_voltage(vdd, new_volt - (ctrl->cpr_enabled ? 0 : 1),
2735                                    aggr_corner->ceiling_volt);
2736         if (rc) {
2737                 cpr3_err(ctrl, "regulator_set_voltage(vdd) == %d failed, rc=%d\n",
2738                         new_volt, rc);
2739                 return rc;
2740         }
2741
2742         if (new_volt == last_volt && ctrl->supports_hw_closed_loop
2743             && ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
2744                 /*
2745                  * CPR4 features enforce voltage reprogramming when the last
2746                  * set voltage and new set voltage are same. This way, we can
2747                  * ensure that SAW PMIC STATUS register is updated with newly
2748                  * programmed voltage.
2749                  */
2750                 rc = regulator_sync_voltage(vdd);
2751                 if (rc) {
2752                         cpr3_err(ctrl, "regulator_sync_voltage(vdd) == %d failed, rc=%d\n",
2753                                 new_volt, rc);
2754                         return rc;
2755                 }
2756         }
2757
2758         if (new_volt >= last_volt) {
2759                 /* Increasing VDD voltage */
2760                 rc = cpr3_regulator_config_ldo(ctrl, aggr_corner->floor_volt,
2761                                                aggr_corner->ceiling_volt,
2762                                                new_volt, new_volt);
2763                 if (rc) {
2764                         cpr3_err(ctrl, "unable to configure LDO state, rc=%d\n",
2765                                  rc);
2766                         return rc;
2767                 }
2768
2769                 rc = cpr3_regulator_config_mem_acc(ctrl, aggr_corner);
2770                 if (rc)
2771                         return rc;
2772         } else {
2773                 /* Decreasing VDD voltage */
2774                 if (ctrl->system_regulator) {
2775                         rc = regulator_set_voltage(ctrl->system_regulator,
2776                                 aggr_corner->system_volt, INT_MAX);
2777                         if (rc) {
2778                                 cpr3_err(ctrl, "regulator_set_voltage(system) == %d failed, rc=%d\n",
2779                                         aggr_corner->system_volt, rc);
2780                                 return rc;
2781                         }
2782                 }
2783         }
2784
2785         return 0;
2786 }
2787
2788 /**
2789  * cpr3_regulator_get_dynamic_floor_volt() - returns the current dynamic floor
2790  *              voltage based upon static configurations and the state of all
2791  *              power domains during the last CPR measurement
2792  * @ctrl:               Pointer to the CPR3 controller
2793  * @reg_last_measurement: Value read from the LAST_MEASUREMENT register
2794  *
2795  * When using HW closed-loop, the dynamic floor voltage is always returned
2796  * regardless of the current state of the power domains.
2797  *
2798  * Return: dynamic floor voltage in microvolts or 0 if dynamic floor is not
2799  *         currently required
2800  */
2801 static int cpr3_regulator_get_dynamic_floor_volt(struct cpr3_controller *ctrl,
2802                 u32 reg_last_measurement)
2803 {
2804         int dynamic_floor_volt = 0;
2805         struct cpr3_regulator *vreg;
2806         bool valid, pd_valid;
2807         u32 bypass_bits;
2808         int i, j;
2809
2810         if (!ctrl->supports_hw_closed_loop)
2811                 return 0;
2812
2813         if (likely(!ctrl->use_hw_closed_loop)) {
2814                 valid = !!(reg_last_measurement & CPR3_LAST_MEASUREMENT_VALID);
2815                 bypass_bits
2816                  = (reg_last_measurement & CPR3_LAST_MEASUREMENT_PD_BYPASS_MASK)
2817                         >> CPR3_LAST_MEASUREMENT_PD_BYPASS_SHIFT;
2818         } else {
2819                 /*
2820                  * Ensure that the dynamic floor voltage is always used for
2821                  * HW closed-loop since the conditions below cannot be evaluated
2822                  * after each CPR measurement.
2823                  */
2824                 valid = false;
2825                 bypass_bits = 0;
2826         }
2827
2828         for (i = 0; i < ctrl->thread_count; i++) {
2829                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
2830                         vreg = &ctrl->thread[i].vreg[j];
2831
2832                         if (!vreg->uses_dynamic_floor)
2833                                 continue;
2834
2835                         pd_valid = !((bypass_bits & vreg->pd_bypass_mask)
2836                                         == vreg->pd_bypass_mask);
2837
2838                         if (!valid || !pd_valid)
2839                                 dynamic_floor_volt = max(dynamic_floor_volt,
2840                                         vreg->corner[
2841                                          vreg->dynamic_floor_corner].last_volt);
2842                 }
2843         }
2844
2845         return dynamic_floor_volt;
2846 }
2847
2848 /**
2849  * cpr3_regulator_max_sdelta_diff() - returns the maximum voltage difference in
2850  *              microvolts that can result from different operating conditions
2851  *              for the specified sdelta struct
2852  * @sdelta:             Pointer to the sdelta structure
2853  * @step_volt:          Step size in microvolts between available set
2854  *                      points of the VDD supply.
2855  *
2856  * Return: voltage difference between the highest and lowest adjustments if
2857  *      sdelta and sdelta->table are valid, else 0.
2858  */
2859 static int cpr3_regulator_max_sdelta_diff(const struct cpr4_sdelta *sdelta,
2860                                 int step_volt)
2861 {
2862         int i, j, index, sdelta_min = INT_MAX, sdelta_max = INT_MIN;
2863
2864         if (!sdelta || !sdelta->table)
2865                 return 0;
2866
2867         for (i = 0; i < sdelta->max_core_count; i++) {
2868                 for (j = 0; j < sdelta->temp_band_count; j++) {
2869                         index = i * sdelta->temp_band_count + j;
2870                         sdelta_min = min(sdelta_min, sdelta->table[index]);
2871                         sdelta_max = max(sdelta_max, sdelta->table[index]);
2872                 }
2873         }
2874
2875         return (sdelta_max - sdelta_min) * step_volt;
2876 }
2877
2878 /**
2879  * cpr3_regulator_aggregate_sdelta() - check open-loop voltages of current
2880  *              aggregated corner and current corner of a given regulator
2881  *              and adjust the sdelta strucuture data of aggregate corner.
2882  * @aggr_corner:        Pointer to accumulated aggregated corner which
2883  *                      is both an input and an output
2884  * @corner:             Pointer to the corner to be aggregated with
2885  *                      aggr_corner
2886  * @step_volt:          Step size in microvolts between available set
2887  *                      points of the VDD supply.
2888  *
2889  * Return: none
2890  */
2891 static void cpr3_regulator_aggregate_sdelta(
2892                                 struct cpr3_corner *aggr_corner,
2893                                 const struct cpr3_corner *corner, int step_volt)
2894 {
2895         struct cpr4_sdelta *aggr_sdelta, *sdelta;
2896         int aggr_core_count, core_count, temp_band_count;
2897         u32 aggr_index, index;
2898         int i, j, sdelta_size, cap_steps, adjust_sdelta;
2899
2900         aggr_sdelta = aggr_corner->sdelta;
2901         sdelta = corner->sdelta;
2902
2903         if (aggr_corner->open_loop_volt < corner->open_loop_volt) {
2904                 /*
2905                  * Found the new dominant regulator as its open-loop requirement
2906                  * is higher than previous dominant regulator. Calculate cap
2907                  * voltage to limit the SDELTA values to make sure the runtime
2908                  * (Core-count/temp) adjustments do not violate other
2909                  * regulators' voltage requirements. Use cpr4_sdelta values of
2910                  * new dominant regulator.
2911                  */
2912                 aggr_sdelta->cap_volt = min(aggr_sdelta->cap_volt,
2913                                                 (corner->open_loop_volt -
2914                                                 aggr_corner->open_loop_volt));
2915
2916                 /* Clear old data in the sdelta table */
2917                 sdelta_size = aggr_sdelta->max_core_count
2918                                         * aggr_sdelta->temp_band_count;
2919
2920                 if (aggr_sdelta->allow_core_count_adj
2921                         || aggr_sdelta->allow_temp_adj)
2922                         memset(aggr_sdelta->table, 0, sdelta_size
2923                                         * sizeof(*aggr_sdelta->table));
2924
2925                 if (sdelta->allow_temp_adj || sdelta->allow_core_count_adj) {
2926                         /* Copy new data in sdelta table */
2927                         sdelta_size = sdelta->max_core_count
2928                                                 * sdelta->temp_band_count;
2929                         if (sdelta->table)
2930                                 memcpy(aggr_sdelta->table, sdelta->table,
2931                                         sdelta_size * sizeof(*sdelta->table));
2932                 }
2933
2934                 if (sdelta->allow_boost) {
2935                         memcpy(aggr_sdelta->boost_table, sdelta->boost_table,
2936                                 sdelta->temp_band_count
2937                                 * sizeof(*sdelta->boost_table));
2938                         aggr_sdelta->boost_num_cores = sdelta->boost_num_cores;
2939                 } else if (aggr_sdelta->allow_boost) {
2940                         for (i = 0; i < aggr_sdelta->temp_band_count; i++) {
2941                                 adjust_sdelta = (corner->open_loop_volt
2942                                                 - aggr_corner->open_loop_volt)
2943                                                 / step_volt;
2944                                 aggr_sdelta->boost_table[i] += adjust_sdelta;
2945                                 aggr_sdelta->boost_table[i]
2946                                         = min(aggr_sdelta->boost_table[i], 0);
2947                         }
2948                 }
2949
2950                 aggr_corner->open_loop_volt = corner->open_loop_volt;
2951                 aggr_sdelta->allow_temp_adj = sdelta->allow_temp_adj;
2952                 aggr_sdelta->allow_core_count_adj
2953                                         = sdelta->allow_core_count_adj;
2954                 aggr_sdelta->max_core_count = sdelta->max_core_count;
2955                 aggr_sdelta->temp_band_count = sdelta->temp_band_count;
2956         } else if (aggr_corner->open_loop_volt > corner->open_loop_volt) {
2957                 /*
2958                  * Adjust the cap voltage if the open-loop requirement of new
2959                  * regulator is the next highest.
2960                  */
2961                 aggr_sdelta->cap_volt = min(aggr_sdelta->cap_volt,
2962                                                 (aggr_corner->open_loop_volt
2963                                                 - corner->open_loop_volt));
2964
2965                 if (sdelta->allow_boost) {
2966                         for (i = 0; i < aggr_sdelta->temp_band_count; i++) {
2967                                 adjust_sdelta = (aggr_corner->open_loop_volt
2968                                                 - corner->open_loop_volt)
2969                                                 / step_volt;
2970                                 aggr_sdelta->boost_table[i] =
2971                                         sdelta->boost_table[i] + adjust_sdelta;
2972                                 aggr_sdelta->boost_table[i]
2973                                         = min(aggr_sdelta->boost_table[i], 0);
2974                         }
2975                         aggr_sdelta->boost_num_cores = sdelta->boost_num_cores;
2976                 }
2977         } else {
2978                 /*
2979                  * Found another dominant regulator with same open-loop
2980                  * requirement. Make cap voltage to '0'. Disable core-count
2981                  * adjustments as we couldn't support for both regulators.
2982                  * Keep enable temp based adjustments if enabled for both
2983                  * regulators and choose mininum margin adjustment values
2984                  * between them.
2985                  */
2986                 aggr_sdelta->cap_volt = 0;
2987                 aggr_sdelta->allow_core_count_adj = false;
2988
2989                 if (aggr_sdelta->allow_temp_adj
2990                                         && sdelta->allow_temp_adj) {
2991                         aggr_core_count = aggr_sdelta->max_core_count - 1;
2992                         core_count = sdelta->max_core_count - 1;
2993                         temp_band_count = sdelta->temp_band_count;
2994                         for (j = 0; j < temp_band_count; j++) {
2995                                 aggr_index = aggr_core_count * temp_band_count
2996                                                 + j;
2997                                 index = core_count * temp_band_count + j;
2998                                 aggr_sdelta->table[aggr_index] =
2999                                         min(aggr_sdelta->table[aggr_index],
3000                                                 sdelta->table[index]);
3001                         }
3002                 } else {
3003                         aggr_sdelta->allow_temp_adj = false;
3004                 }
3005
3006                 if (sdelta->allow_boost) {
3007                         memcpy(aggr_sdelta->boost_table, sdelta->boost_table,
3008                                 sdelta->temp_band_count
3009                                 * sizeof(*sdelta->boost_table));
3010                         aggr_sdelta->boost_num_cores = sdelta->boost_num_cores;
3011                 }
3012         }
3013
3014         /* Keep non-dominant clients boost enable state */
3015         aggr_sdelta->allow_boost |= sdelta->allow_boost;
3016         if (aggr_sdelta->allow_boost)
3017                 aggr_sdelta->allow_core_count_adj = false;
3018
3019         if (aggr_sdelta->cap_volt && !(aggr_sdelta->cap_volt == INT_MAX)) {
3020                 core_count = aggr_sdelta->max_core_count;
3021                 temp_band_count = aggr_sdelta->temp_band_count;
3022                 /*
3023                  * Convert cap voltage from uV to PMIC steps and use to limit
3024                  * sdelta margin adjustments.
3025                  */
3026                 cap_steps = aggr_sdelta->cap_volt / step_volt;
3027                 for (i = 0; i < core_count; i++)
3028                         for (j = 0; j < temp_band_count; j++) {
3029                                 index = i * temp_band_count + j;
3030                                 aggr_sdelta->table[index] =
3031                                                 min(aggr_sdelta->table[index],
3032                                                         cap_steps);
3033                 }
3034         }
3035 }
3036
3037 /**
3038  * cpr3_regulator_aggregate_corners() - aggregate two corners together
3039  * @aggr_corner:                Pointer to accumulated aggregated corner which
3040  *                              is both an input and an output
3041  * @corner:                     Pointer to the corner to be aggregated with
3042  *                              aggr_corner
3043  * @aggr_quot:                  Flag indicating that target quotients should be
3044  *                              aggregated as well.
3045  * @step_volt:                  Step size in microvolts between available set
3046  *                              points of the VDD supply.
3047  *
3048  * Return: none
3049  */
3050 static void cpr3_regulator_aggregate_corners(struct cpr3_corner *aggr_corner,
3051                         const struct cpr3_corner *corner, bool aggr_quot,
3052                         int step_volt)
3053 {
3054         int i;
3055
3056         aggr_corner->ceiling_volt
3057                 = max(aggr_corner->ceiling_volt, corner->ceiling_volt);
3058         aggr_corner->floor_volt
3059                 = max(aggr_corner->floor_volt, corner->floor_volt);
3060         aggr_corner->last_volt
3061                 = max(aggr_corner->last_volt, corner->last_volt);
3062         aggr_corner->system_volt
3063                 = max(aggr_corner->system_volt, corner->system_volt);
3064         aggr_corner->mem_acc_volt
3065                 = max(aggr_corner->mem_acc_volt, corner->mem_acc_volt);
3066         aggr_corner->irq_en |= corner->irq_en;
3067         aggr_corner->use_open_loop |= corner->use_open_loop;
3068         aggr_corner->ldo_mode_allowed |= corner->ldo_mode_allowed;
3069
3070         if (aggr_quot) {
3071                 aggr_corner->ro_mask &= corner->ro_mask;
3072
3073                 for (i = 0; i < CPR3_RO_COUNT; i++)
3074                         aggr_corner->target_quot[i]
3075                                 = max(aggr_corner->target_quot[i],
3076                                       corner->target_quot[i]);
3077         }
3078
3079         if (aggr_corner->sdelta && corner->sdelta
3080                 && (aggr_corner->sdelta->table
3081                 || aggr_corner->sdelta->boost_table)) {
3082                 cpr3_regulator_aggregate_sdelta(aggr_corner, corner, step_volt);
3083         } else {
3084                 aggr_corner->open_loop_volt
3085                         = max(aggr_corner->open_loop_volt,
3086                                 corner->open_loop_volt);
3087         }
3088 }
3089
3090 /**
3091  * cpr3_regulator_update_ctrl_state() - update the state of the CPR controller
3092  *              to reflect the corners used by all CPR3 regulators as well as
3093  *              the CPR operating mode
3094  * @ctrl:               Pointer to the CPR3 controller
3095  *
3096  * This function aggregates the CPR parameters for all CPR3 regulators
3097  * associated with the VDD supply.  Upon success, it sets the aggregated last
3098  * known good voltage.
3099  *
3100  * The VDD supply voltage will not be physically configured unless this
3101  * condition is met by at least one of the regulators of the controller:
3102  * regulator->vreg_enabled == true &&
3103  * regulator->current_corner != CPR3_REGULATOR_CORNER_INVALID
3104  *
3105  * CPR registers for the controller and each thread are updated as long as
3106  * ctrl->cpr_enabled == true.
3107  *
3108  * Note, CPR3 controller lock must be held by the caller.
3109  *
3110  * Return: 0 on success, errno on failure
3111  */
3112 static int _cpr3_regulator_update_ctrl_state(struct cpr3_controller *ctrl)
3113 {
3114         struct cpr3_corner aggr_corner = {};
3115         struct cpr3_thread *thread;
3116         struct cpr3_regulator *vreg;
3117         struct cpr4_sdelta *sdelta;
3118         bool valid = false;
3119         bool thread_valid;
3120         int i, j, rc;
3121         int new_volt, vdd_volt, dynamic_floor_volt, last_corner_volt = 0;
3122         u32 reg_last_measurement = 0, sdelta_size;
3123         int *sdelta_table, *boost_table;
3124
3125         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
3126                 rc = cpr3_ctrl_clear_cpr4_config(ctrl);
3127                 if (rc) {
3128                         cpr3_err(ctrl, "failed to clear CPR4 configuration,rc=%d\n",
3129                                 rc);
3130                         return rc;
3131                 }
3132         }
3133
3134         cpr3_ctrl_loop_disable(ctrl);
3135
3136         vdd_volt = regulator_get_voltage(ctrl->vdd_regulator);
3137         if (vdd_volt < 0) {
3138                 cpr3_err(ctrl, "regulator_get_voltage(vdd) failed, rc=%d\n",
3139                          vdd_volt);
3140                 return vdd_volt;
3141         }
3142
3143         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
3144                 /*
3145                  * Save aggregated corner open-loop voltage which was programmed
3146                  * during last corner switch which is used when programming new
3147                  * aggregated corner open-loop voltage.
3148                  */
3149                 last_corner_volt = ctrl->aggr_corner.open_loop_volt;
3150         }
3151
3152         if (ctrl->cpr_enabled && ctrl->use_hw_closed_loop &&
3153                 ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3)
3154                 reg_last_measurement
3155                         = cpr3_read(ctrl, CPR3_REG_LAST_MEASUREMENT);
3156
3157         aggr_corner.sdelta = ctrl->aggr_corner.sdelta;
3158         if (aggr_corner.sdelta) {
3159                 sdelta = aggr_corner.sdelta;
3160                 sdelta_table = sdelta->table;
3161                 if (sdelta_table) {
3162                         sdelta_size = sdelta->max_core_count *
3163                                         sdelta->temp_band_count;
3164                         memset(sdelta_table, 0, sdelta_size
3165                                         * sizeof(*sdelta_table));
3166                 }
3167
3168                 boost_table = sdelta->boost_table;
3169                 if (boost_table)
3170                         memset(boost_table, 0, sdelta->temp_band_count
3171                                         * sizeof(*boost_table));
3172
3173                 memset(sdelta, 0, sizeof(*sdelta));
3174                 sdelta->table = sdelta_table;
3175                 sdelta->cap_volt = INT_MAX;
3176                 sdelta->boost_table = boost_table;
3177         }
3178
3179         /* Aggregate the requests of all threads */
3180         for (i = 0; i < ctrl->thread_count; i++) {
3181                 thread = &ctrl->thread[i];
3182                 thread_valid = false;
3183
3184                 sdelta = thread->aggr_corner.sdelta;
3185                 if (sdelta) {
3186                         sdelta_table = sdelta->table;
3187                         if (sdelta_table) {
3188                                 sdelta_size = sdelta->max_core_count *
3189                                                 sdelta->temp_band_count;
3190                                 memset(sdelta_table, 0, sdelta_size
3191                                                 * sizeof(*sdelta_table));
3192                         }
3193
3194                         boost_table = sdelta->boost_table;
3195                         if (boost_table)
3196                                 memset(boost_table, 0, sdelta->temp_band_count
3197                                                 * sizeof(*boost_table));
3198
3199                         memset(sdelta, 0, sizeof(*sdelta));
3200                         sdelta->table = sdelta_table;
3201                         sdelta->cap_volt = INT_MAX;
3202                         sdelta->boost_table = boost_table;
3203                 }
3204
3205                 memset(&thread->aggr_corner, 0, sizeof(thread->aggr_corner));
3206                 thread->aggr_corner.sdelta = sdelta;
3207                 thread->aggr_corner.ro_mask = CPR3_RO_MASK;
3208
3209                 for (j = 0; j < thread->vreg_count; j++) {
3210                         vreg = &thread->vreg[j];
3211
3212                         if (ctrl->cpr_enabled && ctrl->use_hw_closed_loop)
3213                                 cpr3_update_vreg_closed_loop_volt(vreg,
3214                                                 vdd_volt, reg_last_measurement);
3215
3216                         if (!vreg->vreg_enabled
3217                             || vreg->current_corner
3218                                             == CPR3_REGULATOR_CORNER_INVALID) {
3219                                 /* Cannot participate in aggregation. */
3220                                 vreg->aggregated = false;
3221                                 continue;
3222                         } else {
3223                                 vreg->aggregated = true;
3224                                 thread_valid = true;
3225                         }
3226
3227                         cpr3_regulator_aggregate_corners(&thread->aggr_corner,
3228                                         &vreg->corner[vreg->current_corner],
3229                                         true, ctrl->step_volt);
3230                 }
3231
3232                 valid |= thread_valid;
3233
3234                 if (thread_valid)
3235                         cpr3_regulator_aggregate_corners(&aggr_corner,
3236                                         &thread->aggr_corner,
3237                                         false, ctrl->step_volt);
3238         }
3239
3240         if (valid && ctrl->cpr_allowed_hw && ctrl->cpr_allowed_sw) {
3241                 rc = cpr3_closed_loop_enable(ctrl);
3242                 if (rc) {
3243                         cpr3_err(ctrl, "could not enable CPR, rc=%d\n", rc);
3244                         return rc;
3245                 }
3246         } else {
3247                 rc = cpr3_closed_loop_disable(ctrl);
3248                 if (rc) {
3249                         cpr3_err(ctrl, "could not disable CPR, rc=%d\n", rc);
3250                         return rc;
3251                 }
3252         }
3253
3254         /* No threads are enabled with a valid corner so exit. */
3255         if (!valid)
3256                 return 0;
3257
3258         /*
3259          * When using CPR hardware closed-loop, the voltage may vary anywhere
3260          * between the floor and ceiling voltage without software notification.
3261          * Therefore, it is required that the floor to ceiling range for the
3262          * aggregated corner not intersect the APM threshold voltage.  Adjust
3263          * the floor to ceiling range if this requirement is violated.
3264          *
3265          * The following algorithm is applied in the case that
3266          * floor < threshold <= ceiling:
3267          *      if open_loop >= threshold - adj, then floor = threshold
3268          *      else ceiling = threshold - step
3269          * where adj = an adjustment factor to ensure sufficient voltage margin
3270          * and step = VDD output step size
3271          *
3272          * The open-loop and last known voltages are also bounded by the new
3273          * floor or ceiling value as needed.
3274          */
3275         if (ctrl->use_hw_closed_loop
3276             && aggr_corner.ceiling_volt >= ctrl->apm_threshold_volt
3277             && aggr_corner.floor_volt < ctrl->apm_threshold_volt) {
3278
3279                 if (aggr_corner.open_loop_volt
3280                     >= ctrl->apm_threshold_volt - ctrl->apm_adj_volt)
3281                         aggr_corner.floor_volt = ctrl->apm_threshold_volt;
3282                 else
3283                         aggr_corner.ceiling_volt
3284                                 = ctrl->apm_threshold_volt - ctrl->step_volt;
3285
3286                 aggr_corner.last_volt
3287                     = max(aggr_corner.last_volt, aggr_corner.floor_volt);
3288                 aggr_corner.last_volt
3289                     = min(aggr_corner.last_volt, aggr_corner.ceiling_volt);
3290                 aggr_corner.open_loop_volt
3291                     = max(aggr_corner.open_loop_volt, aggr_corner.floor_volt);
3292                 aggr_corner.open_loop_volt
3293                     = min(aggr_corner.open_loop_volt, aggr_corner.ceiling_volt);
3294         }
3295
3296         if (ctrl->use_hw_closed_loop
3297             && aggr_corner.ceiling_volt >= ctrl->mem_acc_threshold_volt
3298             && aggr_corner.floor_volt < ctrl->mem_acc_threshold_volt) {
3299                 aggr_corner.floor_volt = ctrl->mem_acc_threshold_volt;
3300                 aggr_corner.last_volt = max(aggr_corner.last_volt,
3301                                              aggr_corner.floor_volt);
3302                 aggr_corner.open_loop_volt = max(aggr_corner.open_loop_volt,
3303                                                   aggr_corner.floor_volt);
3304         }
3305
3306         if (ctrl->use_hw_closed_loop) {
3307                 dynamic_floor_volt
3308                         = cpr3_regulator_get_dynamic_floor_volt(ctrl,
3309                                                         reg_last_measurement);
3310                 if (aggr_corner.floor_volt < dynamic_floor_volt) {
3311                         aggr_corner.floor_volt = dynamic_floor_volt;
3312                         aggr_corner.last_volt = max(aggr_corner.last_volt,
3313                                                         aggr_corner.floor_volt);
3314                         aggr_corner.open_loop_volt
3315                                 = max(aggr_corner.open_loop_volt,
3316                                         aggr_corner.floor_volt);
3317                         aggr_corner.ceiling_volt = max(aggr_corner.ceiling_volt,
3318                                                         aggr_corner.floor_volt);
3319                 }
3320         }
3321
3322         if (ctrl->cpr_enabled && ctrl->last_corner_was_closed_loop) {
3323                 /*
3324                  * Always program open-loop voltage for CPR4 controllers which
3325                  * support hardware closed-loop.  Storing the last closed loop
3326                  * voltage in corner structure can still help with debugging.
3327                  */
3328                 if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3)
3329                         new_volt = aggr_corner.last_volt;
3330                 else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4
3331                          && ctrl->supports_hw_closed_loop)
3332                         new_volt = aggr_corner.open_loop_volt;
3333                 else
3334                         new_volt = min(aggr_corner.last_volt +
3335                               cpr3_regulator_max_sdelta_diff(aggr_corner.sdelta,
3336                                                              ctrl->step_volt),
3337                                        aggr_corner.ceiling_volt);
3338         } else {
3339                 new_volt = aggr_corner.open_loop_volt;
3340                 aggr_corner.last_volt = aggr_corner.open_loop_volt;
3341         }
3342
3343         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4
3344             && ctrl->supports_hw_closed_loop) {
3345                 /*
3346                  * Store last aggregated corner open-loop voltage in vdd_volt
3347                  * which is used when programming current aggregated corner
3348                  * required voltage.
3349                  */
3350                 vdd_volt = last_corner_volt;
3351         }
3352
3353         cpr3_debug(ctrl, "setting new voltage=%d uV\n", new_volt);
3354         rc = cpr3_regulator_scale_vdd_voltage(ctrl, new_volt,
3355                                               vdd_volt, &aggr_corner);
3356         if (rc) {
3357                 cpr3_err(ctrl, "vdd voltage scaling failed, rc=%d\n", rc);
3358                 return rc;
3359         }
3360
3361         /* Only update registers if CPR is enabled. */
3362         if (ctrl->cpr_enabled) {
3363                 if (ctrl->use_hw_closed_loop) {
3364                         /* Hardware closed-loop */
3365
3366                         /* Set ceiling and floor limits in hardware */
3367                         rc = regulator_set_voltage(ctrl->vdd_limit_regulator,
3368                                 aggr_corner.floor_volt,
3369                                 aggr_corner.ceiling_volt);
3370                         if (rc) {
3371                                 cpr3_err(ctrl, "could not configure HW closed-loop voltage limits, rc=%d\n",
3372                                         rc);
3373                                 return rc;
3374                         }
3375                 } else {
3376                         /* Software closed-loop */
3377
3378                         /*
3379                          * Disable UP or DOWN interrupts when at ceiling or
3380                          * floor respectively.
3381                          */
3382                         if (new_volt == aggr_corner.floor_volt)
3383                                 aggr_corner.irq_en &= ~CPR3_IRQ_DOWN;
3384                         if (new_volt == aggr_corner.ceiling_volt)
3385                                 aggr_corner.irq_en &= ~CPR3_IRQ_UP;
3386
3387                         cpr3_write(ctrl, CPR3_REG_IRQ_CLEAR,
3388                                 CPR3_IRQ_UP | CPR3_IRQ_DOWN);
3389                         cpr3_write(ctrl, CPR3_REG_IRQ_EN, aggr_corner.irq_en);
3390                 }
3391
3392                 for (i = 0; i < ctrl->thread_count; i++) {
3393                         cpr3_regulator_set_target_quot(&ctrl->thread[i]);
3394
3395                         for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
3396                                 vreg = &ctrl->thread[i].vreg[j];
3397
3398                                 if (vreg->vreg_enabled)
3399                                         vreg->last_closed_loop_corner
3400                                                 = vreg->current_corner;
3401                         }
3402                 }
3403
3404                 if (ctrl->proc_clock_throttle) {
3405                         if (aggr_corner.ceiling_volt > aggr_corner.floor_volt
3406                             && (ctrl->use_hw_closed_loop
3407                                         || new_volt < aggr_corner.ceiling_volt))
3408                                 cpr3_write(ctrl, CPR3_REG_PD_THROTTLE,
3409                                                 ctrl->proc_clock_throttle);
3410                         else
3411                                 cpr3_write(ctrl, CPR3_REG_PD_THROTTLE,
3412                                                 CPR3_PD_THROTTLE_DISABLE);
3413                 }
3414
3415                 /*
3416                  * Ensure that all CPR register writes complete before
3417                  * re-enabling CPR loop operation.
3418                  */
3419                 wmb();
3420         } else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4
3421                    && ctrl->vdd_limit_regulator) {
3422                 /* Set ceiling and floor limits in hardware */
3423                 rc = regulator_set_voltage(ctrl->vdd_limit_regulator,
3424                         aggr_corner.floor_volt,
3425                         aggr_corner.ceiling_volt);
3426                 if (rc) {
3427                         cpr3_err(ctrl, "could not configure HW closed-loop voltage limits, rc=%d\n",
3428                                 rc);
3429                         return rc;
3430                 }
3431         }
3432
3433         ctrl->aggr_corner = aggr_corner;
3434
3435         if (ctrl->allow_core_count_adj || ctrl->allow_temp_adj
3436                 || ctrl->allow_boost) {
3437                 rc = cpr3_controller_program_sdelta(ctrl);
3438                 if (rc) {
3439                         cpr3_err(ctrl, "failed to program sdelta, rc=%d\n", rc);
3440                         return rc;
3441                 }
3442         }
3443
3444         /*
3445          * Only enable the CPR controller if it is possible to set more than
3446          * one vdd-supply voltage.
3447          */
3448         if (aggr_corner.ceiling_volt > aggr_corner.floor_volt &&
3449                         !aggr_corner.use_open_loop)
3450                 cpr3_ctrl_loop_enable(ctrl);
3451
3452         ctrl->last_corner_was_closed_loop = ctrl->cpr_enabled;
3453         cpr3_debug(ctrl, "CPR configuration updated\n");
3454
3455         return 0;
3456 }
3457
3458 /**
3459  * cpr3_regulator_wait_for_idle() - wait for the CPR controller to no longer be
3460  *              busy
3461  * @ctrl:               Pointer to the CPR3 controller
3462  * @max_wait_ns:        Max wait time in nanoseconds
3463  *
3464  * Return: 0 on success or -ETIMEDOUT if the controller was still busy after
3465  *         the maximum delay time
3466  */
3467 static int cpr3_regulator_wait_for_idle(struct cpr3_controller *ctrl,
3468                                         s64 max_wait_ns)
3469 {
3470         ktime_t start, end;
3471         s64 time_ns;
3472         u32 reg;
3473
3474         /*
3475          * Ensure that all previous CPR register writes have completed before
3476          * checking the status register.
3477          */
3478         mb();
3479
3480         start = ktime_get();
3481         do {
3482                 end = ktime_get();
3483                 time_ns = ktime_to_ns(ktime_sub(end, start));
3484                 if (time_ns > max_wait_ns) {
3485                         cpr3_err(ctrl, "CPR controller still busy after %lld us\n",
3486                                 div_s64(time_ns, 1000));
3487                         return -ETIMEDOUT;
3488                 }
3489                 usleep_range(50, 100);
3490                 reg = cpr3_read(ctrl, CPR3_REG_CPR_STATUS);
3491         } while (reg & CPR3_CPR_STATUS_BUSY_MASK);
3492
3493         return 0;
3494 }
3495
3496 /**
3497  * cmp_int() - int comparison function to be passed into the sort() function
3498  *              which leads to ascending sorting
3499  * @a:                  First int value
3500  * @b:                  Second int value
3501  *
3502  * Return: >0 if a > b, 0 if a == b, <0 if a < b
3503  */
3504 static int cmp_int(const void *a, const void *b)
3505 {
3506         return *(int *)a - *(int *)b;
3507 }
3508
3509 /**
3510  * cpr3_regulator_measure_aging() - measure the quotient difference for the
3511  *              specified CPR aging sensor
3512  * @ctrl:               Pointer to the CPR3 controller
3513  * @aging_sensor:       Aging sensor to measure
3514  *
3515  * Note that vdd-supply must be configured to the aging reference voltage before
3516  * calling this function.
3517  *
3518  * Return: 0 on success, errno on failure
3519  */
3520 static int cpr3_regulator_measure_aging(struct cpr3_controller *ctrl,
3521                                 struct cpr3_aging_sensor_info *aging_sensor)
3522 {
3523         u32 mask, reg, result, quot_min, quot_max, sel_min, sel_max;
3524         u32 quot_min_scaled, quot_max_scaled;
3525         u32 gcnt, gcnt_ref, gcnt0_restore, gcnt1_restore, irq_restore;
3526         u32 ro_mask_restore, cont_dly_restore, up_down_dly_restore = 0;
3527         int quot_delta, quot_delta_scaled, quot_delta_scaled_sum;
3528         int *quot_delta_results;
3529         int rc, rc2, i, aging_measurement_count, filtered_count;
3530         bool is_aging_measurement;
3531
3532         quot_delta_results = kcalloc(CPR3_AGING_MEASUREMENT_ITERATIONS,
3533                         sizeof(*quot_delta_results), GFP_KERNEL);
3534         if (!quot_delta_results)
3535                 return -ENOMEM;
3536
3537         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
3538                 rc = cpr3_ctrl_clear_cpr4_config(ctrl);
3539                 if (rc) {
3540                         cpr3_err(ctrl, "failed to clear CPR4 configuration,rc=%d\n",
3541                                 rc);
3542                         kfree(quot_delta_results);
3543                         return rc;
3544                 }
3545         }
3546
3547         cpr3_ctrl_loop_disable(ctrl);
3548
3549         /* Enable up, down, and mid CPR interrupts */
3550         irq_restore = cpr3_read(ctrl, CPR3_REG_IRQ_EN);
3551         cpr3_write(ctrl, CPR3_REG_IRQ_EN,
3552                         CPR3_IRQ_UP | CPR3_IRQ_DOWN | CPR3_IRQ_MID);
3553
3554         /* Ensure that the aging sensor is assigned to CPR thread 0 */
3555         cpr3_write(ctrl, CPR3_REG_SENSOR_OWNER(aging_sensor->sensor_id), 0);
3556
3557         /* Switch from HW to SW closed-loop if necessary */
3558         if (ctrl->supports_hw_closed_loop) {
3559                 if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4 ||
3560                     ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH) {
3561                         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
3562                                 CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
3563                                 CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_DISABLE);
3564                 } else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
3565                         cpr3_write(ctrl, CPR3_REG_HW_CLOSED_LOOP,
3566                                 CPR3_HW_CLOSED_LOOP_DISABLE);
3567                 }
3568         }
3569
3570         /* Configure the GCNT for RO0 and RO1 that are used for aging */
3571         gcnt0_restore = cpr3_read(ctrl, CPR3_REG_GCNT(0));
3572         gcnt1_restore = cpr3_read(ctrl, CPR3_REG_GCNT(1));
3573         gcnt_ref = cpr3_regulator_get_gcnt(ctrl);
3574
3575         gcnt = gcnt_ref;
3576         if (ctrl->aging_gcnt_scaling_factor)
3577                 gcnt = gcnt_ref * ctrl->aging_gcnt_scaling_factor
3578                                 / CPR3_AGING_GCNT_SCALING_UNITY;
3579
3580         cpr3_write(ctrl, CPR3_REG_GCNT(0), gcnt);
3581         cpr3_write(ctrl, CPR3_REG_GCNT(1), gcnt);
3582
3583         /* Unmask all RO's */
3584         ro_mask_restore = cpr3_read(ctrl, CPR3_REG_RO_MASK(0));
3585         cpr3_write(ctrl, CPR3_REG_RO_MASK(0), 0);
3586
3587         /*
3588          * Mask all sensors except for the one to measure and bypass all
3589          * sensors in collapsible domains.
3590          */
3591         for (i = 0; i <= ctrl->sensor_count / 32; i++) {
3592                 mask = GENMASK(min(31, ctrl->sensor_count - i * 32), 0);
3593                 if (aging_sensor->sensor_id / 32 >= i
3594                     && aging_sensor->sensor_id / 32 < (i + 1))
3595                         mask &= ~BIT(aging_sensor->sensor_id % 32);
3596                 cpr3_write(ctrl, CPR3_REG_SENSOR_MASK_WRITE_BANK(i), mask);
3597                 cpr3_write(ctrl, CPR3_REG_SENSOR_BYPASS_WRITE_BANK(i),
3598                                 aging_sensor->bypass_mask[i]);
3599         }
3600
3601         /* Set CPR loop delays to 0 us */
3602         if (ctrl->supports_hw_closed_loop
3603                 && ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
3604                 cont_dly_restore = cpr3_read(ctrl, CPR3_REG_CPR_TIMER_MID_CONT);
3605                 up_down_dly_restore = cpr3_read(ctrl,
3606                                                 CPR3_REG_CPR_TIMER_UP_DN_CONT);
3607                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_MID_CONT, 0);
3608                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_UP_DN_CONT, 0);
3609         } else {
3610                 cont_dly_restore = cpr3_read(ctrl,
3611                                                 CPR3_REG_CPR_TIMER_AUTO_CONT);
3612                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_AUTO_CONT, 0);
3613         }
3614
3615         /* Set count mode to all-at-once min with no repeat */
3616         cpr3_masked_write(ctrl, CPR3_REG_CPR_CTL,
3617                 CPR3_CPR_CTL_COUNT_MODE_MASK | CPR3_CPR_CTL_COUNT_REPEAT_MASK,
3618                 CPR3_CPR_CTL_COUNT_MODE_ALL_AT_ONCE_MIN
3619                         << CPR3_CPR_CTL_COUNT_MODE_SHIFT);
3620
3621         cpr3_ctrl_loop_enable(ctrl);
3622
3623         rc = cpr3_regulator_wait_for_idle(ctrl,
3624                                         CPR3_AGING_MEASUREMENT_TIMEOUT_NS);
3625         if (rc)
3626                 goto cleanup;
3627
3628         /* Set count mode to all-at-once aging */
3629         cpr3_masked_write(ctrl, CPR3_REG_CPR_CTL, CPR3_CPR_CTL_COUNT_MODE_MASK,
3630                         CPR3_CPR_CTL_COUNT_MODE_ALL_AT_ONCE_AGE
3631                                 << CPR3_CPR_CTL_COUNT_MODE_SHIFT);
3632
3633         aging_measurement_count = 0;
3634         for (i = 0; i < CPR3_AGING_MEASUREMENT_ITERATIONS; i++) {
3635                 /* Send CONT_NACK */
3636                 cpr3_write(ctrl, CPR3_REG_CONT_CMD, CPR3_CONT_CMD_NACK);
3637
3638                 rc = cpr3_regulator_wait_for_idle(ctrl,
3639                                         CPR3_AGING_MEASUREMENT_TIMEOUT_NS);
3640                 if (rc)
3641                         goto cleanup;
3642
3643                 /* Check for PAGE_IS_AGE flag in status register */
3644                 reg = cpr3_read(ctrl, CPR3_REG_CPR_STATUS);
3645                 is_aging_measurement
3646                         = reg & CPR3_CPR_STATUS_AGING_MEASUREMENT_MASK;
3647
3648                 /* Read CPR measurement results */
3649                 result = cpr3_read(ctrl, CPR3_REG_RESULT1(0));
3650                 quot_min = (result & CPR3_RESULT1_QUOT_MIN_MASK)
3651                                 >> CPR3_RESULT1_QUOT_MIN_SHIFT;
3652                 quot_max = (result & CPR3_RESULT1_QUOT_MAX_MASK)
3653                                 >> CPR3_RESULT1_QUOT_MAX_SHIFT;
3654                 sel_min = (result & CPR3_RESULT1_RO_MIN_MASK)
3655                                 >> CPR3_RESULT1_RO_MIN_SHIFT;
3656                 sel_max = (result & CPR3_RESULT1_RO_MAX_MASK)
3657                                 >> CPR3_RESULT1_RO_MAX_SHIFT;
3658
3659                 /*
3660                  * Scale the quotients so that they are equivalent to the fused
3661                  * values.  This accounts for the difference in measurement
3662                  * interval times.
3663                  */
3664                 quot_min_scaled = quot_min * (gcnt_ref + 1) / (gcnt + 1);
3665                 quot_max_scaled = quot_max * (gcnt_ref + 1) / (gcnt + 1);
3666
3667                 if (sel_max == 1) {
3668                         quot_delta = quot_max - quot_min;
3669                         quot_delta_scaled = quot_max_scaled - quot_min_scaled;
3670                 } else {
3671                         quot_delta = quot_min - quot_max;
3672                         quot_delta_scaled = quot_min_scaled - quot_max_scaled;
3673                 }
3674
3675                 if (is_aging_measurement)
3676                         quot_delta_results[aging_measurement_count++]
3677                                 = quot_delta_scaled;
3678
3679                 cpr3_debug(ctrl, "aging results: page_is_age=%u, sel_min=%u, sel_max=%u, quot_min=%u, quot_max=%u, quot_delta=%d, quot_min_scaled=%u, quot_max_scaled=%u, quot_delta_scaled=%d\n",
3680                         is_aging_measurement, sel_min, sel_max, quot_min,
3681                         quot_max, quot_delta, quot_min_scaled, quot_max_scaled,
3682                         quot_delta_scaled);
3683         }
3684
3685         filtered_count
3686                 = aging_measurement_count - CPR3_AGING_MEASUREMENT_FILTER * 2;
3687         if (filtered_count > 0) {
3688                 sort(quot_delta_results, aging_measurement_count,
3689                         sizeof(*quot_delta_results), cmp_int, NULL);
3690
3691                 quot_delta_scaled_sum = 0;
3692                 for (i = 0; i < filtered_count; i++)
3693                         quot_delta_scaled_sum
3694                                 += quot_delta_results[i
3695                                         + CPR3_AGING_MEASUREMENT_FILTER];
3696
3697                 aging_sensor->measured_quot_diff
3698                         = quot_delta_scaled_sum / filtered_count;
3699                 cpr3_info(ctrl, "average quotient delta=%d (count=%d)\n",
3700                         aging_sensor->measured_quot_diff,
3701                         filtered_count);
3702         } else {
3703                 cpr3_err(ctrl, "%d aging measurements completed after %d iterations\n",
3704                         aging_measurement_count,
3705                         CPR3_AGING_MEASUREMENT_ITERATIONS);
3706                 rc = -EBUSY;
3707         }
3708
3709 cleanup:
3710         kfree(quot_delta_results);
3711
3712         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
3713                 rc2 = cpr3_ctrl_clear_cpr4_config(ctrl);
3714                 if (rc2) {
3715                         cpr3_err(ctrl, "failed to clear CPR4 configuration,rc=%d\n",
3716                                 rc2);
3717                         rc = rc2;
3718                 }
3719         }
3720
3721         cpr3_ctrl_loop_disable(ctrl);
3722
3723         cpr3_write(ctrl, CPR3_REG_IRQ_EN, irq_restore);
3724
3725         cpr3_write(ctrl, CPR3_REG_RO_MASK(0), ro_mask_restore);
3726
3727         cpr3_write(ctrl, CPR3_REG_GCNT(0), gcnt0_restore);
3728         cpr3_write(ctrl, CPR3_REG_GCNT(1), gcnt1_restore);
3729
3730         if (ctrl->supports_hw_closed_loop
3731                 && ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
3732                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_MID_CONT, cont_dly_restore);
3733                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_UP_DN_CONT,
3734                                 up_down_dly_restore);
3735         } else {
3736                 cpr3_write(ctrl, CPR3_REG_CPR_TIMER_AUTO_CONT,
3737                                 cont_dly_restore);
3738         }
3739
3740         for (i = 0; i <= ctrl->sensor_count / 32; i++) {
3741                 cpr3_write(ctrl, CPR3_REG_SENSOR_MASK_WRITE_BANK(i), 0);
3742                 cpr3_write(ctrl, CPR3_REG_SENSOR_BYPASS_WRITE_BANK(i), 0);
3743         }
3744
3745         cpr3_masked_write(ctrl, CPR3_REG_CPR_CTL,
3746                 CPR3_CPR_CTL_COUNT_MODE_MASK | CPR3_CPR_CTL_COUNT_REPEAT_MASK,
3747                 (ctrl->count_mode << CPR3_CPR_CTL_COUNT_MODE_SHIFT)
3748                 | (ctrl->count_repeat << CPR3_CPR_CTL_COUNT_REPEAT_SHIFT));
3749
3750         cpr3_write(ctrl, CPR3_REG_SENSOR_OWNER(aging_sensor->sensor_id),
3751                         ctrl->sensor_owner[aging_sensor->sensor_id]);
3752
3753         cpr3_write(ctrl, CPR3_REG_IRQ_CLEAR,
3754                         CPR3_IRQ_UP | CPR3_IRQ_DOWN | CPR3_IRQ_MID);
3755
3756         if (ctrl->supports_hw_closed_loop) {
3757                 if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4 ||
3758                     ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH) {
3759                         cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
3760                                 CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
3761                                 ctrl->use_hw_closed_loop
3762                                 ? CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE
3763                                 : CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_DISABLE);
3764                 } else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
3765                         cpr3_write(ctrl, CPR3_REG_HW_CLOSED_LOOP,
3766                                 ctrl->use_hw_closed_loop
3767                                 ? CPR3_HW_CLOSED_LOOP_ENABLE
3768                                 : CPR3_HW_CLOSED_LOOP_DISABLE);
3769                 }
3770         }
3771
3772         return rc;
3773 }
3774
3775 /**
3776  * cpr3_regulator_readjust_volt_and_quot() - readjust the target quotients as
3777  *              well as the floor, ceiling, and open-loop voltages for the
3778  *              regulator by removing the old adjustment and adding the new one
3779  * @vreg:               Pointer to the CPR3 regulator
3780  * @old_adjust_volt:    Old aging adjustment voltage in microvolts
3781  * @new_adjust_volt:    New aging adjustment voltage in microvolts
3782  *
3783  * Also reset the cached closed loop voltage (last_volt) to equal the open-loop
3784  * voltage for each corner.
3785  *
3786  * Return: None
3787  */
3788 static void cpr3_regulator_readjust_volt_and_quot(struct cpr3_regulator *vreg,
3789                 int old_adjust_volt, int new_adjust_volt)
3790 {
3791         unsigned long long temp;
3792         int i, j, old_volt, new_volt, rounded_volt;
3793
3794         if (!vreg->aging_allowed)
3795                 return;
3796
3797         for (i = 0; i < vreg->corner_count; i++) {
3798                 temp = (unsigned long long)old_adjust_volt
3799                         * (unsigned long long)vreg->corner[i].aging_derate;
3800                 do_div(temp, 1000);
3801                 old_volt = temp;
3802
3803                 temp = (unsigned long long)new_adjust_volt
3804                         * (unsigned long long)vreg->corner[i].aging_derate;
3805                 do_div(temp, 1000);
3806                 new_volt = temp;
3807
3808                 old_volt = min(vreg->aging_max_adjust_volt, old_volt);
3809                 new_volt = min(vreg->aging_max_adjust_volt, new_volt);
3810
3811                 for (j = 0; j < CPR3_RO_COUNT; j++) {
3812                         if (vreg->corner[i].target_quot[j] != 0) {
3813                                 vreg->corner[i].target_quot[j]
3814                                         += cpr3_quot_adjustment(
3815                                                 vreg->corner[i].ro_scale[j],
3816                                                 new_volt)
3817                                            - cpr3_quot_adjustment(
3818                                                 vreg->corner[i].ro_scale[j],
3819                                                 old_volt);
3820                         }
3821                 }
3822
3823                 rounded_volt = CPR3_ROUND(new_volt,
3824                                         vreg->thread->ctrl->step_volt);
3825
3826                 if (!vreg->aging_allow_open_loop_adj)
3827                         rounded_volt = 0;
3828
3829                 vreg->corner[i].ceiling_volt
3830                         = vreg->corner[i].unaged_ceiling_volt + rounded_volt;
3831                 vreg->corner[i].ceiling_volt = min(vreg->corner[i].ceiling_volt,
3832                                               vreg->corner[i].abs_ceiling_volt);
3833                 vreg->corner[i].floor_volt
3834                         = vreg->corner[i].unaged_floor_volt + rounded_volt;
3835                 vreg->corner[i].floor_volt = min(vreg->corner[i].floor_volt,
3836                                                 vreg->corner[i].ceiling_volt);
3837                 vreg->corner[i].open_loop_volt
3838                         = vreg->corner[i].unaged_open_loop_volt + rounded_volt;
3839                 vreg->corner[i].open_loop_volt
3840                         = min(vreg->corner[i].open_loop_volt,
3841                                 vreg->corner[i].ceiling_volt);
3842
3843                 vreg->corner[i].last_volt = vreg->corner[i].open_loop_volt;
3844
3845                 cpr3_debug(vreg, "corner %d: applying %d uV closed-loop and %d uV open-loop voltage margin adjustment\n",
3846                         i, new_volt, rounded_volt);
3847         }
3848 }
3849
3850 /**
3851  * cpr3_regulator_set_aging_ref_adjustment() - adjust target quotients for the
3852  *              regulators managed by this CPR controller to account for aging
3853  * @ctrl:               Pointer to the CPR3 controller
3854  * @ref_adjust_volt:    New aging reference adjustment voltage in microvolts to
3855  *                      apply to all regulators managed by this CPR controller
3856  *
3857  * The existing aging adjustment as defined by ctrl->aging_ref_adjust_volt is
3858  * first removed and then the adjustment is applied.  Lastly, the value of
3859  * ctrl->aging_ref_adjust_volt is updated to ref_adjust_volt.
3860  */
3861 static void cpr3_regulator_set_aging_ref_adjustment(
3862                 struct cpr3_controller *ctrl, int ref_adjust_volt)
3863 {
3864         struct cpr3_regulator *vreg;
3865         int i, j;
3866
3867         for (i = 0; i < ctrl->thread_count; i++) {
3868                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
3869                         vreg = &ctrl->thread[i].vreg[j];
3870                         cpr3_regulator_readjust_volt_and_quot(vreg,
3871                                 ctrl->aging_ref_adjust_volt, ref_adjust_volt);
3872                         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH)
3873                                 cprh_adjust_voltages_for_apm(vreg);
3874                 }
3875         }
3876
3877         ctrl->aging_ref_adjust_volt = ref_adjust_volt;
3878 }
3879
3880 /**
3881  * cpr3_regulator_aging_adjust() - adjust the target quotients for regulators
3882  *              based on the output of CPR aging sensors
3883  * @ctrl:               Pointer to the CPR3 controller
3884  *
3885  * Return: 0 on success, errno on failure
3886  */
3887 static int cpr3_regulator_aging_adjust(struct cpr3_controller *ctrl)
3888 {
3889         struct cpr3_regulator *vreg;
3890         struct cpr3_corner restore_aging_corner;
3891         struct cpr3_corner *corner;
3892         int *restore_current_corner;
3893         bool *restore_vreg_enabled;
3894         int i, j, id, rc, rc2, vreg_count, aging_volt, max_aging_volt = 0;
3895         u32 reg;
3896
3897         if (!ctrl->aging_required || !ctrl->cpr_enabled
3898             || ctrl->aggr_corner.ceiling_volt == 0
3899             || ctrl->aggr_corner.ceiling_volt > ctrl->aging_ref_volt)
3900                 return 0;
3901
3902         for (i = 0, vreg_count = 0; i < ctrl->thread_count; i++) {
3903                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
3904                         vreg = &ctrl->thread[i].vreg[j];
3905                         vreg_count++;
3906
3907                         if (vreg->aging_allowed && vreg->vreg_enabled
3908                             && vreg->current_corner > vreg->aging_corner)
3909                                 return 0;
3910                 }
3911         }
3912
3913         /* Verify that none of the aging sensors are currently masked. */
3914         for (i = 0; i < ctrl->aging_sensor_count; i++) {
3915                 id = ctrl->aging_sensor[i].sensor_id;
3916                 reg = cpr3_read(ctrl, CPR3_REG_SENSOR_MASK_READ(id));
3917                 if (reg & BIT(id % 32))
3918                         return 0;
3919         }
3920
3921         /*
3922          * Verify that the aging possible register (if specified) has an
3923          * acceptable value.
3924          */
3925         if (ctrl->aging_possible_reg) {
3926                 reg = readl_relaxed(ctrl->aging_possible_reg);
3927                 reg &= ctrl->aging_possible_mask;
3928                 if (reg != ctrl->aging_possible_val)
3929                         return 0;
3930         }
3931
3932         restore_current_corner = kcalloc(vreg_count,
3933                                 sizeof(*restore_current_corner), GFP_KERNEL);
3934         restore_vreg_enabled = kcalloc(vreg_count,
3935                                 sizeof(*restore_vreg_enabled), GFP_KERNEL);
3936         if (!restore_current_corner || !restore_vreg_enabled) {
3937                 kfree(restore_current_corner);
3938                 kfree(restore_vreg_enabled);
3939                 return -ENOMEM;
3940         }
3941
3942         /* Force all regulators to the aging corner */
3943         for (i = 0, vreg_count = 0; i < ctrl->thread_count; i++) {
3944                 for (j = 0; j < ctrl->thread[i].vreg_count; j++, vreg_count++) {
3945                         vreg = &ctrl->thread[i].vreg[j];
3946
3947                         restore_current_corner[vreg_count]
3948                                 = vreg->current_corner;
3949                         restore_vreg_enabled[vreg_count]
3950                                 = vreg->vreg_enabled;
3951
3952                         vreg->current_corner = vreg->aging_corner;
3953                         vreg->vreg_enabled = true;
3954                 }
3955         }
3956
3957         /* Force one of the regulators to require the aging reference voltage */
3958         vreg = &ctrl->thread[0].vreg[0];
3959         corner = &vreg->corner[vreg->current_corner];
3960         restore_aging_corner = *corner;
3961         corner->ceiling_volt = ctrl->aging_ref_volt;
3962         corner->floor_volt = ctrl->aging_ref_volt;
3963         corner->open_loop_volt = ctrl->aging_ref_volt;
3964         corner->last_volt = ctrl->aging_ref_volt;
3965
3966         /* Skip last_volt caching */
3967         ctrl->last_corner_was_closed_loop = false;
3968
3969         /* Set the vdd supply voltage to the aging reference voltage */
3970         rc = _cpr3_regulator_update_ctrl_state(ctrl);
3971         if (rc) {
3972                 cpr3_err(ctrl, "unable to force vdd-supply to the aging reference voltage=%d uV, rc=%d\n",
3973                         ctrl->aging_ref_volt, rc);
3974                 goto cleanup;
3975         }
3976
3977         if (ctrl->aging_vdd_mode) {
3978                 rc = regulator_set_mode(ctrl->vdd_regulator,
3979                                         ctrl->aging_vdd_mode);
3980                 if (rc) {
3981                         cpr3_err(ctrl, "unable to configure vdd-supply for mode=%u, rc=%d\n",
3982                                 ctrl->aging_vdd_mode, rc);
3983                         goto cleanup;
3984                 }
3985         }
3986
3987         /* Perform aging measurement on all aging sensors */
3988         for (i = 0; i < ctrl->aging_sensor_count; i++) {
3989                 for (j = 0; j < CPR3_AGING_RETRY_COUNT; j++) {
3990                         rc = cpr3_regulator_measure_aging(ctrl,
3991                                         &ctrl->aging_sensor[i]);
3992                         if (!rc)
3993                                 break;
3994                 }
3995
3996                 if (!rc) {
3997                         aging_volt =
3998                                 cpr3_voltage_adjustment(
3999                                         ctrl->aging_sensor[i].ro_scale,
4000                                         ctrl->aging_sensor[i].measured_quot_diff
4001                                         - ctrl->aging_sensor[i].init_quot_diff);
4002                         max_aging_volt = max(max_aging_volt, aging_volt);
4003                 } else {
4004                         cpr3_err(ctrl, "CPR aging measurement failed after %d tries, rc=%d\n",
4005                                 j, rc);
4006                         ctrl->aging_failed = true;
4007                         ctrl->aging_required = false;
4008                         goto cleanup;
4009                 }
4010         }
4011
4012 cleanup:
4013         vreg = &ctrl->thread[0].vreg[0];
4014         vreg->corner[vreg->current_corner] = restore_aging_corner;
4015
4016         for (i = 0, vreg_count = 0; i < ctrl->thread_count; i++) {
4017                 for (j = 0; j < ctrl->thread[i].vreg_count; j++, vreg_count++) {
4018                         vreg = &ctrl->thread[i].vreg[j];
4019                         vreg->current_corner
4020                                 = restore_current_corner[vreg_count];
4021                         vreg->vreg_enabled = restore_vreg_enabled[vreg_count];
4022                 }
4023         }
4024
4025         kfree(restore_current_corner);
4026         kfree(restore_vreg_enabled);
4027
4028         /* Adjust the CPR target quotients according to the aging measurement */
4029         if (!rc) {
4030                 cpr3_regulator_set_aging_ref_adjustment(ctrl, max_aging_volt);
4031
4032                 cpr3_info(ctrl, "aging measurement successful; aging reference adjustment voltage=%d uV\n",
4033                         ctrl->aging_ref_adjust_volt);
4034                 ctrl->aging_succeeded = true;
4035                 ctrl->aging_required = false;
4036         }
4037
4038         if (ctrl->aging_complete_vdd_mode) {
4039                 rc = regulator_set_mode(ctrl->vdd_regulator,
4040                                         ctrl->aging_complete_vdd_mode);
4041                 if (rc)
4042                         cpr3_err(ctrl, "unable to configure vdd-supply for mode=%u, rc=%d\n",
4043                                 ctrl->aging_complete_vdd_mode, rc);
4044         }
4045
4046         /* Skip last_volt caching */
4047         ctrl->last_corner_was_closed_loop = false;
4048
4049         /*
4050          * Restore vdd-supply to the voltage before the aging measurement and
4051          * restore the CPR3 controller hardware state.
4052          */
4053         rc2 = _cpr3_regulator_update_ctrl_state(ctrl);
4054
4055         /* Stop last_volt caching on for the next request */
4056         ctrl->last_corner_was_closed_loop = false;
4057
4058         return rc ? rc : rc2;
4059 }
4060
4061 /**
4062  * cprh_regulator_aging_adjust() - adjust the target quotients and open-loop
4063  *              voltages for CPRh regulators based on the output of CPR aging
4064  *              sensors
4065  * @ctrl:               Pointer to the CPR3 controller
4066  *
4067  * Return: 0 on success, errno on failure
4068  */
4069 static int cprh_regulator_aging_adjust(struct cpr3_controller *ctrl)
4070 {
4071         int i, j, id, rc, rc2, aging_volt, init_volt;
4072         int max_aging_volt = 0;
4073         u32 reg;
4074
4075         if (!ctrl->aging_required || !ctrl->cpr_enabled)
4076                 return 0;
4077
4078         if (!ctrl->vdd_regulator) {
4079                 cpr3_err(ctrl, "vdd-supply regulator missing\n");
4080                 return -ENODEV;
4081         }
4082
4083         init_volt = regulator_get_voltage(ctrl->vdd_regulator);
4084         if (init_volt < 0) {
4085                 cpr3_err(ctrl, "could not get vdd-supply voltage, rc=%d\n",
4086                         init_volt);
4087                 return init_volt;
4088         }
4089
4090         if (init_volt > ctrl->aging_ref_volt) {
4091                 cpr3_info(ctrl, "unable to perform CPR aging measurement as vdd=%d uV > aging voltage=%d uV\n",
4092                         init_volt, ctrl->aging_ref_volt);
4093                 return 0;
4094         }
4095
4096         /* Verify that none of the aging sensors are currently masked. */
4097         for (i = 0; i < ctrl->aging_sensor_count; i++) {
4098                 id = ctrl->aging_sensor[i].sensor_id;
4099                 reg = cpr3_read(ctrl, CPR3_REG_SENSOR_MASK_READ(id));
4100                 if (reg & BIT(id % 32)) {
4101                         cpr3_info(ctrl, "unable to perform CPR aging measurement as CPR sensor %d is masked\n",
4102                                 id);
4103                         return 0;
4104                 }
4105         }
4106
4107         rc = regulator_set_voltage(ctrl->vdd_regulator, ctrl->aging_ref_volt,
4108                                 INT_MAX);
4109         if (rc) {
4110                 cpr3_err(ctrl, "unable to set vdd-supply to aging voltage=%d uV, rc=%d\n",
4111                         ctrl->aging_ref_volt, rc);
4112                 return rc;
4113         }
4114
4115         if (ctrl->aging_vdd_mode) {
4116                 rc = regulator_set_mode(ctrl->vdd_regulator,
4117                                         ctrl->aging_vdd_mode);
4118                 if (rc) {
4119                         cpr3_err(ctrl, "unable to configure vdd-supply for mode=%u, rc=%d\n",
4120                                 ctrl->aging_vdd_mode, rc);
4121                         goto cleanup;
4122                 }
4123         }
4124
4125         /* Perform aging measurement on all aging sensors */
4126         for (i = 0; i < ctrl->aging_sensor_count; i++) {
4127                 for (j = 0; j < CPR3_AGING_RETRY_COUNT; j++) {
4128                         rc = cpr3_regulator_measure_aging(ctrl,
4129                                         &ctrl->aging_sensor[i]);
4130                         if (!rc)
4131                                 break;
4132                 }
4133
4134                 if (!rc) {
4135                         aging_volt =
4136                                 cpr3_voltage_adjustment(
4137                                         ctrl->aging_sensor[i].ro_scale,
4138                                         ctrl->aging_sensor[i].measured_quot_diff
4139                                         - ctrl->aging_sensor[i].init_quot_diff);
4140                         max_aging_volt = max(max_aging_volt, aging_volt);
4141                 } else {
4142                         cpr3_err(ctrl, "CPR aging measurement failed after %d tries, rc=%d\n",
4143                                 j, rc);
4144                         ctrl->aging_failed = true;
4145                         ctrl->aging_required = false;
4146                         goto cleanup;
4147                 }
4148         }
4149
4150 cleanup:
4151         /* Adjust the CPR target quotients according to the aging measurement */
4152         if (!rc) {
4153                 cpr3_regulator_set_aging_ref_adjustment(ctrl, max_aging_volt);
4154
4155                 cpr3_info(ctrl, "aging measurement successful; aging reference adjustment voltage=%d uV\n",
4156                         ctrl->aging_ref_adjust_volt);
4157                 ctrl->aging_succeeded = true;
4158                 ctrl->aging_required = false;
4159         }
4160
4161         rc2 = regulator_set_voltage(ctrl->vdd_regulator, init_volt, INT_MAX);
4162         if (rc2) {
4163                 cpr3_err(ctrl, "unable to reset vdd-supply to initial voltage=%d uV, rc=%d\n",
4164                         init_volt, rc2);
4165                 return rc2;
4166         }
4167
4168         if (ctrl->aging_complete_vdd_mode) {
4169                 rc2 = regulator_set_mode(ctrl->vdd_regulator,
4170                                         ctrl->aging_complete_vdd_mode);
4171                 if (rc2)  {
4172                         cpr3_err(ctrl, "unable to configure vdd-supply for mode=%u, rc=%d\n",
4173                                 ctrl->aging_complete_vdd_mode, rc2);
4174                         return rc2;
4175                 }
4176         }
4177
4178         return rc;
4179 }
4180
4181 /**
4182  * cpr3_regulator_update_ctrl_state() - update the state of the CPR controller
4183  *              to reflect the corners used by all CPR3 regulators as well as
4184  *              the CPR operating mode and perform aging adjustments if needed
4185  * @ctrl:               Pointer to the CPR3 controller
4186  *
4187  * Note, CPR3 controller lock must be held by the caller.
4188  *
4189  * Return: 0 on success, errno on failure
4190  */
4191 static int cpr3_regulator_update_ctrl_state(struct cpr3_controller *ctrl)
4192 {
4193         int rc;
4194
4195         rc = _cpr3_regulator_update_ctrl_state(ctrl);
4196         if (rc)
4197                 return rc;
4198
4199         return cpr3_regulator_aging_adjust(ctrl);
4200 }
4201
4202 /**
4203  * cpr3_regulator_set_voltage() - set the voltage corner for the CPR3 regulator
4204  *                      associated with the regulator device
4205  * @rdev:               Regulator device pointer for the cpr3-regulator
4206  * @corner:             New voltage corner to set (offset by CPR3_CORNER_OFFSET)
4207  * @corner_max:         Maximum voltage corner allowed (offset by
4208  *                      CPR3_CORNER_OFFSET)
4209  * @selector:           Pointer which is filled with the selector value for the
4210  *                      corner
4211  *
4212  * This function is passed as a callback function into the regulator ops that
4213  * are registered for each cpr3-regulator device.  The VDD voltage will not be
4214  * physically configured until both this function and cpr3_regulator_enable()
4215  * are called.
4216  *
4217  * Return: 0 on success, errno on failure
4218  */
4219 static int cpr3_regulator_set_voltage(struct regulator_dev *rdev,
4220                 int corner, int corner_max, unsigned int *selector)
4221 {
4222         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4223         struct cpr3_controller *ctrl = vreg->thread->ctrl;
4224         int rc = 0;
4225         int last_corner;
4226
4227         corner -= CPR3_CORNER_OFFSET;
4228         corner_max -= CPR3_CORNER_OFFSET;
4229         *selector = corner;
4230
4231         mutex_lock(&ctrl->lock);
4232
4233         if (!vreg->vreg_enabled) {
4234                 vreg->current_corner = corner;
4235                 cpr3_debug(vreg, "stored corner=%d\n", corner);
4236                 goto done;
4237         } else if (vreg->current_corner == corner) {
4238                 goto done;
4239         }
4240
4241         last_corner = vreg->current_corner;
4242         vreg->current_corner = corner;
4243
4244         rc = cpr3_regulator_update_ctrl_state(ctrl);
4245         if (rc) {
4246                 cpr3_err(vreg, "could not update CPR state, rc=%d\n", rc);
4247                 vreg->current_corner = last_corner;
4248         }
4249
4250         cpr3_debug(vreg, "set corner=%d\n", corner);
4251 done:
4252         mutex_unlock(&ctrl->lock);
4253
4254         return rc;
4255 }
4256
4257 /**
4258  * cpr3_regulator_get_voltage() - get the voltage corner for the CPR3 regulator
4259  *                      associated with the regulator device
4260  * @rdev:               Regulator device pointer for the cpr3-regulator
4261  *
4262  * This function is passed as a callback function into the regulator ops that
4263  * are registered for each cpr3-regulator device.
4264  *
4265  * Return: voltage corner value offset by CPR3_CORNER_OFFSET
4266  */
4267 static int cpr3_regulator_get_voltage(struct regulator_dev *rdev)
4268 {
4269         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4270
4271         if (vreg->current_corner == CPR3_REGULATOR_CORNER_INVALID)
4272                 return CPR3_CORNER_OFFSET;
4273         else
4274                 return vreg->current_corner + CPR3_CORNER_OFFSET;
4275 }
4276
4277 /**
4278  * cpr3_regulator_list_voltage() - return the voltage corner mapped to the
4279  *                      specified selector
4280  * @rdev:               Regulator device pointer for the cpr3-regulator
4281  * @selector:           Regulator selector
4282  *
4283  * This function is passed as a callback function into the regulator ops that
4284  * are registered for each cpr3-regulator device.
4285  *
4286  * Return: voltage corner value offset by CPR3_CORNER_OFFSET
4287  */
4288 static int cpr3_regulator_list_voltage(struct regulator_dev *rdev,
4289                 unsigned int selector)
4290 {
4291         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4292
4293         if (selector < vreg->corner_count)
4294                 return selector + CPR3_CORNER_OFFSET;
4295         else
4296                 return 0;
4297 }
4298
4299 /**
4300  * cpr3_regulator_list_corner_voltage() - return the ceiling voltage mapped to
4301  *                      the specified voltage corner
4302  * @rdev:               Regulator device pointer for the cpr3-regulator
4303  * @corner:             Voltage corner
4304  *
4305  * This function is passed as a callback function into the regulator ops that
4306  * are registered for each cpr3-regulator device.
4307  *
4308  * Return: voltage value in microvolts or -EINVAL if the corner is out of range
4309  */
4310 static int cpr3_regulator_list_corner_voltage(struct regulator_dev *rdev,
4311                 int corner)
4312 {
4313         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4314
4315         corner -= CPR3_CORNER_OFFSET;
4316
4317         if (corner >= 0 && corner < vreg->corner_count)
4318                 return vreg->corner[corner].ceiling_volt;
4319         else
4320                 return -EINVAL;
4321 }
4322
4323 /**
4324  * cpr3_regulator_is_enabled() - return the enable state of the CPR3 regulator
4325  * @rdev:               Regulator device pointer for the cpr3-regulator
4326  *
4327  * This function is passed as a callback function into the regulator ops that
4328  * are registered for each cpr3-regulator device.
4329  *
4330  * Return: true if regulator is enabled, false if regulator is disabled
4331  */
4332 static int cpr3_regulator_is_enabled(struct regulator_dev *rdev)
4333 {
4334         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4335
4336         return vreg->vreg_enabled;
4337 }
4338
4339 /**
4340  * cpr3_regulator_enable() - enable the CPR3 regulator
4341  * @rdev:               Regulator device pointer for the cpr3-regulator
4342  *
4343  * This function is passed as a callback function into the regulator ops that
4344  * are registered for each cpr3-regulator device.
4345  *
4346  * Return: 0 on success, errno on failure
4347  */
4348 static int cpr3_regulator_enable(struct regulator_dev *rdev)
4349 {
4350         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4351         struct cpr3_controller *ctrl = vreg->thread->ctrl;
4352         int rc = 0;
4353
4354         if (vreg->vreg_enabled == true)
4355                 return 0;
4356
4357         mutex_lock(&ctrl->lock);
4358
4359         if (ctrl->system_regulator) {
4360                 rc = regulator_enable(ctrl->system_regulator);
4361                 if (rc) {
4362                         cpr3_err(ctrl, "regulator_enable(system) failed, rc=%d\n",
4363                                 rc);
4364                         goto done;
4365                 }
4366         }
4367
4368         rc = regulator_enable(ctrl->vdd_regulator);
4369         if (rc) {
4370                 cpr3_err(vreg, "regulator_enable(vdd) failed, rc=%d\n", rc);
4371                 goto done;
4372         }
4373
4374         if (vreg->ldo_regulator) {
4375                 rc = regulator_enable(vreg->ldo_regulator);
4376                 if (rc) {
4377                         cpr3_err(vreg, "regulator_enable(ldo) failed, rc=%d\n",
4378                                  rc);
4379                         goto done;
4380                 }
4381         }
4382
4383         vreg->vreg_enabled = true;
4384         rc = cpr3_regulator_update_ctrl_state(ctrl);
4385         if (rc) {
4386                 cpr3_err(vreg, "could not update CPR state, rc=%d\n", rc);
4387                 regulator_disable(ctrl->vdd_regulator);
4388                 vreg->vreg_enabled = false;
4389                 goto done;
4390         }
4391
4392         cpr3_debug(vreg, "Enabled\n");
4393 done:
4394         mutex_unlock(&ctrl->lock);
4395
4396         return rc;
4397 }
4398
4399 /**
4400  * cpr3_regulator_disable() - disable the CPR3 regulator
4401  * @rdev:               Regulator device pointer for the cpr3-regulator
4402  *
4403  * This function is passed as a callback function into the regulator ops that
4404  * are registered for each cpr3-regulator device.
4405  *
4406  * Return: 0 on success, errno on failure
4407  */
4408 static int cpr3_regulator_disable(struct regulator_dev *rdev)
4409 {
4410         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4411         struct cpr3_controller *ctrl = vreg->thread->ctrl;
4412         int rc, rc2;
4413
4414         if (vreg->vreg_enabled == false)
4415                 return 0;
4416
4417         mutex_lock(&ctrl->lock);
4418
4419         if (vreg->ldo_regulator && vreg->ldo_regulator_bypass == LDO_MODE) {
4420                 rc = regulator_get_voltage(ctrl->vdd_regulator);
4421                 if (rc < 0) {
4422                         cpr3_err(vreg, "regulator_get_voltage(vdd) failed, rc=%d\n",
4423                                  rc);
4424                         goto done;
4425                 }
4426
4427                 /* Switch back to BHS for safe operation */
4428                 rc = cpr3_regulator_set_bhs_mode(vreg, rc,
4429                                        ctrl->aggr_corner.ceiling_volt);
4430                 if (rc) {
4431                         cpr3_err(vreg, "unable to switch to BHS mode, rc=%d\n",
4432                                  rc);
4433                         goto done;
4434                 }
4435         }
4436
4437         if (vreg->ldo_regulator) {
4438                 rc = regulator_disable(vreg->ldo_regulator);
4439                 if (rc) {
4440                         cpr3_err(vreg, "regulator_disable(ldo) failed, rc=%d\n",
4441                                  rc);
4442                         goto done;
4443                 }
4444         }
4445         rc = regulator_disable(ctrl->vdd_regulator);
4446         if (rc) {
4447                 cpr3_err(vreg, "regulator_disable(vdd) failed, rc=%d\n", rc);
4448                 goto done;
4449         }
4450
4451         vreg->vreg_enabled = false;
4452         rc = cpr3_regulator_update_ctrl_state(ctrl);
4453         if (rc) {
4454                 cpr3_err(vreg, "could not update CPR state, rc=%d\n", rc);
4455                 rc2 = regulator_enable(ctrl->vdd_regulator);
4456                 vreg->vreg_enabled = true;
4457                 goto done;
4458         }
4459
4460         if (ctrl->system_regulator) {
4461                 rc = regulator_disable(ctrl->system_regulator);
4462                 if (rc) {
4463                         cpr3_err(ctrl, "regulator_disable(system) failed, rc=%d\n",
4464                                 rc);
4465                         goto done;
4466                 }
4467                 if (ctrl->support_ldo300_vreg) {
4468                         rc = regulator_set_voltage(ctrl->system_regulator, 0,
4469                                                 INT_MAX);
4470                         if (rc)
4471                                 cpr3_err(ctrl, "failed to set voltage on system rc=%d\n",
4472                                         rc);
4473                         goto done;
4474                 }
4475         }
4476
4477         cpr3_debug(vreg, "Disabled\n");
4478 done:
4479         mutex_unlock(&ctrl->lock);
4480
4481         return rc;
4482 }
4483
4484 static struct regulator_ops cpr3_regulator_ops = {
4485         .enable                 = cpr3_regulator_enable,
4486         .disable                = cpr3_regulator_disable,
4487         .is_enabled             = cpr3_regulator_is_enabled,
4488         .set_voltage            = cpr3_regulator_set_voltage,
4489         .get_voltage            = cpr3_regulator_get_voltage,
4490         .list_voltage           = cpr3_regulator_list_voltage,
4491         .list_corner_voltage    = cpr3_regulator_list_corner_voltage,
4492 };
4493
4494 /**
4495  * cprh_regulator_get_voltage() - get the voltage corner for the CPR3 regulator
4496  *                      associated with the regulator device
4497  * @rdev:               Regulator device pointer for the cpr3-regulator
4498  *
4499  * This function is passed as a callback function into the regulator ops that
4500  * are registered for each cpr3-regulator device of a CPRh controller. The
4501  * corner is read directly from CPRh hardware register.
4502  *
4503  * Return: voltage corner value offset by CPR3_CORNER_OFFSET
4504  */
4505 static int cprh_regulator_get_voltage(struct regulator_dev *rdev)
4506 {
4507         struct cpr3_regulator *vreg = rdev_get_drvdata(rdev);
4508         struct cpr3_controller *ctrl = vreg->thread->ctrl;
4509         bool cpr_enabled;
4510         u32 reg, rc;
4511
4512         mutex_lock(&ctrl->lock);
4513
4514         cpr_enabled = ctrl->cpr_enabled;
4515         if (!cpr_enabled) {
4516                 rc = cpr3_clock_enable(ctrl);
4517                 if (rc) {
4518                         cpr3_err(ctrl, "clock enable failed, rc=%d\n", rc);
4519                         mutex_unlock(&ctrl->lock);
4520                         return CPR3_REGULATOR_CORNER_INVALID;
4521                 }
4522                 ctrl->cpr_enabled = true;
4523         }
4524
4525         reg = cpr3_read(vreg->thread->ctrl, CPRH_REG_STATUS);
4526
4527         if (!cpr_enabled) {
4528                 cpr3_clock_disable(ctrl);
4529                 ctrl->cpr_enabled = false;
4530         }
4531
4532         mutex_unlock(&ctrl->lock);
4533
4534         return (reg & CPRH_STATUS_CORNER)
4535                 + CPR3_CORNER_OFFSET;
4536 }
4537
4538 static struct regulator_ops cprh_regulator_ops = {
4539         .get_voltage            = cprh_regulator_get_voltage,
4540         .list_corner_voltage    = cpr3_regulator_list_corner_voltage,
4541 };
4542
4543 /**
4544  * cpr3_print_result() - print CPR measurement results to the kernel log for
4545  *              debugging purposes
4546  * @thread:             Pointer to the CPR3 thread
4547  *
4548  * Return: None
4549  */
4550 static void cpr3_print_result(struct cpr3_thread *thread)
4551 {
4552         struct cpr3_controller *ctrl = thread->ctrl;
4553         u32 result[3], busy, step_dn, step_up, error_steps, error, negative;
4554         u32 quot_min, quot_max, ro_min, ro_max, step_quot_min, step_quot_max;
4555         u32 sensor_min, sensor_max;
4556         char *sign;
4557
4558         result[0] = cpr3_read(ctrl, CPR3_REG_RESULT0(thread->thread_id));
4559         result[1] = cpr3_read(ctrl, CPR3_REG_RESULT1(thread->thread_id));
4560         result[2] = cpr3_read(ctrl, CPR3_REG_RESULT2(thread->thread_id));
4561
4562         busy = !!(result[0] & CPR3_RESULT0_BUSY_MASK);
4563         step_dn = !!(result[0] & CPR3_RESULT0_STEP_DN_MASK);
4564         step_up = !!(result[0] & CPR3_RESULT0_STEP_UP_MASK);
4565         error_steps = (result[0] & CPR3_RESULT0_ERROR_STEPS_MASK)
4566                         >> CPR3_RESULT0_ERROR_STEPS_SHIFT;
4567         error = (result[0] & CPR3_RESULT0_ERROR_MASK)
4568                         >> CPR3_RESULT0_ERROR_SHIFT;
4569         negative = !!(result[0] & CPR3_RESULT0_NEGATIVE_MASK);
4570
4571         quot_min = (result[1] & CPR3_RESULT1_QUOT_MIN_MASK)
4572                         >> CPR3_RESULT1_QUOT_MIN_SHIFT;
4573         quot_max = (result[1] & CPR3_RESULT1_QUOT_MAX_MASK)
4574                         >> CPR3_RESULT1_QUOT_MAX_SHIFT;
4575         ro_min = (result[1] & CPR3_RESULT1_RO_MIN_MASK)
4576                         >> CPR3_RESULT1_RO_MIN_SHIFT;
4577         ro_max = (result[1] & CPR3_RESULT1_RO_MAX_MASK)
4578                         >> CPR3_RESULT1_RO_MAX_SHIFT;
4579
4580         step_quot_min = (result[2] & CPR3_RESULT2_STEP_QUOT_MIN_MASK)
4581                         >> CPR3_RESULT2_STEP_QUOT_MIN_SHIFT;
4582         step_quot_max = (result[2] & CPR3_RESULT2_STEP_QUOT_MAX_MASK)
4583                         >> CPR3_RESULT2_STEP_QUOT_MAX_SHIFT;
4584         sensor_min = (result[2] & CPR3_RESULT2_SENSOR_MIN_MASK)
4585                         >> CPR3_RESULT2_SENSOR_MIN_SHIFT;
4586         sensor_max = (result[2] & CPR3_RESULT2_SENSOR_MAX_MASK)
4587                         >> CPR3_RESULT2_SENSOR_MAX_SHIFT;
4588
4589         sign = negative ? "-" : "";
4590         cpr3_debug(ctrl, "thread %u: busy=%u, step_dn=%u, step_up=%u, error_steps=%s%u, error=%s%u\n",
4591                 thread->thread_id, busy, step_dn, step_up, sign, error_steps,
4592                 sign, error);
4593         cpr3_debug(ctrl, "thread %u: quot_min=%u, quot_max=%u, ro_min=%u, ro_max=%u\n",
4594                 thread->thread_id, quot_min, quot_max, ro_min, ro_max);
4595         cpr3_debug(ctrl, "thread %u: step_quot_min=%u, step_quot_max=%u, sensor_min=%u, sensor_max=%u\n",
4596                 thread->thread_id, step_quot_min, step_quot_max, sensor_min,
4597                 sensor_max);
4598 }
4599
4600 /**
4601  * cpr3_thread_busy() - returns if the specified CPR3 thread is busy taking
4602  *              a measurement
4603  * @thread:             Pointer to the CPR3 thread
4604  *
4605  * Return: CPR3 busy status
4606  */
4607 static bool cpr3_thread_busy(struct cpr3_thread *thread)
4608 {
4609         u32 result;
4610
4611         result = cpr3_read(thread->ctrl, CPR3_REG_RESULT0(thread->thread_id));
4612
4613         return !!(result & CPR3_RESULT0_BUSY_MASK);
4614 }
4615
4616 /**
4617  * cpr3_irq_handler() - CPR interrupt handler callback function used for
4618  *              software closed-loop operation
4619  * @irq:                CPR interrupt number
4620  * @data:               Private data corresponding to the CPR3 controller
4621  *                      pointer
4622  *
4623  * This function increases or decreases the vdd supply voltage based upon the
4624  * CPR controller recommendation.
4625  *
4626  * Return: IRQ_HANDLED
4627  */
4628 static irqreturn_t cpr3_irq_handler(int irq, void *data)
4629 {
4630         struct cpr3_controller *ctrl = data;
4631         struct cpr3_corner *aggr = &ctrl->aggr_corner;
4632         u32 cont = CPR3_CONT_CMD_NACK;
4633         u32 reg_last_measurement = 0;
4634         struct cpr3_regulator *vreg;
4635         struct cpr3_corner *corner;
4636         unsigned long flags;
4637         int i, j, new_volt, last_volt, dynamic_floor_volt, rc;
4638         u32 irq_en, status, cpr_status, ctl;
4639         bool up, down;
4640
4641         mutex_lock(&ctrl->lock);
4642
4643         if (!ctrl->cpr_enabled) {
4644                 cpr3_debug(ctrl, "CPR interrupt received but CPR is disabled\n");
4645                 mutex_unlock(&ctrl->lock);
4646                 return IRQ_HANDLED;
4647         } else if (ctrl->use_hw_closed_loop) {
4648                 cpr3_debug(ctrl, "CPR interrupt received but CPR is using HW closed-loop\n");
4649                 goto done;
4650         }
4651
4652         /*
4653          * CPR IRQ status checking and CPR controller disabling must happen
4654          * atomically and without invening delay in order to avoid an interrupt
4655          * storm caused by the handler racing with the CPR controller.
4656          */
4657         local_irq_save(flags);
4658         preempt_disable();
4659
4660         status = cpr3_read(ctrl, CPR3_REG_IRQ_STATUS);
4661         up = status & CPR3_IRQ_UP;
4662         down = status & CPR3_IRQ_DOWN;
4663
4664         if (!up && !down) {
4665                 /*
4666                  * Toggle the CPR controller off and then back on since the
4667                  * hardware and software states are out of sync.  This condition
4668                  * occurs after an aging measurement completes as the CPR IRQ
4669                  * physically triggers during the aging measurement but the
4670                  * handler is stuck waiting on the mutex lock.
4671                  */
4672                 cpr3_ctrl_loop_disable(ctrl);
4673
4674                 local_irq_restore(flags);
4675                 preempt_enable();
4676
4677                 /* Wait for the loop disable write to complete */
4678                 mb();
4679
4680                 /* Wait for BUSY=1 and LOOP_EN=0 in CPR controller registers. */
4681                 for (i = 0; i < CPR3_REGISTER_WRITE_DELAY_US / 10; i++) {
4682                         cpr_status = cpr3_read(ctrl, CPR3_REG_CPR_STATUS);
4683                         ctl = cpr3_read(ctrl, CPR3_REG_CPR_CTL);
4684                         if (cpr_status & CPR3_CPR_STATUS_BUSY_MASK
4685                             && (ctl & CPR3_CPR_CTL_LOOP_EN_MASK)
4686                                         == CPR3_CPR_CTL_LOOP_DISABLE)
4687                                 break;
4688                         udelay(10);
4689                 }
4690                 if (i == CPR3_REGISTER_WRITE_DELAY_US / 10)
4691                         cpr3_debug(ctrl, "CPR controller not disabled after %d us\n",
4692                                 CPR3_REGISTER_WRITE_DELAY_US);
4693
4694                 /* Clear interrupt status */
4695                 cpr3_write(ctrl, CPR3_REG_IRQ_CLEAR,
4696                         CPR3_IRQ_UP | CPR3_IRQ_DOWN);
4697
4698                 /* Wait for the interrupt clearing write to complete */
4699                 mb();
4700
4701                 /* Wait for IRQ_STATUS register to be cleared. */
4702                 for (i = 0; i < CPR3_REGISTER_WRITE_DELAY_US / 10; i++) {
4703                         status = cpr3_read(ctrl, CPR3_REG_IRQ_STATUS);
4704                         if (!(status & (CPR3_IRQ_UP | CPR3_IRQ_DOWN)))
4705                                 break;
4706                         udelay(10);
4707                 }
4708                 if (i == CPR3_REGISTER_WRITE_DELAY_US / 10)
4709                         cpr3_debug(ctrl, "CPR interrupts not cleared after %d us\n",
4710                                 CPR3_REGISTER_WRITE_DELAY_US);
4711
4712                 cpr3_ctrl_loop_enable(ctrl);
4713
4714                 cpr3_debug(ctrl, "CPR interrupt received but no up or down status bit is set\n");
4715
4716                 mutex_unlock(&ctrl->lock);
4717                 return IRQ_HANDLED;
4718         } else if (up && down) {
4719                 cpr3_debug(ctrl, "both up and down status bits set\n");
4720                 /* The up flag takes precedence over the down flag. */
4721                 down = false;
4722         }
4723
4724         if (ctrl->supports_hw_closed_loop)
4725                 reg_last_measurement
4726                         = cpr3_read(ctrl, CPR3_REG_LAST_MEASUREMENT);
4727         dynamic_floor_volt = cpr3_regulator_get_dynamic_floor_volt(ctrl,
4728                                                         reg_last_measurement);
4729
4730         local_irq_restore(flags);
4731         preempt_enable();
4732
4733         irq_en = aggr->irq_en;
4734         last_volt = aggr->last_volt;
4735
4736         for (i = 0; i < ctrl->thread_count; i++) {
4737                 if (cpr3_thread_busy(&ctrl->thread[i])) {
4738                         cpr3_debug(ctrl, "CPR thread %u busy when it should be waiting for SW cont\n",
4739                                 ctrl->thread[i].thread_id);
4740                         goto done;
4741                 }
4742         }
4743
4744         new_volt = up ? last_volt + ctrl->step_volt
4745                       : last_volt - ctrl->step_volt;
4746
4747         /* Re-enable UP/DOWN interrupt when its opposite is received. */
4748         irq_en |= up ? CPR3_IRQ_DOWN : CPR3_IRQ_UP;
4749
4750         if (new_volt > aggr->ceiling_volt) {
4751                 new_volt = aggr->ceiling_volt;
4752                 irq_en &= ~CPR3_IRQ_UP;
4753                 cpr3_debug(ctrl, "limiting to ceiling=%d uV\n",
4754                         aggr->ceiling_volt);
4755         } else if (new_volt < aggr->floor_volt) {
4756                 new_volt = aggr->floor_volt;
4757                 irq_en &= ~CPR3_IRQ_DOWN;
4758                 cpr3_debug(ctrl, "limiting to floor=%d uV\n", aggr->floor_volt);
4759         }
4760
4761         if (down && new_volt < dynamic_floor_volt) {
4762                 /*
4763                  * The vdd-supply voltage should not be decreased below the
4764                  * dynamic floor voltage.  However, it is not necessary (and
4765                  * counter productive) to force the voltage up to this level
4766                  * if it happened to be below it since the closed-loop voltage
4767                  * must have gotten there in a safe manner while the power
4768                  * domains for the CPR3 regulator imposing the dynamic floor
4769                  * were not bypassed.
4770                  */
4771                 new_volt = last_volt;
4772                 irq_en &= ~CPR3_IRQ_DOWN;
4773                 cpr3_debug(ctrl, "limiting to dynamic floor=%d uV\n",
4774                         dynamic_floor_volt);
4775         }
4776
4777         for (i = 0; i < ctrl->thread_count; i++)
4778                 cpr3_print_result(&ctrl->thread[i]);
4779
4780         cpr3_debug(ctrl, "%s: new_volt=%d uV, last_volt=%d uV\n",
4781                 up ? "UP" : "DN", new_volt, last_volt);
4782
4783         if (ctrl->proc_clock_throttle && last_volt == aggr->ceiling_volt
4784             && new_volt < last_volt)
4785                 cpr3_write(ctrl, CPR3_REG_PD_THROTTLE,
4786                                 ctrl->proc_clock_throttle);
4787
4788         if (new_volt != last_volt) {
4789                 rc = cpr3_regulator_scale_vdd_voltage(ctrl, new_volt,
4790                                                       last_volt,
4791                                                       aggr);
4792                 if (rc) {
4793                         cpr3_err(ctrl, "scale_vdd() failed to set vdd=%d uV, rc=%d\n",
4794                                  new_volt, rc);
4795                         goto done;
4796                 }
4797                 cont = CPR3_CONT_CMD_ACK;
4798
4799                 /*
4800                  * Update the closed-loop voltage for all regulators managed
4801                  * by this CPR controller.
4802                  */
4803                 for (i = 0; i < ctrl->thread_count; i++) {
4804                         for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
4805                                 vreg = &ctrl->thread[i].vreg[j];
4806                                 cpr3_update_vreg_closed_loop_volt(vreg,
4807                                         new_volt, reg_last_measurement);
4808                         }
4809                 }
4810         }
4811
4812         if (ctrl->proc_clock_throttle && new_volt == aggr->ceiling_volt)
4813                 cpr3_write(ctrl, CPR3_REG_PD_THROTTLE,
4814                                 CPR3_PD_THROTTLE_DISABLE);
4815
4816         corner = &ctrl->thread[0].vreg[0].corner[
4817                         ctrl->thread[0].vreg[0].current_corner];
4818
4819         if (irq_en != aggr->irq_en) {
4820                 aggr->irq_en = irq_en;
4821                 cpr3_write(ctrl, CPR3_REG_IRQ_EN, irq_en);
4822         }
4823
4824         aggr->last_volt = new_volt;
4825
4826 done:
4827         /* Clear interrupt status */
4828         cpr3_write(ctrl, CPR3_REG_IRQ_CLEAR, CPR3_IRQ_UP | CPR3_IRQ_DOWN);
4829
4830         /* ACK or NACK the CPR controller */
4831         cpr3_write(ctrl, CPR3_REG_CONT_CMD, cont);
4832
4833         mutex_unlock(&ctrl->lock);
4834         return IRQ_HANDLED;
4835 }
4836
4837 /**
4838  * cpr3_ceiling_irq_handler() - CPR ceiling reached interrupt handler callback
4839  *              function used for hardware closed-loop operation
4840  * @irq:                CPR ceiling interrupt number
4841  * @data:               Private data corresponding to the CPR3 controller
4842  *                      pointer
4843  *
4844  * This function disables processor clock throttling and closed-loop operation
4845  * when the ceiling voltage is reached.
4846  *
4847  * Return: IRQ_HANDLED
4848  */
4849 static irqreturn_t cpr3_ceiling_irq_handler(int irq, void *data)
4850 {
4851         struct cpr3_controller *ctrl = data;
4852         int rc, volt;
4853
4854         mutex_lock(&ctrl->lock);
4855
4856         if (!ctrl->cpr_enabled) {
4857                 cpr3_debug(ctrl, "CPR ceiling interrupt received but CPR is disabled\n");
4858                 goto done;
4859         } else if (!ctrl->use_hw_closed_loop) {
4860                 cpr3_debug(ctrl, "CPR ceiling interrupt received but CPR is using SW closed-loop\n");
4861                 goto done;
4862         }
4863
4864         volt = regulator_get_voltage(ctrl->vdd_regulator);
4865         if (volt < 0) {
4866                 cpr3_err(ctrl, "could not get vdd voltage, rc=%d\n", volt);
4867                 goto done;
4868         } else if (volt != ctrl->aggr_corner.ceiling_volt) {
4869                 cpr3_debug(ctrl, "CPR ceiling interrupt received but vdd voltage: %d uV != ceiling voltage: %d uV\n",
4870                         volt, ctrl->aggr_corner.ceiling_volt);
4871                 goto done;
4872         }
4873
4874         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
4875                 /*
4876                  * Since the ceiling voltage has been reached, disable processor
4877                  * clock throttling as well as CPR closed-loop operation.
4878                  */
4879                 cpr3_write(ctrl, CPR3_REG_PD_THROTTLE,
4880                                 CPR3_PD_THROTTLE_DISABLE);
4881                 cpr3_ctrl_loop_disable(ctrl);
4882                 cpr3_debug(ctrl, "CPR closed-loop and throttling disabled\n");
4883         }
4884
4885 done:
4886         rc = msm_spm_avs_clear_irq(0, MSM_SPM_AVS_IRQ_MAX);
4887         if (rc)
4888                 cpr3_err(ctrl, "could not clear max IRQ, rc=%d\n", rc);
4889
4890         mutex_unlock(&ctrl->lock);
4891         return IRQ_HANDLED;
4892 }
4893
4894 /**
4895  * cpr3_regulator_vreg_register() - register a regulator device for a CPR3
4896  *              regulator
4897  * @vreg:               Pointer to the CPR3 regulator
4898  *
4899  * This function initializes all regulator framework related structures and then
4900  * calls regulator_register() for the CPR3 regulator.
4901  *
4902  * Return: 0 on success, errno on failure
4903  */
4904 static int cpr3_regulator_vreg_register(struct cpr3_regulator *vreg)
4905 {
4906         struct regulator_config config = {};
4907         struct regulator_desc *rdesc;
4908         struct regulator_init_data *init_data;
4909         int rc;
4910
4911         init_data = of_get_regulator_init_data(vreg->thread->ctrl->dev,
4912                                                 vreg->of_node, &vreg->rdesc);
4913         if (!init_data) {
4914                 cpr3_err(vreg, "regulator init data is missing\n");
4915                 return -EINVAL;
4916         }
4917
4918         init_data->constraints.input_uV = init_data->constraints.max_uV;
4919         rdesc                   = &vreg->rdesc;
4920         if (vreg->thread->ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH) {
4921                 /* CPRh regulators are treated as always-on regulators */
4922                 rdesc->ops = &cprh_regulator_ops;
4923         } else {
4924                 init_data->constraints.valid_ops_mask
4925                         |= REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS;
4926                 rdesc->ops = &cpr3_regulator_ops;
4927         }
4928
4929         rdesc->n_voltages       = vreg->corner_count;
4930         rdesc->name             = init_data->constraints.name;
4931         rdesc->owner            = THIS_MODULE;
4932         rdesc->type             = REGULATOR_VOLTAGE;
4933
4934         config.dev              = vreg->thread->ctrl->dev;
4935         config.driver_data      = vreg;
4936         config.init_data        = init_data;
4937         config.of_node          = vreg->of_node;
4938
4939         vreg->rdev = regulator_register(rdesc, &config);
4940         if (IS_ERR(vreg->rdev)) {
4941                 rc = PTR_ERR(vreg->rdev);
4942                 cpr3_err(vreg, "regulator_register failed, rc=%d\n", rc);
4943                 return rc;
4944         }
4945
4946         return 0;
4947 }
4948
4949 static int debugfs_int_set(void *data, u64 val)
4950 {
4951         *(int *)data = val;
4952         return 0;
4953 }
4954
4955 static int debugfs_int_get(void *data, u64 *val)
4956 {
4957         *val = *(int *)data;
4958         return 0;
4959 }
4960 DEFINE_SIMPLE_ATTRIBUTE(fops_int, debugfs_int_get, debugfs_int_set, "%lld\n");
4961 DEFINE_SIMPLE_ATTRIBUTE(fops_int_ro, debugfs_int_get, NULL, "%lld\n");
4962 DEFINE_SIMPLE_ATTRIBUTE(fops_int_wo, NULL, debugfs_int_set, "%lld\n");
4963
4964 /**
4965  * debugfs_create_int - create a debugfs file that is used to read and write a
4966  *              signed int value
4967  * @name:               Pointer to a string containing the name of the file to
4968  *                      create
4969  * @mode:               The permissions that the file should have
4970  * @parent:             Pointer to the parent dentry for this file.  This should
4971  *                      be a directory dentry if set.  If this parameter is
4972  *                      %NULL, then the file will be created in the root of the
4973  *                      debugfs filesystem.
4974  * @value:              Pointer to the variable that the file should read to and
4975  *                      write from
4976  *
4977  * This function creates a file in debugfs with the given name that
4978  * contains the value of the variable @value.  If the @mode variable is so
4979  * set, it can be read from, and written to.
4980  *
4981  * This function will return a pointer to a dentry if it succeeds.  This
4982  * pointer must be passed to the debugfs_remove() function when the file is
4983  * to be removed.  If an error occurs, %NULL will be returned.
4984  */
4985 static struct dentry *debugfs_create_int(const char *name, umode_t mode,
4986                                 struct dentry *parent, int *value)
4987 {
4988         /* if there are no write bits set, make read only */
4989         if (!(mode & 0222))
4990                 return debugfs_create_file(name, mode, parent, value,
4991                                            &fops_int_ro);
4992         /* if there are no read bits set, make write only */
4993         if (!(mode & 0444))
4994                 return debugfs_create_file(name, mode, parent, value,
4995                                            &fops_int_wo);
4996
4997         return debugfs_create_file(name, mode, parent, value, &fops_int);
4998 }
4999
5000 static int debugfs_bool_get(void *data, u64 *val)
5001 {
5002         *val = *(bool *)data;
5003         return 0;
5004 }
5005 DEFINE_SIMPLE_ATTRIBUTE(fops_bool_ro, debugfs_bool_get, NULL, "%lld\n");
5006
5007 /**
5008  * cpr3_debug_ldo_mode_allowed_set() - debugfs callback used to change the
5009  *              value of the CPR3 regulator ldo_mode_allowed flag
5010  * @data:               Pointer to private data which is equal to the CPR3
5011  *                      regulator pointer
5012  * @val:                New value for ldo_mode_allowed
5013  *
5014  * Return: 0 on success, errno on failure
5015  */
5016 static int cpr3_debug_ldo_mode_allowed_set(void *data, u64 val)
5017 {
5018         struct cpr3_regulator *vreg = data;
5019         struct cpr3_controller *ctrl = vreg->thread->ctrl;
5020         bool allow = !!val;
5021         int rc, vdd_volt;
5022
5023         mutex_lock(&ctrl->lock);
5024
5025         if (vreg->ldo_mode_allowed == allow)
5026                 goto done;
5027
5028         vreg->ldo_mode_allowed = allow;
5029
5030         if (!allow && vreg->ldo_regulator_bypass == LDO_MODE) {
5031                 vdd_volt = regulator_get_voltage(ctrl->vdd_regulator);
5032                 if (vdd_volt < 0) {
5033                         cpr3_err(vreg, "regulator_get_voltage(vdd) failed, rc=%d\n",
5034                                  vdd_volt);
5035                         goto done;
5036                 }
5037
5038                 /* Switch back to BHS */
5039                 rc = cpr3_regulator_set_bhs_mode(vreg, vdd_volt,
5040                                        ctrl->aggr_corner.ceiling_volt);
5041                 if (rc) {
5042                         cpr3_err(vreg, "unable to switch to BHS mode, rc=%d\n",
5043                                  rc);
5044                         goto done;
5045                 }
5046         } else {
5047                 rc = cpr3_regulator_update_ctrl_state(ctrl);
5048                 if (rc) {
5049                         cpr3_err(vreg, "could not change LDO mode=%s, rc=%d\n",
5050                                 allow ? "allowed" : "disallowed", rc);
5051                         goto done;
5052                 }
5053         }
5054
5055         cpr3_debug(vreg, "LDO mode=%s\n", allow ? "allowed" : "disallowed");
5056
5057 done:
5058         mutex_unlock(&ctrl->lock);
5059         return 0;
5060 }
5061
5062 /**
5063  * cpr3_debug_ldo_mode_allowed_get() - debugfs callback used to retrieve the
5064  *              value of the CPR3 regulator ldo_mode_allowed flag
5065  * @data:               Pointer to private data which is equal to the CPR3
5066  *                      regulator pointer
5067  * @val:                Output parameter written with a value of the
5068  *                      ldo_mode_allowed flag
5069  *
5070  * Return: 0 on success, errno on failure
5071  */
5072 static int cpr3_debug_ldo_mode_allowed_get(void *data, u64 *val)
5073 {
5074         struct cpr3_regulator *vreg = data;
5075
5076         *val = vreg->ldo_mode_allowed;
5077
5078         return 0;
5079 }
5080 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_ldo_mode_allowed_fops,
5081                         cpr3_debug_ldo_mode_allowed_get,
5082                         cpr3_debug_ldo_mode_allowed_set,
5083                         "%llu\n");
5084
5085 /**
5086  * cpr3_debug_ldo_mode_get() - debugfs callback used to retrieve the state of
5087  *              the CPR3 regulator's LDO
5088  * @data:               Pointer to private data which is equal to the CPR3
5089  *                      regulator pointer
5090  * @val:                Output parameter written with a value of 1 if using
5091  *                      LDO mode or 0 if the LDO is bypassed
5092  *
5093  * Return: 0 on success, errno on failure
5094  */
5095 static int cpr3_debug_ldo_mode_get(void *data, u64 *val)
5096 {
5097         struct cpr3_regulator *vreg = data;
5098
5099         *val = (vreg->ldo_regulator_bypass == LDO_MODE);
5100
5101         return 0;
5102 }
5103 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_ldo_mode_fops, cpr3_debug_ldo_mode_get,
5104                         NULL, "%llu\n");
5105
5106 /**
5107  * struct cpr3_debug_corner_info - data structure used by the
5108  *              cpr3_debugfs_create_corner_int function
5109  * @vreg:               Pointer to the CPR3 regulator
5110  * @index:              Pointer to the corner array index
5111  * @member_offset:      Offset in bytes from the beginning of struct cpr3_corner
5112  *                      to the beginning of the value to be read from
5113  * @corner:             Pointer to the CPR3 corner array
5114  */
5115 struct cpr3_debug_corner_info {
5116         struct cpr3_regulator   *vreg;
5117         int                     *index;
5118         size_t                  member_offset;
5119         struct cpr3_corner      *corner;
5120 };
5121
5122 static int cpr3_debug_corner_int_get(void *data, u64 *val)
5123 {
5124         struct cpr3_debug_corner_info *info = data;
5125         struct cpr3_controller *ctrl = info->vreg->thread->ctrl;
5126         int i;
5127
5128         mutex_lock(&ctrl->lock);
5129
5130         i = *info->index;
5131         if (i < 0)
5132                 i = 0;
5133
5134         *val = *(int *)((char *)&info->vreg->corner[i] + info->member_offset);
5135
5136         mutex_unlock(&ctrl->lock);
5137
5138         return 0;
5139 }
5140 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_corner_int_fops, cpr3_debug_corner_int_get,
5141                         NULL, "%lld\n");
5142
5143 /**
5144  * cpr3_debugfs_create_corner_int - create a debugfs file that is used to read
5145  *              a signed int value out of a CPR3 regulator's corner array
5146  * @vreg:               Pointer to the CPR3 regulator
5147  * @name:               Pointer to a string containing the name of the file to
5148  *                      create
5149  * @mode:               The permissions that the file should have
5150  * @parent:             Pointer to the parent dentry for this file.  This should
5151  *                      be a directory dentry if set.  If this parameter is
5152  *                      %NULL, then the file will be created in the root of the
5153  *                      debugfs filesystem.
5154  * @index:              Pointer to the corner array index
5155  * @member_offset:      Offset in bytes from the beginning of struct cpr3_corner
5156  *                      to the beginning of the value to be read from
5157  *
5158  * This function creates a file in debugfs with the given name that
5159  * contains the value of the int type variable vreg->corner[index].member
5160  * where member_offset == offsetof(struct cpr3_corner, member).
5161  */
5162 static struct dentry *cpr3_debugfs_create_corner_int(
5163                 struct cpr3_regulator *vreg, const char *name, umode_t mode,
5164                 struct dentry *parent, int *index, size_t member_offset)
5165 {
5166         struct cpr3_debug_corner_info *info;
5167
5168         info = devm_kzalloc(vreg->thread->ctrl->dev, sizeof(*info), GFP_KERNEL);
5169         if (!info)
5170                 return NULL;
5171
5172         info->vreg = vreg;
5173         info->index = index;
5174         info->member_offset = member_offset;
5175
5176         return debugfs_create_file(name, mode, parent, info,
5177                                    &cpr3_debug_corner_int_fops);
5178 }
5179
5180 static int cpr3_debug_quot_open(struct inode *inode, struct file *file)
5181 {
5182         struct cpr3_debug_corner_info *info = inode->i_private;
5183         struct cpr3_thread *thread = info->vreg->thread;
5184         int size, i, pos;
5185         u32 *quot;
5186         char *buf;
5187
5188         /*
5189          * Max size:
5190          *  - 10 digits + ' ' or '\n' = 11 bytes per number
5191          *  - terminating '\0'
5192          */
5193         size = CPR3_RO_COUNT * 11;
5194         buf = kzalloc(size + 1, GFP_KERNEL);
5195         if (!buf)
5196                 return -ENOMEM;
5197
5198         file->private_data = buf;
5199
5200         mutex_lock(&thread->ctrl->lock);
5201
5202         quot = info->corner[*info->index].target_quot;
5203
5204         for (i = 0, pos = 0; i < CPR3_RO_COUNT; i++)
5205                 pos += scnprintf(buf + pos, size - pos, "%u%c",
5206                         quot[i], i < CPR3_RO_COUNT - 1 ? ' ' : '\n');
5207
5208         mutex_unlock(&thread->ctrl->lock);
5209
5210         return nonseekable_open(inode, file);
5211 }
5212
5213 static ssize_t cpr3_debug_quot_read(struct file *file, char __user *buf,
5214                 size_t len, loff_t *ppos)
5215 {
5216         return simple_read_from_buffer(buf, len, ppos, file->private_data,
5217                                         strlen(file->private_data));
5218 }
5219
5220 static int cpr3_debug_quot_release(struct inode *inode, struct file *file)
5221 {
5222         kfree(file->private_data);
5223
5224         return 0;
5225 }
5226
5227 static const struct file_operations cpr3_debug_quot_fops = {
5228         .owner   = THIS_MODULE,
5229         .open    = cpr3_debug_quot_open,
5230         .release = cpr3_debug_quot_release,
5231         .read    = cpr3_debug_quot_read,
5232         .llseek  = no_llseek,
5233 };
5234
5235 /**
5236  * cpr3_regulator_debugfs_corner_add() - add debugfs files to expose
5237  *              configuration data for the CPR corner
5238  * @vreg:               Pointer to the CPR3 regulator
5239  * @corner_dir:         Pointer to the parent corner dentry for the new files
5240  * @index:              Pointer to the corner array index
5241  *
5242  * Return: none
5243  */
5244 static void cpr3_regulator_debugfs_corner_add(struct cpr3_regulator *vreg,
5245                 struct dentry *corner_dir, int *index)
5246 {
5247         struct cpr3_debug_corner_info *info;
5248         struct dentry *temp;
5249
5250         temp = cpr3_debugfs_create_corner_int(vreg, "floor_volt", 0444,
5251                 corner_dir, index, offsetof(struct cpr3_corner, floor_volt));
5252         if (IS_ERR_OR_NULL(temp)) {
5253                 cpr3_err(vreg, "floor_volt debugfs file creation failed\n");
5254                 return;
5255         }
5256
5257         temp = cpr3_debugfs_create_corner_int(vreg, "ceiling_volt", 0444,
5258                 corner_dir, index, offsetof(struct cpr3_corner, ceiling_volt));
5259         if (IS_ERR_OR_NULL(temp)) {
5260                 cpr3_err(vreg, "ceiling_volt debugfs file creation failed\n");
5261                 return;
5262         }
5263
5264         temp = cpr3_debugfs_create_corner_int(vreg, "open_loop_volt", 0444,
5265                 corner_dir, index,
5266                 offsetof(struct cpr3_corner, open_loop_volt));
5267         if (IS_ERR_OR_NULL(temp)) {
5268                 cpr3_err(vreg, "open_loop_volt debugfs file creation failed\n");
5269                 return;
5270         }
5271
5272         temp = cpr3_debugfs_create_corner_int(vreg, "last_volt", 0444,
5273                 corner_dir, index, offsetof(struct cpr3_corner, last_volt));
5274         if (IS_ERR_OR_NULL(temp)) {
5275                 cpr3_err(vreg, "last_volt debugfs file creation failed\n");
5276                 return;
5277         }
5278
5279         info = devm_kzalloc(vreg->thread->ctrl->dev, sizeof(*info), GFP_KERNEL);
5280         if (!info)
5281                 return;
5282
5283         info->vreg = vreg;
5284         info->index = index;
5285         info->corner = vreg->corner;
5286
5287         temp = debugfs_create_file("target_quots", 0444, corner_dir, info,
5288                                 &cpr3_debug_quot_fops);
5289         if (IS_ERR_OR_NULL(temp)) {
5290                 cpr3_err(vreg, "target_quots debugfs file creation failed\n");
5291                 return;
5292         }
5293 }
5294
5295 /**
5296  * cpr3_debug_corner_index_set() - debugfs callback used to change the
5297  *              value of the CPR3 regulator debug_corner index
5298  * @data:               Pointer to private data which is equal to the CPR3
5299  *                      regulator pointer
5300  * @val:                New value for debug_corner
5301  *
5302  * Return: 0 on success, errno on failure
5303  */
5304 static int cpr3_debug_corner_index_set(void *data, u64 val)
5305 {
5306         struct cpr3_regulator *vreg = data;
5307
5308         if (val < CPR3_CORNER_OFFSET || val > vreg->corner_count) {
5309                 cpr3_err(vreg, "invalid corner index %llu; allowed values: %d-%d\n",
5310                         val, CPR3_CORNER_OFFSET, vreg->corner_count);
5311                 return -EINVAL;
5312         }
5313
5314         mutex_lock(&vreg->thread->ctrl->lock);
5315         vreg->debug_corner = val - CPR3_CORNER_OFFSET;
5316         mutex_unlock(&vreg->thread->ctrl->lock);
5317
5318         return 0;
5319 }
5320
5321 /**
5322  * cpr3_debug_corner_index_get() - debugfs callback used to retrieve
5323  *              the value of the CPR3 regulator debug_corner index
5324  * @data:               Pointer to private data which is equal to the CPR3
5325  *                      regulator pointer
5326  * @val:                Output parameter written with the value of
5327  *                      debug_corner
5328  *
5329  * Return: 0 on success, errno on failure
5330  */
5331 static int cpr3_debug_corner_index_get(void *data, u64 *val)
5332 {
5333         struct cpr3_regulator *vreg = data;
5334
5335         *val = vreg->debug_corner + CPR3_CORNER_OFFSET;
5336
5337         return 0;
5338 }
5339 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_corner_index_fops,
5340                         cpr3_debug_corner_index_get,
5341                         cpr3_debug_corner_index_set,
5342                         "%llu\n");
5343
5344 /**
5345  * cpr3_debug_current_corner_index_get() - debugfs callback used to retrieve
5346  *              the value of the CPR3 regulator current_corner index
5347  * @data:               Pointer to private data which is equal to the CPR3
5348  *                      regulator pointer
5349  * @val:                Output parameter written with the value of
5350  *                      current_corner
5351  *
5352  * Return: 0 on success, errno on failure
5353  */
5354 static int cpr3_debug_current_corner_index_get(void *data, u64 *val)
5355 {
5356         struct cpr3_regulator *vreg = data;
5357
5358         *val = vreg->current_corner + CPR3_CORNER_OFFSET;
5359
5360         return 0;
5361 }
5362 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_current_corner_index_fops,
5363                         cpr3_debug_current_corner_index_get,
5364                         NULL, "%llu\n");
5365
5366 /**
5367  * cpr3_regulator_debugfs_vreg_add() - add debugfs files to expose configuration
5368  *              data for the CPR3 regulator
5369  * @vreg:               Pointer to the CPR3 regulator
5370  * @thread_dir          CPR3 thread debugfs directory handle
5371  *
5372  * Return: none
5373  */
5374 static void cpr3_regulator_debugfs_vreg_add(struct cpr3_regulator *vreg,
5375                                 struct dentry *thread_dir)
5376 {
5377         struct dentry *temp, *corner_dir, *vreg_dir;
5378
5379         vreg_dir = debugfs_create_dir(vreg->name, thread_dir);
5380         if (IS_ERR_OR_NULL(vreg_dir)) {
5381                 cpr3_err(vreg, "%s debugfs directory creation failed\n",
5382                         vreg->name);
5383                 return;
5384         }
5385
5386         temp = debugfs_create_int("speed_bin_fuse", 0444, vreg_dir,
5387                                   &vreg->speed_bin_fuse);
5388         if (IS_ERR_OR_NULL(temp)) {
5389                 cpr3_err(vreg, "speed_bin_fuse debugfs file creation failed\n");
5390                 return;
5391         }
5392
5393         temp = debugfs_create_int("cpr_rev_fuse", 0444, vreg_dir,
5394                                   &vreg->cpr_rev_fuse);
5395         if (IS_ERR_OR_NULL(temp)) {
5396                 cpr3_err(vreg, "cpr_rev_fuse debugfs file creation failed\n");
5397                 return;
5398         }
5399
5400         temp = debugfs_create_int("fuse_combo", 0444, vreg_dir,
5401                                   &vreg->fuse_combo);
5402         if (IS_ERR_OR_NULL(temp)) {
5403                 cpr3_err(vreg, "fuse_combo debugfs file creation failed\n");
5404                 return;
5405         }
5406
5407         if (vreg->ldo_regulator) {
5408                 temp = debugfs_create_file("ldo_mode", 0444, vreg_dir, vreg,
5409                                         &cpr3_debug_ldo_mode_fops);
5410                 if (IS_ERR_OR_NULL(temp)) {
5411                         cpr3_err(vreg, "ldo_mode debugfs file creation failed\n");
5412                         return;
5413                 }
5414
5415                 temp = debugfs_create_file("ldo_mode_allowed",
5416                                 0644, vreg_dir, vreg,
5417                                 &cpr3_debug_ldo_mode_allowed_fops);
5418                 if (IS_ERR_OR_NULL(temp)) {
5419                         cpr3_err(vreg, "ldo_mode_allowed debugfs file creation failed\n");
5420                         return;
5421                 }
5422         }
5423
5424         temp = debugfs_create_int("corner_count", 0444, vreg_dir,
5425                                   &vreg->corner_count);
5426         if (IS_ERR_OR_NULL(temp)) {
5427                 cpr3_err(vreg, "corner_count debugfs file creation failed\n");
5428                 return;
5429         }
5430
5431         corner_dir = debugfs_create_dir("corner", vreg_dir);
5432         if (IS_ERR_OR_NULL(corner_dir)) {
5433                 cpr3_err(vreg, "corner debugfs directory creation failed\n");
5434                 return;
5435         }
5436
5437         temp = debugfs_create_file("index", 0644, corner_dir, vreg,
5438                                 &cpr3_debug_corner_index_fops);
5439         if (IS_ERR_OR_NULL(temp)) {
5440                 cpr3_err(vreg, "index debugfs file creation failed\n");
5441                 return;
5442         }
5443
5444         cpr3_regulator_debugfs_corner_add(vreg, corner_dir,
5445                                         &vreg->debug_corner);
5446
5447         corner_dir = debugfs_create_dir("current_corner", vreg_dir);
5448         if (IS_ERR_OR_NULL(corner_dir)) {
5449                 cpr3_err(vreg, "current_corner debugfs directory creation failed\n");
5450                 return;
5451         }
5452
5453         temp = debugfs_create_file("index", 0444, corner_dir, vreg,
5454                                 &cpr3_debug_current_corner_index_fops);
5455         if (IS_ERR_OR_NULL(temp)) {
5456                 cpr3_err(vreg, "index debugfs file creation failed\n");
5457                 return;
5458         }
5459
5460         cpr3_regulator_debugfs_corner_add(vreg, corner_dir,
5461                                           &vreg->current_corner);
5462 }
5463
5464 /**
5465  * cpr3_regulator_debugfs_thread_add() - add debugfs files to expose
5466  *              configuration data for the CPR thread
5467  * @thread:             Pointer to the CPR3 thread
5468  *
5469  * Return: none
5470  */
5471 static void cpr3_regulator_debugfs_thread_add(struct cpr3_thread *thread)
5472 {
5473         struct cpr3_controller *ctrl = thread->ctrl;
5474         struct dentry *aggr_dir, *temp, *thread_dir;
5475         struct cpr3_debug_corner_info *info;
5476         char buf[20];
5477         int *index;
5478         int i;
5479
5480         scnprintf(buf, sizeof(buf), "thread%u", thread->thread_id);
5481         thread_dir = debugfs_create_dir(buf, thread->ctrl->debugfs);
5482         if (IS_ERR_OR_NULL(thread_dir)) {
5483                 cpr3_err(ctrl, "thread %u %s debugfs directory creation failed\n",
5484                         thread->thread_id, buf);
5485                 return;
5486         }
5487
5488         aggr_dir = debugfs_create_dir("max_aggregated_params", thread_dir);
5489         if (IS_ERR_OR_NULL(aggr_dir)) {
5490                 cpr3_err(ctrl, "thread %u max_aggregated_params debugfs directory creation failed\n",
5491                         thread->thread_id);
5492                 return;
5493         }
5494
5495         temp = debugfs_create_int("floor_volt", 0444, aggr_dir,
5496                                   &thread->aggr_corner.floor_volt);
5497         if (IS_ERR_OR_NULL(temp)) {
5498                 cpr3_err(ctrl, "thread %u aggr floor_volt debugfs file creation failed\n",
5499                         thread->thread_id);
5500                 return;
5501         }
5502
5503         temp = debugfs_create_int("ceiling_volt", 0444, aggr_dir,
5504                                   &thread->aggr_corner.ceiling_volt);
5505         if (IS_ERR_OR_NULL(temp)) {
5506                 cpr3_err(ctrl, "thread %u aggr ceiling_volt debugfs file creation failed\n",
5507                         thread->thread_id);
5508                 return;
5509         }
5510
5511         temp = debugfs_create_int("open_loop_volt", 0444, aggr_dir,
5512                                   &thread->aggr_corner.open_loop_volt);
5513         if (IS_ERR_OR_NULL(temp)) {
5514                 cpr3_err(ctrl, "thread %u aggr open_loop_volt debugfs file creation failed\n",
5515                         thread->thread_id);
5516                 return;
5517         }
5518
5519         temp = debugfs_create_int("last_volt", 0444, aggr_dir,
5520                                   &thread->aggr_corner.last_volt);
5521         if (IS_ERR_OR_NULL(temp)) {
5522                 cpr3_err(ctrl, "thread %u aggr last_volt debugfs file creation failed\n",
5523                         thread->thread_id);
5524                 return;
5525         }
5526
5527         info = devm_kzalloc(thread->ctrl->dev, sizeof(*info), GFP_KERNEL);
5528         index = devm_kzalloc(thread->ctrl->dev, sizeof(*index), GFP_KERNEL);
5529         if (!info || !index)
5530                 return;
5531         *index = 0;
5532         info->vreg = &thread->vreg[0];
5533         info->index = index;
5534         info->corner = &thread->aggr_corner;
5535
5536         temp = debugfs_create_file("target_quots", 0444, aggr_dir, info,
5537                                 &cpr3_debug_quot_fops);
5538         if (IS_ERR_OR_NULL(temp)) {
5539                 cpr3_err(ctrl, "thread %u target_quots debugfs file creation failed\n",
5540                         thread->thread_id);
5541                 return;
5542         }
5543
5544         for (i = 0; i < thread->vreg_count; i++)
5545                 cpr3_regulator_debugfs_vreg_add(&thread->vreg[i], thread_dir);
5546 }
5547
5548 /**
5549  * cpr3_debug_closed_loop_enable_set() - debugfs callback used to change the
5550  *              value of the CPR controller cpr_allowed_sw flag which enables or
5551  *              disables closed-loop operation
5552  * @data:               Pointer to private data which is equal to the CPR
5553  *                      controller pointer
5554  * @val:                New value for cpr_allowed_sw
5555  *
5556  * Return: 0 on success, errno on failure
5557  */
5558 static int cpr3_debug_closed_loop_enable_set(void *data, u64 val)
5559 {
5560         struct cpr3_controller *ctrl = data;
5561         bool enable = !!val;
5562         int rc;
5563
5564         mutex_lock(&ctrl->lock);
5565
5566         if (ctrl->cpr_allowed_sw == enable)
5567                 goto done;
5568
5569         if (enable && !ctrl->cpr_allowed_hw) {
5570                 cpr3_err(ctrl, "CPR closed-loop operation is not allowed\n");
5571                 goto done;
5572         }
5573
5574         ctrl->cpr_allowed_sw = enable;
5575
5576         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH) {
5577                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
5578                         CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
5579                         ctrl->cpr_allowed_sw && ctrl->use_hw_closed_loop
5580                         ? CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE
5581                         : CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_DISABLE);
5582         } else {
5583                 rc = cpr3_regulator_update_ctrl_state(ctrl);
5584                 if (rc) {
5585                         cpr3_err(ctrl, "could not change CPR enable state=%u, rc=%d\n",
5586                                  enable, rc);
5587                         goto done;
5588                 }
5589
5590                 if (ctrl->proc_clock_throttle && !ctrl->cpr_enabled) {
5591                         rc = cpr3_clock_enable(ctrl);
5592                         if (rc) {
5593                                 cpr3_err(ctrl, "clock enable failed, rc=%d\n",
5594                                          rc);
5595                                 goto done;
5596                         }
5597                         ctrl->cpr_enabled = true;
5598
5599                         cpr3_write(ctrl, CPR3_REG_PD_THROTTLE,
5600                                    CPR3_PD_THROTTLE_DISABLE);
5601
5602                         cpr3_clock_disable(ctrl);
5603                         ctrl->cpr_enabled = false;
5604                 }
5605         }
5606
5607         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
5608                 cpr3_debug(ctrl, "closed-loop=%s\n", enable ?
5609                            "enabled" : "disabled");
5610         } else {
5611                 cpr3_debug(ctrl, "closed-loop=%s\n", enable &&
5612                            ctrl->use_hw_closed_loop ? "enabled" : "disabled");
5613         }
5614 done:
5615         mutex_unlock(&ctrl->lock);
5616         return 0;
5617 }
5618
5619 /**
5620  * cpr3_debug_closed_loop_enable_get() - debugfs callback used to retrieve
5621  *              the value of the CPR controller cpr_allowed_sw flag which
5622  *              indicates if closed-loop operation is enabled
5623  * @data:               Pointer to private data which is equal to the CPR
5624  *                      controller pointer
5625  * @val:                Output parameter written with the value of
5626  *                      cpr_allowed_sw
5627  *
5628  * Return: 0 on success, errno on failure
5629  */
5630 static int cpr3_debug_closed_loop_enable_get(void *data, u64 *val)
5631 {
5632         struct cpr3_controller *ctrl = data;
5633
5634         *val = ctrl->cpr_allowed_sw;
5635
5636         return 0;
5637 }
5638 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_closed_loop_enable_fops,
5639                         cpr3_debug_closed_loop_enable_get,
5640                         cpr3_debug_closed_loop_enable_set,
5641                         "%llu\n");
5642
5643 /**
5644  * cpr3_debug_hw_closed_loop_enable_set() - debugfs callback used to change the
5645  *              value of the CPR controller use_hw_closed_loop flag which
5646  *              switches between software closed-loop and hardware closed-loop
5647  *              operation for CPR3 and CPR4 controllers and between open-loop
5648  *              and full hardware closed-loop operation for CPRh controllers.
5649  * @data:               Pointer to private data which is equal to the CPR
5650  *                      controller pointer
5651  * @val:                New value for use_hw_closed_loop
5652  *
5653  * Return: 0 on success, errno on failure
5654  */
5655 static int cpr3_debug_hw_closed_loop_enable_set(void *data, u64 val)
5656 {
5657         struct cpr3_controller *ctrl = data;
5658         bool use_hw_closed_loop = !!val;
5659         struct cpr3_regulator *vreg;
5660         bool cpr_enabled;
5661         int i, j, k, rc;
5662
5663         mutex_lock(&ctrl->lock);
5664
5665         if (ctrl->use_hw_closed_loop == use_hw_closed_loop)
5666                 goto done;
5667
5668         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
5669                 rc = cpr3_ctrl_clear_cpr4_config(ctrl);
5670                 if (rc) {
5671                         cpr3_err(ctrl, "failed to clear CPR4 configuration,rc=%d\n",
5672                                 rc);
5673                         goto done;
5674                 }
5675         }
5676
5677         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH)
5678                 cpr3_ctrl_loop_disable(ctrl);
5679
5680         ctrl->use_hw_closed_loop = use_hw_closed_loop;
5681
5682         cpr_enabled = ctrl->cpr_enabled;
5683
5684         /* Ensure that CPR clocks are enabled before writing to registers. */
5685         if (!cpr_enabled) {
5686                 rc = cpr3_clock_enable(ctrl);
5687                 if (rc) {
5688                         cpr3_err(ctrl, "clock enable failed, rc=%d\n", rc);
5689                         goto done;
5690                 }
5691                 ctrl->cpr_enabled = true;
5692         }
5693
5694         if (ctrl->use_hw_closed_loop && ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH)
5695                 cpr3_write(ctrl, CPR3_REG_IRQ_EN, 0);
5696
5697         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
5698                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
5699                         CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
5700                         ctrl->use_hw_closed_loop
5701                         ? CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE
5702                         : CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_DISABLE);
5703         } else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPRH) {
5704                 cpr3_masked_write(ctrl, CPR4_REG_MARGIN_ADJ_CTL,
5705                         CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_EN_MASK,
5706                         ctrl->cpr_allowed_sw && ctrl->use_hw_closed_loop
5707                         ? CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_ENABLE
5708                         : CPR4_MARGIN_ADJ_CTL_HW_CLOSED_LOOP_DISABLE);
5709         } else if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
5710                 cpr3_write(ctrl, CPR3_REG_HW_CLOSED_LOOP,
5711                         ctrl->use_hw_closed_loop
5712                         ? CPR3_HW_CLOSED_LOOP_ENABLE
5713                         : CPR3_HW_CLOSED_LOOP_DISABLE);
5714         }
5715
5716         /* Turn off CPR clocks if they were off before this function call. */
5717         if (!cpr_enabled) {
5718                 cpr3_clock_disable(ctrl);
5719                 ctrl->cpr_enabled = false;
5720         }
5721
5722         if (ctrl->use_hw_closed_loop && ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
5723                 rc = regulator_enable(ctrl->vdd_limit_regulator);
5724                 if (rc) {
5725                         cpr3_err(ctrl, "CPR limit regulator enable failed, rc=%d\n",
5726                                 rc);
5727                         goto done;
5728                 }
5729
5730                 rc = msm_spm_avs_enable_irq(0, MSM_SPM_AVS_IRQ_MAX);
5731                 if (rc) {
5732                         cpr3_err(ctrl, "could not enable max IRQ, rc=%d\n", rc);
5733                         goto done;
5734                 }
5735         } else if (!ctrl->use_hw_closed_loop
5736                         && ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
5737                 rc = regulator_disable(ctrl->vdd_limit_regulator);
5738                 if (rc) {
5739                         cpr3_err(ctrl, "CPR limit regulator disable failed, rc=%d\n",
5740                                 rc);
5741                         goto done;
5742                 }
5743
5744                 rc = msm_spm_avs_disable_irq(0, MSM_SPM_AVS_IRQ_MAX);
5745                 if (rc) {
5746                         cpr3_err(ctrl, "could not disable max IRQ, rc=%d\n",
5747                                 rc);
5748                         goto done;
5749                 }
5750         }
5751
5752         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
5753                 /*
5754                  * Due to APM and mem-acc floor restriction constraints,
5755                  * the closed-loop voltage may be different when using
5756                  * software closed-loop vs hardware closed-loop.  Therefore,
5757                  * reset the cached closed-loop voltage for all corners to the
5758                  * corresponding open-loop voltage when switching between
5759                  * SW and HW closed-loop mode.
5760                  */
5761                 for (i = 0; i < ctrl->thread_count; i++) {
5762                         for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
5763                                 vreg = &ctrl->thread[i].vreg[j];
5764                                 for (k = 0; k < vreg->corner_count; k++)
5765                                         vreg->corner[k].last_volt
5766                                         = vreg->corner[k].open_loop_volt;
5767                         }
5768                 }
5769
5770                 /* Skip last_volt caching */
5771                 ctrl->last_corner_was_closed_loop = false;
5772
5773                 rc = cpr3_regulator_update_ctrl_state(ctrl);
5774                 if (rc) {
5775                         cpr3_err(ctrl, "could not change CPR HW closed-loop enable state=%u, rc=%d\n",
5776                                  use_hw_closed_loop, rc);
5777                         goto done;
5778                 }
5779
5780                 cpr3_debug(ctrl, "CPR mode=%s\n",
5781                            use_hw_closed_loop ?
5782                            "HW closed-loop" : "SW closed-loop");
5783         } else {
5784                 cpr3_debug(ctrl, "CPR mode=%s\n",
5785                            ctrl->cpr_allowed_sw && use_hw_closed_loop ?
5786                            "full HW closed-loop" : "open-loop");
5787         }
5788 done:
5789         mutex_unlock(&ctrl->lock);
5790         return 0;
5791 }
5792
5793 /**
5794  * cpr3_debug_hw_closed_loop_enable_get() - debugfs callback used to retrieve
5795  *              the value of the CPR controller use_hw_closed_loop flag which
5796  *              indicates if hardware closed-loop operation is being used in
5797  *              place of software closed-loop operation
5798  * @data:               Pointer to private data which is equal to the CPR
5799  *                      controller pointer
5800  * @val:                Output parameter written with the value of
5801  *                      use_hw_closed_loop
5802  *
5803  * Return: 0 on success, errno on failure
5804  */
5805 static int cpr3_debug_hw_closed_loop_enable_get(void *data, u64 *val)
5806 {
5807         struct cpr3_controller *ctrl = data;
5808
5809         *val = ctrl->use_hw_closed_loop;
5810
5811         return 0;
5812 }
5813 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_hw_closed_loop_enable_fops,
5814                         cpr3_debug_hw_closed_loop_enable_get,
5815                         cpr3_debug_hw_closed_loop_enable_set,
5816                         "%llu\n");
5817
5818 /**
5819  * cpr3_debug_trigger_aging_measurement_set() - debugfs callback used to trigger
5820  *              another CPR measurement
5821  * @data:               Pointer to private data which is equal to the CPR
5822  *                      controller pointer
5823  * @val:                Unused
5824  *
5825  * Return: 0 on success, errno on failure
5826  */
5827 static int cpr3_debug_trigger_aging_measurement_set(void *data, u64 val)
5828 {
5829         struct cpr3_controller *ctrl = data;
5830         int rc;
5831
5832         mutex_lock(&ctrl->lock);
5833
5834         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
5835                 rc = cpr3_ctrl_clear_cpr4_config(ctrl);
5836                 if (rc) {
5837                         cpr3_err(ctrl, "failed to clear CPR4 configuration,rc=%d\n",
5838                                 rc);
5839                         goto done;
5840                 }
5841         }
5842
5843         cpr3_ctrl_loop_disable(ctrl);
5844
5845         cpr3_regulator_set_aging_ref_adjustment(ctrl, INT_MAX);
5846         ctrl->aging_required = true;
5847         ctrl->aging_succeeded = false;
5848         ctrl->aging_failed = false;
5849
5850         rc = cpr3_regulator_update_ctrl_state(ctrl);
5851         if (rc) {
5852                 cpr3_err(ctrl, "could not update the CPR controller state, rc=%d\n",
5853                         rc);
5854                 goto done;
5855         }
5856
5857 done:
5858         mutex_unlock(&ctrl->lock);
5859         return 0;
5860 }
5861 DEFINE_SIMPLE_ATTRIBUTE(cpr3_debug_trigger_aging_measurement_fops,
5862                         NULL,
5863                         cpr3_debug_trigger_aging_measurement_set,
5864                         "%llu\n");
5865
5866 /**
5867  * cpr3_regulator_debugfs_ctrl_add() - add debugfs files to expose configuration
5868  *              data for the CPR controller
5869  * @ctrl:               Pointer to the CPR3 controller
5870  *
5871  * Return: none
5872  */
5873 static void cpr3_regulator_debugfs_ctrl_add(struct cpr3_controller *ctrl)
5874 {
5875         struct dentry *temp, *aggr_dir;
5876         int i;
5877
5878         /* Add cpr3-regulator base directory if it isn't present already. */
5879         if (cpr3_debugfs_base == NULL) {
5880                 cpr3_debugfs_base = debugfs_create_dir("cpr3-regulator", NULL);
5881                 if (IS_ERR_OR_NULL(cpr3_debugfs_base)) {
5882                         cpr3_err(ctrl, "cpr3-regulator debugfs base directory creation failed\n");
5883                         cpr3_debugfs_base = NULL;
5884                         return;
5885                 }
5886         }
5887
5888         ctrl->debugfs = debugfs_create_dir(ctrl->name, cpr3_debugfs_base);
5889         if (IS_ERR_OR_NULL(ctrl->debugfs)) {
5890                 cpr3_err(ctrl, "cpr3-regulator controller debugfs directory creation failed\n");
5891                 return;
5892         }
5893
5894         temp = debugfs_create_file("cpr_closed_loop_enable", 0644,
5895                                         ctrl->debugfs, ctrl,
5896                                         &cpr3_debug_closed_loop_enable_fops);
5897         if (IS_ERR_OR_NULL(temp)) {
5898                 cpr3_err(ctrl, "cpr_closed_loop_enable debugfs file creation failed\n");
5899                 return;
5900         }
5901
5902         if (ctrl->supports_hw_closed_loop) {
5903                 temp = debugfs_create_file("use_hw_closed_loop", 0644,
5904                                         ctrl->debugfs, ctrl,
5905                                         &cpr3_debug_hw_closed_loop_enable_fops);
5906                 if (IS_ERR_OR_NULL(temp)) {
5907                         cpr3_err(ctrl, "use_hw_closed_loop debugfs file creation failed\n");
5908                         return;
5909                 }
5910         }
5911
5912         temp = debugfs_create_int("thread_count", 0444, ctrl->debugfs,
5913                                   &ctrl->thread_count);
5914         if (IS_ERR_OR_NULL(temp)) {
5915                 cpr3_err(ctrl, "thread_count debugfs file creation failed\n");
5916                 return;
5917         }
5918
5919         if (ctrl->apm) {
5920                 temp = debugfs_create_int("apm_threshold_volt", 0444,
5921                                 ctrl->debugfs, &ctrl->apm_threshold_volt);
5922                 if (IS_ERR_OR_NULL(temp)) {
5923                         cpr3_err(ctrl, "apm_threshold_volt debugfs file creation failed\n");
5924                         return;
5925                 }
5926         }
5927
5928         if (ctrl->aging_required || ctrl->aging_succeeded
5929             || ctrl->aging_failed) {
5930                 temp = debugfs_create_int("aging_adj_volt", 0444,
5931                                 ctrl->debugfs, &ctrl->aging_ref_adjust_volt);
5932                 if (IS_ERR_OR_NULL(temp)) {
5933                         cpr3_err(ctrl, "aging_adj_volt debugfs file creation failed\n");
5934                         return;
5935                 }
5936
5937                 temp = debugfs_create_file("aging_succeeded", 0444,
5938                         ctrl->debugfs, &ctrl->aging_succeeded, &fops_bool_ro);
5939                 if (IS_ERR_OR_NULL(temp)) {
5940                         cpr3_err(ctrl, "aging_succeeded debugfs file creation failed\n");
5941                         return;
5942                 }
5943
5944                 temp = debugfs_create_file("aging_failed", 0444,
5945                         ctrl->debugfs, &ctrl->aging_failed, &fops_bool_ro);
5946                 if (IS_ERR_OR_NULL(temp)) {
5947                         cpr3_err(ctrl, "aging_failed debugfs file creation failed\n");
5948                         return;
5949                 }
5950
5951                 temp = debugfs_create_file("aging_trigger", 0200,
5952                         ctrl->debugfs, ctrl,
5953                         &cpr3_debug_trigger_aging_measurement_fops);
5954                 if (IS_ERR_OR_NULL(temp)) {
5955                         cpr3_err(ctrl, "aging_trigger debugfs file creation failed\n");
5956                         return;
5957                 }
5958         }
5959
5960         aggr_dir = debugfs_create_dir("max_aggregated_voltages", ctrl->debugfs);
5961         if (IS_ERR_OR_NULL(aggr_dir)) {
5962                 cpr3_err(ctrl, "max_aggregated_voltages debugfs directory creation failed\n");
5963                 return;
5964         }
5965
5966         temp = debugfs_create_int("floor_volt", 0444, aggr_dir,
5967                                   &ctrl->aggr_corner.floor_volt);
5968         if (IS_ERR_OR_NULL(temp)) {
5969                 cpr3_err(ctrl, "aggr floor_volt debugfs file creation failed\n");
5970                 return;
5971         }
5972
5973         temp = debugfs_create_int("ceiling_volt", 0444, aggr_dir,
5974                                   &ctrl->aggr_corner.ceiling_volt);
5975         if (IS_ERR_OR_NULL(temp)) {
5976                 cpr3_err(ctrl, "aggr ceiling_volt debugfs file creation failed\n");
5977                 return;
5978         }
5979
5980         temp = debugfs_create_int("open_loop_volt", 0444, aggr_dir,
5981                                   &ctrl->aggr_corner.open_loop_volt);
5982         if (IS_ERR_OR_NULL(temp)) {
5983                 cpr3_err(ctrl, "aggr open_loop_volt debugfs file creation failed\n");
5984                 return;
5985         }
5986
5987         temp = debugfs_create_int("last_volt", 0444, aggr_dir,
5988                                   &ctrl->aggr_corner.last_volt);
5989         if (IS_ERR_OR_NULL(temp)) {
5990                 cpr3_err(ctrl, "aggr last_volt debugfs file creation failed\n");
5991                 return;
5992         }
5993
5994         for (i = 0; i < ctrl->thread_count; i++)
5995                 cpr3_regulator_debugfs_thread_add(&ctrl->thread[i]);
5996 }
5997
5998 /**
5999  * cpr3_regulator_debugfs_ctrl_remove() - remove debugfs files for the CPR
6000  *              controller
6001  * @ctrl:               Pointer to the CPR3 controller
6002  *
6003  * Note, this function must be called after the controller has been removed from
6004  * cpr3_controller_list and while the cpr3_controller_list_mutex lock is held.
6005  *
6006  * Return: none
6007  */
6008 static void cpr3_regulator_debugfs_ctrl_remove(struct cpr3_controller *ctrl)
6009 {
6010         if (list_empty(&cpr3_controller_list)) {
6011                 debugfs_remove_recursive(cpr3_debugfs_base);
6012                 cpr3_debugfs_base = NULL;
6013         } else {
6014                 debugfs_remove_recursive(ctrl->debugfs);
6015         }
6016 }
6017
6018 /**
6019  * cpr3_regulator_init_ctrl_data() - performs initialization of CPR controller
6020  *                                      elements
6021  * @ctrl:               Pointer to the CPR3 controller
6022  *
6023  * Return: 0 on success, errno on failure
6024  */
6025 static int cpr3_regulator_init_ctrl_data(struct cpr3_controller *ctrl)
6026 {
6027         /* Read the initial vdd voltage from hardware. */
6028         ctrl->aggr_corner.last_volt
6029                 = regulator_get_voltage(ctrl->vdd_regulator);
6030         if (ctrl->aggr_corner.last_volt < 0) {
6031                 cpr3_err(ctrl, "regulator_get_voltage(vdd) failed, rc=%d\n",
6032                                 ctrl->aggr_corner.last_volt);
6033                 return ctrl->aggr_corner.last_volt;
6034         }
6035         ctrl->aggr_corner.open_loop_volt = ctrl->aggr_corner.last_volt;
6036
6037         return 0;
6038 }
6039
6040 /**
6041  * cpr3_regulator_init_vreg_data() - performs initialization of common CPR3
6042  *              regulator elements and validate aging configurations
6043  * @vreg:               Pointer to the CPR3 regulator
6044  *
6045  * Return: 0 on success, errno on failure
6046  */
6047 static int cpr3_regulator_init_vreg_data(struct cpr3_regulator *vreg)
6048 {
6049         int i, j;
6050         bool init_aging;
6051
6052         vreg->current_corner = CPR3_REGULATOR_CORNER_INVALID;
6053         vreg->last_closed_loop_corner = CPR3_REGULATOR_CORNER_INVALID;
6054
6055         init_aging = vreg->aging_allowed && vreg->thread->ctrl->aging_required;
6056
6057         for (i = 0; i < vreg->corner_count; i++) {
6058                 vreg->corner[i].last_volt = vreg->corner[i].open_loop_volt;
6059                 vreg->corner[i].irq_en = CPR3_IRQ_UP | CPR3_IRQ_DOWN;
6060
6061                 vreg->corner[i].ro_mask = 0;
6062                 for (j = 0; j < CPR3_RO_COUNT; j++) {
6063                         if (vreg->corner[i].target_quot[j] == 0)
6064                                 vreg->corner[i].ro_mask |= BIT(j);
6065                 }
6066
6067                 if (init_aging) {
6068                         vreg->corner[i].unaged_floor_volt
6069                                 = vreg->corner[i].floor_volt;
6070                         vreg->corner[i].unaged_ceiling_volt
6071                                 = vreg->corner[i].ceiling_volt;
6072                         vreg->corner[i].unaged_open_loop_volt
6073                                 = vreg->corner[i].open_loop_volt;
6074                 }
6075
6076                 if (vreg->aging_allowed) {
6077                         if (vreg->corner[i].unaged_floor_volt <= 0) {
6078                                 cpr3_err(vreg, "invalid unaged_floor_volt[%d] = %d\n",
6079                                         i, vreg->corner[i].unaged_floor_volt);
6080                                 return -EINVAL;
6081                         }
6082                         if (vreg->corner[i].unaged_ceiling_volt <= 0) {
6083                                 cpr3_err(vreg, "invalid unaged_ceiling_volt[%d] = %d\n",
6084                                         i, vreg->corner[i].unaged_ceiling_volt);
6085                                 return -EINVAL;
6086                         }
6087                         if (vreg->corner[i].unaged_open_loop_volt <= 0) {
6088                                 cpr3_err(vreg, "invalid unaged_open_loop_volt[%d] = %d\n",
6089                                       i, vreg->corner[i].unaged_open_loop_volt);
6090                                 return -EINVAL;
6091                         }
6092                 }
6093         }
6094
6095         if (vreg->aging_allowed && vreg->corner[vreg->aging_corner].ceiling_volt
6096             > vreg->thread->ctrl->aging_ref_volt) {
6097                 cpr3_err(vreg, "aging corner %d ceiling voltage = %d > aging ref voltage = %d uV\n",
6098                         vreg->aging_corner,
6099                         vreg->corner[vreg->aging_corner].ceiling_volt,
6100                         vreg->thread->ctrl->aging_ref_volt);
6101                 return -EINVAL;
6102         }
6103
6104         return 0;
6105 }
6106
6107 /**
6108  * cpr3_regulator_suspend() - perform common required CPR3 power down steps
6109  *              before the system enters suspend
6110  * @ctrl:               Pointer to the CPR3 controller
6111  *
6112  * Return: 0 on success, errno on failure
6113  */
6114 int cpr3_regulator_suspend(struct cpr3_controller *ctrl)
6115 {
6116         int rc;
6117
6118         mutex_lock(&ctrl->lock);
6119
6120         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
6121                 rc = cpr3_ctrl_clear_cpr4_config(ctrl);
6122                 if (rc) {
6123                         cpr3_err(ctrl, "failed to clear CPR4 configuration,rc=%d\n",
6124                                 rc);
6125                         mutex_unlock(&ctrl->lock);
6126                         return rc;
6127                 }
6128         }
6129
6130         cpr3_ctrl_loop_disable(ctrl);
6131
6132         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
6133                 rc = cpr3_closed_loop_disable(ctrl);
6134                 if (rc)
6135                         cpr3_err(ctrl, "could not disable CPR, rc=%d\n", rc);
6136
6137                 ctrl->cpr_suspended = true;
6138         }
6139
6140         mutex_unlock(&ctrl->lock);
6141         return 0;
6142 }
6143
6144 /**
6145  * cpr3_regulator_resume() - perform common required CPR3 power up steps after
6146  *              the system resumes from suspend
6147  * @ctrl:               Pointer to the CPR3 controller
6148  *
6149  * Return: 0 on success, errno on failure
6150  */
6151 int cpr3_regulator_resume(struct cpr3_controller *ctrl)
6152 {
6153         int rc;
6154
6155         mutex_lock(&ctrl->lock);
6156
6157         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
6158                 ctrl->cpr_suspended = false;
6159                 rc = cpr3_regulator_update_ctrl_state(ctrl);
6160                 if (rc)
6161                         cpr3_err(ctrl, "could not enable CPR, rc=%d\n", rc);
6162         } else {
6163                 cpr3_ctrl_loop_enable(ctrl);
6164         }
6165
6166         mutex_unlock(&ctrl->lock);
6167         return 0;
6168 }
6169
6170 /**
6171  * cpr3_regulator_cpu_hotplug_callback() - reset CPR IRQ affinity when a CPU is
6172  *              brought online via hotplug
6173  * @nb:                 Pointer to the notifier block
6174  * @action:             hotplug action
6175  * @hcpu:               long value corresponding to the CPU number
6176  *
6177  * Return: NOTIFY_OK
6178  */
6179 static int cpr3_regulator_cpu_hotplug_callback(struct notifier_block *nb,
6180                                             unsigned long action, void *hcpu)
6181 {
6182         struct cpr3_controller *ctrl = container_of(nb, struct cpr3_controller,
6183                                         cpu_hotplug_notifier);
6184         int cpu = (long)hcpu;
6185
6186         action &= ~CPU_TASKS_FROZEN;
6187
6188         if (action == CPU_ONLINE
6189             && cpumask_test_cpu(cpu, &ctrl->irq_affinity_mask))
6190                 irq_set_affinity(ctrl->irq, &ctrl->irq_affinity_mask);
6191
6192         return NOTIFY_OK;
6193 }
6194
6195 /**
6196  * cpr3_regulator_validate_controller() - verify the data passed in via the
6197  *              cpr3_controller data structure
6198  * @ctrl:               Pointer to the CPR3 controller
6199  *
6200  * Return: 0 on success, errno on failure
6201  */
6202 static int cpr3_regulator_validate_controller(struct cpr3_controller *ctrl)
6203 {
6204         struct cpr3_thread *thread;
6205         struct cpr3_regulator *vreg;
6206         int i, j, allow_boost_vreg_count = 0;
6207
6208         if (!ctrl->vdd_regulator && ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
6209                 cpr3_err(ctrl, "vdd regulator missing\n");
6210                 return -EINVAL;
6211         } else if (ctrl->sensor_count <= 0
6212                    || ctrl->sensor_count > CPR3_MAX_SENSOR_COUNT) {
6213                 cpr3_err(ctrl, "invalid CPR sensor count=%d\n",
6214                         ctrl->sensor_count);
6215                 return -EINVAL;
6216         } else if (!ctrl->sensor_owner) {
6217                 cpr3_err(ctrl, "CPR sensor ownership table missing\n");
6218                 return -EINVAL;
6219         }
6220
6221         if (ctrl->aging_required) {
6222                 for (i = 0; i < ctrl->aging_sensor_count; i++) {
6223                         if (ctrl->aging_sensor[i].sensor_id
6224                             >= ctrl->sensor_count) {
6225                                 cpr3_err(ctrl, "aging_sensor[%d] id=%u is not in the value range 0-%d",
6226                                         i, ctrl->aging_sensor[i].sensor_id,
6227                                         ctrl->sensor_count - 1);
6228                                 return -EINVAL;
6229                         }
6230                 }
6231         }
6232
6233         for (i = 0; i < ctrl->thread_count; i++) {
6234                 thread = &ctrl->thread[i];
6235                 for (j = 0; j < thread->vreg_count; j++) {
6236                         vreg = &thread->vreg[j];
6237                         if (vreg->allow_boost)
6238                                 allow_boost_vreg_count++;
6239                 }
6240         }
6241
6242         if (allow_boost_vreg_count > 1) {
6243                 /*
6244                  * Boost feature is not allowed to be used for more
6245                  * than one CPR3 regulator of a CPR3 controller.
6246                  */
6247                 cpr3_err(ctrl, "Boost feature is enabled for more than one regulator\n");
6248                 return -EINVAL;
6249         }
6250
6251         return 0;
6252 }
6253
6254 /**
6255  * cpr3_panic_callback() - panic notification callback function. This function
6256  *              is invoked when a kernel panic occurs.
6257  * @nfb:        Notifier block pointer of CPR3 controller
6258  * @event:      Value passed unmodified to notifier function
6259  * @data:       Pointer passed unmodified to notifier function
6260  *
6261  * Return: NOTIFY_OK
6262  */
6263 static int cpr3_panic_callback(struct notifier_block *nfb,
6264                         unsigned long event, void *data)
6265 {
6266         struct cpr3_controller *ctrl = container_of(nfb,
6267                                 struct cpr3_controller, panic_notifier);
6268         struct cpr3_panic_regs_info *regs_info = ctrl->panic_regs_info;
6269         struct cpr3_reg_info *reg;
6270         int i = 0;
6271
6272         for (i = 0; i < regs_info->reg_count; i++) {
6273                 reg = &(regs_info->regs[i]);
6274                 reg->value = readl_relaxed(reg->virt_addr);
6275                 pr_err("%s[0x%08x] = 0x%08x\n", reg->name, reg->addr,
6276                         reg->value);
6277         }
6278         /*
6279          * Barrier to ensure that the information has been updated in the
6280          * structure.
6281          */
6282         mb();
6283
6284         return NOTIFY_OK;
6285 }
6286
6287 /**
6288  * cpr3_regulator_register() - register the regulators for a CPR3 controller and
6289  *              perform CPR hardware initialization
6290  * @pdev:               Platform device pointer for the CPR3 controller
6291  * @ctrl:               Pointer to the CPR3 controller
6292  *
6293  * Return: 0 on success, errno on failure
6294  */
6295 int cpr3_regulator_register(struct platform_device *pdev,
6296                         struct cpr3_controller *ctrl)
6297 {
6298         struct device *dev = &pdev->dev;
6299         struct resource *res;
6300         int i, j, rc;
6301
6302         if (!dev->of_node) {
6303                 dev_err(dev, "%s: Device tree node is missing\n", __func__);
6304                 return -EINVAL;
6305         }
6306
6307         if (!ctrl || !ctrl->name) {
6308                 dev_err(dev, "%s: CPR controller data is missing\n", __func__);
6309                 return -EINVAL;
6310         }
6311
6312         rc = cpr3_regulator_validate_controller(ctrl);
6313         if (rc) {
6314                 cpr3_err(ctrl, "controller validation failed, rc=%d\n", rc);
6315                 return rc;
6316         }
6317
6318         mutex_init(&ctrl->lock);
6319
6320         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "cpr_ctrl");
6321         if (!res || !res->start) {
6322                 cpr3_err(ctrl, "CPR controller address is missing\n");
6323                 return -ENXIO;
6324         }
6325         ctrl->cpr_ctrl_base = devm_ioremap(dev, res->start, resource_size(res));
6326
6327         if (ctrl->aging_possible_mask) {
6328                 /*
6329                  * Aging possible register address is required if an aging
6330                  * possible mask has been specified.
6331                  */
6332                 res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
6333                                                 "aging_allowed");
6334                 if (!res || !res->start) {
6335                         cpr3_err(ctrl, "CPR aging allowed address is missing\n");
6336                         return -ENXIO;
6337                 }
6338                 ctrl->aging_possible_reg = devm_ioremap(dev, res->start,
6339                                                         resource_size(res));
6340         }
6341
6342         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
6343                 ctrl->irq = platform_get_irq_byname(pdev, "cpr");
6344                 if (ctrl->irq < 0) {
6345                         cpr3_err(ctrl, "missing CPR interrupt\n");
6346                         return ctrl->irq;
6347                 }
6348         }
6349
6350         if (ctrl->supports_hw_closed_loop) {
6351                 rc = msm_spm_probe_done();
6352                 if (rc) {
6353                         if (rc != -EPROBE_DEFER)
6354                                 cpr3_err(ctrl, "spm unavailable, rc=%d\n", rc);
6355                         return rc;
6356                 }
6357
6358                 if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
6359                         ctrl->ceiling_irq = platform_get_irq_byname(pdev,
6360                                                 "ceiling");
6361                         if (ctrl->ceiling_irq < 0) {
6362                                 cpr3_err(ctrl, "missing ceiling interrupt\n");
6363                                 return ctrl->ceiling_irq;
6364                         }
6365                 }
6366         }
6367
6368         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
6369                 rc = cpr3_regulator_init_ctrl_data(ctrl);
6370                 if (rc) {
6371                         cpr3_err(ctrl, "CPR controller data initialization failed, rc=%d\n",
6372                                  rc);
6373                         return rc;
6374                 }
6375         }
6376
6377         for (i = 0; i < ctrl->thread_count; i++) {
6378                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
6379                         rc = cpr3_regulator_init_vreg_data(
6380                                                 &ctrl->thread[i].vreg[j]);
6381                         if (rc)
6382                                 return rc;
6383                         cpr3_print_quots(&ctrl->thread[i].vreg[j]);
6384                 }
6385         }
6386
6387         /*
6388          * Add the maximum possible aging voltage margin until it is possible
6389          * to perform an aging measurement.
6390          */
6391         if (ctrl->aging_required)
6392                 cpr3_regulator_set_aging_ref_adjustment(ctrl, INT_MAX);
6393
6394         rc = cpr3_regulator_init_ctrl(ctrl);
6395         if (rc) {
6396                 cpr3_err(ctrl, "CPR controller initialization failed, rc=%d\n",
6397                         rc);
6398                 return rc;
6399         }
6400
6401         /* Register regulator devices for all threads. */
6402         for (i = 0; i < ctrl->thread_count; i++) {
6403                 for (j = 0; j < ctrl->thread[i].vreg_count; j++) {
6404                         rc = cpr3_regulator_vreg_register(
6405                                         &ctrl->thread[i].vreg[j]);
6406                         if (rc) {
6407                                 cpr3_err(&ctrl->thread[i].vreg[j], "failed to register regulator, rc=%d\n",
6408                                         rc);
6409                                 goto free_regulators;
6410                         }
6411                 }
6412         }
6413
6414         if (ctrl->ctrl_type != CPR_CTRL_TYPE_CPRH) {
6415                 rc = devm_request_threaded_irq(dev, ctrl->irq, NULL,
6416                                                cpr3_irq_handler,
6417                                                IRQF_ONESHOT |
6418                                                IRQF_TRIGGER_RISING,
6419                                                "cpr3", ctrl);
6420                 if (rc) {
6421                         cpr3_err(ctrl, "could not request IRQ %d, rc=%d\n",
6422                                  ctrl->irq, rc);
6423                         goto free_regulators;
6424                 }
6425         }
6426
6427         if (ctrl->supports_hw_closed_loop &&
6428             ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3) {
6429                 rc = devm_request_threaded_irq(dev, ctrl->ceiling_irq, NULL,
6430                         cpr3_ceiling_irq_handler,
6431                         IRQF_ONESHOT | IRQF_TRIGGER_RISING,
6432                         "cpr3_ceiling", ctrl);
6433                 if (rc) {
6434                         cpr3_err(ctrl, "could not request ceiling IRQ %d, rc=%d\n",
6435                                 ctrl->ceiling_irq, rc);
6436                         goto free_regulators;
6437                 }
6438         }
6439
6440         if (ctrl->irq && !cpumask_empty(&ctrl->irq_affinity_mask)) {
6441                 irq_set_affinity(ctrl->irq, &ctrl->irq_affinity_mask);
6442
6443                 ctrl->cpu_hotplug_notifier.notifier_call
6444                         = cpr3_regulator_cpu_hotplug_callback;
6445                 register_hotcpu_notifier(&ctrl->cpu_hotplug_notifier);
6446         }
6447
6448         mutex_lock(&cpr3_controller_list_mutex);
6449         cpr3_regulator_debugfs_ctrl_add(ctrl);
6450         list_add(&ctrl->list, &cpr3_controller_list);
6451         mutex_unlock(&cpr3_controller_list_mutex);
6452
6453         if (ctrl->panic_regs_info) {
6454                 /* Register panic notification call back */
6455                 ctrl->panic_notifier.notifier_call = cpr3_panic_callback;
6456                 atomic_notifier_chain_register(&panic_notifier_list,
6457                         &ctrl->panic_notifier);
6458         }
6459
6460         return 0;
6461
6462 free_regulators:
6463         for (i = 0; i < ctrl->thread_count; i++)
6464                 for (j = 0; j < ctrl->thread[i].vreg_count; j++)
6465                         if (!IS_ERR_OR_NULL(ctrl->thread[i].vreg[j].rdev))
6466                                 regulator_unregister(
6467                                         ctrl->thread[i].vreg[j].rdev);
6468         return rc;
6469 }
6470
6471 /**
6472  * cpr3_regulator_unregister() - unregister the regulators for a CPR3 controller
6473  *              and perform CPR hardware shutdown
6474  * @ctrl:               Pointer to the CPR3 controller
6475  *
6476  * Return: 0 on success, errno on failure
6477  */
6478 int cpr3_regulator_unregister(struct cpr3_controller *ctrl)
6479 {
6480         int i, j, rc = 0;
6481
6482         mutex_lock(&cpr3_controller_list_mutex);
6483         list_del(&ctrl->list);
6484         cpr3_regulator_debugfs_ctrl_remove(ctrl);
6485         mutex_unlock(&cpr3_controller_list_mutex);
6486
6487         if (ctrl->irq && !cpumask_empty(&ctrl->irq_affinity_mask))
6488                 unregister_hotcpu_notifier(&ctrl->cpu_hotplug_notifier);
6489
6490         if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR4) {
6491                 rc = cpr3_ctrl_clear_cpr4_config(ctrl);
6492                 if (rc)
6493                         cpr3_err(ctrl, "failed to clear CPR4 configuration,rc=%d\n",
6494                                 rc);
6495         }
6496
6497         cpr3_ctrl_loop_disable(ctrl);
6498
6499         cpr3_closed_loop_disable(ctrl);
6500
6501         if (ctrl->vdd_limit_regulator) {
6502                 regulator_disable(ctrl->vdd_limit_regulator);
6503
6504                 if (ctrl->ctrl_type == CPR_CTRL_TYPE_CPR3)
6505                         msm_spm_avs_disable_irq(0, MSM_SPM_AVS_IRQ_MAX);
6506         }
6507
6508         for (i = 0; i < ctrl->thread_count; i++)
6509                 for (j = 0; j < ctrl->thread[i].vreg_count; j++)
6510                         regulator_unregister(ctrl->thread[i].vreg[j].rdev);
6511
6512         if (ctrl->panic_notifier.notifier_call)
6513                 atomic_notifier_chain_unregister(&panic_notifier_list,
6514                         &ctrl->panic_notifier);
6515
6516         return 0;
6517 }