]> rtime.felk.cvut.cz Git - sojka/nv-tegra/linux-3.10.git/blob - drivers/mmc/host/sdhci-tegra.c
mmc: tegra: unlock mutex before returning
[sojka/nv-tegra/linux-3.10.git] / drivers / mmc / host / sdhci-tegra.c
1 /*
2  * Copyright (C) 2010 Google, Inc.
3  *
4  * Copyright (c) 2012-2014, NVIDIA CORPORATION.  All rights reserved.
5  *
6  * This software is licensed under the terms of the GNU General Public
7  * License version 2, as published by the Free Software Foundation, and
8  * may be copied, distributed, and modified under those terms.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  */
16
17 #include <linux/err.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/platform_device.h>
21 #include <linux/clk.h>
22 #include <linux/io.h>
23 #include <linux/of.h>
24 #include <linux/of_device.h>
25 #include <linux/of_gpio.h>
26 #include <linux/gpio.h>
27 #include <linux/slab.h>
28 #include <linux/mmc/card.h>
29 #include <linux/mmc/host.h>
30 #include <linux/module.h>
31 #include <linux/mmc/sd.h>
32 #include <linux/regulator/consumer.h>
33 #include <linux/delay.h>
34 #include <linux/pm_runtime.h>
35
36 #ifndef CONFIG_ARM64
37 #include <asm/gpio.h>
38 #endif
39 #include <linux/debugfs.h>
40 #include <linux/seq_file.h>
41 #include <linux/reboot.h>
42 #include <linux/devfreq.h>
43 #include <linux/clk/tegra.h>
44 #include <linux/tegra-soc.h>
45
46 #include <linux/platform_data/mmc-sdhci-tegra.h>
47 #include <mach/pinmux.h>
48 #include <mach/pm_domains.h>
49
50 #include "sdhci-pltfm.h"
51
52 #if 0
53 #define SDHCI_TEGRA_DBG(stuff...)       pr_info(stuff)
54 #else
55 #define SDHCI_TEGRA_DBG(stuff...)       do {} while (0)
56 #endif
57
58 #define SDHCI_VNDR_CLK_CTRL                             0x100
59 #define SDHCI_VNDR_CLK_CTRL_SDMMC_CLK                   0x1
60 #define SDHCI_VNDR_CLK_CTRL_PADPIPE_CLKEN_OVERRIDE      0x8
61 #define SDHCI_VNDR_CLK_CTRL_SPI_MODE_CLKEN_OVERRIDE     0x4
62 #define SDHCI_VNDR_CLK_CTRL_INPUT_IO_CLK                0x2
63 #define SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT             16
64 #define SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT            24
65 #define SDHCI_VNDR_CLK_CTRL_SDR50_TUNING                0x20
66 #define SDHCI_VNDR_CLK_CTRL_INTERNAL_CLK                0x2
67
68 #define SDHCI_VNDR_MISC_CTRL                            0x120
69 #define SDHCI_VNDR_MISC_CTRL_ENABLE_SDR104_SUPPORT      0x8
70 #define SDHCI_VNDR_MISC_CTRL_ENABLE_SDR50_SUPPORT       0x10
71 #define SDHCI_VNDR_MISC_CTRL_ENABLE_DDR50_SUPPORT       0x200
72 #define SDHCI_VNDR_MISC_CTRL_ENABLE_SD_3_0              0x20
73 #define SDHCI_VNDR_MISC_CTRL_INFINITE_ERASE_TIMEOUT     0x1
74 #define SDHCI_VNDR_MISC_CTRL_PIPE_STAGES_MASK           0x180
75 #define SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT      17
76
77 #define SDHCI_VNDR_PRESET_VAL0_0        0x1d4
78 #define SDCLK_FREQ_SEL_HS_SHIFT         20
79 #define SDCLK_FREQ_SEL_DEFAULT_SHIFT    10
80
81 #define SDHCI_VNDR_PRESET_VAL1_0        0x1d8
82 #define SDCLK_FREQ_SEL_SDR50_SHIFT      20
83 #define SDCLK_FREQ_SEL_SDR25_SHIFT      10
84
85 #define SDHCI_VNDR_PRESET_VAL2_0        0x1dc
86 #define SDCLK_FREQ_SEL_DDR50_SHIFT      10
87
88 #define SDMMC_SDMEMCOMPPADCTRL  0x1E0
89 #define SDMMC_SDMEMCOMPPADCTRL_VREF_SEL_MASK    0xF
90 #define SDMMC_SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD_MASK       0x80000000
91
92 #define SDMMC_AUTO_CAL_CONFIG   0x1E4
93 #define SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_START    0x80000000
94 #define SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_ENABLE   0x20000000
95 #define SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_PD_OFFSET_SHIFT  0x8
96
97 #define SDMMC_AUTO_CAL_STATUS   0x1EC
98 #define SDMMC_AUTO_CAL_STATUS_AUTO_CAL_ACTIVE   0x80000000
99 #define SDMMC_AUTO_CAL_STATUS_PULLDOWN_OFFSET   24
100 #define PULLUP_ADJUSTMENT_OFFSET        20
101
102 /* Erratum: Version register is invalid in HW */
103 #define NVQUIRK_FORCE_SDHCI_SPEC_200            BIT(0)
104 /* Erratum: Enable block gap interrupt detection */
105 #define NVQUIRK_ENABLE_BLOCK_GAP_DET            BIT(1)
106 /* Do not enable auto calibration if the platform doesn't support */
107 #define NVQUIRK_DISABLE_AUTO_CALIBRATION        BIT(2)
108 /* Set Calibration Offsets */
109 #define NVQUIRK_SET_CALIBRATION_OFFSETS         BIT(3)
110 /* Set Drive Strengths */
111 #define NVQUIRK_SET_DRIVE_STRENGTH              BIT(4)
112 /* Enable PADPIPE CLKEN */
113 #define NVQUIRK_ENABLE_PADPIPE_CLKEN            BIT(5)
114 /* DISABLE SPI_MODE CLKEN */
115 #define NVQUIRK_DISABLE_SPI_MODE_CLKEN          BIT(6)
116 /* Set tap delay */
117 #define NVQUIRK_SET_TAP_DELAY                   BIT(7)
118 /* Set trim delay */
119 #define NVQUIRK_SET_TRIM_DELAY                  BIT(8)
120 /* Enable SDHOST v3.0 support */
121 #define NVQUIRK_ENABLE_SD_3_0                   BIT(9)
122 /* Enable SDR50 mode */
123 #define NVQUIRK_ENABLE_SDR50                    BIT(10)
124 /* Enable SDR104 mode */
125 #define NVQUIRK_ENABLE_SDR104                   BIT(11)
126 /*Enable DDR50 mode */
127 #define NVQUIRK_ENABLE_DDR50                    BIT(12)
128 /* Enable Frequency Tuning for SDR50 mode */
129 #define NVQUIRK_ENABLE_SDR50_TUNING             BIT(13)
130 /* Enable HS200 mode */
131 #define NVQUIRK_ENABLE_HS200                    BIT(14)
132 /* Enable Infinite Erase Timeout*/
133 #define NVQUIRK_INFINITE_ERASE_TIMEOUT          BIT(15)
134 /* No Calibration for sdmmc4 */
135 #define NVQUIRK_DISABLE_SDMMC4_CALIB            BIT(16)
136 /* ENAABLE FEEDBACK IO CLOCK */
137 #define NVQUIRK_EN_FEEDBACK_CLK                 BIT(17)
138 /* Disable AUTO CMD23 */
139 #define NVQUIRK_DISABLE_AUTO_CMD23              BIT(18)
140 /* Shadow write xfer mode reg and write it alongwith CMD register */
141 #define NVQUIRK_SHADOW_XFER_MODE_REG            BIT(19)
142 /* update PAD_E_INPUT_OR_E_PWRD bit */
143 #define NVQUIRK_SET_PAD_E_INPUT_OR_E_PWRD       BIT(20)
144 /* Shadow write xfer mode reg and write it alongwith CMD register */
145 #define NVQUIRK_SET_PIPE_STAGES_MASK_0          BIT(21)
146 #define NVQUIRK_HIGH_FREQ_TAP_PROCEDURE         BIT(22)
147 /* Disable SDMMC3 external loopback */
148 #define NVQUIRK_DISABLE_EXTERNAL_LOOPBACK       BIT(23)
149 #define NVQUIRK_TMP_VAR_1_5_TAP_MARGIN          BIT(24)
150
151 /* Common subset of quirks for Tegra3 and later sdmmc controllers */
152 #define TEGRA_SDHCI_NVQUIRKS    (NVQUIRK_ENABLE_PADPIPE_CLKEN | \
153                   NVQUIRK_DISABLE_SPI_MODE_CLKEN | \
154                   NVQUIRK_EN_FEEDBACK_CLK | \
155                   NVQUIRK_SET_TAP_DELAY | \
156                   NVQUIRK_ENABLE_SDR50_TUNING | \
157                   NVQUIRK_ENABLE_SDR50 | \
158                   NVQUIRK_ENABLE_SDR104 | \
159                   NVQUIRK_SHADOW_XFER_MODE_REG | \
160                   NVQUIRK_DISABLE_AUTO_CMD23)
161
162 #define TEGRA_SDHCI_QUIRKS              (SDHCI_QUIRK_BROKEN_TIMEOUT_VAL | \
163                   SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK | \
164                   SDHCI_QUIRK_SINGLE_POWER_WRITE | \
165                   SDHCI_QUIRK_NO_HISPD_BIT | \
166                   SDHCI_QUIRK_BROKEN_ADMA_ZEROLEN_DESC | \
167                   SDHCI_QUIRK_BROKEN_CARD_DETECTION)
168
169 #define TEGRA_SDHCI_QUIRKS2     (SDHCI_QUIRK2_PRESET_VALUE_BROKEN | \
170                   SDHCI_QUIRK2_NON_STD_VOLTAGE_SWITCHING | \
171                   SDHCI_QUIRK2_NON_STANDARD_TUNING | \
172                   SDHCI_QUIRK2_NO_CALC_MAX_DISCARD_TO | \
173                   SDHCI_QUIRK2_REG_ACCESS_REQ_HOST_CLK)
174
175 #define IS_QUIRKS2_DELAYED_CLK_GATE(host) \
176                 (host->quirks2 & SDHCI_QUIRK2_DELAYED_CLK_GATE)
177
178 /* Interface voltages */
179 #define SDHOST_1V8_OCR_MASK     0x8
180 #define SDHOST_HIGH_VOLT_MIN    2700000
181 #define SDHOST_HIGH_VOLT_MAX    3600000
182 #define SDHOST_HIGH_VOLT_2V8    2800000
183 #define SDHOST_LOW_VOLT_MIN     1800000
184 #define SDHOST_LOW_VOLT_MAX     1800000
185 #define SDHOST_HIGH_VOLT_3V2    3200000
186 #define SDHOST_HIGH_VOLT_3V3    3300000
187
188 /* Clock related definitions */
189 #define MAX_DIVISOR_VALUE       128
190 #define DEFAULT_SDHOST_FREQ     50000000
191 #define SDMMC_AHB_MAX_FREQ      150000000
192 #define SDMMC_EMC_MAX_FREQ      150000000
193 #define SDMMC_EMC_NOM_VOLT_FREQ 900000000
194
195 /* Tuning related definitions */
196 #define MMC_TUNING_BLOCK_SIZE_BUS_WIDTH_8       128
197 #define MMC_TUNING_BLOCK_SIZE_BUS_WIDTH_4       64
198 #define MAX_TAP_VALUES  255
199 #define TUNING_FREQ_COUNT       3
200 #define TUNING_VOLTAGES_COUNT   3
201 #define TUNING_RETRIES  1
202 #define DFS_FREQ_COUNT  2
203 #define NEG_MAR_CHK_WIN_COUNT   2
204 /* Tuning core voltage requirements */
205 #define NOMINAL_VCORE_TUN       BIT(0)
206 #define BOOT_VCORE_TUN  BIT(1)
207 #define MIN_OVERRIDE_VCORE_TUN  BIT(2)
208
209 /* Tap cmd sysfs commands */
210 #define TAP_CMD_TRIM_DEFAULT_VOLTAGE    1
211 #define TAP_CMD_TRIM_HIGH_VOLTAGE       2
212
213 /*
214  * Defined the chip specific quirks and clock sources. For now, the used clock
215  * sources vary only from chip to chip. If the sources allowed varies from
216  * platform to platform, then move the clock sources list to platform data.
217  * When filling the tuning_freq_list in soc_data, the number of entries should
218  * be equal to TUNNG_FREQ_COUNT. Depending on number DFS frequencies supported,
219  * set the desired low, high or max frequencies and set the remaining entries
220  * as 0s. The number of entries should always be equal to TUNING_FREQ_COUNT
221  * inorder to get the right tuning data.
222  */
223 struct sdhci_tegra_soc_data {
224         const struct sdhci_pltfm_data *pdata;
225         u32 nvquirks;
226         const char *parent_clk_list[2];
227         unsigned int tuning_freq_list[TUNING_FREQ_COUNT];
228         u8 t2t_coeffs_count;
229         u8 tap_hole_coeffs_count;
230         struct tuning_t2t_coeffs *t2t_coeffs;
231         struct tap_hole_coeffs *tap_hole_coeffs;
232 };
233
234
235 enum tegra_regulator_config_ops {
236         CONFIG_REG_EN,
237         CONFIG_REG_DIS,
238         CONFIG_REG_SET_VOLT,
239 };
240
241 enum tegra_tuning_freq {
242         TUNING_LOW_FREQ,
243         TUNING_HIGH_FREQ,
244         TUNING_MAX_FREQ,
245 };
246
247 struct tuning_t2t_coeffs {
248         const char *dev_id;
249         int vmax;
250         int vmin;
251         unsigned int t2t_vnom_slope;
252         unsigned int t2t_vnom_int;
253         unsigned int t2t_vmax_slope;
254         unsigned int t2t_vmax_int;
255         unsigned int t2t_vmin_slope;
256         unsigned int t2t_vmin_int;
257 };
258
259 #define SET_TUNING_COEFFS(_device_id, _vmax, _vmin, _t2t_vnom_slope,    \
260         _t2t_vnom_int, _t2t_vmax_slope, _t2t_vmax_int, _t2t_vmin_slope, \
261         _t2t_vmin_int)  \
262         {                                               \
263                 .dev_id = _device_id,                   \
264                 .vmax = _vmax,                          \
265                 .vmin = _vmin,                          \
266                 .t2t_vnom_slope = _t2t_vnom_slope,      \
267                 .t2t_vnom_int = _t2t_vnom_int,          \
268                 .t2t_vmax_slope = _t2t_vmax_slope,      \
269                 .t2t_vmax_int = _t2t_vmax_int,          \
270                 .t2t_vmin_slope = _t2t_vmin_slope,      \
271                 .t2t_vmin_int = _t2t_vmin_int,          \
272         }
273
274 struct tuning_t2t_coeffs t11x_tuning_coeffs[] = {
275         SET_TUNING_COEFFS("sdhci-tegra.3",      1250,   950,    55,     135434,
276                 73,     170493, 243,    455948),
277         SET_TUNING_COEFFS("sdhci-tegra.2",      1250,   950,    50,     129738,
278                 73,     168898, 241,    453050),
279         SET_TUNING_COEFFS("sdhci-tegra.0",      1250,   950,    62,     143469,
280                 82,     180096, 238,    444285),
281 };
282
283 struct tuning_t2t_coeffs t12x_tuning_coeffs[] = {
284         SET_TUNING_COEFFS("sdhci-tegra.3",      1150,   950,    27,     118295,
285                 27,     118295, 48,     188148),
286         SET_TUNING_COEFFS("sdhci-tegra.2",      1150,   950,    29,     124427,
287                 29, 124427,      54,    203707),
288         SET_TUNING_COEFFS("sdhci-tegra.0",      1150,   950,    25,     115933,
289                 25,     115933, 47,     187224),
290 };
291
292 struct tap_hole_coeffs {
293         const char *dev_id;
294         unsigned int freq_khz;
295         unsigned int thole_vnom_slope;
296         unsigned int thole_vnom_int;
297         unsigned int thole_vmax_slope;
298         unsigned int thole_vmax_int;
299         unsigned int thole_vmin_slope;
300         unsigned int thole_vmin_int;
301 };
302
303 #define SET_TAP_HOLE_COEFFS(_device_id, _freq_khz, _thole_vnom_slope,   \
304         _thole_vnom_int, _thole_vmax_slope, _thole_vmax_int,    \
305         _thole_vmin_slope, _thole_vmin_int)     \
306         {                                       \
307                 .dev_id = _device_id,           \
308                 .freq_khz = _freq_khz,          \
309                 .thole_vnom_slope = _thole_vnom_slope,  \
310                 .thole_vnom_int = _thole_vnom_int,      \
311                 .thole_vmax_slope = _thole_vmax_slope,  \
312                 .thole_vmax_int = _thole_vmax_int,      \
313                 .thole_vmin_slope = _thole_vmin_slope,  \
314                 .thole_vmin_int = _thole_vmin_int,      \
315         }
316
317 struct tap_hole_coeffs t11x_tap_hole_coeffs[] = {
318         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    200000, 765,    102357, 507,
319                 81144,  131,    36346),
320         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    156000, 1042,   142044, 776,
321                 121659, 152,    48728),
322         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    136000, 1215,   167702, 905,
323                 143825, 207,    63477),
324         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    81600,  1925,   284516, 1528,
325                 253188, 366,    120001),
326         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    204000, 472,    53312,  318,
327                 41756,  84,     15496),
328         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    156000, 765,    95512,  526,
329                 77404,  134,    33032),
330         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    136000, 949,    121887, 656,
331                 99684,  165,    43992),
332         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    81600,  1901,   259035, 1334,
333                 215539, 326,    100986),
334         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    204000, 411,    54495,  305,
335                 46415,  91,     20366),
336         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    156000, 715,    97623,  516,
337                 82375,  145,    38278),
338         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    136000, 905,    124579, 648,
339                 104850, 179,    50204),
340         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    81600,  1893,   264746, 1333,
341                 221722, 354,    109880),
342 };
343
344 struct tap_hole_coeffs t12x_tap_hole_coeffs[] = {
345         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    200000, 1037,   106934, 1037,
346                 106934, 558,    74315),
347         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    136000, 1703,   186307, 1703,
348                 186307, 890,    130617),
349         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    100000, 2452,   275601, 2452,
350                 275601, 1264,   193957),
351         SET_TAP_HOLE_COEFFS("sdhci-tegra.3",    81600,  3090,   351666, 3090,
352                 351666, 1583,   247913),
353         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    204000, 468,    36031,  468,
354                 36031,  253,    21264),
355         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    136000, 1146,   117841, 1146,
356                 117841, 589,    78993),
357         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    100000, 1879,   206195, 1879,
358                 206195, 953,    141341),
359         SET_TAP_HOLE_COEFFS("sdhci-tegra.2",    81600,  2504,   281460, 2504,
360                 281460, 1262,   194452),
361         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    204000, 874,    85243,  874,
362                 85243,  449,    57321),
363         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    136000, 1554,   167210, 1554,
364                 167210, 793,    115672),
365         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    100000, 2290,   255734, 2290,
366                 255734, 1164,   178691),
367         SET_TAP_HOLE_COEFFS("sdhci-tegra.0",    81600,  2916,   331143, 2916,
368                 331143, 1480,   232373),
369 };
370
371 struct freq_tuning_constraints {
372         unsigned int vcore_mask;
373 };
374
375 static struct freq_tuning_constraints tuning_vcore_constraints[3] = {
376         [0] = {
377                 .vcore_mask = BOOT_VCORE_TUN,
378         },
379         [1] = {
380                 .vcore_mask = BOOT_VCORE_TUN,
381         },
382         [2] = {
383                 .vcore_mask = BOOT_VCORE_TUN,
384         },
385 };
386
387 struct tuning_ui {
388         int ui;
389         bool is_valid_ui;
390 };
391
392 enum tap_win_edge_attr {
393         WIN_EDGE_BOUN_START,
394         WIN_EDGE_BOUN_END,
395         WIN_EDGE_HOLE,
396 };
397
398 struct tap_window_data {
399         int win_start;
400         int win_end;
401         enum tap_win_edge_attr win_start_attr;
402         enum tap_win_edge_attr win_end_attr;
403         u8 win_size;
404         u8 hole_pos;
405 };
406
407 struct tuning_values {
408         int t2t_vmax;
409         int t2t_vmin;
410         int ui;
411         int ui_vmin;
412         int vmax_thole;
413         int vmin_thole;
414 };
415 struct tegra_tuning_data {
416         unsigned int freq_hz;
417         int best_tap_value;
418         int nom_best_tap_value;
419         struct freq_tuning_constraints constraints;
420         struct tap_hole_coeffs *thole_coeffs;
421         struct tuning_t2t_coeffs *t2t_coeffs;
422         struct tuning_values est_values;
423         struct tuning_values calc_values;
424         struct tap_window_data *tap_data;
425         struct tap_window_data *final_tap_data;
426         u8 num_of_valid_tap_wins;
427         u8 nr_voltages;
428         u8 freq_band;
429         bool tuning_done;
430         bool is_partial_win_valid;
431 };
432
433 #ifdef CONFIG_MMC_FREQ_SCALING
434 struct freq_gov_params {
435         u8      idle_mon_cycles;
436         u8      polling_interval_ms;
437         u8      active_load_threshold;
438 };
439
440 static struct freq_gov_params gov_params[3] = {
441         [MMC_TYPE_MMC] = {
442                 .idle_mon_cycles = 3,
443                 .polling_interval_ms = 50,
444                 .active_load_threshold = 25,
445         },
446         [MMC_TYPE_SDIO] = {
447                 .idle_mon_cycles = 3,
448                 .polling_interval_ms = 50,
449                 .active_load_threshold = 25,
450         },
451         [MMC_TYPE_SD] = {
452                 .idle_mon_cycles = 3,
453                 .polling_interval_ms = 50,
454                 .active_load_threshold = 25,
455         },
456 };
457 #endif
458
459 struct tegra_freq_gov_data {
460         unsigned int            curr_active_load;
461         unsigned int            avg_active_load;
462         unsigned int            act_load_high_threshold;
463         unsigned int            max_idle_monitor_cycles;
464         unsigned int            curr_freq;
465         unsigned int            freqs[DFS_FREQ_COUNT];
466         unsigned int            freq_switch_count;
467         bool                    monitor_idle_load;
468 };
469
470 struct sdhci_tegra_sd_stats {
471         unsigned int data_crc_count;
472         unsigned int cmd_crc_count;
473         unsigned int data_to_count;
474         unsigned int cmd_to_count;
475 };
476
477 #ifdef CONFIG_DEBUG_FS
478 struct dbg_cfg_data {
479         unsigned int            tap_val;
480         unsigned int            trim_val;
481         bool                    clk_ungated;
482 };
483 #endif
484 struct sdhci_tegra {
485         const struct tegra_sdhci_platform_data *plat;
486         const struct sdhci_tegra_soc_data *soc_data;
487         bool    clk_enabled;
488         /* ensure atomic set clock calls */
489         struct mutex            set_clock_mutex;
490         struct regulator *vdd_io_reg;
491         struct regulator *vdd_slot_reg;
492         struct regulator *vcore_reg;
493         /* Host controller instance */
494         unsigned int instance;
495         /* vddio_min */
496         unsigned int vddio_min_uv;
497         /* vddio_max */
498         unsigned int vddio_max_uv;
499         /* DDR and low speed modes clock */
500         struct clk *ddr_clk;
501         /* HS200, SDR104 modes clock */
502         struct clk *sdr_clk;
503         /* Check if ddr_clk is being used */
504         bool is_ddr_clk_set;
505         /* max clk supported by the platform */
506         unsigned int max_clk_limit;
507         /* max ddr clk supported by the platform */
508         unsigned int ddr_clk_limit;
509         bool card_present;
510         bool is_rail_enabled;
511         struct clk *emc_clk;
512         bool is_sdmmc_emc_clk_on;
513         struct clk *sclk;
514         bool is_sdmmc_sclk_on;
515         struct sdhci_tegra_sd_stats *sd_stat_head;
516         struct notifier_block reboot_notify;
517         bool is_parent_pllc;
518         bool set_1v8_calib_offsets;
519         int nominal_vcore_mv;
520         int min_vcore_override_mv;
521         int boot_vcore_mv;
522         /* Tuning related structures and variables */
523         /* Tuning opcode to be used */
524         unsigned int tuning_opcode;
525         /* Tuning packet size */
526         unsigned int tuning_bsize;
527         /* Num of tuning freqs selected */
528         int tuning_freq_count;
529         unsigned int tap_cmd;
530         /* Tuning status */
531         unsigned int tuning_status;
532         bool force_retune;
533 #define TUNING_STATUS_DONE      1
534 #define TUNING_STATUS_RETUNE    2
535         /* Freq tuning information for each sampling clock freq */
536         struct tegra_tuning_data tuning_data[DFS_FREQ_COUNT];
537         struct tegra_freq_gov_data *gov_data;
538         u32 speedo;
539 #ifdef CONFIG_DEBUG_FS
540         /* Override debug config data */
541         struct dbg_cfg_data dbg_cfg;
542 #endif
543 };
544
545 static struct clk *pll_c;
546 static struct clk *pll_p;
547 static unsigned long pll_c_rate;
548 static unsigned long pll_p_rate;
549 static bool vcore_overrides_allowed;
550 static bool maintain_boot_voltage;
551 static unsigned int boot_volt_req_refcount;
552 DEFINE_MUTEX(tuning_mutex);
553
554 static struct tegra_tuning_data *sdhci_tegra_get_tuning_data(
555         struct sdhci_host *sdhci, unsigned int clock);
556 static unsigned long get_nearest_clock_freq(unsigned long pll_rate,
557                 unsigned long desired_rate);
558 static void sdhci_tegra_set_tap_delay(struct sdhci_host *sdhci,
559         unsigned int tap_delay);
560 static int tegra_sdhci_configure_regulators(struct sdhci_tegra *tegra_host,
561         u8 option, int min_uV, int max_uV);
562 static void sdhci_tegra_set_trim_delay(struct sdhci_host *sdhci,
563         unsigned int trim_delay);
564 static void tegra_sdhci_do_calibration(struct sdhci_host *sdhci,
565         unsigned char signal_voltage);
566
567 static int show_error_stats_dump(struct seq_file *s, void *data)
568 {
569         struct sdhci_host *host = s->private;
570         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
571         struct sdhci_tegra *tegra_host = pltfm_host->priv;
572         struct sdhci_tegra_sd_stats *head;
573
574         seq_printf(s, "ErrorStatistics:\n");
575         seq_printf(s, "DataCRC\tCmdCRC\tDataTimeout\tCmdTimeout\n");
576         head = tegra_host->sd_stat_head;
577         if (head != NULL)
578                 seq_printf(s, "%d\t%d\t%d\t%d\n", head->data_crc_count,
579                         head->cmd_crc_count, head->data_to_count,
580                         head->cmd_to_count);
581         return 0;
582 }
583
584 static int show_dfs_stats_dump(struct seq_file *s, void *data)
585 {
586         struct sdhci_host *host = s->private;
587         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
588         struct sdhci_tegra *tegra_host = pltfm_host->priv;
589         struct tegra_freq_gov_data *gov_data = tegra_host->gov_data;
590
591         seq_printf(s, "DFS statistics:\n");
592
593         if (host->mmc->dev_stats != NULL)
594                 seq_printf(s, "Polling_period: %d\n",
595                         host->mmc->dev_stats->polling_interval);
596
597         if (gov_data != NULL) {
598                 seq_printf(s, "cur_active_load: %d\n",
599                         gov_data->curr_active_load);
600                 seq_printf(s, "avg_active_load: %d\n",
601                         gov_data->avg_active_load);
602                 seq_printf(s, "act_load_high_threshold: %d\n",
603                         gov_data->act_load_high_threshold);
604                 seq_printf(s, "freq_switch_count: %d\n",
605                         gov_data->freq_switch_count);
606         }
607         return 0;
608 }
609
610 static int sdhci_error_stats_dump(struct inode *inode, struct file *file)
611 {
612         return single_open(file, show_error_stats_dump, inode->i_private);
613 }
614
615 static int sdhci_dfs_stats_dump(struct inode *inode, struct file *file)
616 {
617         return single_open(file, show_dfs_stats_dump, inode->i_private);
618 }
619
620
621 static const struct file_operations sdhci_host_fops = {
622         .open           = sdhci_error_stats_dump,
623         .read           = seq_read,
624         .llseek         = seq_lseek,
625         .release        = single_release,
626 };
627
628 static const struct file_operations sdhci_host_dfs_fops = {
629         .open           = sdhci_dfs_stats_dump,
630         .read           = seq_read,
631         .llseek         = seq_lseek,
632         .release        = single_release,
633 };
634
635 static u32 tegra_sdhci_readl(struct sdhci_host *host, int reg)
636 {
637         u32 val;
638
639         if (unlikely(reg == SDHCI_PRESENT_STATE)) {
640                 /* Use wp_gpio here instead? */
641                 val = readl(host->ioaddr + reg);
642                 return val | SDHCI_WRITE_PROTECT;
643         }
644         return readl(host->ioaddr + reg);
645 }
646
647 static u16 tegra_sdhci_readw(struct sdhci_host *host, int reg)
648 {
649         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
650         struct sdhci_tegra *tegra_host = pltfm_host->priv;
651         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
652
653         if (unlikely((soc_data->nvquirks & NVQUIRK_FORCE_SDHCI_SPEC_200) &&
654                         (reg == SDHCI_HOST_VERSION))) {
655                 return SDHCI_SPEC_200;
656         }
657         return readw(host->ioaddr + reg);
658 }
659
660 static void tegra_sdhci_writel(struct sdhci_host *host, u32 val, int reg)
661 {
662         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
663         struct sdhci_tegra *tegra_host = pltfm_host->priv;
664         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
665
666         /* Seems like we're getting spurious timeout and crc errors, so
667          * disable signalling of them. In case of real errors software
668          * timers should take care of eventually detecting them.
669          */
670         if (unlikely(reg == SDHCI_SIGNAL_ENABLE))
671                 val &= ~(SDHCI_INT_TIMEOUT|SDHCI_INT_CRC);
672
673         writel(val, host->ioaddr + reg);
674
675         if (unlikely((soc_data->nvquirks & NVQUIRK_ENABLE_BLOCK_GAP_DET) &&
676                         (reg == SDHCI_INT_ENABLE))) {
677                 u8 gap_ctrl = readb(host->ioaddr + SDHCI_BLOCK_GAP_CONTROL);
678                 if (val & SDHCI_INT_CARD_INT)
679                         gap_ctrl |= 0x8;
680                 else
681                         gap_ctrl &= ~0x8;
682                 writeb(gap_ctrl, host->ioaddr + SDHCI_BLOCK_GAP_CONTROL);
683         }
684 }
685
686 static void tegra_sdhci_writew(struct sdhci_host *host, u16 val, int reg)
687 {
688         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
689         struct sdhci_tegra *tegra_host = pltfm_host->priv;
690         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
691
692         if (soc_data->nvquirks & NVQUIRK_SHADOW_XFER_MODE_REG) {
693                 switch (reg) {
694                 case SDHCI_TRANSFER_MODE:
695                         /*
696                          * Postpone this write, we must do it together with a
697                          * command write that is down below.
698                          */
699                         pltfm_host->xfer_mode_shadow = val;
700                         return;
701                 case SDHCI_COMMAND:
702                         writel((val << 16) | pltfm_host->xfer_mode_shadow,
703                                 host->ioaddr + SDHCI_TRANSFER_MODE);
704                         pltfm_host->xfer_mode_shadow = 0;
705                         return;
706                 }
707         }
708
709         writew(val, host->ioaddr + reg);
710 }
711
712 #ifdef CONFIG_MMC_FREQ_SCALING
713
714 static bool disable_scaling __read_mostly;
715 module_param(disable_scaling, bool, 0644);
716
717 /*
718  * Dynamic frequency calculation.
719  * The active load for the current period and the average active load
720  * are calculated at the end of each polling interval.
721  *
722  * If the current active load is greater than the threshold load, then the
723  * frequency is boosted(156MHz).
724  * If the active load is lower than the threshold, then the load is monitored
725  * for a max of three cycles before reducing the frequency(82MHz). If the
726  * average active load is lower, then the monitoring cycles is reduced.
727  *
728  * The active load threshold value for both eMMC and SDIO is set to 25 which
729  * is found to give the optimal power and performance. The polling interval is
730  * set to 50 msec.
731  *
732  * The polling interval and active load threshold values can be changed by
733  * the user through sysfs.
734 */
735 static unsigned long calculate_mmc_target_freq(
736         struct tegra_freq_gov_data *gov_data)
737 {
738         unsigned long desired_freq = gov_data->curr_freq;
739         unsigned int type = MMC_TYPE_MMC;
740
741         if (gov_data->curr_active_load >= gov_data->act_load_high_threshold) {
742                 desired_freq = gov_data->freqs[TUNING_HIGH_FREQ];
743                 gov_data->monitor_idle_load = false;
744                 gov_data->max_idle_monitor_cycles =
745                         gov_params[type].idle_mon_cycles;
746         } else {
747                 if (gov_data->monitor_idle_load) {
748                         if (!gov_data->max_idle_monitor_cycles) {
749                                 desired_freq = gov_data->freqs[TUNING_LOW_FREQ];
750                                 gov_data->max_idle_monitor_cycles =
751                                         gov_params[type].idle_mon_cycles;
752                         } else {
753                                 gov_data->max_idle_monitor_cycles--;
754                         }
755                 } else {
756                         gov_data->monitor_idle_load = true;
757                         gov_data->max_idle_monitor_cycles *=
758                                 gov_data->avg_active_load;
759                         gov_data->max_idle_monitor_cycles /= 100;
760                 }
761         }
762
763         return desired_freq;
764 }
765
766 static unsigned long calculate_sdio_target_freq(
767         struct tegra_freq_gov_data *gov_data)
768 {
769         unsigned long desired_freq = gov_data->curr_freq;
770         unsigned int type = MMC_TYPE_SDIO;
771
772         if (gov_data->curr_active_load >= gov_data->act_load_high_threshold) {
773                 desired_freq = gov_data->freqs[TUNING_HIGH_FREQ];
774                 gov_data->monitor_idle_load = false;
775                 gov_data->max_idle_monitor_cycles =
776                         gov_params[type].idle_mon_cycles;
777         } else {
778                 if (gov_data->monitor_idle_load) {
779                         if (!gov_data->max_idle_monitor_cycles) {
780                                 desired_freq = gov_data->freqs[TUNING_LOW_FREQ];
781                                 gov_data->max_idle_monitor_cycles =
782                                         gov_params[type].idle_mon_cycles;
783                         } else {
784                                 gov_data->max_idle_monitor_cycles--;
785                         }
786                 } else {
787                         gov_data->monitor_idle_load = true;
788                         gov_data->max_idle_monitor_cycles *=
789                                 gov_data->avg_active_load;
790                         gov_data->max_idle_monitor_cycles /= 100;
791                 }
792         }
793
794         return desired_freq;
795 }
796
797 static unsigned long calculate_sd_target_freq(
798         struct tegra_freq_gov_data *gov_data)
799 {
800         unsigned long desired_freq = gov_data->curr_freq;
801         unsigned int type = MMC_TYPE_SD;
802
803         if (gov_data->curr_active_load >= gov_data->act_load_high_threshold) {
804                 desired_freq = gov_data->freqs[TUNING_HIGH_FREQ];
805                 gov_data->monitor_idle_load = false;
806                 gov_data->max_idle_monitor_cycles =
807                         gov_params[type].idle_mon_cycles;
808         } else {
809                 if (gov_data->monitor_idle_load) {
810                         if (!gov_data->max_idle_monitor_cycles) {
811                                 desired_freq = gov_data->freqs[TUNING_LOW_FREQ];
812                                 gov_data->max_idle_monitor_cycles =
813                                         gov_params[type].idle_mon_cycles;
814                         } else {
815                                 gov_data->max_idle_monitor_cycles--;
816                         }
817                 } else {
818                         gov_data->monitor_idle_load = true;
819                         gov_data->max_idle_monitor_cycles *=
820                                 gov_data->avg_active_load;
821                         gov_data->max_idle_monitor_cycles /= 100;
822                 }
823         }
824
825         return desired_freq;
826 }
827
828 static unsigned long sdhci_tegra_get_target_freq(struct sdhci_host *sdhci,
829         struct devfreq_dev_status *dfs_stats)
830 {
831         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
832         struct sdhci_tegra *tegra_host = pltfm_host->priv;
833         struct tegra_freq_gov_data *gov_data = tegra_host->gov_data;
834         unsigned long freq = sdhci->mmc->actual_clock;
835
836         if (!gov_data) {
837                 dev_err(mmc_dev(sdhci->mmc),
838                         "No gov data. Continue using current freq %ld", freq);
839                 return freq;
840         }
841
842         if (disable_scaling)
843                 return freq;
844
845         /*
846          * If clock gating is enabled and clock is currently disabled, then
847          * return freq as 0.
848          */
849         if (!tegra_host->clk_enabled)
850                 return 0;
851
852         if (dfs_stats->total_time) {
853                 gov_data->curr_active_load = (dfs_stats->busy_time * 100) /
854                         dfs_stats->total_time;
855         } else {
856                 gov_data->curr_active_load = 0;
857         }
858
859         gov_data->avg_active_load += gov_data->curr_active_load;
860         gov_data->avg_active_load >>= 1;
861
862         if (sdhci->mmc->card) {
863                 if (sdhci->mmc->card->type == MMC_TYPE_SDIO)
864                         freq = calculate_sdio_target_freq(gov_data);
865                 else if (sdhci->mmc->card->type == MMC_TYPE_MMC)
866                         freq = calculate_mmc_target_freq(gov_data);
867                 else if (sdhci->mmc->card->type == MMC_TYPE_SD)
868                         freq = calculate_sd_target_freq(gov_data);
869                 if (gov_data->curr_freq != freq)
870                         gov_data->freq_switch_count++;
871                 gov_data->curr_freq = freq;
872         }
873
874         return freq;
875 }
876
877 static int sdhci_tegra_freq_gov_init(struct sdhci_host *sdhci)
878 {
879         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
880         struct sdhci_tegra *tegra_host = pltfm_host->priv;
881         unsigned int i;
882         unsigned int freq;
883         unsigned int type;
884
885         if (!((sdhci->mmc->ios.timing == MMC_TIMING_UHS_SDR104) ||
886                 (sdhci->mmc->ios.timing == MMC_TIMING_MMC_HS200))) {
887                 dev_info(mmc_dev(sdhci->mmc),
888                         "DFS not required for current operating mode\n");
889                 return -EACCES;
890         }
891
892         if (!tegra_host->gov_data) {
893                 tegra_host->gov_data = devm_kzalloc(mmc_dev(sdhci->mmc),
894                         sizeof(struct tegra_freq_gov_data), GFP_KERNEL);
895                 if (!tegra_host->gov_data) {
896                         dev_err(mmc_dev(sdhci->mmc),
897                                 "Failed to allocate memory for dfs data\n");
898                         return -ENOMEM;
899                 }
900         }
901
902         /* Find the supported frequencies */
903         dev_info(mmc_dev(sdhci->mmc), "DFS supported freqs");
904         for (i = 0; i < tegra_host->tuning_freq_count; i++) {
905                 freq = tegra_host->tuning_data[i].freq_hz;
906                 /*
907                  * Check the nearest possible clock with pll_c and pll_p as
908                  * the clock sources. Choose the higher frequency.
909                  */
910                 tegra_host->gov_data->freqs[i] =
911                         get_nearest_clock_freq(pll_c_rate, freq);
912                 freq = get_nearest_clock_freq(pll_p_rate, freq);
913                 if (freq > tegra_host->gov_data->freqs[i])
914                         tegra_host->gov_data->freqs[i] = freq;
915                 pr_err("%d,", tegra_host->gov_data->freqs[i]);
916         }
917
918         tegra_host->gov_data->monitor_idle_load = false;
919         tegra_host->gov_data->curr_freq = sdhci->mmc->actual_clock;
920         if (sdhci->mmc->card) {
921                 type = sdhci->mmc->card->type;
922                 sdhci->mmc->dev_stats->polling_interval =
923                         gov_params[type].polling_interval_ms;
924                 tegra_host->gov_data->act_load_high_threshold =
925                         gov_params[type].active_load_threshold;
926                 tegra_host->gov_data->max_idle_monitor_cycles =
927                         gov_params[type].idle_mon_cycles;
928         }
929
930         return 0;
931 }
932
933 #endif
934
935 static unsigned int tegra_sdhci_get_cd(struct sdhci_host *sdhci)
936 {
937         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
938         struct sdhci_tegra *tegra_host = pltfm_host->priv;
939
940         return tegra_host->card_present;
941 }
942
943 static unsigned int tegra_sdhci_get_ro(struct sdhci_host *sdhci)
944 {
945         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
946         struct sdhci_tegra *tegra_host = pltfm_host->priv;
947         const struct tegra_sdhci_platform_data *plat = tegra_host->plat;
948
949         if (!gpio_is_valid(plat->wp_gpio))
950                 return -1;
951
952         return gpio_get_value_cansleep(plat->wp_gpio);
953 }
954
955 static int tegra_sdhci_set_uhs_signaling(struct sdhci_host *host,
956                 unsigned int uhs)
957 {
958         u16 clk, ctrl_2;
959         u32 vndr_ctrl, trim_delay, best_tap_value;
960         struct tegra_tuning_data *tuning_data;
961         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
962         struct sdhci_tegra *tegra_host = pltfm_host->priv;
963         const struct tegra_sdhci_platform_data *plat = tegra_host->plat;
964
965         ctrl_2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
966
967         /* Select Bus Speed Mode for host
968          * For HS200 we need to set UHS_MODE_SEL to SDR104.
969          * It works as SDR 104 in SD 4-bit mode and HS200 in eMMC 8-bit mode.
970          * SDR50 mode timing seems to have issues. Programming SDR104
971          * mode for SDR50 mode for reliable transfers over interface.
972          */
973         ctrl_2 &= ~SDHCI_CTRL_UHS_MASK;
974         switch (uhs) {
975         case MMC_TIMING_UHS_SDR12:
976                 ctrl_2 |= SDHCI_CTRL_UHS_SDR12;
977                 break;
978         case MMC_TIMING_UHS_SDR25:
979                 ctrl_2 |= SDHCI_CTRL_UHS_SDR25;
980                 break;
981         case MMC_TIMING_UHS_SDR50:
982                 ctrl_2 |= SDHCI_CTRL_UHS_SDR104;
983                 break;
984         case MMC_TIMING_UHS_SDR104:
985         case MMC_TIMING_MMC_HS200:
986                 ctrl_2 |= SDHCI_CTRL_UHS_SDR104;
987                 break;
988         case MMC_TIMING_UHS_DDR50:
989                 ctrl_2 |= SDHCI_CTRL_UHS_DDR50;
990                 break;
991         }
992
993         sdhci_writew(host, ctrl_2, SDHCI_HOST_CONTROL2);
994
995         if (uhs == MMC_TIMING_UHS_DDR50) {
996                 clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
997                 clk &= ~(0xFF << SDHCI_DIVIDER_SHIFT);
998                 clk |= 1 << SDHCI_DIVIDER_SHIFT;
999                 sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1000
1001                 /* Set the ddr mode trim delay if required */
1002                 if (plat->ddr_trim_delay != -1) {
1003                         trim_delay = plat->ddr_trim_delay;
1004                         vndr_ctrl = sdhci_readl(host, SDHCI_VNDR_CLK_CTRL);
1005                         vndr_ctrl &= ~(0x1F <<
1006                                 SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1007                         vndr_ctrl |= (trim_delay <<
1008                                 SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1009                         sdhci_writel(host, vndr_ctrl, SDHCI_VNDR_CLK_CTRL);
1010                 }
1011         }
1012         /* Set the best tap value based on timing */
1013         if (((uhs == MMC_TIMING_MMC_HS200) ||
1014                 (uhs == MMC_TIMING_UHS_SDR104) ||
1015                 (uhs == MMC_TIMING_UHS_SDR50)) &&
1016                 (tegra_host->tuning_status == TUNING_STATUS_DONE)) {
1017                 tuning_data = sdhci_tegra_get_tuning_data(host,
1018                         host->mmc->ios.clock);
1019                 best_tap_value = (tegra_host->tap_cmd ==
1020                         TAP_CMD_TRIM_HIGH_VOLTAGE) ?
1021                         tuning_data->nom_best_tap_value :
1022                         tuning_data->best_tap_value;
1023         } else {
1024                 best_tap_value = tegra_host->plat->tap_delay;
1025         }
1026         vndr_ctrl = sdhci_readl(host, SDHCI_VNDR_CLK_CTRL);
1027         vndr_ctrl &= ~(0xFF <<
1028                 SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1029         vndr_ctrl |= (best_tap_value <<
1030                 SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1031         sdhci_writel(host, vndr_ctrl, SDHCI_VNDR_CLK_CTRL);
1032         return 0;
1033 }
1034
1035 static void sdhci_status_notify_cb(int card_present, void *dev_id)
1036 {
1037         struct sdhci_host *sdhci = (struct sdhci_host *)dev_id;
1038         struct platform_device *pdev = to_platform_device(mmc_dev(sdhci->mmc));
1039         struct tegra_sdhci_platform_data *plat;
1040         unsigned int status, oldstat;
1041
1042         pr_debug("%s: card_present %d\n", mmc_hostname(sdhci->mmc),
1043                 card_present);
1044
1045         plat = pdev->dev.platform_data;
1046         if (!plat->mmc_data.status) {
1047                 if (card_present == 1) {
1048                         sdhci->mmc->rescan_disable = 0;
1049                         mmc_detect_change(sdhci->mmc, 0);
1050                 } else if (card_present == 0) {
1051                         sdhci->mmc->detect_change = 0;
1052                         sdhci->mmc->rescan_disable = 1;
1053                 }
1054                 return;
1055         }
1056
1057         status = plat->mmc_data.status(mmc_dev(sdhci->mmc));
1058
1059         oldstat = plat->mmc_data.card_present;
1060         plat->mmc_data.card_present = status;
1061         if (status ^ oldstat) {
1062                 pr_debug("%s: Slot status change detected (%d -> %d)\n",
1063                         mmc_hostname(sdhci->mmc), oldstat, status);
1064                 if (status && !plat->mmc_data.built_in)
1065                         mmc_detect_change(sdhci->mmc, (5 * HZ) / 2);
1066                 else
1067                         mmc_detect_change(sdhci->mmc, 0);
1068         }
1069 }
1070
1071 static irqreturn_t carddetect_irq(int irq, void *data)
1072 {
1073         struct sdhci_host *sdhost = (struct sdhci_host *)data;
1074         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhost);
1075         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1076         struct platform_device *pdev = to_platform_device(mmc_dev(sdhost->mmc));
1077         struct tegra_sdhci_platform_data *plat;
1078         int err;
1079
1080         plat = pdev->dev.platform_data;
1081
1082         tegra_host->card_present =
1083                         (gpio_get_value_cansleep(plat->cd_gpio) == 0);
1084
1085         if (tegra_host->card_present) {
1086                 err = tegra_sdhci_configure_regulators(tegra_host,
1087                         CONFIG_REG_EN, 0, 0);
1088                 if (err)
1089                         dev_err(mmc_dev(sdhost->mmc),
1090                                 "Failed to enable card regulators %d\n", err);
1091         } else {
1092                 err = tegra_sdhci_configure_regulators(tegra_host,
1093                         CONFIG_REG_DIS, 0 , 0);
1094                 if (err)
1095                         dev_err(mmc_dev(sdhost->mmc),
1096                                 "Failed to disable card regulators %d\n", err);
1097                 /*
1098                  * Set retune request as tuning should be done next time
1099                  * a card is inserted.
1100                  */
1101                 tegra_host->tuning_status = TUNING_STATUS_RETUNE;
1102                 tegra_host->force_retune = true;
1103         }
1104
1105         tasklet_schedule(&sdhost->card_tasklet);
1106         return IRQ_HANDLED;
1107 };
1108
1109 static void tegra_sdhci_reset_exit(struct sdhci_host *host, u8 mask)
1110 {
1111         u32 misc_ctrl;
1112         u32 vendor_ctrl;
1113         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
1114         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1115         struct tegra_tuning_data *tuning_data;
1116         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
1117         const struct tegra_sdhci_platform_data *plat = tegra_host->plat;
1118         unsigned int best_tap_value;
1119
1120         if (!(mask & SDHCI_RESET_ALL))
1121                 return;
1122
1123         if (tegra_host->sd_stat_head != NULL) {
1124                 tegra_host->sd_stat_head->data_crc_count = 0;
1125                 tegra_host->sd_stat_head->cmd_crc_count = 0;
1126                 tegra_host->sd_stat_head->data_to_count = 0;
1127                 tegra_host->sd_stat_head->cmd_to_count = 0;
1128         }
1129
1130         if (tegra_host->gov_data != NULL)
1131                 tegra_host->gov_data->freq_switch_count = 0;
1132
1133         vendor_ctrl = sdhci_readl(host, SDHCI_VNDR_CLK_CTRL);
1134         if (soc_data->nvquirks & NVQUIRK_ENABLE_PADPIPE_CLKEN) {
1135                 vendor_ctrl |=
1136                         SDHCI_VNDR_CLK_CTRL_PADPIPE_CLKEN_OVERRIDE;
1137         }
1138         if (soc_data->nvquirks & NVQUIRK_DISABLE_SPI_MODE_CLKEN) {
1139                 vendor_ctrl &=
1140                         ~SDHCI_VNDR_CLK_CTRL_SPI_MODE_CLKEN_OVERRIDE;
1141         }
1142         if (soc_data->nvquirks & NVQUIRK_EN_FEEDBACK_CLK) {
1143                 vendor_ctrl &=
1144                         ~SDHCI_VNDR_CLK_CTRL_INPUT_IO_CLK;
1145         } else {
1146                 vendor_ctrl |= SDHCI_VNDR_CLK_CTRL_INTERNAL_CLK;
1147         }
1148
1149         if (soc_data->nvquirks & NVQUIRK_SET_TAP_DELAY) {
1150                 if ((tegra_host->tuning_status == TUNING_STATUS_DONE)
1151                         && (host->mmc->pm_flags & MMC_PM_KEEP_POWER)) {
1152                         tuning_data = sdhci_tegra_get_tuning_data(host,
1153                                 host->mmc->ios.clock);
1154                         best_tap_value = (tegra_host->tap_cmd ==
1155                                 TAP_CMD_TRIM_HIGH_VOLTAGE) ?
1156                                 tuning_data->nom_best_tap_value :
1157                                 tuning_data->best_tap_value;
1158                 } else {
1159                         best_tap_value = tegra_host->plat->tap_delay;
1160                 }
1161                 vendor_ctrl &= ~(0xFF << SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1162                 vendor_ctrl |= (best_tap_value <<
1163                         SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1164         }
1165
1166         if (soc_data->nvquirks & NVQUIRK_SET_TRIM_DELAY) {
1167                 vendor_ctrl &= ~(0x1F <<
1168                 SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1169                 vendor_ctrl |= (plat->trim_delay <<
1170                 SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1171         }
1172         if (soc_data->nvquirks & NVQUIRK_ENABLE_SDR50_TUNING)
1173                 vendor_ctrl |= SDHCI_VNDR_CLK_CTRL_SDR50_TUNING;
1174         sdhci_writel(host, vendor_ctrl, SDHCI_VNDR_CLK_CTRL);
1175
1176         misc_ctrl = sdhci_readl(host, SDHCI_VNDR_MISC_CTRL);
1177         if (soc_data->nvquirks & NVQUIRK_ENABLE_SD_3_0)
1178                 misc_ctrl |= SDHCI_VNDR_MISC_CTRL_ENABLE_SD_3_0;
1179         if (soc_data->nvquirks & NVQUIRK_ENABLE_SDR104) {
1180                 misc_ctrl |=
1181                 SDHCI_VNDR_MISC_CTRL_ENABLE_SDR104_SUPPORT;
1182         }
1183         if (soc_data->nvquirks & NVQUIRK_ENABLE_SDR50) {
1184                 misc_ctrl |=
1185                 SDHCI_VNDR_MISC_CTRL_ENABLE_SDR50_SUPPORT;
1186         }
1187         /* Enable DDR mode support only for SDMMC4 */
1188         if (soc_data->nvquirks & NVQUIRK_ENABLE_DDR50) {
1189                 if (tegra_host->instance == 3) {
1190                         misc_ctrl |=
1191                         SDHCI_VNDR_MISC_CTRL_ENABLE_DDR50_SUPPORT;
1192                 }
1193         }
1194         if (soc_data->nvquirks & NVQUIRK_INFINITE_ERASE_TIMEOUT) {
1195                 misc_ctrl |=
1196                 SDHCI_VNDR_MISC_CTRL_INFINITE_ERASE_TIMEOUT;
1197         }
1198         if (soc_data->nvquirks & NVQUIRK_SET_PIPE_STAGES_MASK_0)
1199                 misc_ctrl &= ~SDHCI_VNDR_MISC_CTRL_PIPE_STAGES_MASK;
1200
1201         /* External loopback is valid for sdmmc3 only */
1202         if ((soc_data->nvquirks & NVQUIRK_DISABLE_EXTERNAL_LOOPBACK) &&
1203                 (tegra_host->instance == 2)) {
1204                 if ((tegra_host->tuning_status == TUNING_STATUS_DONE)
1205                         && (host->mmc->pm_flags &
1206                         MMC_PM_KEEP_POWER)) {
1207                         misc_ctrl &= ~(1 <<
1208                         SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
1209                 } else {
1210                         misc_ctrl |= (1 <<
1211                         SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
1212                 }
1213         }
1214         sdhci_writel(host, misc_ctrl, SDHCI_VNDR_MISC_CTRL);
1215
1216         if (soc_data->nvquirks & NVQUIRK_DISABLE_AUTO_CMD23)
1217                 host->flags &= ~SDHCI_AUTO_CMD23;
1218
1219         /* Mask the support for any UHS modes if specified */
1220         if (plat->uhs_mask & MMC_UHS_MASK_SDR104)
1221                 host->mmc->caps &= ~MMC_CAP_UHS_SDR104;
1222
1223         if (plat->uhs_mask & MMC_UHS_MASK_DDR50)
1224                 host->mmc->caps &= ~MMC_CAP_UHS_DDR50;
1225
1226         if (plat->uhs_mask & MMC_UHS_MASK_SDR50)
1227                 host->mmc->caps &= ~MMC_CAP_UHS_SDR50;
1228
1229         if (plat->uhs_mask & MMC_UHS_MASK_SDR25)
1230                 host->mmc->caps &= ~MMC_CAP_UHS_SDR25;
1231
1232         if (plat->uhs_mask & MMC_UHS_MASK_SDR12)
1233                 host->mmc->caps &= ~MMC_CAP_UHS_SDR12;
1234
1235 #ifdef CONFIG_MMC_SDHCI_TEGRA_HS200_DISABLE
1236         host->mmc->caps2 &= ~MMC_CAP2_HS200;
1237 #else
1238         if (plat->uhs_mask & MMC_MASK_HS200)
1239                 host->mmc->caps2 &= ~MMC_CAP2_HS200;
1240 #endif
1241 }
1242
1243 static int tegra_sdhci_buswidth(struct sdhci_host *sdhci, int bus_width)
1244 {
1245         struct platform_device *pdev = to_platform_device(mmc_dev(sdhci->mmc));
1246         const struct tegra_sdhci_platform_data *plat;
1247         u32 ctrl;
1248
1249         plat = pdev->dev.platform_data;
1250
1251         ctrl = sdhci_readb(sdhci, SDHCI_HOST_CONTROL);
1252         if (plat->is_8bit && bus_width == MMC_BUS_WIDTH_8) {
1253                 ctrl &= ~SDHCI_CTRL_4BITBUS;
1254                 ctrl |= SDHCI_CTRL_8BITBUS;
1255         } else {
1256                 ctrl &= ~SDHCI_CTRL_8BITBUS;
1257                 if (bus_width == MMC_BUS_WIDTH_4)
1258                         ctrl |= SDHCI_CTRL_4BITBUS;
1259                 else
1260                         ctrl &= ~SDHCI_CTRL_4BITBUS;
1261         }
1262         sdhci_writeb(sdhci, ctrl, SDHCI_HOST_CONTROL);
1263         return 0;
1264 }
1265
1266 /*
1267 * Calculation of nearest clock frequency for desired rate:
1268 * Get the divisor value, div = p / d_rate
1269 * 1. If it is nearer to ceil(p/d_rate) then increment the div value by 0.5 and
1270 * nearest_rate, i.e. result = p / (div + 0.5) = (p << 1)/((div << 1) + 1).
1271 * 2. If not, result = p / div
1272 * As the nearest clk freq should be <= to desired_rate,
1273 * 3. If result > desired_rate then increment the div by 0.5
1274 * and do, (p << 1)/((div << 1) + 1)
1275 * 4. Else return result
1276 * Here, If condtions 1 & 3 are both satisfied then to keep track of div value,
1277 * defined index variable.
1278 */
1279 static unsigned long get_nearest_clock_freq(unsigned long pll_rate,
1280                 unsigned long desired_rate)
1281 {
1282         unsigned long result;
1283         int div;
1284         int index = 1;
1285
1286         div = pll_rate / desired_rate;
1287         if (div > MAX_DIVISOR_VALUE) {
1288                 div = MAX_DIVISOR_VALUE;
1289                 result = pll_rate / div;
1290         } else {
1291                 if ((pll_rate % desired_rate) >= (desired_rate / 2))
1292                         result = (pll_rate << 1) / ((div << 1) + index++);
1293                 else
1294                         result = pll_rate / div;
1295
1296                 if (desired_rate < result) {
1297                         /*
1298                         * Trying to get lower clock freq than desired clock,
1299                         * by increasing the divisor value by 0.5
1300                         */
1301                         result = (pll_rate << 1) / ((div << 1) + index);
1302                 }
1303         }
1304
1305         return result;
1306 }
1307
1308 static void tegra_sdhci_clock_set_parent(struct sdhci_host *host,
1309                 unsigned long desired_rate)
1310 {
1311         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
1312         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1313         struct clk *parent_clk;
1314         unsigned long pll_c_freq;
1315         unsigned long pll_p_freq;
1316         int rc;
1317
1318 #ifdef CONFIG_TEGRA_FPGA_PLATFORM
1319         return;
1320 #endif
1321         /*
1322          * Currently pll_p and pll_c are used as clock sources for SDMMC. If clk
1323          * rate is missing for either of them, then no selection is needed and
1324          * the default parent is used.
1325          */
1326         if (!pll_c_rate || !pll_p_rate)
1327                 return ;
1328
1329         pll_c_freq = get_nearest_clock_freq(pll_c_rate, desired_rate);
1330         pll_p_freq = get_nearest_clock_freq(pll_p_rate, desired_rate);
1331
1332         /*
1333          * For low freq requests, both the desired rates might be higher than
1334          * the requested clock frequency. In such cases, select the parent
1335          * with the lower frequency rate.
1336          */
1337         if ((pll_c_freq > desired_rate) && (pll_p_freq > desired_rate)) {
1338                 if (pll_p_freq <= pll_c_freq) {
1339                         desired_rate = pll_p_freq;
1340                         pll_c_freq = 0;
1341                 } else {
1342                         desired_rate = pll_c_freq;
1343                         pll_p_freq = 0;
1344                 }
1345                 rc = clk_set_rate(pltfm_host->clk, desired_rate);
1346         }
1347
1348         if (pll_c_freq > pll_p_freq) {
1349                 if (!tegra_host->is_parent_pllc) {
1350                         parent_clk = pll_c;
1351                         tegra_host->is_parent_pllc = true;
1352                         clk_set_rate(pltfm_host->clk, DEFAULT_SDHOST_FREQ);
1353                 } else
1354                         return;
1355         } else if (tegra_host->is_parent_pllc) {
1356                 parent_clk = pll_p;
1357                 tegra_host->is_parent_pllc = false;
1358         } else
1359                 return;
1360
1361         rc = clk_set_parent(pltfm_host->clk, parent_clk);
1362         if (rc)
1363                 pr_err("%s: failed to set pll parent clock %d\n",
1364                         mmc_hostname(host->mmc), rc);
1365 }
1366
1367 static void tegra_sdhci_set_clk_rate(struct sdhci_host *sdhci,
1368         unsigned int clock)
1369 {
1370         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1371         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1372         unsigned int clk_rate;
1373 #ifdef CONFIG_MMC_FREQ_SCALING
1374         unsigned int tap_value;
1375         struct tegra_tuning_data *tuning_data;
1376 #endif
1377
1378         if (sdhci->mmc->ios.timing == MMC_TIMING_UHS_DDR50) {
1379                 /*
1380                  * In ddr mode, tegra sdmmc controller clock frequency
1381                  * should be double the card clock frequency.
1382                  */
1383                 if (tegra_host->ddr_clk_limit)
1384                         clk_rate = tegra_host->ddr_clk_limit * 2;
1385                 else
1386                         clk_rate = clock * 2;
1387         } else {
1388                 clk_rate = clock;
1389         }
1390
1391         if (sdhci->mmc->ios.timing == MMC_TIMING_UHS_SDR50)
1392                 clk_rate = tegra_host->soc_data->tuning_freq_list[0];
1393
1394         if (tegra_host->max_clk_limit &&
1395                 (clk_rate > tegra_host->max_clk_limit))
1396                 clk_rate = tegra_host->max_clk_limit;
1397
1398         tegra_sdhci_clock_set_parent(sdhci, clk_rate);
1399         clk_set_rate(pltfm_host->clk, clk_rate);
1400         sdhci->max_clk = clk_get_rate(pltfm_host->clk);
1401
1402         /* FPGA supports 26MHz of clock for SDMMC. */
1403         if (tegra_platform_is_fpga())
1404                 sdhci->max_clk = 26000000;
1405
1406 #ifdef CONFIG_MMC_FREQ_SCALING
1407         /* Set the tap delay if tuning is done and dfs is enabled */
1408         if (sdhci->mmc->df &&
1409                 (tegra_host->tuning_status == TUNING_STATUS_DONE)) {
1410                 tuning_data = sdhci_tegra_get_tuning_data(sdhci, clock);
1411                 tap_value = (tegra_host->tap_cmd == TAP_CMD_TRIM_HIGH_VOLTAGE) ?
1412                         tuning_data->nom_best_tap_value :
1413                         tuning_data->best_tap_value;
1414                 sdhci_tegra_set_tap_delay(sdhci, tap_value);
1415         }
1416 #endif
1417 }
1418
1419 static void tegra_sdhci_set_clock(struct sdhci_host *sdhci, unsigned int clock)
1420 {
1421         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1422         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1423         struct platform_device *pdev = to_platform_device(mmc_dev(sdhci->mmc));
1424         u8 ctrl;
1425         int ret = 0;
1426
1427         mutex_lock(&tegra_host->set_clock_mutex);
1428         pr_debug("%s %s %u enabled=%u\n", __func__,
1429                 mmc_hostname(sdhci->mmc), clock, tegra_host->clk_enabled);
1430         if (clock) {
1431                 if (!tegra_host->clk_enabled) {
1432                         pm_runtime_get_sync(&pdev->dev);
1433                         ret = clk_prepare_enable(pltfm_host->clk);
1434                         if (ret) {
1435                                 dev_err(mmc_dev(sdhci->mmc),
1436                                 "clock enable is failed, ret: %d\n", ret);
1437                                 mutex_unlock(&tegra_host->set_clock_mutex);
1438                                 return;
1439                         }
1440                         tegra_host->clk_enabled = true;
1441                         sdhci->is_clk_on = tegra_host->clk_enabled;
1442                         ctrl = sdhci_readb(sdhci, SDHCI_VNDR_CLK_CTRL);
1443                         ctrl |= SDHCI_VNDR_CLK_CTRL_SDMMC_CLK;
1444                         sdhci_writeb(sdhci, ctrl, SDHCI_VNDR_CLK_CTRL);
1445                 }
1446                 tegra_sdhci_set_clk_rate(sdhci, clock);
1447
1448                 if (tegra_host->emc_clk && (!tegra_host->is_sdmmc_emc_clk_on)) {
1449                         ret = clk_prepare_enable(tegra_host->emc_clk);
1450                         if (ret) {
1451                                 dev_err(mmc_dev(sdhci->mmc),
1452                                 "clock enable is failed, ret: %d\n", ret);
1453                                 mutex_unlock(&tegra_host->set_clock_mutex);
1454                                 return;
1455                         }
1456                         tegra_host->is_sdmmc_emc_clk_on = true;
1457                 }
1458                 if (tegra_host->sclk && (!tegra_host->is_sdmmc_sclk_on)) {
1459                         ret = clk_prepare_enable(tegra_host->sclk);
1460                         if (ret) {
1461                                 dev_err(mmc_dev(sdhci->mmc),
1462                                 "clock enable is failed, ret: %d\n", ret);
1463                                 mutex_unlock(&tegra_host->set_clock_mutex);
1464                                 return;
1465                         }
1466                         tegra_host->is_sdmmc_sclk_on = true;
1467                 }
1468         } else if (!clock && tegra_host->clk_enabled) {
1469                 if (tegra_host->emc_clk && tegra_host->is_sdmmc_emc_clk_on) {
1470                         clk_disable_unprepare(tegra_host->emc_clk);
1471                         tegra_host->is_sdmmc_emc_clk_on = false;
1472                 }
1473                 if (tegra_host->sclk && tegra_host->is_sdmmc_sclk_on) {
1474                         clk_disable_unprepare(tegra_host->sclk);
1475                         tegra_host->is_sdmmc_sclk_on = false;
1476                 }
1477                 ctrl = sdhci_readb(sdhci, SDHCI_VNDR_CLK_CTRL);
1478                 ctrl &= ~SDHCI_VNDR_CLK_CTRL_SDMMC_CLK;
1479                 sdhci_writeb(sdhci, ctrl, SDHCI_VNDR_CLK_CTRL);
1480                 clk_disable_unprepare(pltfm_host->clk);
1481                 tegra_host->clk_enabled = false;
1482                 sdhci->is_clk_on = tegra_host->clk_enabled;
1483                 pm_runtime_put_sync(&pdev->dev);
1484         }
1485         mutex_unlock(&tegra_host->set_clock_mutex);
1486 }
1487
1488 static void tegra_sdhci_do_calibration(struct sdhci_host *sdhci,
1489         unsigned char signal_voltage)
1490 {
1491         unsigned int val;
1492         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1493         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1494         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
1495         unsigned int timeout = 10;
1496         unsigned int calib_offsets = 0;
1497
1498         /* No Calibration for sdmmc4 */
1499         if (unlikely(soc_data->nvquirks & NVQUIRK_DISABLE_SDMMC4_CALIB) &&
1500                 (tegra_host->instance == 3))
1501                 return;
1502
1503         if (unlikely(soc_data->nvquirks & NVQUIRK_DISABLE_AUTO_CALIBRATION))
1504                 return;
1505
1506         val = sdhci_readl(sdhci, SDMMC_SDMEMCOMPPADCTRL);
1507         val &= ~SDMMC_SDMEMCOMPPADCTRL_VREF_SEL_MASK;
1508         if (soc_data->nvquirks & NVQUIRK_SET_PAD_E_INPUT_OR_E_PWRD)
1509                 val |= SDMMC_SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD_MASK;
1510         val |= 0x7;
1511         sdhci_writel(sdhci, val, SDMMC_SDMEMCOMPPADCTRL);
1512
1513         /* Enable Auto Calibration*/
1514         val = sdhci_readl(sdhci, SDMMC_AUTO_CAL_CONFIG);
1515         val |= SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_ENABLE;
1516         val |= SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_START;
1517         if (unlikely(soc_data->nvquirks & NVQUIRK_SET_CALIBRATION_OFFSETS)) {
1518                 if (signal_voltage == MMC_SIGNAL_VOLTAGE_330)
1519                         calib_offsets = tegra_host->plat->calib_3v3_offsets;
1520                 else if (signal_voltage == MMC_SIGNAL_VOLTAGE_180)
1521                         calib_offsets = tegra_host->plat->calib_1v8_offsets;
1522                 if (calib_offsets) {
1523                         /* Program Auto cal PD offset(bits 8:14) */
1524                         val &= ~(0x7F <<
1525                                 SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_PD_OFFSET_SHIFT);
1526                         val |= (((calib_offsets >> 8) & 0xFF) <<
1527                                 SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_PD_OFFSET_SHIFT);
1528                         /* Program Auto cal PU offset(bits 0:6) */
1529                         val &= ~0x7F;
1530                         val |= (calib_offsets & 0xFF);
1531                 }
1532         }
1533         sdhci_writel(sdhci, val, SDMMC_AUTO_CAL_CONFIG);
1534
1535         /* Wait until the calibration is done */
1536         do {
1537                 if (!(sdhci_readl(sdhci, SDMMC_AUTO_CAL_STATUS) &
1538                         SDMMC_AUTO_CAL_STATUS_AUTO_CAL_ACTIVE))
1539                         break;
1540
1541                 mdelay(1);
1542                 timeout--;
1543         } while (timeout);
1544
1545         if (!timeout)
1546                 dev_err(mmc_dev(sdhci->mmc), "Auto calibration failed\n");
1547
1548         if (soc_data->nvquirks & NVQUIRK_SET_PAD_E_INPUT_OR_E_PWRD) {
1549                 val = sdhci_readl(sdhci, SDMMC_SDMEMCOMPPADCTRL);
1550                 val &= ~SDMMC_SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD_MASK;
1551                 sdhci_writel(sdhci, val, SDMMC_SDMEMCOMPPADCTRL);
1552         }
1553
1554         if (unlikely(soc_data->nvquirks & NVQUIRK_SET_DRIVE_STRENGTH)) {
1555                 unsigned int pulldown_code;
1556                 unsigned int pullup_code;
1557                 int pg;
1558                 int err;
1559
1560                 /* Disable Auto calibration */
1561                 val = sdhci_readl(sdhci, SDMMC_AUTO_CAL_CONFIG);
1562                 val &= ~SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_ENABLE;
1563                 sdhci_writel(sdhci, val, SDMMC_AUTO_CAL_CONFIG);
1564
1565                 pg = tegra_drive_get_pingroup(mmc_dev(sdhci->mmc));
1566                 if (pg != -1) {
1567                         /* Get the pull down codes from auto cal status reg */
1568                         pulldown_code = (
1569                                 sdhci_readl(sdhci, SDMMC_AUTO_CAL_STATUS) >>
1570                                 SDMMC_AUTO_CAL_STATUS_PULLDOWN_OFFSET);
1571                         /* Set the pull down in the pinmux reg */
1572                         err = tegra_drive_pinmux_set_pull_down(pg,
1573                                 pulldown_code);
1574                         if (err)
1575                                 dev_err(mmc_dev(sdhci->mmc),
1576                                 "Failed to set pulldown codes %d err %d\n",
1577                                 pulldown_code, err);
1578
1579                         /* Calculate the pull up codes */
1580                         pullup_code = pulldown_code + PULLUP_ADJUSTMENT_OFFSET;
1581                         if (pullup_code >= TEGRA_MAX_PULL)
1582                                 pullup_code = TEGRA_MAX_PULL - 1;
1583                         /* Set the pull up code in the pinmux reg */
1584                         err = tegra_drive_pinmux_set_pull_up(pg, pullup_code);
1585                         if (err)
1586                                 dev_err(mmc_dev(sdhci->mmc),
1587                                 "Failed to set pullup codes %d err %d\n",
1588                                 pullup_code, err);
1589                 }
1590         }
1591 }
1592
1593 static int tegra_sdhci_signal_voltage_switch(struct sdhci_host *sdhci,
1594         unsigned int signal_voltage)
1595 {
1596         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1597         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1598         unsigned int min_uV = tegra_host->vddio_min_uv;
1599         unsigned int max_uV = tegra_host->vddio_max_uv;
1600         unsigned int rc = 0;
1601         u16 ctrl;
1602
1603
1604         ctrl = sdhci_readw(sdhci, SDHCI_HOST_CONTROL2);
1605         if (signal_voltage == MMC_SIGNAL_VOLTAGE_180) {
1606                 ctrl |= SDHCI_CTRL_VDD_180;
1607                 min_uV = SDHOST_LOW_VOLT_MIN;
1608                 max_uV = SDHOST_LOW_VOLT_MAX;
1609         } else if (signal_voltage == MMC_SIGNAL_VOLTAGE_330) {
1610                 if (ctrl & SDHCI_CTRL_VDD_180)
1611                         ctrl &= ~SDHCI_CTRL_VDD_180;
1612         }
1613
1614         /* Check if the slot can support the required voltage */
1615         if (min_uV > tegra_host->vddio_max_uv)
1616                 return 0;
1617
1618         /* Set/clear the 1.8V signalling */
1619         sdhci_writew(sdhci, ctrl, SDHCI_HOST_CONTROL2);
1620
1621         /* Switch the I/O rail voltage */
1622         rc = tegra_sdhci_configure_regulators(tegra_host, CONFIG_REG_SET_VOLT,
1623                 min_uV, max_uV);
1624         if (rc && (signal_voltage == MMC_SIGNAL_VOLTAGE_180)) {
1625                 dev_err(mmc_dev(sdhci->mmc),
1626                         "setting 1.8V failed %d. Revert to 3.3V\n", rc);
1627                 rc = tegra_sdhci_configure_regulators(tegra_host,
1628                         CONFIG_REG_SET_VOLT, SDHOST_HIGH_VOLT_MIN,
1629                         SDHOST_HIGH_VOLT_MAX);
1630         }
1631
1632         return rc;
1633 }
1634
1635 static int tegra_sdhci_configure_regulators(struct sdhci_tegra *tegra_host,
1636         u8 option, int min_uV, int max_uV)
1637 {
1638         int rc = 0;
1639
1640         switch (option) {
1641         case CONFIG_REG_EN:
1642                 if (!tegra_host->is_rail_enabled) {
1643                         if (tegra_host->vdd_slot_reg)
1644                                 rc = regulator_enable(tegra_host->vdd_slot_reg);
1645                         if (tegra_host->vdd_io_reg)
1646                                 rc = regulator_enable(tegra_host->vdd_io_reg);
1647                         tegra_host->is_rail_enabled = true;
1648                 }
1649         break;
1650         case CONFIG_REG_DIS:
1651                 if (tegra_host->is_rail_enabled) {
1652                         if (tegra_host->vdd_io_reg)
1653                                 rc = regulator_disable(tegra_host->vdd_io_reg);
1654                         if (tegra_host->vdd_slot_reg)
1655                                 rc = regulator_disable(
1656                                         tegra_host->vdd_slot_reg);
1657                         tegra_host->is_rail_enabled = false;
1658                 }
1659         break;
1660         case CONFIG_REG_SET_VOLT:
1661                 if (tegra_host->vdd_io_reg)
1662                         rc = regulator_set_voltage(tegra_host->vdd_io_reg,
1663                                 min_uV, max_uV);
1664         break;
1665         default:
1666                 pr_err("Invalid argument passed to reg config %d\n", option);
1667         }
1668
1669         return rc;
1670 }
1671
1672 static void tegra_sdhci_reset(struct sdhci_host *sdhci, u8 mask)
1673 {
1674         unsigned long timeout;
1675
1676         sdhci_writeb(sdhci, mask, SDHCI_SOFTWARE_RESET);
1677
1678         /* Wait max 100 ms */
1679         timeout = 100;
1680
1681         /* hw clears the bit when it's done */
1682         while (sdhci_readb(sdhci, SDHCI_SOFTWARE_RESET) & mask) {
1683                 if (timeout == 0) {
1684                         dev_err(mmc_dev(sdhci->mmc), "Reset 0x%x never"
1685                                 "completed.\n", (int)mask);
1686                         return;
1687                 }
1688                 timeout--;
1689                 mdelay(1);
1690         }
1691
1692         tegra_sdhci_reset_exit(sdhci, mask);
1693 }
1694
1695 static void sdhci_tegra_set_tap_delay(struct sdhci_host *sdhci,
1696         unsigned int tap_delay)
1697 {
1698         u32 vendor_ctrl;
1699
1700         /* Max tap delay value is 255 */
1701         if (tap_delay > MAX_TAP_VALUES) {
1702                 dev_err(mmc_dev(sdhci->mmc),
1703                         "Valid tap range (0-255). Setting tap value %d\n",
1704                         tap_delay);
1705                 dump_stack();
1706                 return;
1707         }
1708
1709         vendor_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_CLK_CTRL);
1710         vendor_ctrl &= ~(0xFF << SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1711         vendor_ctrl |= (tap_delay << SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1712         sdhci_writel(sdhci, vendor_ctrl, SDHCI_VNDR_CLK_CTRL);
1713 }
1714
1715 static void sdhci_tegra_set_trim_delay(struct sdhci_host *sdhci,
1716         unsigned int trim_delay)
1717 {
1718         u32 vendor_ctrl;
1719
1720         vendor_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_CLK_CTRL);
1721         vendor_ctrl &= ~(0x1F << SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1722         vendor_ctrl |= (trim_delay << SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1723         sdhci_writel(sdhci, vendor_ctrl, SDHCI_VNDR_CLK_CTRL);
1724 }
1725
1726 static int sdhci_tegra_sd_error_stats(struct sdhci_host *host, u32 int_status)
1727 {
1728         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
1729         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1730         struct sdhci_tegra_sd_stats *head = tegra_host->sd_stat_head;
1731
1732         if (int_status & SDHCI_INT_DATA_CRC)
1733                 head->data_crc_count++;
1734         if (int_status & SDHCI_INT_CRC)
1735                 head->cmd_crc_count++;
1736         if (int_status & SDHCI_INT_TIMEOUT)
1737                 head->cmd_to_count++;
1738         if (int_status & SDHCI_INT_DATA_TIMEOUT)
1739                 head->data_to_count++;
1740         return 0;
1741 }
1742
1743 static struct tegra_tuning_data *sdhci_tegra_get_tuning_data(
1744         struct sdhci_host *sdhci, unsigned int clock)
1745 {
1746         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1747         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1748         struct tegra_tuning_data *tuning_data;
1749         unsigned int low_freq;
1750         u8 i = 0;
1751
1752         if (tegra_host->tuning_freq_count == 1) {
1753                 tuning_data = &tegra_host->tuning_data[0];
1754                 goto out;
1755         }
1756
1757         /* Get the lowest supported freq */
1758         for (i = 0; i < TUNING_FREQ_COUNT; ++i) {
1759                 low_freq = tegra_host->soc_data->tuning_freq_list[i];
1760                 if (low_freq)
1761                         break;
1762         }
1763
1764         if (clock <= low_freq)
1765                 tuning_data = &tegra_host->tuning_data[0];
1766         else
1767                 tuning_data = &tegra_host->tuning_data[1];
1768
1769 out:
1770         return tuning_data;
1771 }
1772
1773 static void calculate_vmin_values(struct sdhci_host *sdhci,
1774         struct tegra_tuning_data *tuning_data, int vmin, int boot_mv)
1775 {
1776         struct tuning_values *est_values = &tuning_data->est_values;
1777         struct tuning_values *calc_values = &tuning_data->calc_values;
1778         struct tuning_t2t_coeffs *t2t_coeffs = tuning_data->t2t_coeffs;
1779         struct tap_hole_coeffs *thole_coeffs = tuning_data->thole_coeffs;
1780         int vmin_slope, vmin_int, temp_calc_vmin;
1781         int t2t_vmax, t2t_vmin;
1782         int vmax_thole, vmin_thole;
1783
1784         /*
1785          * If current vmin is equal to vmin or vmax of tuning data, use the
1786          * previously calculated estimated T2T values directly. Note that the
1787          * estimated T2T_vmax is not at Vmax specified in tuning data. It is
1788          * the T2T at the boot or max voltage for the current SKU. Hence,
1789          * boot_mv is used in place of t2t_coeffs->vmax.
1790          */
1791         if (vmin == t2t_coeffs->vmin) {
1792                 t2t_vmin = est_values->t2t_vmin;
1793         } else if (vmin == boot_mv) {
1794                 t2t_vmin = est_values->t2t_vmax;
1795         } else {
1796                 /*
1797                  * For any intermediate voltage between boot voltage and vmin
1798                  * of tuning data, calculate the slope and intercept from the
1799                  * t2t at boot_mv and vmin and calculate the actual values.
1800                  */
1801                 t2t_vmax = 1000 / est_values->t2t_vmax;
1802                 t2t_vmin = 1000 / est_values->t2t_vmin;
1803                 vmin_slope = ((t2t_vmax - t2t_vmin) * 1000) /
1804                         (boot_mv - t2t_coeffs->vmin);
1805                 vmin_int = (t2t_vmax * 1000 - (vmin_slope * boot_mv)) / 1000;
1806                 t2t_vmin = (vmin_slope * vmin) / 1000 + vmin_int;
1807                 t2t_vmin = (1000 / t2t_vmin);
1808         }
1809
1810         calc_values->t2t_vmin = (t2t_vmin * calc_values->t2t_vmax) /
1811                 est_values->t2t_vmax;
1812
1813         calc_values->ui_vmin = (1000000 / (tuning_data->freq_hz / 1000000)) /
1814                 calc_values->t2t_vmin;
1815
1816         /* Calculate the vmin tap hole at vmin of tuning data */
1817         temp_calc_vmin = (est_values->t2t_vmin * calc_values->t2t_vmax) /
1818                 est_values->t2t_vmax;
1819         vmin_thole = (thole_coeffs->thole_vmin_int -
1820                 (thole_coeffs->thole_vmin_slope * temp_calc_vmin)) /
1821                 1000;
1822         vmax_thole = calc_values->vmax_thole;
1823
1824         if (vmin == t2t_coeffs->vmin) {
1825                 calc_values->vmin_thole = vmin_thole;
1826         } else if (vmin == boot_mv) {
1827                 calc_values->vmin_thole = vmax_thole;
1828         } else {
1829                 /*
1830                  * Interpolate the tap hole for any intermediate voltage.
1831                  * Calculate the slope and intercept from the available data
1832                  * and use them to calculate the actual values.
1833                  */
1834                 vmin_slope = ((vmax_thole - vmin_thole) * 1000) /
1835                         (boot_mv - t2t_coeffs->vmin);
1836                 vmin_int = (vmax_thole * 1000 - (vmin_slope * boot_mv)) / 1000;
1837                 calc_values->vmin_thole = (vmin_slope * vmin) / 1000 + vmin_int;
1838         }
1839
1840         /* Adjust the partial win start for Vmin boundary */
1841         if (tuning_data->is_partial_win_valid)
1842                 tuning_data->final_tap_data[0].win_start =
1843                         (tuning_data->final_tap_data[0].win_start *
1844                         tuning_data->calc_values.t2t_vmax) /
1845                         tuning_data->calc_values.t2t_vmin;
1846
1847         pr_info("**********Tuning values*********\n");
1848         pr_info("**estimated values**\n");
1849         pr_info("T2T_Vmax %d, T2T_Vmin %d, 1'st_hole_Vmax %d, UI_Vmax %d\n",
1850                 est_values->t2t_vmax, est_values->t2t_vmin,
1851                 est_values->vmax_thole, est_values->ui);
1852         pr_info("**Calculated values**\n");
1853         pr_info("T2T_Vmax %d, 1'st_hole_Vmax %d, UI_Vmax %d\n",
1854                 calc_values->t2t_vmax, calc_values->vmax_thole,
1855                 calc_values->ui);
1856         pr_info("T2T_Vmin %d, 1'st_hole_Vmin %d, UI_Vmin %d\n",
1857                 calc_values->t2t_vmin, calc_values->vmin_thole,
1858                 calc_values->ui_vmin);
1859         pr_info("***********************************\n");
1860 }
1861
1862 static int slide_window_start(struct sdhci_host *sdhci,
1863         struct tegra_tuning_data *tuning_data,
1864         int tap_value, enum tap_win_edge_attr edge_attr, int tap_hole)
1865 {
1866         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1867         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1868         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
1869
1870         if (edge_attr == WIN_EDGE_BOUN_START) {
1871                 if (tap_value < 0)
1872                         tap_value += (1000 / tuning_data->calc_values.t2t_vmin);
1873                 else
1874                         tap_value += (1000 / tuning_data->calc_values.t2t_vmax);
1875         } else if (edge_attr == WIN_EDGE_HOLE) {
1876                 if (soc_data->nvquirks & NVQUIRK_TMP_VAR_1_5_TAP_MARGIN)
1877                         tap_value += ((7 * tap_hole) / 100) + 2;
1878                 else
1879                         tap_value += ((7 * tap_hole) / 100) +
1880                         (((2 * (450 / tuning_data->calc_values.t2t_vmax))
1881                         + 1) / 2);
1882         }
1883
1884         if (tap_value > MAX_TAP_VALUES)
1885                 tap_value = MAX_TAP_VALUES;
1886
1887         return tap_value;
1888 }
1889
1890 static int slide_window_end(struct sdhci_host *sdhci,
1891         struct tegra_tuning_data *tuning_data,
1892         int tap_value, enum tap_win_edge_attr edge_attr, int tap_hole)
1893 {
1894         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1895         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1896         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
1897
1898         if (edge_attr == WIN_EDGE_BOUN_END) {
1899                 tap_value = (tap_value * tuning_data->calc_values.t2t_vmax) /
1900                         tuning_data->calc_values.t2t_vmin;
1901                 tap_value -= (1000 / tuning_data->calc_values.t2t_vmin);
1902         } else if (edge_attr == WIN_EDGE_HOLE) {
1903                 if (tap_hole > 0)
1904                         tap_value = tap_hole;
1905                 if (soc_data->nvquirks & NVQUIRK_TMP_VAR_1_5_TAP_MARGIN)
1906                         tap_value -= ((7 * tap_hole) / 100) + 2;
1907                 else
1908                         tap_value -= ((7 * tap_hole) / 100) +
1909                         (((2 * (450 / tuning_data->calc_values.t2t_vmin))
1910                         + 1) / 2);
1911         }
1912
1913         return tap_value;
1914 }
1915
1916 static int adjust_window_boundaries(struct sdhci_host *sdhci,
1917         struct tegra_tuning_data *tuning_data,
1918         struct tap_window_data *temp_tap_data)
1919 {
1920         struct tap_window_data *tap_data;
1921         int vmin_tap_hole;
1922         int vmax_tap_hole;
1923         u8 i = 0;
1924
1925         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
1926                 tap_data = &temp_tap_data[i];
1927                 /* Update with next hole if first hole is taken care of */
1928                 if (tap_data->win_start_attr == WIN_EDGE_HOLE)
1929                         vmax_tap_hole = tuning_data->calc_values.vmax_thole +
1930                                 (tap_data->hole_pos - 1) *
1931                                 tuning_data->calc_values.ui;
1932                 tap_data->win_start = slide_window_start(sdhci, tuning_data,
1933                         tap_data->win_start, tap_data->win_start_attr,
1934                         vmax_tap_hole);
1935
1936                 /* Update with next hole if first hole is taken care of */
1937                 if (tap_data->win_end_attr == WIN_EDGE_HOLE)
1938                         vmin_tap_hole = tuning_data->calc_values.vmin_thole +
1939                                 (tap_data->hole_pos - 1) *
1940                                 tuning_data->calc_values.ui_vmin;
1941                 tap_data->win_end = slide_window_end(sdhci, tuning_data,
1942                         tap_data->win_end, tap_data->win_end_attr,
1943                         vmin_tap_hole);
1944         }
1945
1946         pr_info("***********final tuning windows**********\n");
1947         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
1948                 tap_data = &temp_tap_data[i];
1949                 pr_info("win[%d]: %d - %d\n", i, tap_data->win_start,
1950                         tap_data->win_end);
1951         }
1952         pr_info("********************************\n");
1953         return 0;
1954 }
1955
1956 static int find_best_tap_value(struct tegra_tuning_data *tuning_data,
1957         struct tap_window_data *temp_tap_data, int vmin)
1958 {
1959         struct tap_window_data *tap_data;
1960         u8 i = 0, sel_win = 0;
1961         int pref_win = 0, curr_win_size = 0;
1962         int best_tap_value = 0;
1963
1964         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
1965                 tap_data = &temp_tap_data[i];
1966                 if (!i && tuning_data->is_partial_win_valid) {
1967                         pref_win = tap_data->win_end - tap_data->win_start;
1968                         if ((tap_data->win_end * 2) < pref_win)
1969                                 pref_win = tap_data->win_end * 2;
1970                         sel_win = 0;
1971                 } else {
1972                         curr_win_size = tap_data->win_end - tap_data->win_start;
1973                         if ((curr_win_size > 0) && (curr_win_size > pref_win)) {
1974                                 pref_win = curr_win_size;
1975                                 sel_win = i;
1976                         }
1977                 }
1978         }
1979
1980         if (pref_win <= 0) {
1981                 pr_err("No window opening for %d vmin\n", vmin);
1982                 return -1;
1983         }
1984
1985         tap_data = &temp_tap_data[sel_win];
1986         if (!sel_win && tuning_data->is_partial_win_valid) {
1987                 i = sel_win;
1988                 best_tap_value = tap_data->win_end - (pref_win / 2);
1989                 if (best_tap_value < 0)
1990                         best_tap_value = 0;
1991         } else {
1992                 best_tap_value = tap_data->win_start +
1993                         ((tap_data->win_end - tap_data->win_start) *
1994                         tuning_data->calc_values.t2t_vmin) /
1995                         (tuning_data->calc_values.t2t_vmin +
1996                         tuning_data->calc_values.t2t_vmax);
1997         }
1998
1999         pr_err("best tap win - (%d-%d), best tap value %d\n",
2000                 tap_data->win_start, tap_data->win_end, best_tap_value);
2001         return best_tap_value;
2002 }
2003
2004 static int sdhci_tegra_calculate_best_tap(struct sdhci_host *sdhci,
2005         struct tegra_tuning_data *tuning_data)
2006 {
2007         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2008         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2009         struct tap_window_data *temp_tap_data = NULL;
2010         int vmin, curr_vmin, best_tap_value = 0;
2011         int err = 0;
2012
2013         curr_vmin = tegra_dvfs_predict_millivolts(pltfm_host->clk,
2014                 tuning_data->freq_hz);
2015         if (!curr_vmin)
2016                 curr_vmin = tegra_host->boot_vcore_mv;
2017
2018         vmin = curr_vmin;
2019         do {
2020                 SDHCI_TEGRA_DBG("%s: checking for win opening with vmin %d\n",
2021                         mmc_hostname(sdhci->mmc), vmin);
2022                 if ((best_tap_value < 0) &&
2023                         (vmin > tegra_host->boot_vcore_mv)) {
2024                         dev_err(mmc_dev(sdhci->mmc),
2025                                 "No best tap for any vcore range\n");
2026                         return -EINVAL;
2027                 }
2028
2029                 calculate_vmin_values(sdhci, tuning_data, vmin,
2030                         tegra_host->boot_vcore_mv);
2031
2032                 if (temp_tap_data == NULL) {
2033                         temp_tap_data = kzalloc(sizeof(struct tap_window_data) *
2034                                 tuning_data->num_of_valid_tap_wins, GFP_KERNEL);
2035                         if (IS_ERR_OR_NULL(temp_tap_data)) {
2036                                 dev_err(mmc_dev(sdhci->mmc),
2037                                 "No memory for final tap value calculation\n");
2038                                 return -ENOMEM;
2039                         }
2040                 }
2041
2042                 memcpy(temp_tap_data, tuning_data->final_tap_data,
2043                         sizeof(struct tap_window_data) *
2044                         tuning_data->num_of_valid_tap_wins);
2045
2046                 adjust_window_boundaries(sdhci, tuning_data, temp_tap_data);
2047
2048                 best_tap_value = find_best_tap_value(tuning_data,
2049                         temp_tap_data, vmin);
2050
2051                 if (best_tap_value < 0)
2052                         vmin += 50;
2053         } while (best_tap_value < 0);
2054
2055         tuning_data->best_tap_value = best_tap_value;
2056         tuning_data->nom_best_tap_value = best_tap_value;
2057
2058         /*
2059          * Set the new vmin if there is any change. If dvfs overrides are
2060          * disabled, then print the error message but continue execution
2061          * rather than disabling tuning altogether.
2062          */
2063         if ((tuning_data->best_tap_value >= 0) && (curr_vmin != vmin)) {
2064                 err = tegra_dvfs_set_fmax_at_vmin(pltfm_host->clk,
2065                         tuning_data->freq_hz, vmin);
2066                 if ((err == -EPERM) || (err == -ENOSYS)) {
2067                         /*
2068                          * tegra_dvfs_set_fmax_at_vmin: will return EPERM or
2069                          * ENOSYS, when DVFS override is not enabled, continue
2070                          * tuning with default core voltage.
2071                          */
2072                         SDHCI_TEGRA_DBG(
2073                                 "dvfs overrides disabled. Vmin not updated\n");
2074                         err = 0;
2075                 }
2076         }
2077         kfree(temp_tap_data);
2078         return err;
2079 }
2080
2081 static int sdhci_tegra_issue_tuning_cmd(struct sdhci_host *sdhci)
2082 {
2083         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2084         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2085         int err = 0;
2086         u8 ctrl;
2087         u32 mask;
2088         unsigned int timeout = 10;
2089         int flags;
2090         u32 intstatus;
2091
2092         mask = SDHCI_CMD_INHIBIT | SDHCI_DATA_INHIBIT;
2093         while (sdhci_readl(sdhci, SDHCI_PRESENT_STATE) & mask) {
2094                 if (timeout == 0) {
2095                         dev_err(mmc_dev(sdhci->mmc), "Controller never"
2096                                 "released inhibit bit(s).\n");
2097                         err = -ETIMEDOUT;
2098                         goto out;
2099                 }
2100                 timeout--;
2101                 mdelay(1);
2102         }
2103
2104         ctrl = sdhci_readb(sdhci, SDHCI_HOST_CONTROL2);
2105         ctrl &= ~SDHCI_CTRL_TUNED_CLK;
2106         sdhci_writeb(sdhci, ctrl, SDHCI_HOST_CONTROL2);
2107
2108         ctrl = sdhci_readb(sdhci, SDHCI_HOST_CONTROL2);
2109         ctrl |= SDHCI_CTRL_EXEC_TUNING;
2110         sdhci_writeb(sdhci, ctrl, SDHCI_HOST_CONTROL2);
2111
2112         /*
2113          * In response to CMD19, the card sends 64 bytes of tuning
2114          * block to the Host Controller. So we set the block size
2115          * to 64 here.
2116          * In response to CMD21, the card sends 128 bytes of tuning
2117          * block for MMC_BUS_WIDTH_8 and 64 bytes for MMC_BUS_WIDTH_4
2118          * to the Host Controller. So we set the block size to 64 here.
2119          */
2120         sdhci_writew(sdhci, SDHCI_MAKE_BLKSZ(7, tegra_host->tuning_bsize),
2121                 SDHCI_BLOCK_SIZE);
2122
2123         sdhci_writeb(sdhci, 0xE, SDHCI_TIMEOUT_CONTROL);
2124
2125         sdhci_writew(sdhci, SDHCI_TRNS_READ, SDHCI_TRANSFER_MODE);
2126
2127         sdhci_writel(sdhci, 0x0, SDHCI_ARGUMENT);
2128
2129         /* Set the cmd flags */
2130         flags = SDHCI_CMD_RESP_SHORT | SDHCI_CMD_CRC | SDHCI_CMD_DATA;
2131         /* Issue the command */
2132         sdhci_writew(sdhci, SDHCI_MAKE_CMD(
2133                 tegra_host->tuning_opcode, flags), SDHCI_COMMAND);
2134
2135         timeout = 5;
2136         do {
2137                 timeout--;
2138                 mdelay(1);
2139                 intstatus = sdhci_readl(sdhci, SDHCI_INT_STATUS);
2140                 if (intstatus) {
2141                         sdhci_writel(sdhci, intstatus, SDHCI_INT_STATUS);
2142                         break;
2143                 }
2144         } while(timeout);
2145
2146         if ((intstatus & SDHCI_INT_DATA_AVAIL) &&
2147                 !(intstatus & SDHCI_INT_DATA_CRC)) {
2148                 err = 0;
2149                 sdhci->tuning_done = 1;
2150         } else {
2151                 tegra_sdhci_reset(sdhci, SDHCI_RESET_DATA);
2152                 tegra_sdhci_reset(sdhci, SDHCI_RESET_CMD);
2153                 err = -EIO;
2154         }
2155
2156         if (sdhci->tuning_done) {
2157                 sdhci->tuning_done = 0;
2158                 ctrl = sdhci_readb(sdhci, SDHCI_HOST_CONTROL2);
2159                 if (!(ctrl & SDHCI_CTRL_EXEC_TUNING) &&
2160                         (ctrl & SDHCI_CTRL_TUNED_CLK))
2161                         err = 0;
2162                 else
2163                         err = -EIO;
2164         }
2165         mdelay(1);
2166 out:
2167         return err;
2168 }
2169
2170 static int sdhci_tegra_scan_tap_values(struct sdhci_host *sdhci,
2171         unsigned int starting_tap, bool expect_failure)
2172 {
2173         unsigned int tap_value = starting_tap;
2174         int err;
2175         unsigned int retry = TUNING_RETRIES;
2176
2177         do {
2178                 /* Set the tap delay */
2179                 sdhci_tegra_set_tap_delay(sdhci, tap_value);
2180
2181                 /* Run frequency tuning */
2182                 err = sdhci_tegra_issue_tuning_cmd(sdhci);
2183                 if (err && retry) {
2184                         retry--;
2185                         continue;
2186                 } else {
2187                         retry = TUNING_RETRIES;
2188                         if ((expect_failure && !err) ||
2189                                 (!expect_failure && err))
2190                                 break;
2191                 }
2192                 tap_value++;
2193         } while (tap_value <= MAX_TAP_VALUES);
2194
2195         return tap_value;
2196 }
2197
2198 static int calculate_actual_tuning_values(int speedo,
2199         struct tegra_tuning_data *tuning_data, int voltage_mv)
2200 {
2201         struct tuning_t2t_coeffs *t2t_coeffs = tuning_data->t2t_coeffs;
2202         struct tap_hole_coeffs *thole_coeffs = tuning_data->thole_coeffs;
2203         struct tuning_values *calc_values = &tuning_data->calc_values;
2204         int slope, inpt;
2205         int vmax_thole, vmin_thole;
2206
2207         /* T2T_Vmax = (1000000/freq_MHz)/Calc_UI */
2208         calc_values->t2t_vmax = (1000000 / (tuning_data->freq_hz / 1000000)) /
2209                 calc_values->ui;
2210
2211         /*
2212          * Interpolate the tap hole.
2213          * Vmax_1'st_hole = (Calc_T2T_Vmax*(-thole_slope)+thole_tint.
2214          */
2215         vmax_thole = (thole_coeffs->thole_vmax_int -
2216                 (thole_coeffs->thole_vmax_slope * calc_values->t2t_vmax)) /
2217                 1000;
2218         vmin_thole = (thole_coeffs->thole_vmin_int -
2219                 (thole_coeffs->thole_vmin_slope * calc_values->t2t_vmax)) /
2220                 1000;
2221         if (voltage_mv == t2t_coeffs->vmin) {
2222                 calc_values->vmax_thole = vmin_thole;
2223         } else if (voltage_mv == t2t_coeffs->vmax) {
2224                 calc_values->vmax_thole = vmax_thole;
2225         } else {
2226                 slope = (vmax_thole - vmin_thole) /
2227                         (t2t_coeffs->vmax - t2t_coeffs->vmin);
2228                 inpt = ((vmax_thole * 1000) - (slope * 1250)) / 1000;
2229                 calc_values->vmax_thole = slope * voltage_mv + inpt;
2230         }
2231
2232         return 0;
2233 }
2234
2235 /*
2236  * All coeffs are filled up in the table after multiplying by 1000. So, all
2237  * calculations should have a divide by 1000 at the end.
2238  */
2239 static int calculate_estimated_tuning_values(int speedo,
2240         struct tegra_tuning_data *tuning_data, int voltage_mv)
2241 {
2242         struct tuning_t2t_coeffs *t2t_coeffs = tuning_data->t2t_coeffs;
2243         struct tap_hole_coeffs *thole_coeffs = tuning_data->thole_coeffs;
2244         struct tuning_values *est_values = &tuning_data->est_values;
2245         int slope, inpt;
2246         int vmax_t2t, vmin_t2t;
2247         int vmax_thole, vmin_thole;
2248
2249         /* Est_T2T_Vmax = (speedo*(-t2t_slope)+t2t_int */
2250         vmax_t2t = (t2t_coeffs->t2t_vmax_int - (speedo *
2251                 t2t_coeffs->t2t_vmax_slope)) / 1000;
2252         vmin_t2t = (t2t_coeffs->t2t_vmin_int - (speedo *
2253                 t2t_coeffs->t2t_vmin_slope)) / 1000;
2254         est_values->t2t_vmin = vmin_t2t;
2255
2256         if (voltage_mv == t2t_coeffs->vmin) {
2257                 est_values->t2t_vmax = vmin_t2t;
2258         } else if (voltage_mv == t2t_coeffs->vmax) {
2259                 est_values->t2t_vmax = vmax_t2t;
2260         } else {
2261                 vmax_t2t = 1000 / vmax_t2t;
2262                 vmin_t2t = 1000 / vmin_t2t;
2263                 /*
2264                  * For any intermediate voltage between 0.95V and 1.25V,
2265                  * calculate the slope and intercept from the T2T and tap hole
2266                  * values of 0.95V and 1.25V and use them to calculate the
2267                  * actual values. 1/T2T is a linear function of voltage.
2268                  */
2269                 slope = ((vmax_t2t - vmin_t2t) * 1000) /
2270                         (t2t_coeffs->vmax - t2t_coeffs->vmin);
2271                 inpt = (vmax_t2t * 1000 - (slope * t2t_coeffs->vmax)) / 1000;
2272                 est_values->t2t_vmax = (slope * voltage_mv) / 1000 + inpt;
2273                 est_values->t2t_vmax = (1000 / est_values->t2t_vmax);
2274         }
2275
2276         /* Est_UI  = (1000000/freq_MHz)/Est_T2T_Vmax */
2277         est_values->ui = (1000000 / (thole_coeffs->freq_khz / 1000)) /
2278                 est_values->t2t_vmax;
2279
2280         /*
2281          * Est_1'st_hole = (Est_T2T_Vmax*(-thole_slope)) + thole_int.
2282          */
2283         vmax_thole = (thole_coeffs->thole_vmax_int -
2284                 (thole_coeffs->thole_vmax_slope * est_values->t2t_vmax)) / 1000;
2285         vmin_thole = (thole_coeffs->thole_vmin_int -
2286                 (thole_coeffs->thole_vmin_slope * est_values->t2t_vmax)) / 1000;
2287
2288         if (voltage_mv == t2t_coeffs->vmin) {
2289                 est_values->vmax_thole = vmin_thole;
2290         } else if (voltage_mv == t2t_coeffs->vmax) {
2291                 est_values->vmax_thole = vmax_thole;
2292         } else {
2293                 /*
2294                  * For any intermediate voltage between 0.95V and 1.25V,
2295                  * calculate the slope and intercept from the t2t and tap hole
2296                  * values of 0.95V and 1.25V and use them to calculate the
2297                  * actual values. Tap hole is a linear function of voltage.
2298                  */
2299                 slope = ((vmax_thole - vmin_thole) * 1000) /
2300                         (t2t_coeffs->vmax - t2t_coeffs->vmin);
2301                 inpt = (vmax_thole * 1000 - (slope * t2t_coeffs->vmax)) / 1000;
2302                 est_values->vmax_thole = (slope * voltage_mv) / 1000 + inpt;
2303         }
2304         est_values->vmin_thole = vmin_thole;
2305
2306         return 0;
2307 }
2308
2309 /*
2310  * Insert the calculated holes and get the final tap windows
2311  * with the boundaries and holes set.
2312  */
2313 static int adjust_holes_in_tap_windows(struct sdhci_host *sdhci,
2314         struct tegra_tuning_data *tuning_data)
2315 {
2316         struct tap_window_data *tap_data;
2317         struct tap_window_data *final_tap_data;
2318         struct tuning_values *calc_values = &tuning_data->calc_values;
2319         int tap_hole, size = 0;
2320         u8 i = 0, j = 0, num_of_wins, hole_pos = 0;
2321
2322         tuning_data->final_tap_data =
2323                 devm_kzalloc(mmc_dev(sdhci->mmc),
2324                         sizeof(struct tap_window_data) * 42, GFP_KERNEL);
2325         if (IS_ERR_OR_NULL(tuning_data->final_tap_data)) {
2326                 dev_err(mmc_dev(sdhci->mmc), "No mem for final tap wins\n");
2327                 return -ENOMEM;
2328         }
2329
2330         num_of_wins = tuning_data->num_of_valid_tap_wins;
2331         tap_hole = calc_values->vmax_thole;
2332         hole_pos++;
2333         do {
2334                 tap_data = &tuning_data->tap_data[i];
2335                 final_tap_data = &tuning_data->final_tap_data[j];
2336                 if (tap_hole < tap_data->win_start) {
2337                         tap_hole += calc_values->ui;
2338                         hole_pos++;
2339                         continue;
2340                 } else if (tap_hole > tap_data->win_end) {
2341                         memcpy(final_tap_data, tap_data,
2342                                 sizeof(struct tap_window_data));
2343                         i++;
2344                         j++;
2345                         num_of_wins--;
2346                         continue;
2347                 } else if ((tap_hole >= tap_data->win_start) &&
2348                         (tap_hole <= tap_data->win_end)) {
2349                         size = tap_data->win_end - tap_data->win_start;
2350                         do {
2351                                 final_tap_data =
2352                                         &tuning_data->final_tap_data[j];
2353                                 if (tap_hole == tap_data->win_start) {
2354                                         final_tap_data->win_start =
2355                                                 tap_hole + 1;
2356                                         final_tap_data->win_start_attr =
2357                                                 WIN_EDGE_HOLE;
2358                                         final_tap_data->hole_pos = hole_pos;
2359                                         tap_hole += calc_values->ui;
2360                                         hole_pos++;
2361                                 } else {
2362                                         final_tap_data->win_start =
2363                                                 tap_data->win_start;
2364                                         final_tap_data->win_start_attr =
2365                                                 WIN_EDGE_BOUN_START;
2366                                 }
2367                                 if (tap_hole <= tap_data->win_end) {
2368                                         final_tap_data->win_end = tap_hole - 1;
2369                                         final_tap_data->win_end_attr =
2370                                                 WIN_EDGE_HOLE;
2371                                         final_tap_data->hole_pos = hole_pos;
2372                                         tap_data->win_start = tap_hole;
2373                                 } else if (tap_hole > tap_data->win_end) {
2374                                         final_tap_data->win_end =
2375                                                 tap_data->win_end;
2376                                         final_tap_data->win_end_attr =
2377                                                 WIN_EDGE_BOUN_END;
2378                                         tap_data->win_start =
2379                                                 tap_data->win_end;
2380                                 }
2381                                 size = tap_data->win_end - tap_data->win_start;
2382                                 j++;
2383                         } while (size > 0);
2384                         i++;
2385                         num_of_wins--;
2386                 }
2387         } while (num_of_wins > 0);
2388
2389         /* Update the num of valid wins count after tap holes insertion */
2390         tuning_data->num_of_valid_tap_wins = j;
2391
2392         pr_info("********tuning windows after inserting holes*****\n");
2393         pr_info("WIN_ATTR legend: 0-BOUN_ST, 1-BOUN_END, 2-HOLE\n");
2394         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
2395                 final_tap_data = &tuning_data->final_tap_data[i];
2396                 pr_info("win[%d]:%d(%d) - %d(%d)\n", i,
2397                         final_tap_data->win_start,
2398                         final_tap_data->win_start_attr,
2399                         final_tap_data->win_end, final_tap_data->win_end_attr);
2400         }
2401         pr_info("***********************************************\n");
2402
2403         return 0;
2404 }
2405
2406 /*
2407  * Insert the boundaries from negative margin calculations into the windows
2408  * from auto tuning.
2409  */
2410 static int insert_boundaries_in_tap_windows(struct sdhci_host *sdhci,
2411         struct tegra_tuning_data *tuning_data, u8 boun_end)
2412 {
2413         struct tap_window_data *tap_data;
2414         struct tap_window_data *new_tap_data;
2415         struct tap_window_data *temp_tap_data;
2416         struct tuning_values *calc_values = &tuning_data->calc_values;
2417         int curr_boun;
2418         u8 i = 0, j = 0, num_of_wins;
2419         bool get_next_boun = false;
2420
2421         temp_tap_data = devm_kzalloc(mmc_dev(sdhci->mmc),
2422                         sizeof(struct tap_window_data) * 42, GFP_KERNEL);
2423         if (IS_ERR_OR_NULL(temp_tap_data)) {
2424                 dev_err(mmc_dev(sdhci->mmc), "No mem for final tap wins\n");
2425                 return -ENOMEM;
2426         }
2427
2428         num_of_wins = tuning_data->num_of_valid_tap_wins;
2429         curr_boun = boun_end % calc_values->ui;
2430         do {
2431                 if (get_next_boun) {
2432                         curr_boun += calc_values->ui;
2433                         /*
2434                          * If the boun_end exceeds the intial boundary end,
2435                          * just copy remaining windows and return.
2436                          */
2437                         if (curr_boun >= boun_end)
2438                                 curr_boun += MAX_TAP_VALUES;
2439                 }
2440
2441                 tap_data = &tuning_data->tap_data[i];
2442                 new_tap_data = &temp_tap_data[j];
2443                 if (curr_boun <= tap_data->win_start) {
2444                         get_next_boun = true;
2445                         continue;
2446                 } else if (curr_boun >= tap_data->win_end) {
2447                         memcpy(new_tap_data, tap_data,
2448                                 sizeof(struct tap_window_data));
2449                         i++;
2450                         j++;
2451                         num_of_wins--;
2452                         get_next_boun = false;
2453                         continue;
2454                 } else if ((curr_boun >= tap_data->win_start) &&
2455                         (curr_boun <= tap_data->win_end)) {
2456                                 new_tap_data->win_start = tap_data->win_start;
2457                                 new_tap_data->win_start_attr =
2458                                         tap_data->win_start_attr;
2459                                 new_tap_data->win_end = curr_boun - 1;
2460                                 new_tap_data->win_end_attr =
2461                                         tap_data->win_end_attr;
2462                                 j++;
2463                                 new_tap_data = &temp_tap_data[j];
2464                                 new_tap_data->win_start = curr_boun;
2465                                 new_tap_data->win_end = curr_boun;
2466                                 new_tap_data->win_start_attr =
2467                                         WIN_EDGE_BOUN_START;
2468                                 new_tap_data->win_end_attr =
2469                                         WIN_EDGE_BOUN_END;
2470                                 j++;
2471                                 new_tap_data = &temp_tap_data[j];
2472                                 new_tap_data->win_start = curr_boun + 1;
2473                                 new_tap_data->win_start_attr = WIN_EDGE_BOUN_START;
2474                                 new_tap_data->win_end = tap_data->win_end;
2475                                 new_tap_data->win_end_attr =
2476                                         tap_data->win_end_attr;
2477                                 i++;
2478                                 j++;
2479                                 num_of_wins--;
2480                                 get_next_boun = true;
2481                 }
2482         } while (num_of_wins > 0);
2483
2484         /* Update the num of valid wins count after tap holes insertion */
2485         tuning_data->num_of_valid_tap_wins = j;
2486
2487         memcpy(tuning_data->tap_data, temp_tap_data,
2488                 j * sizeof(struct tap_window_data));
2489         SDHCI_TEGRA_DBG("***tuning windows after inserting boundaries***\n");
2490         SDHCI_TEGRA_DBG("WIN_ATTR legend: 0-BOUN_ST, 1-BOUN_END, 2-HOLE\n");
2491         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
2492                 new_tap_data = &tuning_data->tap_data[i];
2493                 SDHCI_TEGRA_DBG("win[%d]:%d(%d) - %d(%d)\n", i,
2494                         new_tap_data->win_start,
2495                         new_tap_data->win_start_attr,
2496                         new_tap_data->win_end, new_tap_data->win_end_attr);
2497         }
2498         SDHCI_TEGRA_DBG("***********************************************\n");
2499
2500         return 0;
2501 }
2502
2503 /*
2504  * Scan for all tap values and get all passing tap windows.
2505  */
2506 static int sdhci_tegra_get_tap_window_data(struct sdhci_host *sdhci,
2507         struct tegra_tuning_data *tuning_data)
2508 {
2509         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2510         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2511         struct tap_window_data *tap_data;
2512         struct tuning_ui tuning_ui[10];
2513         int err = 0, partial_win_start = 0, temp_margin = 0;
2514         unsigned int tap_value, calc_ui = 0;
2515         u8 prev_boundary_end = 0, num_of_wins = 0;
2516         u8 num_of_uis = 0, valid_num_uis = 0;
2517         u8 ref_ui, first_valid_full_win = 0;
2518         u8 boun_end = 0, next_boun_end = 0;
2519         u8 j = 0;
2520         bool valid_ui_found = false;
2521
2522         /*
2523          * Assume there are a max of 10 windows and allocate tap window
2524          * structures for the same. If there are more windows, the array
2525          * size can be adjusted later using realloc.
2526          */
2527         tuning_data->tap_data = devm_kzalloc(mmc_dev(sdhci->mmc),
2528                 sizeof(struct tap_window_data) * 42, GFP_KERNEL);
2529         if (IS_ERR_OR_NULL(tuning_data->tap_data)) {
2530                 dev_err(mmc_dev(sdhci->mmc), "No memory for tap data\n");
2531                 return -ENOMEM;
2532         }
2533
2534         spin_lock(&sdhci->lock);
2535         tap_value = 0;
2536         do {
2537                 tap_data = &tuning_data->tap_data[num_of_wins];
2538                 /* Get the window start */
2539                 tap_value = sdhci_tegra_scan_tap_values(sdhci, tap_value, true);
2540                 tap_data->win_start = min_t(u8, tap_value, MAX_TAP_VALUES);
2541                 tap_value++;
2542                 if (tap_value >= MAX_TAP_VALUES) {
2543                         /* If it's first iteration, then all taps failed */
2544                         if (!num_of_wins) {
2545                                 dev_err(mmc_dev(sdhci->mmc),
2546                                         "All tap values(0-255) failed\n");
2547                                 spin_unlock(&sdhci->lock);
2548                                 return -EINVAL;
2549                         } else {
2550                                 /* All windows obtained */
2551                                 break;
2552                         }
2553                 }
2554
2555                 /* Get the window end */
2556                 tap_value = sdhci_tegra_scan_tap_values(sdhci,
2557                                 tap_value, false);
2558                 tap_data->win_end = min_t(u8, (tap_value - 1), MAX_TAP_VALUES);
2559                 tap_data->win_size = tap_data->win_end - tap_data->win_start;
2560                 tap_value++;
2561
2562                 /*
2563                  * If the size of window is more than 4 taps wide, then it is a
2564                  * valid window. If tap value 0 has passed, then a partial
2565                  * window exists. Mark all the window edges as boundary edges.
2566                  */
2567                 if (tap_data->win_size > 4) {
2568                         if (tap_data->win_start == 0)
2569                                 tuning_data->is_partial_win_valid = true;
2570                         tap_data->win_start_attr = WIN_EDGE_BOUN_START;
2571                         tap_data->win_end_attr = WIN_EDGE_BOUN_END;
2572                 } else {
2573                         /* Invalid window as size is less than 5 taps */
2574                         SDHCI_TEGRA_DBG("Invalid tuning win (%d-%d) ignored\n",
2575                                 tap_data->win_start, tap_data->win_end);
2576                         continue;
2577                 }
2578
2579                 /* Ignore first and last partial UIs */
2580                 if (tap_data->win_end_attr == WIN_EDGE_BOUN_END) {
2581                                 tuning_ui[num_of_uis].ui = tap_data->win_end -
2582                                         prev_boundary_end;
2583                                 tuning_ui[num_of_uis].is_valid_ui = true;
2584                                 num_of_uis++;
2585                         prev_boundary_end = tap_data->win_end;
2586                 }
2587                 num_of_wins++;
2588         } while (tap_value < MAX_TAP_VALUES);
2589         spin_unlock(&sdhci->lock);
2590
2591         tuning_data->num_of_valid_tap_wins = num_of_wins;
2592         valid_num_uis = num_of_uis;
2593
2594         /* Print info of all tap windows */
2595         pr_info("**********Auto tuning windows*************\n");
2596         pr_info("WIN_ATTR legend: 0-BOUN_ST, 1-BOUN_END, 2-HOLE\n");
2597         for (j = 0; j < tuning_data->num_of_valid_tap_wins; j++) {
2598                 tap_data = &tuning_data->tap_data[j];
2599                 pr_info("win[%d]: %d(%d) - %d(%d)\n",
2600                         j, tap_data->win_start, tap_data->win_start_attr,
2601                         tap_data->win_end, tap_data->win_end_attr);
2602         }
2603         pr_info("***************************************\n");
2604
2605         /* Mark the first last partial UIs as invalid */
2606         tuning_ui[0].is_valid_ui = false;
2607         tuning_ui[num_of_uis - 1].is_valid_ui = false;
2608         valid_num_uis -= 2;
2609
2610         /* Discredit all uis at either end with size less than 30% of est ui */
2611         ref_ui = (30 * tuning_data->est_values.ui) / 100;
2612         for (j = 0; j < num_of_uis; j++) {
2613                 if (tuning_ui[j].is_valid_ui) {
2614                         tuning_ui[j].is_valid_ui = false;
2615                         valid_num_uis--;
2616                 }
2617                 if (tuning_ui[j].ui > ref_ui)
2618                         break;
2619         }
2620
2621         for (j = num_of_uis; j > 0; j--) {
2622                 if (tuning_ui[j - 1].ui < ref_ui) {
2623                         if (tuning_ui[j - 1].is_valid_ui) {
2624                                 tuning_ui[j - 1].is_valid_ui = false;
2625                                 valid_num_uis--;
2626                         }
2627                 } else
2628                         break;
2629         }
2630
2631         /* Calculate 0.75*est_UI */
2632         ref_ui = (75 * tuning_data->est_values.ui) / 100;
2633
2634         /*
2635          * Check for valid UIs and discredit invalid UIs. A UI is considered
2636          * valid if it's greater than (0.75*est_UI). If an invalid UI is found,
2637          * also discredit the smaller of the two adjacent windows.
2638          */
2639         for (j = 1; j < (num_of_uis - 1); j++) {
2640                 if (tuning_ui[j].ui > ref_ui && tuning_ui[j].is_valid_ui) {
2641                         tuning_ui[j].is_valid_ui = true;
2642                 } else {
2643                         if (tuning_ui[j].is_valid_ui) {
2644                                 tuning_ui[j].is_valid_ui = false;
2645                                 valid_num_uis--;
2646                         }
2647                         if (!tuning_ui[j + 1].is_valid_ui ||
2648                                 !tuning_ui[j - 1].is_valid_ui) {
2649                                 if (tuning_ui[j - 1].is_valid_ui) {
2650                                         tuning_ui[j - 1].is_valid_ui = false;
2651                                         valid_num_uis--;
2652                                 } else if (tuning_ui[j + 1].is_valid_ui) {
2653                                         tuning_ui[j + 1].is_valid_ui = false;
2654                                         valid_num_uis--;
2655                                 }
2656                         } else {
2657
2658                                 if (tuning_ui[j - 1].ui > tuning_ui[j + 1].ui)
2659                                         tuning_ui[j + 1].is_valid_ui = false;
2660                                 else
2661                                         tuning_ui[j - 1].is_valid_ui = false;
2662                                 valid_num_uis--;
2663                         }
2664                 }
2665         }
2666
2667         /* Calculate the cumulative UI if there are valid UIs left */
2668         if (valid_num_uis) {
2669                 for (j = 0; j < num_of_uis; j++)
2670                         if (tuning_ui[j].is_valid_ui) {
2671                                 calc_ui += tuning_ui[j].ui;
2672                                 if (!first_valid_full_win)
2673                                         first_valid_full_win = j;
2674                         }
2675         }
2676
2677         if (calc_ui) {
2678                 tuning_data->calc_values.ui = (calc_ui / valid_num_uis);
2679                 valid_ui_found = true;
2680         } else {
2681                 tuning_data->calc_values.ui = tuning_data->est_values.ui;
2682                 valid_ui_found = false;
2683         }
2684
2685         SDHCI_TEGRA_DBG("****Tuning UIs***********\n");
2686         for (j = 0; j < num_of_uis; j++)
2687                 SDHCI_TEGRA_DBG("Tuning UI[%d] : %d, Is valid[%d]\n",
2688                         j, tuning_ui[j].ui, tuning_ui[j].is_valid_ui);
2689         SDHCI_TEGRA_DBG("*************************\n");
2690
2691         /* Get the calculated tuning values */
2692         err = calculate_actual_tuning_values(tegra_host->speedo, tuning_data,
2693                 tegra_host->boot_vcore_mv);
2694
2695         /*
2696          * Calculate negative margin if partial win is valid. There are two
2697          * cases here.
2698          * Case 1: If Avg_UI is found, then keep subtracting avg_ui from start
2699          * of first valid full window until a value <=0 is obtained.
2700          * Case 2: If Avg_UI is not found, subtract avg_ui from all boundary
2701          * starts until a value <=0 is found.
2702          */
2703         if (tuning_data->is_partial_win_valid && (num_of_wins > 1)) {
2704                 if (valid_ui_found) {
2705                         partial_win_start =
2706                         tuning_data->tap_data[first_valid_full_win].win_start;
2707                         boun_end = partial_win_start;
2708                         partial_win_start %= tuning_data->calc_values.ui;
2709                         partial_win_start -= tuning_data->calc_values.ui;
2710                 } else {
2711                         for (j = 0; j < NEG_MAR_CHK_WIN_COUNT; j++) {
2712                                 temp_margin =
2713                                         tuning_data->tap_data[j + 1].win_start;
2714                                 if (!boun_end)
2715                                         boun_end = temp_margin;
2716                                 else if (!next_boun_end)
2717                                         next_boun_end = temp_margin;
2718                                 temp_margin %= tuning_data->calc_values.ui;
2719                                 temp_margin -= tuning_data->calc_values.ui;
2720                                 if (!partial_win_start ||
2721                                         (temp_margin > partial_win_start))
2722                                         partial_win_start = temp_margin;
2723                         }
2724                 }
2725                 if (partial_win_start <= 0)
2726                         tuning_data->tap_data[0].win_start = partial_win_start;
2727         }
2728
2729         if (boun_end)
2730                 insert_boundaries_in_tap_windows(sdhci, tuning_data, boun_end);
2731         if (next_boun_end)
2732                 insert_boundaries_in_tap_windows(sdhci, tuning_data, next_boun_end);
2733
2734         /* Insert calculated holes into the windows */
2735         err = adjust_holes_in_tap_windows(sdhci, tuning_data);
2736
2737         return err;
2738 }
2739
2740 static void sdhci_tegra_dump_tuning_constraints(struct sdhci_host *sdhci)
2741 {
2742         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2743         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2744         struct tegra_tuning_data *tuning_data;
2745         u8 i;
2746
2747         SDHCI_TEGRA_DBG("%s: Num of tuning frequencies%d\n",
2748                 mmc_hostname(sdhci->mmc), tegra_host->tuning_freq_count);
2749         for (i = 0; i < tegra_host->tuning_freq_count; ++i) {
2750                 tuning_data = &tegra_host->tuning_data[i];
2751                 SDHCI_TEGRA_DBG("%s: Tuning freq[%d]: %d, freq band %d\n",
2752                         mmc_hostname(sdhci->mmc), i,
2753                         tuning_data->freq_hz, tuning_data->freq_band);
2754         }
2755 }
2756
2757 static unsigned int get_tuning_voltage(struct sdhci_tegra *tegra_host, u8 *mask)
2758 {
2759         u8 i = 0;
2760
2761         i = ffs(*mask) - 1;
2762         *mask &= ~(1 << i);
2763         switch (BIT(i)) {
2764         case NOMINAL_VCORE_TUN:
2765                 return tegra_host->nominal_vcore_mv;
2766         case BOOT_VCORE_TUN:
2767                 return tegra_host->boot_vcore_mv;
2768         case MIN_OVERRIDE_VCORE_TUN:
2769                 return tegra_host->min_vcore_override_mv;
2770         }
2771
2772         return tegra_host->boot_vcore_mv;
2773 }
2774
2775 static u8 sdhci_tegra_get_freq_point(struct sdhci_host *sdhci)
2776 {
2777         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2778         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2779         const unsigned int *freq_list;
2780         u32 curr_clock;
2781         u8 i;
2782
2783         curr_clock = sdhci->max_clk;
2784         freq_list = tegra_host->soc_data->tuning_freq_list;
2785
2786         for (i = 0; i < TUNING_FREQ_COUNT; ++i)
2787                 if (curr_clock <= freq_list[i])
2788                         return i;
2789
2790         return TUNING_MAX_FREQ;
2791 }
2792
2793 /*
2794  * The frequency tuning algorithm tries to calculate the tap-to-tap delay
2795  * UI and estimate holes using equations and predetermined coefficients from
2796  * the characterization data. The algorithm will not work without this data.
2797  */
2798 static int find_tuning_coeffs_data(struct sdhci_host *sdhci,
2799                                         bool force_retuning)
2800 {
2801         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2802         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2803         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
2804         struct tegra_tuning_data *tuning_data;
2805         struct tuning_t2t_coeffs *t2t_coeffs;
2806         struct tap_hole_coeffs *thole_coeffs;
2807         const char *dev_id;
2808         unsigned int freq_khz;
2809         u8 i, j;
2810         bool coeffs_set = false;
2811
2812         dev_id = dev_name(mmc_dev(sdhci->mmc));
2813         /* Find the coeffs data for all supported frequencies */
2814         for (i = 0; i < tegra_host->tuning_freq_count; i++) {
2815                 tuning_data = &tegra_host->tuning_data[i];
2816
2817                 /* Skip if T2T coeffs are already found */
2818                 if (tuning_data->t2t_coeffs == NULL || force_retuning) {
2819                         t2t_coeffs = soc_data->t2t_coeffs;
2820                         for (j = 0; j < soc_data->t2t_coeffs_count; j++) {
2821                                 if (!strcmp(dev_id, t2t_coeffs->dev_id)) {
2822                                         tuning_data->t2t_coeffs = t2t_coeffs;
2823                                         coeffs_set = true;
2824                                         dev_info(mmc_dev(sdhci->mmc),
2825                                                 "Found T2T coeffs data\n");
2826                                         break;
2827                                 }
2828                                 t2t_coeffs++;
2829                         }
2830                         if (!coeffs_set) {
2831                                 dev_err(mmc_dev(sdhci->mmc),
2832                                         "T2T coeffs data missing\n");
2833                                 tuning_data->t2t_coeffs = NULL;
2834                                 return -ENODATA;
2835                         }
2836                 }
2837
2838                 coeffs_set = false;
2839                 /* Skip if tap hole coeffs are already found */
2840                 if (tuning_data->thole_coeffs == NULL || force_retuning) {
2841                         thole_coeffs = soc_data->tap_hole_coeffs;
2842                         freq_khz = tuning_data->freq_hz / 1000;
2843                         for (j = 0; j < soc_data->tap_hole_coeffs_count; j++) {
2844                                 if (!strcmp(dev_id, thole_coeffs->dev_id) &&
2845                                         (freq_khz == thole_coeffs->freq_khz)) {
2846                                         tuning_data->thole_coeffs =
2847                                                 thole_coeffs;
2848                                         coeffs_set = true;
2849                                         dev_info(mmc_dev(sdhci->mmc),
2850                                                 "%dMHz tap hole coeffs found\n",
2851                                                 (freq_khz / 1000));
2852                                         break;
2853                                 }
2854                                 thole_coeffs++;
2855                         }
2856
2857                         if (!coeffs_set) {
2858                                 dev_err(mmc_dev(sdhci->mmc),
2859                                         "%dMHz Tap hole coeffs data missing\n",
2860                                         (freq_khz / 1000));
2861                                 tuning_data->thole_coeffs = NULL;
2862                                 return -ENODATA;
2863                         }
2864                 }
2865         }
2866
2867         return 0;
2868 }
2869
2870 /*
2871  * Determines the numbers of frequencies required and then fills up the tuning
2872  * constraints for each of the frequencies. The data of lower frequency is
2873  * filled first and then the higher frequency data. Max supported frequencies
2874  * is currently two.
2875  */
2876 static int setup_freq_constraints(struct sdhci_host *sdhci,
2877         const unsigned int *freq_list)
2878 {
2879         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2880         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2881         struct tegra_tuning_data *tuning_data;
2882         int i, freq_count;
2883         u8 freq_band;
2884
2885         if ((sdhci->mmc->ios.timing != MMC_TIMING_UHS_SDR50) &&
2886                 (sdhci->mmc->caps2 & MMC_CAP2_FREQ_SCALING))
2887                 freq_count = DFS_FREQ_COUNT;
2888         else
2889                 freq_count = 1;
2890
2891         freq_band = sdhci_tegra_get_freq_point(sdhci);
2892         /* Fill up the req frequencies */
2893         switch (freq_count) {
2894         case 1:
2895                 tuning_data = &tegra_host->tuning_data[0];
2896                 tuning_data->freq_hz = sdhci->max_clk;
2897                 tuning_data->freq_band = freq_band;
2898                 tuning_data->constraints.vcore_mask =
2899                         tuning_vcore_constraints[freq_band].vcore_mask;
2900                 tuning_data->nr_voltages =
2901                         hweight32(tuning_data->constraints.vcore_mask);
2902         break;
2903         case 2:
2904                 tuning_data = &tegra_host->tuning_data[1];
2905                 tuning_data->freq_hz = sdhci->max_clk;
2906                 tuning_data->freq_band = freq_band;
2907                 tuning_data->constraints.vcore_mask =
2908                         tuning_vcore_constraints[freq_band].vcore_mask;
2909                 tuning_data->nr_voltages =
2910                         hweight32(tuning_data->constraints.vcore_mask);
2911
2912                 tuning_data = &tegra_host->tuning_data[0];
2913                 for (i = (freq_band - 1); i >= 0; i--) {
2914                         if (!freq_list[i])
2915                                 continue;
2916                         tuning_data->freq_hz = freq_list[i];
2917                         tuning_data->freq_band = i;
2918                         tuning_data->nr_voltages = 1;
2919                         tuning_data->constraints.vcore_mask =
2920                                 tuning_vcore_constraints[i].vcore_mask;
2921                         tuning_data->nr_voltages =
2922                                 hweight32(tuning_data->constraints.vcore_mask);
2923                 }
2924         break;
2925         default:
2926                 dev_err(mmc_dev(sdhci->mmc), "Unsupported freq count\n");
2927                 freq_count = -1;
2928         }
2929
2930         return freq_count;
2931 }
2932
2933 /*
2934  * Get the supported frequencies and other tuning related constraints for each
2935  * frequency. The supported frequencies should be determined from the list of
2936  * frequencies in the soc data and also consider the platform clock limits as
2937  * well as any DFS related restrictions.
2938  */
2939 static int sdhci_tegra_get_tuning_constraints(struct sdhci_host *sdhci,
2940                                                         bool force_retuning)
2941 {
2942         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2943         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2944         const unsigned int *freq_list;
2945         int err = 0;
2946
2947         /* A valid freq count means freq constraints are already set up */
2948         if (!tegra_host->tuning_freq_count || force_retuning) {
2949                 freq_list = tegra_host->soc_data->tuning_freq_list;
2950                 tegra_host->tuning_freq_count =
2951                         setup_freq_constraints(sdhci, freq_list);
2952                 if (tegra_host->tuning_freq_count < 0) {
2953                         dev_err(mmc_dev(sdhci->mmc),
2954                                 "Invalid tuning freq count\n");
2955                         return -EINVAL;
2956                 }
2957         }
2958
2959         err = find_tuning_coeffs_data(sdhci, force_retuning);
2960         if (err)
2961                 return err;
2962
2963         sdhci_tegra_dump_tuning_constraints(sdhci);
2964
2965         return err;
2966 }
2967
2968 /*
2969  * During boot, only boot voltage for vcore can be set. Check if the current
2970  * voltage is allowed to be used. Nominal and min override voltages can be
2971  * set once boot is done. This will be notified through late subsys init call.
2972  */
2973 static int sdhci_tegra_set_tuning_voltage(struct sdhci_host *sdhci,
2974         unsigned int voltage)
2975 {
2976         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2977         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2978         int err = 0;
2979         bool nom_emc_freq_set = false;
2980
2981         if (voltage && (voltage != tegra_host->boot_vcore_mv) &&
2982                 !vcore_overrides_allowed) {
2983                 SDHCI_TEGRA_DBG("%s: Override vcore %dmv not allowed\n",
2984                         mmc_hostname(sdhci->mmc), voltage);
2985                 return -EPERM;
2986         }
2987
2988         SDHCI_TEGRA_DBG("%s: Setting vcore override %d\n",
2989                 mmc_hostname(sdhci->mmc), voltage);
2990         /*
2991          * First clear any previous dvfs override settings. If dvfs overrides
2992          * are disabled, then print the error message but continue execution
2993          * rather than failing tuning altogether.
2994          */
2995         err = tegra_dvfs_override_core_voltage(pltfm_host->clk, 0);
2996         if ((err == -EPERM) || (err == -ENOSYS)) {
2997                 /*
2998                  * tegra_dvfs_override_core_voltage will return EPERM or ENOSYS,
2999                  * when DVFS override is not enabled. Continue tuning
3000                  * with default core voltage
3001                  */
3002                 SDHCI_TEGRA_DBG("dvfs overrides disabled. Nothing to clear\n");
3003                 err = 0;
3004         }
3005         if (!voltage)
3006                 return err;
3007
3008         /* EMC clock freq boost might be required for nominal core voltage */
3009         if ((voltage == tegra_host->nominal_vcore_mv) &&
3010                 tegra_host->plat->en_nominal_vcore_tuning &&
3011                 tegra_host->emc_clk) {
3012                 err = clk_set_rate(tegra_host->emc_clk,
3013                         SDMMC_EMC_NOM_VOLT_FREQ);
3014                 if (err)
3015                         dev_err(mmc_dev(sdhci->mmc),
3016                                 "Failed to set emc nom clk freq %d\n", err);
3017                 else
3018                         nom_emc_freq_set = true;
3019         }
3020
3021         /*
3022          * If dvfs overrides are disabled, then print the error message but
3023          * continue tuning execution rather than failing tuning altogether.
3024          */
3025         err = tegra_dvfs_override_core_voltage(pltfm_host->clk, voltage);
3026         if ((err == -EPERM) || (err == -ENOSYS)) {
3027                 /*
3028                  * tegra_dvfs_override_core_voltage will return EPERM or ENOSYS,
3029                  * when DVFS override is not enabled. Continue tuning
3030                  * with default core voltage
3031                  */
3032                 SDHCI_TEGRA_DBG("dvfs overrides disabled. No overrides set\n");
3033                 err = 0;
3034         } else if (err)
3035                 dev_err(mmc_dev(sdhci->mmc),
3036                         "failed to set vcore override %dmv\n", voltage);
3037
3038         /* Revert emc clock to normal freq */
3039         if (nom_emc_freq_set) {
3040                 err = clk_set_rate(tegra_host->emc_clk, SDMMC_EMC_MAX_FREQ);
3041                 if (err)
3042                         dev_err(mmc_dev(sdhci->mmc),
3043                                 "Failed to revert emc nom clk freq %d\n", err);
3044         }
3045
3046         return err;
3047 }
3048
3049 static int sdhci_tegra_run_tuning(struct sdhci_host *sdhci,
3050         struct tegra_tuning_data *tuning_data)
3051 {
3052         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3053         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3054         int err = 0;
3055         int voltage = 0;
3056         u8 i, vcore_mask = 0;
3057
3058         vcore_mask = tuning_data->constraints.vcore_mask;
3059         for (i = 0; i < tuning_data->nr_voltages; i++) {
3060                 voltage = get_tuning_voltage(tegra_host, &vcore_mask);
3061                 err = sdhci_tegra_set_tuning_voltage(sdhci, voltage);
3062                 if (err) {
3063                         dev_err(mmc_dev(sdhci->mmc),
3064                                 "Unable to set override voltage.\n");
3065                         return err;
3066                 }
3067
3068                 /* Get the tuning window info */
3069                 SDHCI_TEGRA_DBG("Getting tuning windows...\n");
3070                 err = sdhci_tegra_get_tap_window_data(sdhci, tuning_data);
3071                 if (err) {
3072                         dev_err(mmc_dev(sdhci->mmc),
3073                                 "Failed to get tap win %d\n", err);
3074                         return err;
3075                 }
3076                 SDHCI_TEGRA_DBG("%s: %d tuning window data obtained\n",
3077                         mmc_hostname(sdhci->mmc), tuning_data->freq_hz);
3078         }
3079         return err;
3080 }
3081
3082 static int sdhci_tegra_verify_best_tap(struct sdhci_host *sdhci)
3083 {
3084         struct tegra_tuning_data *tuning_data;
3085         int err = 0;
3086
3087         tuning_data = sdhci_tegra_get_tuning_data(sdhci, sdhci->max_clk);
3088         if ((tuning_data->best_tap_value < 0) ||
3089                 (tuning_data->best_tap_value > MAX_TAP_VALUES)) {
3090                 dev_err(mmc_dev(sdhci->mmc),
3091                         "Trying to verify invalid best tap value\n");
3092                 return -EINVAL;
3093         } else {
3094                 dev_err(mmc_dev(sdhci->mmc),
3095                         "%s: tuning freq %dhz, best tap %d\n",
3096                         __func__, tuning_data->freq_hz,
3097                         tuning_data->best_tap_value);
3098         }
3099
3100         /* Set the best tap value */
3101         sdhci_tegra_set_tap_delay(sdhci, tuning_data->best_tap_value);
3102
3103         /* Run tuning after setting the best tap value */
3104         err = sdhci_tegra_issue_tuning_cmd(sdhci);
3105         if (err)
3106                 dev_err(mmc_dev(sdhci->mmc),
3107                         "%dMHz best tap value verification failed %d\n",
3108                         tuning_data->freq_hz, err);
3109         return err;
3110 }
3111
3112 static int sdhci_tegra_execute_tuning(struct sdhci_host *sdhci, u32 opcode)
3113 {
3114         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3115         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3116         struct tegra_tuning_data *tuning_data;
3117         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
3118         int err;
3119         u16 ctrl_2;
3120         u32 misc_ctrl;
3121         u32 ier;
3122         u8 i, set_retuning = 0;
3123         bool force_retuning = false;
3124         bool enable_lb_clk;
3125
3126         /* Tuning is valid only in SDR104 and SDR50 modes */
3127         ctrl_2 = sdhci_readw(sdhci, SDHCI_HOST_CONTROL2);
3128         if (!(((ctrl_2 & SDHCI_CTRL_UHS_MASK) == SDHCI_CTRL_UHS_SDR104) ||
3129                 (((ctrl_2 & SDHCI_CTRL_UHS_MASK) == SDHCI_CTRL_UHS_SDR50) &&
3130                 (sdhci->flags & SDHCI_SDR50_NEEDS_TUNING))))
3131                         return 0;
3132
3133         /* Tuning should be done only for MMC_BUS_WIDTH_8 and MMC_BUS_WIDTH_4 */
3134         if (sdhci->mmc->ios.bus_width == MMC_BUS_WIDTH_8)
3135                 tegra_host->tuning_bsize = MMC_TUNING_BLOCK_SIZE_BUS_WIDTH_8;
3136         else if (sdhci->mmc->ios.bus_width == MMC_BUS_WIDTH_4)
3137                 tegra_host->tuning_bsize = MMC_TUNING_BLOCK_SIZE_BUS_WIDTH_4;
3138         else
3139                 return -EINVAL;
3140
3141         SDHCI_TEGRA_DBG("%s: Starting freq tuning\n", mmc_hostname(sdhci->mmc));
3142         enable_lb_clk = (soc_data->nvquirks &
3143                         NVQUIRK_DISABLE_EXTERNAL_LOOPBACK) &&
3144                         (tegra_host->instance == 2);
3145         if (enable_lb_clk) {
3146                 misc_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_MISC_CTRL);
3147                 misc_ctrl &= ~(1 <<
3148                         SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
3149                 sdhci_writel(sdhci, misc_ctrl, SDHCI_VNDR_MISC_CTRL);
3150         }
3151         mutex_lock(&tuning_mutex);
3152
3153         /* Set the tuning command to be used */
3154         tegra_host->tuning_opcode = opcode;
3155
3156         /*
3157          * Disable all interrupts signalling.Enable interrupt status
3158          * detection for buffer read ready and data crc. We use
3159          * polling for tuning as it involves less overhead.
3160          */
3161         ier = sdhci_readl(sdhci, SDHCI_INT_ENABLE);
3162         sdhci_writel(sdhci, 0, SDHCI_SIGNAL_ENABLE);
3163         sdhci_writel(sdhci, SDHCI_INT_DATA_AVAIL |
3164                 SDHCI_INT_DATA_CRC, SDHCI_INT_ENABLE);
3165
3166         /*
3167          * If tuning is already done and retune request is not set, then skip
3168          * best tap value calculation and use the old best tap value. If the
3169          * previous best tap value verification failed, force retuning.
3170          */
3171         if (tegra_host->tuning_status == TUNING_STATUS_DONE) {
3172                 err = sdhci_tegra_verify_best_tap(sdhci);
3173                 if (err) {
3174                         dev_err(mmc_dev(sdhci->mmc),
3175                                 "Prev best tap failed. Re-running tuning\n");
3176                         force_retuning = true;
3177                 } else {
3178                         goto out;
3179                 }
3180         }
3181
3182         if (tegra_host->force_retune == true) {
3183                 force_retuning = true;
3184                 tegra_host->force_retune = false;
3185         }
3186
3187         tegra_host->tuning_status = 0;
3188         err = sdhci_tegra_get_tuning_constraints(sdhci, force_retuning);
3189         if (err) {
3190                 dev_err(mmc_dev(sdhci->mmc),
3191                         "Failed to get tuning constraints\n");
3192                 goto out;
3193         }
3194
3195         for (i = 0; i < tegra_host->tuning_freq_count; i++) {
3196                 tuning_data = &tegra_host->tuning_data[i];
3197                 if (tuning_data->tuning_done && !force_retuning)
3198                         continue;
3199
3200                 SDHCI_TEGRA_DBG("%s: Setting tuning freq%d\n",
3201                         mmc_hostname(sdhci->mmc), tuning_data->freq_hz);
3202                 tegra_sdhci_set_clock(sdhci, tuning_data->freq_hz);
3203
3204                 SDHCI_TEGRA_DBG("%s: Calculating estimated tuning values\n",
3205                         mmc_hostname(sdhci->mmc));
3206                 err = calculate_estimated_tuning_values(tegra_host->speedo,
3207                         tuning_data, tegra_host->boot_vcore_mv);
3208                 if (err)
3209                         goto out;
3210
3211                 SDHCI_TEGRA_DBG("Running tuning...\n");
3212                 err = sdhci_tegra_run_tuning(sdhci, tuning_data);
3213                 if (err)
3214                         goto out;
3215
3216                 SDHCI_TEGRA_DBG("calculating best tap value\n");
3217                 err = sdhci_tegra_calculate_best_tap(sdhci, tuning_data);
3218                 if (err)
3219                         goto out;
3220
3221                 err = sdhci_tegra_verify_best_tap(sdhci);
3222                 if (!err && !set_retuning) {
3223                         tuning_data->tuning_done = true;
3224                         tegra_host->tuning_status |= TUNING_STATUS_DONE;
3225                 } else {
3226                         tegra_host->tuning_status |= TUNING_STATUS_RETUNE;
3227                 }
3228         }
3229 out:
3230         /* Release any override core voltages set */
3231         sdhci_tegra_set_tuning_voltage(sdhci, 0);
3232
3233         /* Enable interrupts. Enable full range for core voltage */
3234         sdhci_writel(sdhci, ier, SDHCI_INT_ENABLE);
3235         sdhci_writel(sdhci, ier, SDHCI_SIGNAL_ENABLE);
3236         mutex_unlock(&tuning_mutex);
3237
3238         SDHCI_TEGRA_DBG("%s: Freq tuning done\n", mmc_hostname(sdhci->mmc));
3239         if (enable_lb_clk) {
3240                 misc_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_MISC_CTRL);
3241                 if (err) {
3242                         /* Tuning is failed and card will try to enumerate in
3243                          * Legacy High Speed mode. So, Enable External Loopback
3244                          * for SDMMC3.
3245                          */
3246                         misc_ctrl |= (1 <<
3247                                 SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
3248                 } else {
3249                         misc_ctrl &= ~(1 <<
3250                                 SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
3251                 }
3252                 sdhci_writel(sdhci, misc_ctrl, SDHCI_VNDR_MISC_CTRL);
3253         }
3254         return err;
3255 }
3256
3257 static int __init sdhci_tegra_enable_vcore_override_tuning(void)
3258 {
3259         vcore_overrides_allowed = true;
3260         maintain_boot_voltage = false;
3261         return 0;
3262 }
3263 late_initcall(sdhci_tegra_enable_vcore_override_tuning);
3264
3265 static int tegra_sdhci_suspend(struct sdhci_host *sdhci)
3266 {
3267         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3268         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3269         int err = 0;
3270
3271         tegra_sdhci_set_clock(sdhci, 0);
3272
3273         /* Disable the power rails if any */
3274         if (tegra_host->card_present) {
3275                 err = tegra_sdhci_configure_regulators(tegra_host,
3276                         CONFIG_REG_DIS, 0, 0);
3277                 if (err)
3278                         dev_err(mmc_dev(sdhci->mmc),
3279                         "Regulators disable in suspend failed %d\n", err);
3280         }
3281         return err;
3282 }
3283
3284 static int tegra_sdhci_resume(struct sdhci_host *sdhci)
3285 {
3286         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3287         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3288         struct platform_device *pdev;
3289         struct tegra_sdhci_platform_data *plat;
3290         unsigned int signal_voltage = 0;
3291         int err;
3292
3293         pdev = to_platform_device(mmc_dev(sdhci->mmc));
3294         plat = pdev->dev.platform_data;
3295
3296         if (gpio_is_valid(plat->cd_gpio)) {
3297                 tegra_host->card_present =
3298                         (gpio_get_value_cansleep(plat->cd_gpio) == 0);
3299         }
3300
3301         /* Setting the min identification clock of freq 400KHz */
3302         tegra_sdhci_set_clock(sdhci, 400000);
3303
3304         /* Enable the power rails if any */
3305         if (tegra_host->card_present) {
3306                 err = tegra_sdhci_configure_regulators(tegra_host,
3307                         CONFIG_REG_EN, 0, 0);
3308                 if (err) {
3309                         dev_err(mmc_dev(sdhci->mmc),
3310                                 "Regulators enable in resume failed %d\n", err);
3311                         return err;
3312                 }
3313                 if (tegra_host->vdd_io_reg) {
3314                         if (plat->mmc_data.ocr_mask & SDHOST_1V8_OCR_MASK)
3315                                 signal_voltage = MMC_SIGNAL_VOLTAGE_180;
3316                         else
3317                                 signal_voltage = MMC_SIGNAL_VOLTAGE_330;
3318                         tegra_sdhci_signal_voltage_switch(sdhci,
3319                                 signal_voltage);
3320                 }
3321         }
3322
3323         /* Reset the controller and power on if MMC_KEEP_POWER flag is set*/
3324         if (sdhci->mmc->pm_flags & MMC_PM_KEEP_POWER) {
3325                 tegra_sdhci_reset(sdhci, SDHCI_RESET_ALL);
3326                 sdhci_writeb(sdhci, SDHCI_POWER_ON, SDHCI_POWER_CONTROL);
3327                 sdhci->pwr = 0;
3328
3329                 tegra_sdhci_do_calibration(sdhci, signal_voltage);
3330         }
3331
3332         return 0;
3333 }
3334
3335 static void tegra_sdhci_post_resume(struct sdhci_host *sdhci)
3336 {
3337         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3338         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3339
3340         /* Turn OFF the clocks if the device is not present */
3341         if ((!tegra_host->card_present || !sdhci->mmc->card) &&
3342                 tegra_host->clk_enabled)
3343                 tegra_sdhci_set_clock(sdhci, 0);
3344 }
3345
3346 /*
3347  * For tegra specific tuning, core voltage has to be fixed at different
3348  * voltages to get the tap values. Fixing the core voltage during tuning for one
3349  * device might affect transfers of other SDMMC devices. Check if tuning mutex
3350  * is locked before starting a data transfer. The new tuning procedure might
3351  * take at max 1.5s for completion for a single run. Taking DFS into count,
3352  * setting the max timeout for tuning mutex check a 3 secs. Since tuning is
3353  * run only during boot or the first time device is inserted, there wouldn't
3354  * be any delays in cmd/xfer execution once devices enumeration is done.
3355  */
3356 static void tegra_sdhci_get_bus(struct sdhci_host *sdhci)
3357 {
3358         unsigned int timeout = 300;
3359
3360         while (mutex_is_locked(&tuning_mutex)) {
3361                 msleep(10);
3362                 --timeout;
3363                 if (!timeout) {
3364                         dev_err(mmc_dev(sdhci->mmc),
3365                                 "Tuning mutex locked for long time\n");
3366                         return;
3367                 }
3368         };
3369 }
3370
3371 /*
3372  * The host/device can be powered off before the retuning request is handled in
3373  * case of SDIDO being off if Wifi is turned off, sd card removal etc. In such
3374  * cases, cancel the pending tuning timer and remove any core voltage
3375  * constraints that are set earlier.
3376  */
3377 static void tegra_sdhci_power_off(struct sdhci_host *sdhci, u8 power_mode)
3378 {
3379         int retuning_req_set = 0;
3380
3381         retuning_req_set = (timer_pending(&sdhci->tuning_timer) ||
3382                 (sdhci->flags & SDHCI_NEEDS_RETUNING));
3383
3384         if (retuning_req_set) {
3385                 del_timer_sync(&sdhci->tuning_timer);
3386
3387                 if (boot_volt_req_refcount)
3388                         --boot_volt_req_refcount;
3389
3390                 if (!boot_volt_req_refcount) {
3391                         sdhci_tegra_set_tuning_voltage(sdhci, 0);
3392                         SDHCI_TEGRA_DBG("%s: Release override as host is off\n",
3393                                 mmc_hostname(sdhci->mmc));
3394                 }
3395         }
3396 }
3397
3398 static int show_polling_period(void *data, u64 *value)
3399 {
3400         struct sdhci_host *host = (struct sdhci_host *)data;
3401
3402         if (host->mmc->dev_stats != NULL)
3403                 *value = host->mmc->dev_stats->polling_interval;
3404
3405         return 0;
3406 }
3407
3408 static int set_polling_period(void *data, u64 value)
3409 {
3410         struct sdhci_host *host = (struct sdhci_host *)data;
3411
3412         if (host->mmc->dev_stats != NULL) {
3413                 /* Limiting the maximum polling period to 1 sec */
3414                 if (value > 1000)
3415                         value = 1000;
3416                 host->mmc->dev_stats->polling_interval = value;
3417         }
3418
3419         return 0;
3420 }
3421 static int show_active_load_high_threshold(void *data, u64 *value)
3422 {
3423         struct sdhci_host *host = (struct sdhci_host *)data;
3424         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3425         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3426         struct tegra_freq_gov_data *gov_data = tegra_host->gov_data;
3427
3428         if (gov_data != NULL)
3429                 *value = gov_data->act_load_high_threshold;
3430
3431         return 0;
3432 }
3433
3434 static int set_active_load_high_threshold(void *data, u64 value)
3435 {
3436         struct sdhci_host *host = (struct sdhci_host *)data;
3437         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3438         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3439         struct tegra_freq_gov_data *gov_data = tegra_host->gov_data;
3440
3441         if (gov_data != NULL) {
3442                 /* Maximum threshold load percentage is 100.*/
3443                 if (value > 100)
3444                         value = 100;
3445                 gov_data->act_load_high_threshold = value;
3446         }
3447
3448         return 0;
3449 }
3450
3451 static int show_disableclkgating_value(void *data, u64 *value)
3452 {
3453         struct sdhci_host *host = (struct sdhci_host *)data;
3454         if (host != NULL) {
3455                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3456                 struct sdhci_tegra *tegra_host = pltfm_host->priv;
3457                 if (tegra_host != NULL)
3458                         *value = tegra_host->dbg_cfg.clk_ungated;
3459         }
3460         return 0;
3461 }
3462
3463 static int set_disableclkgating_value(void *data, u64 value)
3464 {
3465         struct sdhci_host *host = (struct sdhci_host *)data;
3466         if (host != NULL) {
3467                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3468                 if (pltfm_host != NULL) {
3469                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3470                         /* Set the CAPS2 register to reflect
3471                          * the clk gating value
3472                          */
3473                         if (tegra_host != NULL) {
3474                                 if (value) {
3475                                         host->mmc->ops->set_ios(host->mmc,
3476                                                 &host->mmc->ios);
3477                                         tegra_host->dbg_cfg.clk_ungated = true;
3478                                         host->mmc->caps2 &=
3479                                                 ~MMC_CAP2_CLOCK_GATING;
3480                                 } else {
3481                                         tegra_host->dbg_cfg.clk_ungated = false;
3482                                         host->mmc->caps2 |=
3483                                                 MMC_CAP2_CLOCK_GATING;
3484                                 }
3485                         }
3486                 }
3487         }
3488         return 0;
3489 }
3490
3491 static int set_trim_override_value(void *data, u64 value)
3492 {
3493         struct sdhci_host *host = (struct sdhci_host *)data;
3494         if (host != NULL) {
3495                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3496                 if (pltfm_host != NULL) {
3497                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3498                         if (tegra_host != NULL) {
3499                                 /* Make sure clock gating is disabled */
3500                                 if ((tegra_host->dbg_cfg.clk_ungated) &&
3501                                 (tegra_host->clk_enabled)) {
3502                                         sdhci_tegra_set_trim_delay(host, value);
3503                                         tegra_host->dbg_cfg.trim_val =
3504                                                 value;
3505                                 } else {
3506                                         pr_info("%s: Disable clock gating before setting value\n",
3507                                                 mmc_hostname(host->mmc));
3508                                 }
3509                         }
3510                 }
3511         }
3512         return 0;
3513 }
3514
3515 static int show_trim_override_value(void *data, u64 *value)
3516 {
3517         struct sdhci_host *host = (struct sdhci_host *)data;
3518         if (host != NULL) {
3519                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3520                 if (pltfm_host != NULL) {
3521                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3522                         if (tegra_host != NULL)
3523                                 *value = tegra_host->dbg_cfg.trim_val;
3524                 }
3525         }
3526         return 0;
3527 }
3528
3529 static int show_tap_override_value(void *data, u64 *value)
3530 {
3531         struct sdhci_host *host = (struct sdhci_host *)data;
3532         if (host != NULL) {
3533                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3534                 if (pltfm_host != NULL) {
3535                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3536                         if (tegra_host != NULL)
3537                                 *value = tegra_host->dbg_cfg.tap_val;
3538                 }
3539         }
3540         return 0;
3541 }
3542
3543 static int set_tap_override_value(void *data, u64 value)
3544 {
3545         struct sdhci_host *host = (struct sdhci_host *)data;
3546         if (host != NULL) {
3547                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3548                 if (pltfm_host != NULL) {
3549                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3550                         if (tegra_host != NULL) {
3551                                 /* Make sure clock gating is disabled */
3552                                 if ((tegra_host->dbg_cfg.clk_ungated) &&
3553                                 (tegra_host->clk_enabled)) {
3554                                         sdhci_tegra_set_tap_delay(host, value);
3555                                         tegra_host->dbg_cfg.tap_val = value;
3556                                 } else {
3557                                         pr_info("%s: Disable clock gating before setting value\n",
3558                                                 mmc_hostname(host->mmc));
3559                                 }
3560                         }
3561                 }
3562         }
3563         return 0;
3564 }
3565 DEFINE_SIMPLE_ATTRIBUTE(sdhci_polling_period_fops, show_polling_period,
3566                 set_polling_period, "%llu\n");
3567 DEFINE_SIMPLE_ATTRIBUTE(sdhci_active_load_high_threshold_fops,
3568                 show_active_load_high_threshold,
3569                 set_active_load_high_threshold, "%llu\n");
3570 DEFINE_SIMPLE_ATTRIBUTE(sdhci_disable_clkgating_fops,
3571                 show_disableclkgating_value,
3572                 set_disableclkgating_value, "%llu\n");
3573 DEFINE_SIMPLE_ATTRIBUTE(sdhci_override_trim_data_fops,
3574                 show_trim_override_value,
3575                 set_trim_override_value, "%llu\n");
3576 DEFINE_SIMPLE_ATTRIBUTE(sdhci_override_tap_data_fops,
3577                 show_tap_override_value,
3578                 set_tap_override_value, "%llu\n");
3579
3580 static void sdhci_tegra_error_stats_debugfs(struct sdhci_host *host)
3581 {
3582         struct dentry *root = host->debugfs_root;
3583         struct dentry *dfs_root;
3584         unsigned saved_line;
3585
3586         if (!root) {
3587                 root = debugfs_create_dir(dev_name(mmc_dev(host->mmc)), NULL);
3588                 if (IS_ERR_OR_NULL(root)) {
3589                         saved_line = __LINE__;
3590                         goto err_root;
3591                 }
3592                 host->debugfs_root = root;
3593         }
3594
3595         dfs_root = debugfs_create_dir("dfs_stats_dir", root);
3596         if (IS_ERR_OR_NULL(dfs_root)) {
3597                 saved_line = __LINE__;
3598                 goto err_node;
3599         }
3600
3601         if (!debugfs_create_file("error_stats", S_IRUSR, root, host,
3602                                 &sdhci_host_fops)) {
3603                 saved_line = __LINE__;
3604                 goto err_node;
3605         }
3606         if (!debugfs_create_file("dfs_stats", S_IRUSR, dfs_root, host,
3607                                 &sdhci_host_dfs_fops)) {
3608                 saved_line = __LINE__;
3609                 goto err_node;
3610         }
3611         if (!debugfs_create_file("polling_period", 0644, dfs_root, (void *)host,
3612                                 &sdhci_polling_period_fops)) {
3613                 saved_line = __LINE__;
3614                 goto err_node;
3615         }
3616         if (!debugfs_create_file("active_load_high_threshold", 0644,
3617                                 dfs_root, (void *)host,
3618                                 &sdhci_active_load_high_threshold_fops)) {
3619                 saved_line = __LINE__;
3620                 goto err_node;
3621         }
3622
3623         dfs_root = debugfs_create_dir("override_data", root);
3624         if (IS_ERR_OR_NULL(dfs_root)) {
3625                 saved_line = __LINE__;
3626                 goto err_node;
3627         }
3628
3629         if (!debugfs_create_file("clk_gate_disabled", 0644,
3630                                 dfs_root, (void *)host,
3631                                 &sdhci_disable_clkgating_fops)) {
3632                 saved_line = __LINE__;
3633                 goto err_node;
3634         }
3635
3636         if (!debugfs_create_file("tap_value", 0644,
3637                                 dfs_root, (void *)host,
3638                                 &sdhci_override_tap_data_fops)) {
3639                 saved_line = __LINE__;
3640                 goto err_node;
3641         }
3642
3643         if (!debugfs_create_file("trim_value", 0644,
3644                                 dfs_root, (void *)host,
3645                                 &sdhci_override_trim_data_fops)) {
3646                 saved_line = __LINE__;
3647                 goto err_node;
3648         }
3649         if (IS_QUIRKS2_DELAYED_CLK_GATE(host)) {
3650                 host->clk_gate_tmout_ticks = -1;
3651                 if (!debugfs_create_u32("clk_gate_tmout_ticks",
3652                         S_IRUGO | S_IWUSR,
3653                         root, (u32 *)&host->clk_gate_tmout_ticks)) {
3654                         saved_line = __LINE__;
3655                         goto err_node;
3656                 }
3657         }
3658
3659         return;
3660
3661 err_node:
3662         debugfs_remove_recursive(root);
3663         host->debugfs_root = NULL;
3664 err_root:
3665         pr_err("%s %s: Failed to initialize debugfs functionality at line=%d\n", __func__,
3666                 mmc_hostname(host->mmc), saved_line);
3667         return;
3668 }
3669
3670 static ssize_t sdhci_handle_boost_mode_tap(struct device *dev,
3671         struct device_attribute *attr, const char *buf, size_t count)
3672 {
3673         int tap_cmd;
3674         struct mmc_card *card;
3675         char *p = (char *)buf;
3676         struct sdhci_host *host = dev_get_drvdata(dev);
3677         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3678         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3679         struct tegra_tuning_data *tuning_data;
3680         u32 present_state;
3681         u8 timeout;
3682         bool clk_set_for_tap_prog = false;
3683
3684         tap_cmd = memparse(p, &p);
3685
3686         card = host->mmc->card;
3687         if (!card)
3688                 return -ENODEV;
3689
3690         /* if not uhs -- no tuning and no tap value to set */
3691         if (!mmc_sd_card_uhs(card) && !mmc_card_hs200(card))
3692                 return count;
3693
3694         /* if no change in tap value -- just exit */
3695         if (tap_cmd == tegra_host->tap_cmd)
3696                 return count;
3697
3698         if ((tap_cmd != TAP_CMD_TRIM_DEFAULT_VOLTAGE) &&
3699                 (tap_cmd != TAP_CMD_TRIM_HIGH_VOLTAGE)) {
3700                 pr_info("echo 1 > cmd_state  # to set normal voltage\n");
3701                 pr_info("echo 2 > cmd_state  # to set high voltage\n");
3702                 return -EINVAL;
3703         }
3704
3705         tegra_host->tap_cmd = tap_cmd;
3706         tuning_data = sdhci_tegra_get_tuning_data(host, host->max_clk);
3707         /* Check if host clock is enabled */
3708         if (!tegra_host->clk_enabled) {
3709                 /* Nothing to do if the host is not powered ON */
3710                 if (host->mmc->ios.power_mode != MMC_POWER_ON)
3711                         return count;
3712                 else {
3713                         tegra_sdhci_set_clock(host, host->mmc->ios.clock);
3714                         clk_set_for_tap_prog = true;
3715                 }
3716         } else {
3717                 timeout = 10;
3718                 /* Wait for any on-going data transfers */
3719                 present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
3720                 while (present_state & (SDHCI_DOING_WRITE | SDHCI_DOING_READ)) {
3721                         if (!timeout)
3722                                 break;
3723                         timeout--;
3724                         mdelay(1);
3725                         present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
3726                 };
3727         }
3728         spin_lock(&host->lock);
3729         switch (tap_cmd) {
3730         case TAP_CMD_TRIM_DEFAULT_VOLTAGE:
3731                 /* set tap value for voltage range 1.1 to 1.25 */
3732                 sdhci_tegra_set_tap_delay(host, tuning_data->best_tap_value);
3733                 break;
3734
3735         case TAP_CMD_TRIM_HIGH_VOLTAGE:
3736                 /* set tap value for voltage range 1.25 to 1.39 */
3737                 sdhci_tegra_set_tap_delay(host,
3738                         tuning_data->nom_best_tap_value);
3739                 break;
3740         }
3741         spin_unlock(&host->lock);
3742         if (clk_set_for_tap_prog) {
3743                 tegra_sdhci_set_clock(host, 0);
3744                 clk_set_for_tap_prog = false;
3745         }
3746         return count;
3747 }
3748
3749 static ssize_t sdhci_show_turbo_mode(struct device *dev,
3750                         struct device_attribute *attr, char *buf)
3751 {
3752         struct sdhci_host *host = dev_get_drvdata(dev);
3753         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3754         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3755
3756         return sprintf(buf, "%d\n", tegra_host->tap_cmd);
3757 }
3758
3759 static DEVICE_ATTR(cmd_state, 0644, sdhci_show_turbo_mode,
3760                         sdhci_handle_boost_mode_tap);
3761
3762 static int tegra_sdhci_reboot_notify(struct notifier_block *nb,
3763                                 unsigned long event, void *data)
3764 {
3765         struct sdhci_tegra *tegra_host =
3766                 container_of(nb, struct sdhci_tegra, reboot_notify);
3767         int err;
3768
3769         switch (event) {
3770         case SYS_RESTART:
3771         case SYS_POWER_OFF:
3772                 err = tegra_sdhci_configure_regulators(tegra_host,
3773                         CONFIG_REG_DIS, 0, 0);
3774                 if (err)
3775                         pr_err("Disable regulator in reboot notify failed %d\n",
3776                                 err);
3777                 return NOTIFY_OK;
3778         }
3779         return NOTIFY_DONE;
3780 }
3781
3782 void tegra_sdhci_ios_config_enter(struct sdhci_host *sdhci, struct mmc_ios *ios)
3783 {
3784         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3785         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3786         struct clk *new_mode_clk;
3787         bool change_clk = false;
3788
3789         /*
3790          * Tegra sdmmc controllers require clock to be enabled for any register
3791          * access. Set the minimum controller clock if no clock is requested.
3792          */
3793         if (!sdhci->clock && !ios->clock) {
3794                 tegra_sdhci_set_clock(sdhci, sdhci->mmc->f_min);
3795                 sdhci->clock = sdhci->mmc->f_min;
3796         } else if (ios->clock && (ios->clock != sdhci->clock)) {
3797                 tegra_sdhci_set_clock(sdhci, ios->clock);
3798         }
3799
3800         /*
3801          * Check for DDR50 mode setting and set ddr_clk if not already
3802          * done. Return if only one clock option is available.
3803          */
3804         if (!tegra_host->ddr_clk || !tegra_host->sdr_clk) {
3805                 return;
3806         } else {
3807                 if ((ios->timing == MMC_TIMING_UHS_DDR50) &&
3808                         !tegra_host->is_ddr_clk_set) {
3809                         change_clk = true;
3810                         new_mode_clk = tegra_host->ddr_clk;
3811                 } else if ((ios->timing != MMC_TIMING_UHS_DDR50) &&
3812                         tegra_host->is_ddr_clk_set) {
3813                         change_clk = true;
3814                         new_mode_clk = tegra_host->sdr_clk;
3815                 }
3816
3817                 if (change_clk) {
3818                         tegra_sdhci_set_clock(sdhci, 0);
3819                         pltfm_host->clk = new_mode_clk;
3820                         /* Restore the previous frequency */
3821                         tegra_sdhci_set_clock(sdhci, sdhci->max_clk);
3822                         tegra_host->is_ddr_clk_set =
3823                                 !tegra_host->is_ddr_clk_set;
3824                 }
3825         }
3826 }
3827
3828 void tegra_sdhci_ios_config_exit(struct sdhci_host *sdhci, struct mmc_ios *ios)
3829 {
3830         /*
3831          * Do any required handling for retuning requests before powering off
3832          * the host.
3833          */
3834         if (ios->power_mode == MMC_POWER_OFF)
3835                 tegra_sdhci_power_off(sdhci, ios->power_mode);
3836
3837         /*
3838          * In case of power off, turn off controller clock now as all the
3839          * required register accesses are already done.
3840          */
3841         if (!ios->clock && !sdhci->mmc->skip_host_clkgate)
3842                 tegra_sdhci_set_clock(sdhci, 0);
3843 }
3844
3845 static int tegra_sdhci_get_drive_strength(struct sdhci_host *sdhci,
3846                 unsigned int max_dtr, int host_drv, int card_drv)
3847 {
3848         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3849         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3850         const struct tegra_sdhci_platform_data *plat = tegra_host->plat;
3851
3852         return plat->default_drv_type;
3853 }
3854
3855 static const struct sdhci_ops tegra_sdhci_ops = {
3856         .get_ro     = tegra_sdhci_get_ro,
3857         .get_cd     = tegra_sdhci_get_cd,
3858         .read_l     = tegra_sdhci_readl,
3859         .read_w     = tegra_sdhci_readw,
3860         .write_l    = tegra_sdhci_writel,
3861         .write_w    = tegra_sdhci_writew,
3862         .platform_bus_width = tegra_sdhci_buswidth,
3863         .set_clock              = tegra_sdhci_set_clock,
3864         .suspend                = tegra_sdhci_suspend,
3865         .resume                 = tegra_sdhci_resume,
3866         .platform_resume        = tegra_sdhci_post_resume,
3867         .platform_reset_exit    = tegra_sdhci_reset_exit,
3868         .platform_get_bus       = tegra_sdhci_get_bus,
3869         .platform_ios_config_enter      = tegra_sdhci_ios_config_enter,
3870         .platform_ios_config_exit       = tegra_sdhci_ios_config_exit,
3871         .set_uhs_signaling      = tegra_sdhci_set_uhs_signaling,
3872         .switch_signal_voltage  = tegra_sdhci_signal_voltage_switch,
3873         .switch_signal_voltage_exit = tegra_sdhci_do_calibration,
3874         .execute_freq_tuning    = sdhci_tegra_execute_tuning,
3875         .sd_error_stats         = sdhci_tegra_sd_error_stats,
3876 #ifdef CONFIG_MMC_FREQ_SCALING
3877         .dfs_gov_init           = sdhci_tegra_freq_gov_init,
3878         .dfs_gov_get_target_freq        = sdhci_tegra_get_target_freq,
3879 #endif
3880         .get_drive_strength     = tegra_sdhci_get_drive_strength,
3881 };
3882
3883 static struct sdhci_pltfm_data sdhci_tegra11_pdata = {
3884         .quirks = TEGRA_SDHCI_QUIRKS,
3885         .quirks2 = TEGRA_SDHCI_QUIRKS2,
3886         .ops  = &tegra_sdhci_ops,
3887 };
3888
3889 static struct sdhci_tegra_soc_data soc_data_tegra11 = {
3890         .pdata = &sdhci_tegra11_pdata,
3891         .nvquirks = TEGRA_SDHCI_NVQUIRKS |
3892                     NVQUIRK_SET_DRIVE_STRENGTH |
3893                     NVQUIRK_SET_TRIM_DELAY |
3894                     NVQUIRK_ENABLE_DDR50 |
3895                     NVQUIRK_ENABLE_HS200 |
3896                     NVQUIRK_INFINITE_ERASE_TIMEOUT |
3897                     NVQUIRK_DISABLE_EXTERNAL_LOOPBACK |
3898                     NVQUIRK_DISABLE_SDMMC4_CALIB,
3899         .parent_clk_list = {"pll_p", "pll_c"},
3900         .tuning_freq_list = {81600000, 156000000, 200000000},
3901         .t2t_coeffs = t11x_tuning_coeffs,
3902         .t2t_coeffs_count = 3,
3903         .tap_hole_coeffs = t11x_tap_hole_coeffs,
3904         .tap_hole_coeffs_count = 12,
3905 };
3906
3907 static struct sdhci_pltfm_data sdhci_tegra12_pdata = {
3908         .quirks = TEGRA_SDHCI_QUIRKS,
3909         .quirks2 = TEGRA_SDHCI_QUIRKS2 |
3910                 SDHCI_QUIRK2_HOST_OFF_CARD_ON |
3911                 SDHCI_QUIRK2_SUPPORT_64BIT_DMA |
3912                 SDHCI_QUIRK2_USE_64BIT_ADDR,
3913         .ops  = &tegra_sdhci_ops,
3914 };
3915
3916 static struct sdhci_tegra_soc_data soc_data_tegra12 = {
3917         .pdata = &sdhci_tegra12_pdata,
3918         .nvquirks = TEGRA_SDHCI_NVQUIRKS |
3919                     NVQUIRK_SET_TRIM_DELAY |
3920                     NVQUIRK_ENABLE_DDR50 |
3921                     NVQUIRK_ENABLE_HS200 |
3922                     NVQUIRK_INFINITE_ERASE_TIMEOUT |
3923                     NVQUIRK_SET_PAD_E_INPUT_OR_E_PWRD |
3924                     NVQUIRK_HIGH_FREQ_TAP_PROCEDURE |
3925                     NVQUIRK_SET_CALIBRATION_OFFSETS |
3926                     NVQUIRK_DISABLE_EXTERNAL_LOOPBACK,
3927         .parent_clk_list = {"pll_p", "pll_c"},
3928         .tuning_freq_list = {81600000, 136000000, 200000000},
3929         .t2t_coeffs = t12x_tuning_coeffs,
3930         .t2t_coeffs_count = 3,
3931         .tap_hole_coeffs = t12x_tap_hole_coeffs,
3932         .tap_hole_coeffs_count = 12,
3933 };
3934
3935 static const struct of_device_id sdhci_tegra_dt_match[] = {
3936         { .compatible = "nvidia,tegra124-sdhci", .data = &soc_data_tegra12 },
3937         { .compatible = "nvidia,tegra114-sdhci", .data = &soc_data_tegra11 },
3938         {}
3939 };
3940 MODULE_DEVICE_TABLE(of, sdhci_dt_ids);
3941
3942 static struct tegra_sdhci_platform_data *sdhci_tegra_dt_parse_pdata(
3943                                                 struct platform_device *pdev)
3944 {
3945         int val;
3946         struct tegra_sdhci_platform_data *plat;
3947         struct device_node *np = pdev->dev.of_node;
3948         u32 bus_width;
3949
3950         if (!np)
3951                 return NULL;
3952
3953         plat = devm_kzalloc(&pdev->dev, sizeof(*plat), GFP_KERNEL);
3954         if (!plat) {
3955                 dev_err(&pdev->dev, "Can't allocate platform data\n");
3956                 return NULL;
3957         }
3958
3959         plat->cd_gpio = of_get_named_gpio(np, "cd-gpios", 0);
3960         plat->wp_gpio = of_get_named_gpio(np, "wp-gpios", 0);
3961         plat->power_gpio = of_get_named_gpio(np, "power-gpios", 0);
3962
3963         if (of_property_read_u32(np, "bus-width", &bus_width) == 0 &&
3964             bus_width == 8)
3965                 plat->is_8bit = 1;
3966
3967         of_property_read_u32(np, "tap-delay", &plat->tap_delay);
3968         of_property_read_u32(np, "trim-delay", &plat->trim_delay);
3969         of_property_read_u32(np, "ddr-clk-limit", &plat->ddr_clk_limit);
3970         of_property_read_u32(np, "max-clk-limit", &plat->max_clk_limit);
3971
3972         of_property_read_u32(np, "uhs_mask", &plat->uhs_mask);
3973
3974         if (of_find_property(np, "built-in", NULL))
3975                 plat->mmc_data.built_in = 1;
3976
3977         if (!of_property_read_u32(np, "mmc-ocr-mask", &val)) {
3978                 if (val == 0)
3979                         plat->mmc_data.ocr_mask = MMC_OCR_1V8_MASK;
3980                 else if (val == 1)
3981                         plat->mmc_data.ocr_mask = MMC_OCR_2V8_MASK;
3982                 else if (val == 2)
3983                         plat->mmc_data.ocr_mask = MMC_OCR_3V2_MASK;
3984                 else if (val == 3)
3985                         plat->mmc_data.ocr_mask = MMC_OCR_3V3_MASK;
3986         }
3987         return plat;
3988 }
3989
3990 static int sdhci_tegra_probe(struct platform_device *pdev)
3991 {
3992         const struct of_device_id *match;
3993         const struct sdhci_tegra_soc_data *soc_data;
3994         struct sdhci_host *host;
3995         struct sdhci_pltfm_host *pltfm_host;
3996         struct tegra_sdhci_platform_data *plat;
3997         struct sdhci_tegra *tegra_host;
3998         unsigned int low_freq;
3999         int rc;
4000         u8 i;
4001
4002         match = of_match_device(sdhci_tegra_dt_match, &pdev->dev);
4003         if (match) {
4004                 soc_data = match->data;
4005         } else {
4006                 /* Use id tables and remove the following chip defines */
4007 #if defined(CONFIG_ARCH_TEGRA_11x_SOC)
4008                 soc_data = &soc_data_tegra11;
4009 #else
4010                 soc_data = &soc_data_tegra12;
4011 #endif
4012         }
4013
4014         host = sdhci_pltfm_init(pdev, soc_data->pdata);
4015
4016         /* sdio delayed clock gate quirk in sdhci_host used */
4017         host->quirks2 |= SDHCI_QUIRK2_DELAYED_CLK_GATE;
4018
4019         if (IS_ERR(host))
4020                 return PTR_ERR(host);
4021
4022         pltfm_host = sdhci_priv(host);
4023
4024         plat = pdev->dev.platform_data;
4025
4026         if (plat == NULL)
4027                 plat = sdhci_tegra_dt_parse_pdata(pdev);
4028
4029         if (plat == NULL) {
4030                 dev_err(mmc_dev(host->mmc), "missing platform data\n");
4031                 rc = -ENXIO;
4032                 goto err_no_plat;
4033         }
4034
4035         tegra_host = devm_kzalloc(&pdev->dev, sizeof(*tegra_host), GFP_KERNEL);
4036         if (!tegra_host) {
4037                 dev_err(mmc_dev(host->mmc), "failed to allocate tegra_host\n");
4038                 rc = -ENOMEM;
4039                 goto err_no_plat;
4040         }
4041
4042         tegra_host->plat = plat;
4043         pdev->dev.platform_data = plat;
4044
4045         tegra_host->sd_stat_head = devm_kzalloc(&pdev->dev,
4046                 sizeof(struct sdhci_tegra_sd_stats), GFP_KERNEL);
4047         if (!tegra_host->sd_stat_head) {
4048                 dev_err(mmc_dev(host->mmc), "failed to allocate sd_stat_head\n");
4049                 rc = -ENOMEM;
4050                 goto err_power_req;
4051         }
4052
4053         tegra_host->soc_data = soc_data;
4054         pltfm_host->priv = tegra_host;
4055
4056         for (i = 0; i < ARRAY_SIZE(soc_data->parent_clk_list); i++) {
4057                 if (!soc_data->parent_clk_list[i])
4058                         continue;
4059                 if (!strcmp(soc_data->parent_clk_list[i], "pll_c")) {
4060                         pll_c = clk_get_sys(NULL, "pll_c");
4061                         if (IS_ERR(pll_c)) {
4062                                 rc = PTR_ERR(pll_c);
4063                                 dev_err(mmc_dev(host->mmc),
4064                                         "clk error in getting pll_c: %d\n", rc);
4065                         }
4066                         pll_c_rate = clk_get_rate(pll_c);
4067                 }
4068
4069                 if (!strcmp(soc_data->parent_clk_list[i], "pll_p")) {
4070                         pll_p = clk_get_sys(NULL, "pll_p");
4071                         if (IS_ERR(pll_p)) {
4072                                 rc = PTR_ERR(pll_p);
4073                                 dev_err(mmc_dev(host->mmc),
4074                                         "clk error in getting pll_p: %d\n", rc);
4075                         }
4076                         pll_p_rate = clk_get_rate(pll_p);
4077                 }
4078         }
4079
4080 #ifdef CONFIG_MMC_EMBEDDED_SDIO
4081         if (plat->mmc_data.embedded_sdio)
4082                 mmc_set_embedded_sdio_data(host->mmc,
4083                         &plat->mmc_data.embedded_sdio->cis,
4084                         &plat->mmc_data.embedded_sdio->cccr,
4085                         plat->mmc_data.embedded_sdio->funcs,
4086                         plat->mmc_data.embedded_sdio->num_funcs);
4087 #endif
4088
4089         if (gpio_is_valid(plat->power_gpio)) {
4090                 rc = gpio_request(plat->power_gpio, "sdhci_power");
4091                 if (rc) {
4092                         dev_err(mmc_dev(host->mmc),
4093                                 "failed to allocate power gpio\n");
4094                         goto err_power_req;
4095                 }
4096                 gpio_direction_output(plat->power_gpio, 1);
4097         }
4098
4099         if (gpio_is_valid(plat->cd_gpio)) {
4100                 rc = gpio_request(plat->cd_gpio, "sdhci_cd");
4101                 if (rc) {
4102                         dev_err(mmc_dev(host->mmc),
4103                                 "failed to allocate cd gpio\n");
4104                         goto err_cd_req;
4105                 }
4106                 gpio_direction_input(plat->cd_gpio);
4107
4108                 tegra_host->card_present =
4109                         (gpio_get_value_cansleep(plat->cd_gpio) == 0);
4110
4111         } else if (plat->mmc_data.register_status_notify) {
4112                 plat->mmc_data.register_status_notify(sdhci_status_notify_cb, host);
4113         }
4114
4115         if (plat->mmc_data.status) {
4116                 plat->mmc_data.card_present = plat->mmc_data.status(mmc_dev(host->mmc));
4117         }
4118
4119         if (gpio_is_valid(plat->wp_gpio)) {
4120                 rc = gpio_request(plat->wp_gpio, "sdhci_wp");
4121                 if (rc) {
4122                         dev_err(mmc_dev(host->mmc),
4123                                 "failed to allocate wp gpio\n");
4124                         goto err_wp_req;
4125                 }
4126                 gpio_direction_input(plat->wp_gpio);
4127         }
4128
4129         /*
4130          * If there is no card detect gpio, assume that the
4131          * card is always present.
4132          */
4133         if (!gpio_is_valid(plat->cd_gpio))
4134                 tegra_host->card_present = 1;
4135
4136         if (plat->mmc_data.ocr_mask & SDHOST_1V8_OCR_MASK) {
4137                 tegra_host->vddio_min_uv = SDHOST_LOW_VOLT_MIN;
4138                 tegra_host->vddio_max_uv = SDHOST_LOW_VOLT_MAX;
4139         } else if (plat->mmc_data.ocr_mask & MMC_OCR_2V8_MASK) {
4140                         tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_2V8;
4141                         tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4142         } else if (plat->mmc_data.ocr_mask & MMC_OCR_3V2_MASK) {
4143                         tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_3V2;
4144                         tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4145         } else if (plat->mmc_data.ocr_mask & MMC_OCR_3V3_MASK) {
4146                         tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_3V3;
4147                         tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4148         } else {
4149                 /*
4150                  * Set the minV and maxV to default
4151                  * voltage range of 2.7V - 3.6V
4152                  */
4153                 tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_MIN;
4154                 tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4155         }
4156
4157         tegra_host->vdd_io_reg = regulator_get(mmc_dev(host->mmc),
4158                                                         "vddio_sdmmc");
4159         if (IS_ERR_OR_NULL(tegra_host->vdd_io_reg)) {
4160                 dev_info(mmc_dev(host->mmc), "%s regulator not found: %ld."
4161                         "Assuming vddio_sdmmc is not required.\n",
4162                         "vddio_sdmmc", PTR_ERR(tegra_host->vdd_io_reg));
4163                 tegra_host->vdd_io_reg = NULL;
4164         } else {
4165                 rc = tegra_sdhci_configure_regulators(tegra_host,
4166                         CONFIG_REG_SET_VOLT,
4167                         tegra_host->vddio_min_uv,
4168                         tegra_host->vddio_max_uv);
4169                 if (rc) {
4170                         dev_err(mmc_dev(host->mmc),
4171                                 "Init volt(%duV-%duV) setting failed %d\n",
4172                                 tegra_host->vddio_min_uv,
4173                                 tegra_host->vddio_max_uv, rc);
4174                         regulator_put(tegra_host->vdd_io_reg);
4175                         tegra_host->vdd_io_reg = NULL;
4176                 }
4177         }
4178
4179         tegra_host->vdd_slot_reg = regulator_get(mmc_dev(host->mmc),
4180                                                         "vddio_sd_slot");
4181         if (IS_ERR_OR_NULL(tegra_host->vdd_slot_reg)) {
4182                 dev_info(mmc_dev(host->mmc), "%s regulator not found: %ld."
4183                         " Assuming vddio_sd_slot is not required.\n",
4184                         "vddio_sd_slot", PTR_ERR(tegra_host->vdd_slot_reg));
4185                 tegra_host->vdd_slot_reg = NULL;
4186         }
4187
4188         if (tegra_host->card_present) {
4189                 rc = tegra_sdhci_configure_regulators(tegra_host, CONFIG_REG_EN,
4190                         0, 0);
4191                 if (rc) {
4192                         dev_err(mmc_dev(host->mmc),
4193                                 "Enable regulators failed in probe %d\n", rc);
4194                         goto err_clk_get;
4195                 }
4196         }
4197
4198         tegra_pd_add_device(&pdev->dev);
4199         pm_runtime_enable(&pdev->dev);
4200
4201         /* Get the ddr clock */
4202         tegra_host->ddr_clk = clk_get(mmc_dev(host->mmc), "ddr");
4203         if (IS_ERR(tegra_host->ddr_clk)) {
4204                 dev_err(mmc_dev(host->mmc), "ddr clk err\n");
4205                 tegra_host->ddr_clk = NULL;
4206         }
4207
4208         /* Get high speed clock */
4209         tegra_host->sdr_clk = clk_get(mmc_dev(host->mmc), NULL);
4210         if (IS_ERR(tegra_host->sdr_clk)) {
4211                 dev_err(mmc_dev(host->mmc), "sdr clk err\n");
4212                 tegra_host->sdr_clk = NULL;
4213                 /* If both ddr and sdr clks are missing, then fail probe */
4214                 if (!tegra_host->ddr_clk && !tegra_host->sdr_clk) {
4215                         dev_err(mmc_dev(host->mmc),
4216                                 "Failed to get ddr and sdr clks\n");
4217                         rc = -EINVAL;
4218                         goto err_clk_get;
4219                 }
4220         }
4221
4222         if (tegra_host->sdr_clk) {
4223                 pltfm_host->clk = tegra_host->sdr_clk;
4224                 tegra_host->is_ddr_clk_set = false;
4225         } else {
4226                 pltfm_host->clk = tegra_host->ddr_clk;
4227                 tegra_host->is_ddr_clk_set = true;
4228         }
4229
4230         if (clk_get_parent(pltfm_host->clk) == pll_c)
4231                 tegra_host->is_parent_pllc = true;
4232
4233         pm_runtime_get_sync(&pdev->dev);
4234         rc = clk_prepare_enable(pltfm_host->clk);
4235         if (rc != 0)
4236                 goto err_clk_put;
4237
4238         tegra_host->emc_clk = devm_clk_get(mmc_dev(host->mmc), "emc");
4239         if (IS_ERR_OR_NULL(tegra_host->emc_clk)) {
4240                 dev_err(mmc_dev(host->mmc), "Can't get emc clk\n");
4241                 tegra_host->emc_clk = NULL;
4242         } else {
4243                 clk_set_rate(tegra_host->emc_clk, SDMMC_EMC_MAX_FREQ);
4244         }
4245
4246         tegra_host->sclk = devm_clk_get(mmc_dev(host->mmc), "sclk");
4247         if (IS_ERR_OR_NULL(tegra_host->sclk)) {
4248                 dev_err(mmc_dev(host->mmc), "Can't get sclk clock\n");
4249                 tegra_host->sclk = NULL;
4250         } else {
4251                 clk_set_rate(tegra_host->sclk, SDMMC_AHB_MAX_FREQ);
4252         }
4253         pltfm_host->priv = tegra_host;
4254         tegra_host->clk_enabled = true;
4255         host->is_clk_on = tegra_host->clk_enabled;
4256         mutex_init(&tegra_host->set_clock_mutex);
4257
4258         tegra_host->max_clk_limit = plat->max_clk_limit;
4259         tegra_host->ddr_clk_limit = plat->ddr_clk_limit;
4260         tegra_host->instance = pdev->id;
4261         tegra_host->tap_cmd = TAP_CMD_TRIM_DEFAULT_VOLTAGE;
4262         tegra_host->speedo = plat->cpu_speedo;
4263         dev_info(mmc_dev(host->mmc), "Speedo value %d\n", tegra_host->speedo);
4264         host->mmc->pm_caps |= plat->pm_caps;
4265         host->mmc->pm_flags |= plat->pm_flags;
4266
4267         host->mmc->caps |= MMC_CAP_ERASE;
4268         /* enable 1/8V DDR capable */
4269         host->mmc->caps |= MMC_CAP_1_8V_DDR;
4270         if (plat->is_8bit)
4271                 host->mmc->caps |= MMC_CAP_8_BIT_DATA;
4272         host->mmc->caps |= MMC_CAP_SDIO_IRQ;
4273         host->mmc->pm_caps |= MMC_PM_KEEP_POWER | MMC_PM_IGNORE_PM_NOTIFY;
4274         if (plat->mmc_data.built_in) {
4275                 host->mmc->caps |= MMC_CAP_NONREMOVABLE;
4276         }
4277         host->mmc->pm_flags |= MMC_PM_IGNORE_PM_NOTIFY;
4278
4279         /* disable access to boot partitions */
4280         host->mmc->caps2 |= MMC_CAP2_BOOTPART_NOACC;
4281
4282 #if !defined(CONFIG_ARCH_TEGRA_2x_SOC) && !defined(CONFIG_ARCH_TEGRA_3x_SOC)
4283         if (soc_data->nvquirks & NVQUIRK_ENABLE_HS200)
4284                 host->mmc->caps2 |= MMC_CAP2_HS200;
4285 #ifdef CONFIG_TEGRA_FPGA_PLATFORM
4286         /* Enable HS200 mode */
4287         host->mmc->caps2 |= MMC_CAP2_HS200;
4288 #else
4289         host->mmc->caps2 |= MMC_CAP2_CACHE_CTRL;
4290         host->mmc->caps |= MMC_CAP_CMD23;
4291         host->mmc->caps2 |= MMC_CAP2_PACKED_CMD;
4292 #endif
4293 #endif
4294
4295         /*
4296          * Enable dyamic frequency scaling support only if the platform clock
4297          * limit is higher than the lowest supported frequency by tuning.
4298          */
4299         for (i = 0; i < TUNING_FREQ_COUNT; i++) {
4300                 low_freq = soc_data->tuning_freq_list[i];
4301                 if (low_freq)
4302                         break;
4303         }
4304         if (plat->en_freq_scaling && (plat->max_clk_limit > low_freq))
4305                 host->mmc->caps2 |= MMC_CAP2_FREQ_SCALING;
4306
4307         if (!plat->disable_clock_gate)
4308                 host->mmc->caps2 |= MMC_CAP2_CLOCK_GATING;
4309
4310         if (plat->nominal_vcore_mv)
4311                 tegra_host->nominal_vcore_mv = plat->nominal_vcore_mv;
4312         if (plat->min_vcore_override_mv)
4313                 tegra_host->min_vcore_override_mv = plat->min_vcore_override_mv;
4314         if (plat->boot_vcore_mv)
4315                 tegra_host->boot_vcore_mv = plat->boot_vcore_mv;
4316         dev_info(mmc_dev(host->mmc),
4317                 "Tuning constraints: nom_mv %d, boot_mv %d, min_or_mv %d\n",
4318                 tegra_host->nominal_vcore_mv, tegra_host->boot_vcore_mv,
4319                 tegra_host->min_vcore_override_mv);
4320
4321         /*
4322          * If nominal voltage is equal to boot voltage, there is no need for
4323          * nominal voltage tuning.
4324          */
4325         if (plat->nominal_vcore_mv <= plat->boot_vcore_mv)
4326                 plat->en_nominal_vcore_tuning = false;
4327
4328         INIT_DELAYED_WORK(&host->delayed_clk_gate_wrk, delayed_clk_gate_cb);
4329         rc = sdhci_add_host(host);
4330         if (rc)
4331                 goto err_add_host;
4332
4333         if (gpio_is_valid(plat->cd_gpio)) {
4334                 rc = request_threaded_irq(gpio_to_irq(plat->cd_gpio), NULL,
4335                         carddetect_irq,
4336                         IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING | IRQF_ONESHOT,
4337                         mmc_hostname(host->mmc), host);
4338                 if (rc) {
4339                         dev_err(mmc_dev(host->mmc), "request irq error\n");
4340                         goto err_cd_irq_req;
4341                 }
4342                 if (!plat->cd_wakeup_incapable) {
4343                         rc = enable_irq_wake(gpio_to_irq(plat->cd_gpio));
4344                         if (rc < 0)
4345                                 dev_err(mmc_dev(host->mmc),
4346                                         "SD card wake-up event registration "
4347                                         "failed with error: %d\n", rc);
4348                 }
4349         }
4350         sdhci_tegra_error_stats_debugfs(host);
4351         device_create_file(&pdev->dev, &dev_attr_cmd_state);
4352
4353         /* Enable async suspend/resume to reduce LP0 latency */
4354         device_enable_async_suspend(&pdev->dev);
4355
4356         if (plat->power_off_rail) {
4357                 tegra_host->reboot_notify.notifier_call =
4358                         tegra_sdhci_reboot_notify;
4359                 register_reboot_notifier(&tegra_host->reboot_notify);
4360         }
4361 #ifdef CONFIG_DEBUG_FS
4362         tegra_host->dbg_cfg.tap_val =
4363                 plat->tap_delay;
4364         tegra_host->dbg_cfg.trim_val =
4365                 plat->ddr_trim_delay;
4366         tegra_host->dbg_cfg.clk_ungated =
4367                 plat->disable_clock_gate;
4368 #endif
4369         return 0;
4370
4371 err_cd_irq_req:
4372         if (gpio_is_valid(plat->cd_gpio))
4373                 gpio_free(plat->cd_gpio);
4374 err_add_host:
4375         if (tegra_host->is_ddr_clk_set)
4376                 clk_disable_unprepare(tegra_host->ddr_clk);
4377         else
4378                 clk_disable_unprepare(tegra_host->sdr_clk);
4379         pm_runtime_put_sync(&pdev->dev);
4380 err_clk_put:
4381         if (tegra_host->ddr_clk)
4382                 clk_put(tegra_host->ddr_clk);
4383         if (tegra_host->sdr_clk)
4384                 clk_put(tegra_host->sdr_clk);
4385 err_clk_get:
4386         if (gpio_is_valid(plat->wp_gpio))
4387                 gpio_free(plat->wp_gpio);
4388 err_wp_req:
4389         if (gpio_is_valid(plat->cd_gpio))
4390                 free_irq(gpio_to_irq(plat->cd_gpio), host);
4391 err_cd_req:
4392         if (gpio_is_valid(plat->power_gpio))
4393                 gpio_free(plat->power_gpio);
4394 err_power_req:
4395 err_no_plat:
4396         sdhci_pltfm_free(pdev);
4397         return rc;
4398 }
4399
4400 static int sdhci_tegra_remove(struct platform_device *pdev)
4401 {
4402         struct sdhci_host *host = platform_get_drvdata(pdev);
4403         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
4404         struct sdhci_tegra *tegra_host = pltfm_host->priv;
4405         const struct tegra_sdhci_platform_data *plat = tegra_host->plat;
4406         int dead = (readl(host->ioaddr + SDHCI_INT_STATUS) == 0xffffffff);
4407         int rc = 0;
4408
4409         sdhci_remove_host(host, dead);
4410
4411         disable_irq_wake(gpio_to_irq(plat->cd_gpio));
4412
4413         rc = tegra_sdhci_configure_regulators(tegra_host, CONFIG_REG_DIS, 0, 0);
4414         if (rc)
4415                 dev_err(mmc_dev(host->mmc),
4416                         "Regulator disable in remove failed %d\n", rc);
4417
4418         if (tegra_host->vdd_slot_reg)
4419                 regulator_put(tegra_host->vdd_slot_reg);
4420         if (tegra_host->vdd_io_reg)
4421                 regulator_put(tegra_host->vdd_io_reg);
4422
4423         if (gpio_is_valid(plat->wp_gpio))
4424                 gpio_free(plat->wp_gpio);
4425
4426         if (gpio_is_valid(plat->cd_gpio)) {
4427                 free_irq(gpio_to_irq(plat->cd_gpio), host);
4428                 gpio_free(plat->cd_gpio);
4429         }
4430
4431         if (gpio_is_valid(plat->power_gpio))
4432                 gpio_free(plat->power_gpio);
4433
4434         if (tegra_host->clk_enabled) {
4435                 if (tegra_host->is_ddr_clk_set)
4436                         clk_disable_unprepare(tegra_host->ddr_clk);
4437                 else
4438                         clk_disable_unprepare(tegra_host->sdr_clk);
4439                 pm_runtime_put_sync(&pdev->dev);
4440         }
4441
4442         if (tegra_host->ddr_clk)
4443                 clk_put(tegra_host->ddr_clk);
4444         if (tegra_host->sdr_clk)
4445                 clk_put(tegra_host->sdr_clk);
4446
4447         if (tegra_host->emc_clk && tegra_host->is_sdmmc_emc_clk_on)
4448                 clk_disable_unprepare(tegra_host->emc_clk);
4449         if (tegra_host->sclk && tegra_host->is_sdmmc_sclk_on)
4450                 clk_disable_unprepare(tegra_host->sclk);
4451         if (plat->power_off_rail)
4452                 unregister_reboot_notifier(&tegra_host->reboot_notify);
4453
4454         sdhci_pltfm_free(pdev);
4455
4456         return rc;
4457 }
4458
4459 static struct platform_driver sdhci_tegra_driver = {
4460         .driver         = {
4461                 .name   = "sdhci-tegra",
4462                 .owner  = THIS_MODULE,
4463                 .of_match_table = sdhci_tegra_dt_match,
4464                 .pm     = SDHCI_PLTFM_PMOPS,
4465         },
4466         .probe          = sdhci_tegra_probe,
4467         .remove         = sdhci_tegra_remove,
4468 };
4469
4470 module_platform_driver(sdhci_tegra_driver);
4471
4472 MODULE_DESCRIPTION("SDHCI driver for Tegra");
4473 MODULE_AUTHOR("Google, Inc.");
4474 MODULE_LICENSE("GPL v2");