]> rtime.felk.cvut.cz Git - sojka/nv-tegra/linux-3.10.git/blob - drivers/mmc/host/sdhci-tegra.c
84386f0dee9e25c1875878c23059f33d75ddbbf1
[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                                 return;
1438                         }
1439                         tegra_host->clk_enabled = true;
1440                         sdhci->is_clk_on = tegra_host->clk_enabled;
1441                         ctrl = sdhci_readb(sdhci, SDHCI_VNDR_CLK_CTRL);
1442                         ctrl |= SDHCI_VNDR_CLK_CTRL_SDMMC_CLK;
1443                         sdhci_writeb(sdhci, ctrl, SDHCI_VNDR_CLK_CTRL);
1444                 }
1445                 tegra_sdhci_set_clk_rate(sdhci, clock);
1446
1447                 if (tegra_host->emc_clk && (!tegra_host->is_sdmmc_emc_clk_on)) {
1448                         ret = clk_prepare_enable(tegra_host->emc_clk);
1449                         if (ret) {
1450                                 dev_err(mmc_dev(sdhci->mmc),
1451                                 "clock enable is failed, ret: %d\n", ret);
1452                                 return;
1453                         }
1454                         tegra_host->is_sdmmc_emc_clk_on = true;
1455                 }
1456                 if (tegra_host->sclk && (!tegra_host->is_sdmmc_sclk_on)) {
1457                         ret = clk_prepare_enable(tegra_host->sclk);
1458                         if (ret) {
1459                                 dev_err(mmc_dev(sdhci->mmc),
1460                                 "clock enable is failed, ret: %d\n", ret);
1461                                 return;
1462                         }
1463                         tegra_host->is_sdmmc_sclk_on = true;
1464                 }
1465         } else if (!clock && tegra_host->clk_enabled) {
1466                 if (tegra_host->emc_clk && tegra_host->is_sdmmc_emc_clk_on) {
1467                         clk_disable_unprepare(tegra_host->emc_clk);
1468                         tegra_host->is_sdmmc_emc_clk_on = false;
1469                 }
1470                 if (tegra_host->sclk && tegra_host->is_sdmmc_sclk_on) {
1471                         clk_disable_unprepare(tegra_host->sclk);
1472                         tegra_host->is_sdmmc_sclk_on = false;
1473                 }
1474                 ctrl = sdhci_readb(sdhci, SDHCI_VNDR_CLK_CTRL);
1475                 ctrl &= ~SDHCI_VNDR_CLK_CTRL_SDMMC_CLK;
1476                 sdhci_writeb(sdhci, ctrl, SDHCI_VNDR_CLK_CTRL);
1477                 clk_disable_unprepare(pltfm_host->clk);
1478                 tegra_host->clk_enabled = false;
1479                 sdhci->is_clk_on = tegra_host->clk_enabled;
1480                 pm_runtime_put_sync(&pdev->dev);
1481         }
1482         mutex_unlock(&tegra_host->set_clock_mutex);
1483 }
1484
1485 static void tegra_sdhci_do_calibration(struct sdhci_host *sdhci,
1486         unsigned char signal_voltage)
1487 {
1488         unsigned int val;
1489         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1490         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1491         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
1492         unsigned int timeout = 10;
1493         unsigned int calib_offsets = 0;
1494
1495         /* No Calibration for sdmmc4 */
1496         if (unlikely(soc_data->nvquirks & NVQUIRK_DISABLE_SDMMC4_CALIB) &&
1497                 (tegra_host->instance == 3))
1498                 return;
1499
1500         if (unlikely(soc_data->nvquirks & NVQUIRK_DISABLE_AUTO_CALIBRATION))
1501                 return;
1502
1503         val = sdhci_readl(sdhci, SDMMC_SDMEMCOMPPADCTRL);
1504         val &= ~SDMMC_SDMEMCOMPPADCTRL_VREF_SEL_MASK;
1505         if (soc_data->nvquirks & NVQUIRK_SET_PAD_E_INPUT_OR_E_PWRD)
1506                 val |= SDMMC_SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD_MASK;
1507         val |= 0x7;
1508         sdhci_writel(sdhci, val, SDMMC_SDMEMCOMPPADCTRL);
1509
1510         /* Enable Auto Calibration*/
1511         val = sdhci_readl(sdhci, SDMMC_AUTO_CAL_CONFIG);
1512         val |= SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_ENABLE;
1513         val |= SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_START;
1514         if (unlikely(soc_data->nvquirks & NVQUIRK_SET_CALIBRATION_OFFSETS)) {
1515                 if (signal_voltage == MMC_SIGNAL_VOLTAGE_330)
1516                         calib_offsets = tegra_host->plat->calib_3v3_offsets;
1517                 else if (signal_voltage == MMC_SIGNAL_VOLTAGE_180)
1518                         calib_offsets = tegra_host->plat->calib_1v8_offsets;
1519                 if (calib_offsets) {
1520                         /* Program Auto cal PD offset(bits 8:14) */
1521                         val &= ~(0x7F <<
1522                                 SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_PD_OFFSET_SHIFT);
1523                         val |= (((calib_offsets >> 8) & 0xFF) <<
1524                                 SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_PD_OFFSET_SHIFT);
1525                         /* Program Auto cal PU offset(bits 0:6) */
1526                         val &= ~0x7F;
1527                         val |= (calib_offsets & 0xFF);
1528                 }
1529         }
1530         sdhci_writel(sdhci, val, SDMMC_AUTO_CAL_CONFIG);
1531
1532         /* Wait until the calibration is done */
1533         do {
1534                 if (!(sdhci_readl(sdhci, SDMMC_AUTO_CAL_STATUS) &
1535                         SDMMC_AUTO_CAL_STATUS_AUTO_CAL_ACTIVE))
1536                         break;
1537
1538                 mdelay(1);
1539                 timeout--;
1540         } while (timeout);
1541
1542         if (!timeout)
1543                 dev_err(mmc_dev(sdhci->mmc), "Auto calibration failed\n");
1544
1545         if (soc_data->nvquirks & NVQUIRK_SET_PAD_E_INPUT_OR_E_PWRD) {
1546                 val = sdhci_readl(sdhci, SDMMC_SDMEMCOMPPADCTRL);
1547                 val &= ~SDMMC_SDMEMCOMPPADCTRL_PAD_E_INPUT_OR_E_PWRD_MASK;
1548                 sdhci_writel(sdhci, val, SDMMC_SDMEMCOMPPADCTRL);
1549         }
1550
1551         if (unlikely(soc_data->nvquirks & NVQUIRK_SET_DRIVE_STRENGTH)) {
1552                 unsigned int pulldown_code;
1553                 unsigned int pullup_code;
1554                 int pg;
1555                 int err;
1556
1557                 /* Disable Auto calibration */
1558                 val = sdhci_readl(sdhci, SDMMC_AUTO_CAL_CONFIG);
1559                 val &= ~SDMMC_AUTO_CAL_CONFIG_AUTO_CAL_ENABLE;
1560                 sdhci_writel(sdhci, val, SDMMC_AUTO_CAL_CONFIG);
1561
1562                 pg = tegra_drive_get_pingroup(mmc_dev(sdhci->mmc));
1563                 if (pg != -1) {
1564                         /* Get the pull down codes from auto cal status reg */
1565                         pulldown_code = (
1566                                 sdhci_readl(sdhci, SDMMC_AUTO_CAL_STATUS) >>
1567                                 SDMMC_AUTO_CAL_STATUS_PULLDOWN_OFFSET);
1568                         /* Set the pull down in the pinmux reg */
1569                         err = tegra_drive_pinmux_set_pull_down(pg,
1570                                 pulldown_code);
1571                         if (err)
1572                                 dev_err(mmc_dev(sdhci->mmc),
1573                                 "Failed to set pulldown codes %d err %d\n",
1574                                 pulldown_code, err);
1575
1576                         /* Calculate the pull up codes */
1577                         pullup_code = pulldown_code + PULLUP_ADJUSTMENT_OFFSET;
1578                         if (pullup_code >= TEGRA_MAX_PULL)
1579                                 pullup_code = TEGRA_MAX_PULL - 1;
1580                         /* Set the pull up code in the pinmux reg */
1581                         err = tegra_drive_pinmux_set_pull_up(pg, pullup_code);
1582                         if (err)
1583                                 dev_err(mmc_dev(sdhci->mmc),
1584                                 "Failed to set pullup codes %d err %d\n",
1585                                 pullup_code, err);
1586                 }
1587         }
1588 }
1589
1590 static int tegra_sdhci_signal_voltage_switch(struct sdhci_host *sdhci,
1591         unsigned int signal_voltage)
1592 {
1593         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1594         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1595         unsigned int min_uV = tegra_host->vddio_min_uv;
1596         unsigned int max_uV = tegra_host->vddio_max_uv;
1597         unsigned int rc = 0;
1598         u16 ctrl;
1599
1600
1601         ctrl = sdhci_readw(sdhci, SDHCI_HOST_CONTROL2);
1602         if (signal_voltage == MMC_SIGNAL_VOLTAGE_180) {
1603                 ctrl |= SDHCI_CTRL_VDD_180;
1604                 min_uV = SDHOST_LOW_VOLT_MIN;
1605                 max_uV = SDHOST_LOW_VOLT_MAX;
1606         } else if (signal_voltage == MMC_SIGNAL_VOLTAGE_330) {
1607                 if (ctrl & SDHCI_CTRL_VDD_180)
1608                         ctrl &= ~SDHCI_CTRL_VDD_180;
1609         }
1610
1611         /* Check if the slot can support the required voltage */
1612         if (min_uV > tegra_host->vddio_max_uv)
1613                 return 0;
1614
1615         /* Set/clear the 1.8V signalling */
1616         sdhci_writew(sdhci, ctrl, SDHCI_HOST_CONTROL2);
1617
1618         /* Switch the I/O rail voltage */
1619         rc = tegra_sdhci_configure_regulators(tegra_host, CONFIG_REG_SET_VOLT,
1620                 min_uV, max_uV);
1621         if (rc && (signal_voltage == MMC_SIGNAL_VOLTAGE_180)) {
1622                 dev_err(mmc_dev(sdhci->mmc),
1623                         "setting 1.8V failed %d. Revert to 3.3V\n", rc);
1624                 rc = tegra_sdhci_configure_regulators(tegra_host,
1625                         CONFIG_REG_SET_VOLT, SDHOST_HIGH_VOLT_MIN,
1626                         SDHOST_HIGH_VOLT_MAX);
1627         }
1628
1629         return rc;
1630 }
1631
1632 static int tegra_sdhci_configure_regulators(struct sdhci_tegra *tegra_host,
1633         u8 option, int min_uV, int max_uV)
1634 {
1635         int rc = 0;
1636
1637         switch (option) {
1638         case CONFIG_REG_EN:
1639                 if (!tegra_host->is_rail_enabled) {
1640                         if (tegra_host->vdd_slot_reg)
1641                                 rc = regulator_enable(tegra_host->vdd_slot_reg);
1642                         if (tegra_host->vdd_io_reg)
1643                                 rc = regulator_enable(tegra_host->vdd_io_reg);
1644                         tegra_host->is_rail_enabled = true;
1645                 }
1646         break;
1647         case CONFIG_REG_DIS:
1648                 if (tegra_host->is_rail_enabled) {
1649                         if (tegra_host->vdd_io_reg)
1650                                 rc = regulator_disable(tegra_host->vdd_io_reg);
1651                         if (tegra_host->vdd_slot_reg)
1652                                 rc = regulator_disable(
1653                                         tegra_host->vdd_slot_reg);
1654                         tegra_host->is_rail_enabled = false;
1655                 }
1656         break;
1657         case CONFIG_REG_SET_VOLT:
1658                 if (tegra_host->vdd_io_reg)
1659                         rc = regulator_set_voltage(tegra_host->vdd_io_reg,
1660                                 min_uV, max_uV);
1661         break;
1662         default:
1663                 pr_err("Invalid argument passed to reg config %d\n", option);
1664         }
1665
1666         return rc;
1667 }
1668
1669 static void tegra_sdhci_reset(struct sdhci_host *sdhci, u8 mask)
1670 {
1671         unsigned long timeout;
1672
1673         sdhci_writeb(sdhci, mask, SDHCI_SOFTWARE_RESET);
1674
1675         /* Wait max 100 ms */
1676         timeout = 100;
1677
1678         /* hw clears the bit when it's done */
1679         while (sdhci_readb(sdhci, SDHCI_SOFTWARE_RESET) & mask) {
1680                 if (timeout == 0) {
1681                         dev_err(mmc_dev(sdhci->mmc), "Reset 0x%x never"
1682                                 "completed.\n", (int)mask);
1683                         return;
1684                 }
1685                 timeout--;
1686                 mdelay(1);
1687         }
1688
1689         tegra_sdhci_reset_exit(sdhci, mask);
1690 }
1691
1692 static void sdhci_tegra_set_tap_delay(struct sdhci_host *sdhci,
1693         unsigned int tap_delay)
1694 {
1695         u32 vendor_ctrl;
1696
1697         /* Max tap delay value is 255 */
1698         if (tap_delay > MAX_TAP_VALUES) {
1699                 dev_err(mmc_dev(sdhci->mmc),
1700                         "Valid tap range (0-255). Setting tap value %d\n",
1701                         tap_delay);
1702                 dump_stack();
1703                 return;
1704         }
1705
1706         vendor_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_CLK_CTRL);
1707         vendor_ctrl &= ~(0xFF << SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1708         vendor_ctrl |= (tap_delay << SDHCI_VNDR_CLK_CTRL_TAP_VALUE_SHIFT);
1709         sdhci_writel(sdhci, vendor_ctrl, SDHCI_VNDR_CLK_CTRL);
1710 }
1711
1712 static void sdhci_tegra_set_trim_delay(struct sdhci_host *sdhci,
1713         unsigned int trim_delay)
1714 {
1715         u32 vendor_ctrl;
1716
1717         vendor_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_CLK_CTRL);
1718         vendor_ctrl &= ~(0x1F << SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1719         vendor_ctrl |= (trim_delay << SDHCI_VNDR_CLK_CTRL_TRIM_VALUE_SHIFT);
1720         sdhci_writel(sdhci, vendor_ctrl, SDHCI_VNDR_CLK_CTRL);
1721 }
1722
1723 static int sdhci_tegra_sd_error_stats(struct sdhci_host *host, u32 int_status)
1724 {
1725         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
1726         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1727         struct sdhci_tegra_sd_stats *head = tegra_host->sd_stat_head;
1728
1729         if (int_status & SDHCI_INT_DATA_CRC)
1730                 head->data_crc_count++;
1731         if (int_status & SDHCI_INT_CRC)
1732                 head->cmd_crc_count++;
1733         if (int_status & SDHCI_INT_TIMEOUT)
1734                 head->cmd_to_count++;
1735         if (int_status & SDHCI_INT_DATA_TIMEOUT)
1736                 head->data_to_count++;
1737         return 0;
1738 }
1739
1740 static struct tegra_tuning_data *sdhci_tegra_get_tuning_data(
1741         struct sdhci_host *sdhci, unsigned int clock)
1742 {
1743         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1744         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1745         struct tegra_tuning_data *tuning_data;
1746         unsigned int low_freq;
1747         u8 i = 0;
1748
1749         if (tegra_host->tuning_freq_count == 1) {
1750                 tuning_data = &tegra_host->tuning_data[0];
1751                 goto out;
1752         }
1753
1754         /* Get the lowest supported freq */
1755         for (i = 0; i < TUNING_FREQ_COUNT; ++i) {
1756                 low_freq = tegra_host->soc_data->tuning_freq_list[i];
1757                 if (low_freq)
1758                         break;
1759         }
1760
1761         if (clock <= low_freq)
1762                 tuning_data = &tegra_host->tuning_data[0];
1763         else
1764                 tuning_data = &tegra_host->tuning_data[1];
1765
1766 out:
1767         return tuning_data;
1768 }
1769
1770 static void calculate_vmin_values(struct sdhci_host *sdhci,
1771         struct tegra_tuning_data *tuning_data, int vmin, int boot_mv)
1772 {
1773         struct tuning_values *est_values = &tuning_data->est_values;
1774         struct tuning_values *calc_values = &tuning_data->calc_values;
1775         struct tuning_t2t_coeffs *t2t_coeffs = tuning_data->t2t_coeffs;
1776         struct tap_hole_coeffs *thole_coeffs = tuning_data->thole_coeffs;
1777         int vmin_slope, vmin_int, temp_calc_vmin;
1778         int t2t_vmax, t2t_vmin;
1779         int vmax_thole, vmin_thole;
1780
1781         /*
1782          * If current vmin is equal to vmin or vmax of tuning data, use the
1783          * previously calculated estimated T2T values directly. Note that the
1784          * estimated T2T_vmax is not at Vmax specified in tuning data. It is
1785          * the T2T at the boot or max voltage for the current SKU. Hence,
1786          * boot_mv is used in place of t2t_coeffs->vmax.
1787          */
1788         if (vmin == t2t_coeffs->vmin) {
1789                 t2t_vmin = est_values->t2t_vmin;
1790         } else if (vmin == boot_mv) {
1791                 t2t_vmin = est_values->t2t_vmax;
1792         } else {
1793                 /*
1794                  * For any intermediate voltage between boot voltage and vmin
1795                  * of tuning data, calculate the slope and intercept from the
1796                  * t2t at boot_mv and vmin and calculate the actual values.
1797                  */
1798                 t2t_vmax = 1000 / est_values->t2t_vmax;
1799                 t2t_vmin = 1000 / est_values->t2t_vmin;
1800                 vmin_slope = ((t2t_vmax - t2t_vmin) * 1000) /
1801                         (boot_mv - t2t_coeffs->vmin);
1802                 vmin_int = (t2t_vmax * 1000 - (vmin_slope * boot_mv)) / 1000;
1803                 t2t_vmin = (vmin_slope * vmin) / 1000 + vmin_int;
1804                 t2t_vmin = (1000 / t2t_vmin);
1805         }
1806
1807         calc_values->t2t_vmin = (t2t_vmin * calc_values->t2t_vmax) /
1808                 est_values->t2t_vmax;
1809
1810         calc_values->ui_vmin = (1000000 / (tuning_data->freq_hz / 1000000)) /
1811                 calc_values->t2t_vmin;
1812
1813         /* Calculate the vmin tap hole at vmin of tuning data */
1814         temp_calc_vmin = (est_values->t2t_vmin * calc_values->t2t_vmax) /
1815                 est_values->t2t_vmax;
1816         vmin_thole = (thole_coeffs->thole_vmin_int -
1817                 (thole_coeffs->thole_vmin_slope * temp_calc_vmin)) /
1818                 1000;
1819         vmax_thole = calc_values->vmax_thole;
1820
1821         if (vmin == t2t_coeffs->vmin) {
1822                 calc_values->vmin_thole = vmin_thole;
1823         } else if (vmin == boot_mv) {
1824                 calc_values->vmin_thole = vmax_thole;
1825         } else {
1826                 /*
1827                  * Interpolate the tap hole for any intermediate voltage.
1828                  * Calculate the slope and intercept from the available data
1829                  * and use them to calculate the actual values.
1830                  */
1831                 vmin_slope = ((vmax_thole - vmin_thole) * 1000) /
1832                         (boot_mv - t2t_coeffs->vmin);
1833                 vmin_int = (vmax_thole * 1000 - (vmin_slope * boot_mv)) / 1000;
1834                 calc_values->vmin_thole = (vmin_slope * vmin) / 1000 + vmin_int;
1835         }
1836
1837         /* Adjust the partial win start for Vmin boundary */
1838         if (tuning_data->is_partial_win_valid)
1839                 tuning_data->final_tap_data[0].win_start =
1840                         (tuning_data->final_tap_data[0].win_start *
1841                         tuning_data->calc_values.t2t_vmax) /
1842                         tuning_data->calc_values.t2t_vmin;
1843
1844         pr_info("**********Tuning values*********\n");
1845         pr_info("**estimated values**\n");
1846         pr_info("T2T_Vmax %d, T2T_Vmin %d, 1'st_hole_Vmax %d, UI_Vmax %d\n",
1847                 est_values->t2t_vmax, est_values->t2t_vmin,
1848                 est_values->vmax_thole, est_values->ui);
1849         pr_info("**Calculated values**\n");
1850         pr_info("T2T_Vmax %d, 1'st_hole_Vmax %d, UI_Vmax %d\n",
1851                 calc_values->t2t_vmax, calc_values->vmax_thole,
1852                 calc_values->ui);
1853         pr_info("T2T_Vmin %d, 1'st_hole_Vmin %d, UI_Vmin %d\n",
1854                 calc_values->t2t_vmin, calc_values->vmin_thole,
1855                 calc_values->ui_vmin);
1856         pr_info("***********************************\n");
1857 }
1858
1859 static int slide_window_start(struct sdhci_host *sdhci,
1860         struct tegra_tuning_data *tuning_data,
1861         int tap_value, enum tap_win_edge_attr edge_attr, int tap_hole)
1862 {
1863         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1864         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1865         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
1866
1867         if (edge_attr == WIN_EDGE_BOUN_START) {
1868                 if (tap_value < 0)
1869                         tap_value += (1000 / tuning_data->calc_values.t2t_vmin);
1870                 else
1871                         tap_value += (1000 / tuning_data->calc_values.t2t_vmax);
1872         } else if (edge_attr == WIN_EDGE_HOLE) {
1873                 if (soc_data->nvquirks & NVQUIRK_TMP_VAR_1_5_TAP_MARGIN)
1874                         tap_value += ((7 * tap_hole) / 100) + 2;
1875                 else
1876                         tap_value += ((7 * tap_hole) / 100) +
1877                         (((2 * (450 / tuning_data->calc_values.t2t_vmax))
1878                         + 1) / 2);
1879         }
1880
1881         if (tap_value > MAX_TAP_VALUES)
1882                 tap_value = MAX_TAP_VALUES;
1883
1884         return tap_value;
1885 }
1886
1887 static int slide_window_end(struct sdhci_host *sdhci,
1888         struct tegra_tuning_data *tuning_data,
1889         int tap_value, enum tap_win_edge_attr edge_attr, int tap_hole)
1890 {
1891         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
1892         struct sdhci_tegra *tegra_host = pltfm_host->priv;
1893         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
1894
1895         if (edge_attr == WIN_EDGE_BOUN_END) {
1896                 tap_value = (tap_value * tuning_data->calc_values.t2t_vmax) /
1897                         tuning_data->calc_values.t2t_vmin;
1898                 tap_value -= (1000 / tuning_data->calc_values.t2t_vmin);
1899         } else if (edge_attr == WIN_EDGE_HOLE) {
1900                 if (tap_hole > 0)
1901                         tap_value = tap_hole;
1902                 if (soc_data->nvquirks & NVQUIRK_TMP_VAR_1_5_TAP_MARGIN)
1903                         tap_value -= ((7 * tap_hole) / 100) + 2;
1904                 else
1905                         tap_value -= ((7 * tap_hole) / 100) +
1906                         (((2 * (450 / tuning_data->calc_values.t2t_vmin))
1907                         + 1) / 2);
1908         }
1909
1910         return tap_value;
1911 }
1912
1913 static int adjust_window_boundaries(struct sdhci_host *sdhci,
1914         struct tegra_tuning_data *tuning_data,
1915         struct tap_window_data *temp_tap_data)
1916 {
1917         struct tap_window_data *tap_data;
1918         int vmin_tap_hole;
1919         int vmax_tap_hole;
1920         u8 i = 0;
1921
1922         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
1923                 tap_data = &temp_tap_data[i];
1924                 /* Update with next hole if first hole is taken care of */
1925                 if (tap_data->win_start_attr == WIN_EDGE_HOLE)
1926                         vmax_tap_hole = tuning_data->calc_values.vmax_thole +
1927                                 (tap_data->hole_pos - 1) *
1928                                 tuning_data->calc_values.ui;
1929                 tap_data->win_start = slide_window_start(sdhci, tuning_data,
1930                         tap_data->win_start, tap_data->win_start_attr,
1931                         vmax_tap_hole);
1932
1933                 /* Update with next hole if first hole is taken care of */
1934                 if (tap_data->win_end_attr == WIN_EDGE_HOLE)
1935                         vmin_tap_hole = tuning_data->calc_values.vmin_thole +
1936                                 (tap_data->hole_pos - 1) *
1937                                 tuning_data->calc_values.ui_vmin;
1938                 tap_data->win_end = slide_window_end(sdhci, tuning_data,
1939                         tap_data->win_end, tap_data->win_end_attr,
1940                         vmin_tap_hole);
1941         }
1942
1943         pr_info("***********final tuning windows**********\n");
1944         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
1945                 tap_data = &temp_tap_data[i];
1946                 pr_info("win[%d]: %d - %d\n", i, tap_data->win_start,
1947                         tap_data->win_end);
1948         }
1949         pr_info("********************************\n");
1950         return 0;
1951 }
1952
1953 static int find_best_tap_value(struct tegra_tuning_data *tuning_data,
1954         struct tap_window_data *temp_tap_data, int vmin)
1955 {
1956         struct tap_window_data *tap_data;
1957         u8 i = 0, sel_win = 0;
1958         int pref_win = 0, curr_win_size = 0;
1959         int best_tap_value = 0;
1960
1961         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
1962                 tap_data = &temp_tap_data[i];
1963                 if (!i && tuning_data->is_partial_win_valid) {
1964                         pref_win = tap_data->win_end - tap_data->win_start;
1965                         if ((tap_data->win_end * 2) < pref_win)
1966                                 pref_win = tap_data->win_end * 2;
1967                         sel_win = 0;
1968                 } else {
1969                         curr_win_size = tap_data->win_end - tap_data->win_start;
1970                         if ((curr_win_size > 0) && (curr_win_size > pref_win)) {
1971                                 pref_win = curr_win_size;
1972                                 sel_win = i;
1973                         }
1974                 }
1975         }
1976
1977         if (pref_win <= 0) {
1978                 pr_err("No window opening for %d vmin\n", vmin);
1979                 return -1;
1980         }
1981
1982         tap_data = &temp_tap_data[sel_win];
1983         if (!sel_win && tuning_data->is_partial_win_valid) {
1984                 i = sel_win;
1985                 best_tap_value = tap_data->win_end - (pref_win / 2);
1986                 if (best_tap_value < 0)
1987                         best_tap_value = 0;
1988         } else {
1989                 best_tap_value = tap_data->win_start +
1990                         ((tap_data->win_end - tap_data->win_start) *
1991                         tuning_data->calc_values.t2t_vmin) /
1992                         (tuning_data->calc_values.t2t_vmin +
1993                         tuning_data->calc_values.t2t_vmax);
1994         }
1995
1996         pr_err("best tap win - (%d-%d), best tap value %d\n",
1997                 tap_data->win_start, tap_data->win_end, best_tap_value);
1998         return best_tap_value;
1999 }
2000
2001 static int sdhci_tegra_calculate_best_tap(struct sdhci_host *sdhci,
2002         struct tegra_tuning_data *tuning_data)
2003 {
2004         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2005         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2006         struct tap_window_data *temp_tap_data = NULL;
2007         int vmin, curr_vmin, best_tap_value = 0;
2008         int err = 0;
2009
2010         curr_vmin = tegra_dvfs_predict_millivolts(pltfm_host->clk,
2011                 tuning_data->freq_hz);
2012         if (!curr_vmin)
2013                 curr_vmin = tegra_host->boot_vcore_mv;
2014
2015         vmin = curr_vmin;
2016         do {
2017                 SDHCI_TEGRA_DBG("%s: checking for win opening with vmin %d\n",
2018                         mmc_hostname(sdhci->mmc), vmin);
2019                 if ((best_tap_value < 0) &&
2020                         (vmin > tegra_host->boot_vcore_mv)) {
2021                         dev_err(mmc_dev(sdhci->mmc),
2022                                 "No best tap for any vcore range\n");
2023                         return -EINVAL;
2024                 }
2025
2026                 calculate_vmin_values(sdhci, tuning_data, vmin,
2027                         tegra_host->boot_vcore_mv);
2028
2029                 if (temp_tap_data == NULL) {
2030                         temp_tap_data = kzalloc(sizeof(struct tap_window_data) *
2031                                 tuning_data->num_of_valid_tap_wins, GFP_KERNEL);
2032                         if (IS_ERR_OR_NULL(temp_tap_data)) {
2033                                 dev_err(mmc_dev(sdhci->mmc),
2034                                 "No memory for final tap value calculation\n");
2035                                 return -ENOMEM;
2036                         }
2037                 }
2038
2039                 memcpy(temp_tap_data, tuning_data->final_tap_data,
2040                         sizeof(struct tap_window_data) *
2041                         tuning_data->num_of_valid_tap_wins);
2042
2043                 adjust_window_boundaries(sdhci, tuning_data, temp_tap_data);
2044
2045                 best_tap_value = find_best_tap_value(tuning_data,
2046                         temp_tap_data, vmin);
2047
2048                 if (best_tap_value < 0)
2049                         vmin += 50;
2050         } while (best_tap_value < 0);
2051
2052         tuning_data->best_tap_value = best_tap_value;
2053         tuning_data->nom_best_tap_value = best_tap_value;
2054
2055         /*
2056          * Set the new vmin if there is any change. If dvfs overrides are
2057          * disabled, then print the error message but continue execution
2058          * rather than disabling tuning altogether.
2059          */
2060         if ((tuning_data->best_tap_value >= 0) && (curr_vmin != vmin)) {
2061                 err = tegra_dvfs_set_fmax_at_vmin(pltfm_host->clk,
2062                         tuning_data->freq_hz, vmin);
2063                 if ((err == -EPERM) || (err == -ENOSYS)) {
2064                         /*
2065                          * tegra_dvfs_set_fmax_at_vmin: will return EPERM or
2066                          * ENOSYS, when DVFS override is not enabled, continue
2067                          * tuning with default core voltage.
2068                          */
2069                         SDHCI_TEGRA_DBG(
2070                                 "dvfs overrides disabled. Vmin not updated\n");
2071                         err = 0;
2072                 }
2073         }
2074         kfree(temp_tap_data);
2075         return err;
2076 }
2077
2078 static int sdhci_tegra_issue_tuning_cmd(struct sdhci_host *sdhci)
2079 {
2080         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2081         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2082         int err = 0;
2083         u8 ctrl;
2084         u32 mask;
2085         unsigned int timeout = 10;
2086         int flags;
2087         u32 intstatus;
2088
2089         mask = SDHCI_CMD_INHIBIT | SDHCI_DATA_INHIBIT;
2090         while (sdhci_readl(sdhci, SDHCI_PRESENT_STATE) & mask) {
2091                 if (timeout == 0) {
2092                         dev_err(mmc_dev(sdhci->mmc), "Controller never"
2093                                 "released inhibit bit(s).\n");
2094                         err = -ETIMEDOUT;
2095                         goto out;
2096                 }
2097                 timeout--;
2098                 mdelay(1);
2099         }
2100
2101         ctrl = sdhci_readb(sdhci, SDHCI_HOST_CONTROL2);
2102         ctrl &= ~SDHCI_CTRL_TUNED_CLK;
2103         sdhci_writeb(sdhci, ctrl, SDHCI_HOST_CONTROL2);
2104
2105         ctrl = sdhci_readb(sdhci, SDHCI_HOST_CONTROL2);
2106         ctrl |= SDHCI_CTRL_EXEC_TUNING;
2107         sdhci_writeb(sdhci, ctrl, SDHCI_HOST_CONTROL2);
2108
2109         /*
2110          * In response to CMD19, the card sends 64 bytes of tuning
2111          * block to the Host Controller. So we set the block size
2112          * to 64 here.
2113          * In response to CMD21, the card sends 128 bytes of tuning
2114          * block for MMC_BUS_WIDTH_8 and 64 bytes for MMC_BUS_WIDTH_4
2115          * to the Host Controller. So we set the block size to 64 here.
2116          */
2117         sdhci_writew(sdhci, SDHCI_MAKE_BLKSZ(7, tegra_host->tuning_bsize),
2118                 SDHCI_BLOCK_SIZE);
2119
2120         sdhci_writeb(sdhci, 0xE, SDHCI_TIMEOUT_CONTROL);
2121
2122         sdhci_writew(sdhci, SDHCI_TRNS_READ, SDHCI_TRANSFER_MODE);
2123
2124         sdhci_writel(sdhci, 0x0, SDHCI_ARGUMENT);
2125
2126         /* Set the cmd flags */
2127         flags = SDHCI_CMD_RESP_SHORT | SDHCI_CMD_CRC | SDHCI_CMD_DATA;
2128         /* Issue the command */
2129         sdhci_writew(sdhci, SDHCI_MAKE_CMD(
2130                 tegra_host->tuning_opcode, flags), SDHCI_COMMAND);
2131
2132         timeout = 5;
2133         do {
2134                 timeout--;
2135                 mdelay(1);
2136                 intstatus = sdhci_readl(sdhci, SDHCI_INT_STATUS);
2137                 if (intstatus) {
2138                         sdhci_writel(sdhci, intstatus, SDHCI_INT_STATUS);
2139                         break;
2140                 }
2141         } while(timeout);
2142
2143         if ((intstatus & SDHCI_INT_DATA_AVAIL) &&
2144                 !(intstatus & SDHCI_INT_DATA_CRC)) {
2145                 err = 0;
2146                 sdhci->tuning_done = 1;
2147         } else {
2148                 tegra_sdhci_reset(sdhci, SDHCI_RESET_DATA);
2149                 tegra_sdhci_reset(sdhci, SDHCI_RESET_CMD);
2150                 err = -EIO;
2151         }
2152
2153         if (sdhci->tuning_done) {
2154                 sdhci->tuning_done = 0;
2155                 ctrl = sdhci_readb(sdhci, SDHCI_HOST_CONTROL2);
2156                 if (!(ctrl & SDHCI_CTRL_EXEC_TUNING) &&
2157                         (ctrl & SDHCI_CTRL_TUNED_CLK))
2158                         err = 0;
2159                 else
2160                         err = -EIO;
2161         }
2162         mdelay(1);
2163 out:
2164         return err;
2165 }
2166
2167 static int sdhci_tegra_scan_tap_values(struct sdhci_host *sdhci,
2168         unsigned int starting_tap, bool expect_failure)
2169 {
2170         unsigned int tap_value = starting_tap;
2171         int err;
2172         unsigned int retry = TUNING_RETRIES;
2173
2174         do {
2175                 /* Set the tap delay */
2176                 sdhci_tegra_set_tap_delay(sdhci, tap_value);
2177
2178                 /* Run frequency tuning */
2179                 err = sdhci_tegra_issue_tuning_cmd(sdhci);
2180                 if (err && retry) {
2181                         retry--;
2182                         continue;
2183                 } else {
2184                         retry = TUNING_RETRIES;
2185                         if ((expect_failure && !err) ||
2186                                 (!expect_failure && err))
2187                                 break;
2188                 }
2189                 tap_value++;
2190         } while (tap_value <= MAX_TAP_VALUES);
2191
2192         return tap_value;
2193 }
2194
2195 static int calculate_actual_tuning_values(int speedo,
2196         struct tegra_tuning_data *tuning_data, int voltage_mv)
2197 {
2198         struct tuning_t2t_coeffs *t2t_coeffs = tuning_data->t2t_coeffs;
2199         struct tap_hole_coeffs *thole_coeffs = tuning_data->thole_coeffs;
2200         struct tuning_values *calc_values = &tuning_data->calc_values;
2201         int slope, inpt;
2202         int vmax_thole, vmin_thole;
2203
2204         /* T2T_Vmax = (1000000/freq_MHz)/Calc_UI */
2205         calc_values->t2t_vmax = (1000000 / (tuning_data->freq_hz / 1000000)) /
2206                 calc_values->ui;
2207
2208         /*
2209          * Interpolate the tap hole.
2210          * Vmax_1'st_hole = (Calc_T2T_Vmax*(-thole_slope)+thole_tint.
2211          */
2212         vmax_thole = (thole_coeffs->thole_vmax_int -
2213                 (thole_coeffs->thole_vmax_slope * calc_values->t2t_vmax)) /
2214                 1000;
2215         vmin_thole = (thole_coeffs->thole_vmin_int -
2216                 (thole_coeffs->thole_vmin_slope * calc_values->t2t_vmax)) /
2217                 1000;
2218         if (voltage_mv == t2t_coeffs->vmin) {
2219                 calc_values->vmax_thole = vmin_thole;
2220         } else if (voltage_mv == t2t_coeffs->vmax) {
2221                 calc_values->vmax_thole = vmax_thole;
2222         } else {
2223                 slope = (vmax_thole - vmin_thole) /
2224                         (t2t_coeffs->vmax - t2t_coeffs->vmin);
2225                 inpt = ((vmax_thole * 1000) - (slope * 1250)) / 1000;
2226                 calc_values->vmax_thole = slope * voltage_mv + inpt;
2227         }
2228
2229         return 0;
2230 }
2231
2232 /*
2233  * All coeffs are filled up in the table after multiplying by 1000. So, all
2234  * calculations should have a divide by 1000 at the end.
2235  */
2236 static int calculate_estimated_tuning_values(int speedo,
2237         struct tegra_tuning_data *tuning_data, int voltage_mv)
2238 {
2239         struct tuning_t2t_coeffs *t2t_coeffs = tuning_data->t2t_coeffs;
2240         struct tap_hole_coeffs *thole_coeffs = tuning_data->thole_coeffs;
2241         struct tuning_values *est_values = &tuning_data->est_values;
2242         int slope, inpt;
2243         int vmax_t2t, vmin_t2t;
2244         int vmax_thole, vmin_thole;
2245
2246         /* Est_T2T_Vmax = (speedo*(-t2t_slope)+t2t_int */
2247         vmax_t2t = (t2t_coeffs->t2t_vmax_int - (speedo *
2248                 t2t_coeffs->t2t_vmax_slope)) / 1000;
2249         vmin_t2t = (t2t_coeffs->t2t_vmin_int - (speedo *
2250                 t2t_coeffs->t2t_vmin_slope)) / 1000;
2251         est_values->t2t_vmin = vmin_t2t;
2252
2253         if (voltage_mv == t2t_coeffs->vmin) {
2254                 est_values->t2t_vmax = vmin_t2t;
2255         } else if (voltage_mv == t2t_coeffs->vmax) {
2256                 est_values->t2t_vmax = vmax_t2t;
2257         } else {
2258                 vmax_t2t = 1000 / vmax_t2t;
2259                 vmin_t2t = 1000 / vmin_t2t;
2260                 /*
2261                  * For any intermediate voltage between 0.95V and 1.25V,
2262                  * calculate the slope and intercept from the T2T and tap hole
2263                  * values of 0.95V and 1.25V and use them to calculate the
2264                  * actual values. 1/T2T is a linear function of voltage.
2265                  */
2266                 slope = ((vmax_t2t - vmin_t2t) * 1000) /
2267                         (t2t_coeffs->vmax - t2t_coeffs->vmin);
2268                 inpt = (vmax_t2t * 1000 - (slope * t2t_coeffs->vmax)) / 1000;
2269                 est_values->t2t_vmax = (slope * voltage_mv) / 1000 + inpt;
2270                 est_values->t2t_vmax = (1000 / est_values->t2t_vmax);
2271         }
2272
2273         /* Est_UI  = (1000000/freq_MHz)/Est_T2T_Vmax */
2274         est_values->ui = (1000000 / (thole_coeffs->freq_khz / 1000)) /
2275                 est_values->t2t_vmax;
2276
2277         /*
2278          * Est_1'st_hole = (Est_T2T_Vmax*(-thole_slope)) + thole_int.
2279          */
2280         vmax_thole = (thole_coeffs->thole_vmax_int -
2281                 (thole_coeffs->thole_vmax_slope * est_values->t2t_vmax)) / 1000;
2282         vmin_thole = (thole_coeffs->thole_vmin_int -
2283                 (thole_coeffs->thole_vmin_slope * est_values->t2t_vmax)) / 1000;
2284
2285         if (voltage_mv == t2t_coeffs->vmin) {
2286                 est_values->vmax_thole = vmin_thole;
2287         } else if (voltage_mv == t2t_coeffs->vmax) {
2288                 est_values->vmax_thole = vmax_thole;
2289         } else {
2290                 /*
2291                  * For any intermediate voltage between 0.95V and 1.25V,
2292                  * calculate the slope and intercept from the t2t and tap hole
2293                  * values of 0.95V and 1.25V and use them to calculate the
2294                  * actual values. Tap hole is a linear function of voltage.
2295                  */
2296                 slope = ((vmax_thole - vmin_thole) * 1000) /
2297                         (t2t_coeffs->vmax - t2t_coeffs->vmin);
2298                 inpt = (vmax_thole * 1000 - (slope * t2t_coeffs->vmax)) / 1000;
2299                 est_values->vmax_thole = (slope * voltage_mv) / 1000 + inpt;
2300         }
2301         est_values->vmin_thole = vmin_thole;
2302
2303         return 0;
2304 }
2305
2306 /*
2307  * Insert the calculated holes and get the final tap windows
2308  * with the boundaries and holes set.
2309  */
2310 static int adjust_holes_in_tap_windows(struct sdhci_host *sdhci,
2311         struct tegra_tuning_data *tuning_data)
2312 {
2313         struct tap_window_data *tap_data;
2314         struct tap_window_data *final_tap_data;
2315         struct tuning_values *calc_values = &tuning_data->calc_values;
2316         int tap_hole, size = 0;
2317         u8 i = 0, j = 0, num_of_wins, hole_pos = 0;
2318
2319         tuning_data->final_tap_data =
2320                 devm_kzalloc(mmc_dev(sdhci->mmc),
2321                         sizeof(struct tap_window_data) * 42, GFP_KERNEL);
2322         if (IS_ERR_OR_NULL(tuning_data->final_tap_data)) {
2323                 dev_err(mmc_dev(sdhci->mmc), "No mem for final tap wins\n");
2324                 return -ENOMEM;
2325         }
2326
2327         num_of_wins = tuning_data->num_of_valid_tap_wins;
2328         tap_hole = calc_values->vmax_thole;
2329         hole_pos++;
2330         do {
2331                 tap_data = &tuning_data->tap_data[i];
2332                 final_tap_data = &tuning_data->final_tap_data[j];
2333                 if (tap_hole < tap_data->win_start) {
2334                         tap_hole += calc_values->ui;
2335                         hole_pos++;
2336                         continue;
2337                 } else if (tap_hole > tap_data->win_end) {
2338                         memcpy(final_tap_data, tap_data,
2339                                 sizeof(struct tap_window_data));
2340                         i++;
2341                         j++;
2342                         num_of_wins--;
2343                         continue;
2344                 } else if ((tap_hole >= tap_data->win_start) &&
2345                         (tap_hole <= tap_data->win_end)) {
2346                         size = tap_data->win_end - tap_data->win_start;
2347                         do {
2348                                 final_tap_data =
2349                                         &tuning_data->final_tap_data[j];
2350                                 if (tap_hole == tap_data->win_start) {
2351                                         final_tap_data->win_start =
2352                                                 tap_hole + 1;
2353                                         final_tap_data->win_start_attr =
2354                                                 WIN_EDGE_HOLE;
2355                                         final_tap_data->hole_pos = hole_pos;
2356                                         tap_hole += calc_values->ui;
2357                                         hole_pos++;
2358                                 } else {
2359                                         final_tap_data->win_start =
2360                                                 tap_data->win_start;
2361                                         final_tap_data->win_start_attr =
2362                                                 WIN_EDGE_BOUN_START;
2363                                 }
2364                                 if (tap_hole <= tap_data->win_end) {
2365                                         final_tap_data->win_end = tap_hole - 1;
2366                                         final_tap_data->win_end_attr =
2367                                                 WIN_EDGE_HOLE;
2368                                         final_tap_data->hole_pos = hole_pos;
2369                                         tap_data->win_start = tap_hole;
2370                                 } else if (tap_hole > tap_data->win_end) {
2371                                         final_tap_data->win_end =
2372                                                 tap_data->win_end;
2373                                         final_tap_data->win_end_attr =
2374                                                 WIN_EDGE_BOUN_END;
2375                                         tap_data->win_start =
2376                                                 tap_data->win_end;
2377                                 }
2378                                 size = tap_data->win_end - tap_data->win_start;
2379                                 j++;
2380                         } while (size > 0);
2381                         i++;
2382                         num_of_wins--;
2383                 }
2384         } while (num_of_wins > 0);
2385
2386         /* Update the num of valid wins count after tap holes insertion */
2387         tuning_data->num_of_valid_tap_wins = j;
2388
2389         pr_info("********tuning windows after inserting holes*****\n");
2390         pr_info("WIN_ATTR legend: 0-BOUN_ST, 1-BOUN_END, 2-HOLE\n");
2391         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
2392                 final_tap_data = &tuning_data->final_tap_data[i];
2393                 pr_info("win[%d]:%d(%d) - %d(%d)\n", i,
2394                         final_tap_data->win_start,
2395                         final_tap_data->win_start_attr,
2396                         final_tap_data->win_end, final_tap_data->win_end_attr);
2397         }
2398         pr_info("***********************************************\n");
2399
2400         return 0;
2401 }
2402
2403 /*
2404  * Insert the boundaries from negative margin calculations into the windows
2405  * from auto tuning.
2406  */
2407 static int insert_boundaries_in_tap_windows(struct sdhci_host *sdhci,
2408         struct tegra_tuning_data *tuning_data, u8 boun_end)
2409 {
2410         struct tap_window_data *tap_data;
2411         struct tap_window_data *new_tap_data;
2412         struct tap_window_data *temp_tap_data;
2413         struct tuning_values *calc_values = &tuning_data->calc_values;
2414         int curr_boun;
2415         u8 i = 0, j = 0, num_of_wins;
2416         bool get_next_boun = false;
2417
2418         temp_tap_data = devm_kzalloc(mmc_dev(sdhci->mmc),
2419                         sizeof(struct tap_window_data) * 42, GFP_KERNEL);
2420         if (IS_ERR_OR_NULL(temp_tap_data)) {
2421                 dev_err(mmc_dev(sdhci->mmc), "No mem for final tap wins\n");
2422                 return -ENOMEM;
2423         }
2424
2425         num_of_wins = tuning_data->num_of_valid_tap_wins;
2426         curr_boun = boun_end % calc_values->ui;
2427         do {
2428                 if (get_next_boun) {
2429                         curr_boun += calc_values->ui;
2430                         /*
2431                          * If the boun_end exceeds the intial boundary end,
2432                          * just copy remaining windows and return.
2433                          */
2434                         if (curr_boun >= boun_end)
2435                                 curr_boun += MAX_TAP_VALUES;
2436                 }
2437
2438                 tap_data = &tuning_data->tap_data[i];
2439                 new_tap_data = &temp_tap_data[j];
2440                 if (curr_boun <= tap_data->win_start) {
2441                         get_next_boun = true;
2442                         continue;
2443                 } else if (curr_boun >= tap_data->win_end) {
2444                         memcpy(new_tap_data, tap_data,
2445                                 sizeof(struct tap_window_data));
2446                         i++;
2447                         j++;
2448                         num_of_wins--;
2449                         get_next_boun = false;
2450                         continue;
2451                 } else if ((curr_boun >= tap_data->win_start) &&
2452                         (curr_boun <= tap_data->win_end)) {
2453                                 new_tap_data->win_start = tap_data->win_start;
2454                                 new_tap_data->win_start_attr =
2455                                         tap_data->win_start_attr;
2456                                 new_tap_data->win_end = curr_boun - 1;
2457                                 new_tap_data->win_end_attr =
2458                                         tap_data->win_end_attr;
2459                                 j++;
2460                                 new_tap_data = &temp_tap_data[j];
2461                                 new_tap_data->win_start = curr_boun;
2462                                 new_tap_data->win_end = curr_boun;
2463                                 new_tap_data->win_start_attr =
2464                                         WIN_EDGE_BOUN_START;
2465                                 new_tap_data->win_end_attr =
2466                                         WIN_EDGE_BOUN_END;
2467                                 j++;
2468                                 new_tap_data = &temp_tap_data[j];
2469                                 new_tap_data->win_start = curr_boun + 1;
2470                                 new_tap_data->win_start_attr = WIN_EDGE_BOUN_START;
2471                                 new_tap_data->win_end = tap_data->win_end;
2472                                 new_tap_data->win_end_attr =
2473                                         tap_data->win_end_attr;
2474                                 i++;
2475                                 j++;
2476                                 num_of_wins--;
2477                                 get_next_boun = true;
2478                 }
2479         } while (num_of_wins > 0);
2480
2481         /* Update the num of valid wins count after tap holes insertion */
2482         tuning_data->num_of_valid_tap_wins = j;
2483
2484         memcpy(tuning_data->tap_data, temp_tap_data,
2485                 j * sizeof(struct tap_window_data));
2486         SDHCI_TEGRA_DBG("***tuning windows after inserting boundaries***\n");
2487         SDHCI_TEGRA_DBG("WIN_ATTR legend: 0-BOUN_ST, 1-BOUN_END, 2-HOLE\n");
2488         for (i = 0; i < tuning_data->num_of_valid_tap_wins; i++) {
2489                 new_tap_data = &tuning_data->tap_data[i];
2490                 SDHCI_TEGRA_DBG("win[%d]:%d(%d) - %d(%d)\n", i,
2491                         new_tap_data->win_start,
2492                         new_tap_data->win_start_attr,
2493                         new_tap_data->win_end, new_tap_data->win_end_attr);
2494         }
2495         SDHCI_TEGRA_DBG("***********************************************\n");
2496
2497         return 0;
2498 }
2499
2500 /*
2501  * Scan for all tap values and get all passing tap windows.
2502  */
2503 static int sdhci_tegra_get_tap_window_data(struct sdhci_host *sdhci,
2504         struct tegra_tuning_data *tuning_data)
2505 {
2506         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2507         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2508         struct tap_window_data *tap_data;
2509         struct tuning_ui tuning_ui[10];
2510         int err = 0, partial_win_start = 0, temp_margin = 0;
2511         unsigned int tap_value, calc_ui = 0;
2512         u8 prev_boundary_end = 0, num_of_wins = 0;
2513         u8 num_of_uis = 0, valid_num_uis = 0;
2514         u8 ref_ui, first_valid_full_win = 0;
2515         u8 boun_end = 0, next_boun_end = 0;
2516         u8 j = 0;
2517         bool valid_ui_found = false;
2518
2519         /*
2520          * Assume there are a max of 10 windows and allocate tap window
2521          * structures for the same. If there are more windows, the array
2522          * size can be adjusted later using realloc.
2523          */
2524         tuning_data->tap_data = devm_kzalloc(mmc_dev(sdhci->mmc),
2525                 sizeof(struct tap_window_data) * 42, GFP_KERNEL);
2526         if (IS_ERR_OR_NULL(tuning_data->tap_data)) {
2527                 dev_err(mmc_dev(sdhci->mmc), "No memory for tap data\n");
2528                 return -ENOMEM;
2529         }
2530
2531         spin_lock(&sdhci->lock);
2532         tap_value = 0;
2533         do {
2534                 tap_data = &tuning_data->tap_data[num_of_wins];
2535                 /* Get the window start */
2536                 tap_value = sdhci_tegra_scan_tap_values(sdhci, tap_value, true);
2537                 tap_data->win_start = min_t(u8, tap_value, MAX_TAP_VALUES);
2538                 tap_value++;
2539                 if (tap_value >= MAX_TAP_VALUES) {
2540                         /* If it's first iteration, then all taps failed */
2541                         if (!num_of_wins) {
2542                                 dev_err(mmc_dev(sdhci->mmc),
2543                                         "All tap values(0-255) failed\n");
2544                                 spin_unlock(&sdhci->lock);
2545                                 return -EINVAL;
2546                         } else {
2547                                 /* All windows obtained */
2548                                 break;
2549                         }
2550                 }
2551
2552                 /* Get the window end */
2553                 tap_value = sdhci_tegra_scan_tap_values(sdhci,
2554                                 tap_value, false);
2555                 tap_data->win_end = min_t(u8, (tap_value - 1), MAX_TAP_VALUES);
2556                 tap_data->win_size = tap_data->win_end - tap_data->win_start;
2557                 tap_value++;
2558
2559                 /*
2560                  * If the size of window is more than 4 taps wide, then it is a
2561                  * valid window. If tap value 0 has passed, then a partial
2562                  * window exists. Mark all the window edges as boundary edges.
2563                  */
2564                 if (tap_data->win_size > 4) {
2565                         if (tap_data->win_start == 0)
2566                                 tuning_data->is_partial_win_valid = true;
2567                         tap_data->win_start_attr = WIN_EDGE_BOUN_START;
2568                         tap_data->win_end_attr = WIN_EDGE_BOUN_END;
2569                 } else {
2570                         /* Invalid window as size is less than 5 taps */
2571                         SDHCI_TEGRA_DBG("Invalid tuning win (%d-%d) ignored\n",
2572                                 tap_data->win_start, tap_data->win_end);
2573                         continue;
2574                 }
2575
2576                 /* Ignore first and last partial UIs */
2577                 if (tap_data->win_end_attr == WIN_EDGE_BOUN_END) {
2578                                 tuning_ui[num_of_uis].ui = tap_data->win_end -
2579                                         prev_boundary_end;
2580                                 tuning_ui[num_of_uis].is_valid_ui = true;
2581                                 num_of_uis++;
2582                         prev_boundary_end = tap_data->win_end;
2583                 }
2584                 num_of_wins++;
2585         } while (tap_value < MAX_TAP_VALUES);
2586         spin_unlock(&sdhci->lock);
2587
2588         tuning_data->num_of_valid_tap_wins = num_of_wins;
2589         valid_num_uis = num_of_uis;
2590
2591         /* Print info of all tap windows */
2592         pr_info("**********Auto tuning windows*************\n");
2593         pr_info("WIN_ATTR legend: 0-BOUN_ST, 1-BOUN_END, 2-HOLE\n");
2594         for (j = 0; j < tuning_data->num_of_valid_tap_wins; j++) {
2595                 tap_data = &tuning_data->tap_data[j];
2596                 pr_info("win[%d]: %d(%d) - %d(%d)\n",
2597                         j, tap_data->win_start, tap_data->win_start_attr,
2598                         tap_data->win_end, tap_data->win_end_attr);
2599         }
2600         pr_info("***************************************\n");
2601
2602         /* Mark the first last partial UIs as invalid */
2603         tuning_ui[0].is_valid_ui = false;
2604         tuning_ui[num_of_uis - 1].is_valid_ui = false;
2605         valid_num_uis -= 2;
2606
2607         /* Discredit all uis at either end with size less than 30% of est ui */
2608         ref_ui = (30 * tuning_data->est_values.ui) / 100;
2609         for (j = 0; j < num_of_uis; j++) {
2610                 if (tuning_ui[j].is_valid_ui) {
2611                         tuning_ui[j].is_valid_ui = false;
2612                         valid_num_uis--;
2613                 }
2614                 if (tuning_ui[j].ui > ref_ui)
2615                         break;
2616         }
2617
2618         for (j = num_of_uis; j > 0; j--) {
2619                 if (tuning_ui[j - 1].ui < ref_ui) {
2620                         if (tuning_ui[j - 1].is_valid_ui) {
2621                                 tuning_ui[j - 1].is_valid_ui = false;
2622                                 valid_num_uis--;
2623                         }
2624                 } else
2625                         break;
2626         }
2627
2628         /* Calculate 0.75*est_UI */
2629         ref_ui = (75 * tuning_data->est_values.ui) / 100;
2630
2631         /*
2632          * Check for valid UIs and discredit invalid UIs. A UI is considered
2633          * valid if it's greater than (0.75*est_UI). If an invalid UI is found,
2634          * also discredit the smaller of the two adjacent windows.
2635          */
2636         for (j = 1; j < (num_of_uis - 1); j++) {
2637                 if (tuning_ui[j].ui > ref_ui && tuning_ui[j].is_valid_ui) {
2638                         tuning_ui[j].is_valid_ui = true;
2639                 } else {
2640                         if (tuning_ui[j].is_valid_ui) {
2641                                 tuning_ui[j].is_valid_ui = false;
2642                                 valid_num_uis--;
2643                         }
2644                         if (!tuning_ui[j + 1].is_valid_ui ||
2645                                 !tuning_ui[j - 1].is_valid_ui) {
2646                                 if (tuning_ui[j - 1].is_valid_ui) {
2647                                         tuning_ui[j - 1].is_valid_ui = false;
2648                                         valid_num_uis--;
2649                                 } else if (tuning_ui[j + 1].is_valid_ui) {
2650                                         tuning_ui[j + 1].is_valid_ui = false;
2651                                         valid_num_uis--;
2652                                 }
2653                         } else {
2654
2655                                 if (tuning_ui[j - 1].ui > tuning_ui[j + 1].ui)
2656                                         tuning_ui[j + 1].is_valid_ui = false;
2657                                 else
2658                                         tuning_ui[j - 1].is_valid_ui = false;
2659                                 valid_num_uis--;
2660                         }
2661                 }
2662         }
2663
2664         /* Calculate the cumulative UI if there are valid UIs left */
2665         if (valid_num_uis) {
2666                 for (j = 0; j < num_of_uis; j++)
2667                         if (tuning_ui[j].is_valid_ui) {
2668                                 calc_ui += tuning_ui[j].ui;
2669                                 if (!first_valid_full_win)
2670                                         first_valid_full_win = j;
2671                         }
2672         }
2673
2674         if (calc_ui) {
2675                 tuning_data->calc_values.ui = (calc_ui / valid_num_uis);
2676                 valid_ui_found = true;
2677         } else {
2678                 tuning_data->calc_values.ui = tuning_data->est_values.ui;
2679                 valid_ui_found = false;
2680         }
2681
2682         SDHCI_TEGRA_DBG("****Tuning UIs***********\n");
2683         for (j = 0; j < num_of_uis; j++)
2684                 SDHCI_TEGRA_DBG("Tuning UI[%d] : %d, Is valid[%d]\n",
2685                         j, tuning_ui[j].ui, tuning_ui[j].is_valid_ui);
2686         SDHCI_TEGRA_DBG("*************************\n");
2687
2688         /* Get the calculated tuning values */
2689         err = calculate_actual_tuning_values(tegra_host->speedo, tuning_data,
2690                 tegra_host->boot_vcore_mv);
2691
2692         /*
2693          * Calculate negative margin if partial win is valid. There are two
2694          * cases here.
2695          * Case 1: If Avg_UI is found, then keep subtracting avg_ui from start
2696          * of first valid full window until a value <=0 is obtained.
2697          * Case 2: If Avg_UI is not found, subtract avg_ui from all boundary
2698          * starts until a value <=0 is found.
2699          */
2700         if (tuning_data->is_partial_win_valid && (num_of_wins > 1)) {
2701                 if (valid_ui_found) {
2702                         partial_win_start =
2703                         tuning_data->tap_data[first_valid_full_win].win_start;
2704                         boun_end = partial_win_start;
2705                         partial_win_start %= tuning_data->calc_values.ui;
2706                         partial_win_start -= tuning_data->calc_values.ui;
2707                 } else {
2708                         for (j = 0; j < NEG_MAR_CHK_WIN_COUNT; j++) {
2709                                 temp_margin =
2710                                         tuning_data->tap_data[j + 1].win_start;
2711                                 if (!boun_end)
2712                                         boun_end = temp_margin;
2713                                 else if (!next_boun_end)
2714                                         next_boun_end = temp_margin;
2715                                 temp_margin %= tuning_data->calc_values.ui;
2716                                 temp_margin -= tuning_data->calc_values.ui;
2717                                 if (!partial_win_start ||
2718                                         (temp_margin > partial_win_start))
2719                                         partial_win_start = temp_margin;
2720                         }
2721                 }
2722                 if (partial_win_start <= 0)
2723                         tuning_data->tap_data[0].win_start = partial_win_start;
2724         }
2725
2726         if (boun_end)
2727                 insert_boundaries_in_tap_windows(sdhci, tuning_data, boun_end);
2728         if (next_boun_end)
2729                 insert_boundaries_in_tap_windows(sdhci, tuning_data, next_boun_end);
2730
2731         /* Insert calculated holes into the windows */
2732         err = adjust_holes_in_tap_windows(sdhci, tuning_data);
2733
2734         return err;
2735 }
2736
2737 static void sdhci_tegra_dump_tuning_constraints(struct sdhci_host *sdhci)
2738 {
2739         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2740         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2741         struct tegra_tuning_data *tuning_data;
2742         u8 i;
2743
2744         SDHCI_TEGRA_DBG("%s: Num of tuning frequencies%d\n",
2745                 mmc_hostname(sdhci->mmc), tegra_host->tuning_freq_count);
2746         for (i = 0; i < tegra_host->tuning_freq_count; ++i) {
2747                 tuning_data = &tegra_host->tuning_data[i];
2748                 SDHCI_TEGRA_DBG("%s: Tuning freq[%d]: %d, freq band %d\n",
2749                         mmc_hostname(sdhci->mmc), i,
2750                         tuning_data->freq_hz, tuning_data->freq_band);
2751         }
2752 }
2753
2754 static unsigned int get_tuning_voltage(struct sdhci_tegra *tegra_host, u8 *mask)
2755 {
2756         u8 i = 0;
2757
2758         i = ffs(*mask) - 1;
2759         *mask &= ~(1 << i);
2760         switch (BIT(i)) {
2761         case NOMINAL_VCORE_TUN:
2762                 return tegra_host->nominal_vcore_mv;
2763         case BOOT_VCORE_TUN:
2764                 return tegra_host->boot_vcore_mv;
2765         case MIN_OVERRIDE_VCORE_TUN:
2766                 return tegra_host->min_vcore_override_mv;
2767         }
2768
2769         return tegra_host->boot_vcore_mv;
2770 }
2771
2772 static u8 sdhci_tegra_get_freq_point(struct sdhci_host *sdhci)
2773 {
2774         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2775         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2776         const unsigned int *freq_list;
2777         u32 curr_clock;
2778         u8 i;
2779
2780         curr_clock = sdhci->max_clk;
2781         freq_list = tegra_host->soc_data->tuning_freq_list;
2782
2783         for (i = 0; i < TUNING_FREQ_COUNT; ++i)
2784                 if (curr_clock <= freq_list[i])
2785                         return i;
2786
2787         return TUNING_MAX_FREQ;
2788 }
2789
2790 /*
2791  * The frequency tuning algorithm tries to calculate the tap-to-tap delay
2792  * UI and estimate holes using equations and predetermined coefficients from
2793  * the characterization data. The algorithm will not work without this data.
2794  */
2795 static int find_tuning_coeffs_data(struct sdhci_host *sdhci,
2796                                         bool force_retuning)
2797 {
2798         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2799         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2800         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
2801         struct tegra_tuning_data *tuning_data;
2802         struct tuning_t2t_coeffs *t2t_coeffs;
2803         struct tap_hole_coeffs *thole_coeffs;
2804         const char *dev_id;
2805         unsigned int freq_khz;
2806         u8 i, j;
2807         bool coeffs_set = false;
2808
2809         dev_id = dev_name(mmc_dev(sdhci->mmc));
2810         /* Find the coeffs data for all supported frequencies */
2811         for (i = 0; i < tegra_host->tuning_freq_count; i++) {
2812                 tuning_data = &tegra_host->tuning_data[i];
2813
2814                 /* Skip if T2T coeffs are already found */
2815                 if (tuning_data->t2t_coeffs == NULL || force_retuning) {
2816                         t2t_coeffs = soc_data->t2t_coeffs;
2817                         for (j = 0; j < soc_data->t2t_coeffs_count; j++) {
2818                                 if (!strcmp(dev_id, t2t_coeffs->dev_id)) {
2819                                         tuning_data->t2t_coeffs = t2t_coeffs;
2820                                         coeffs_set = true;
2821                                         dev_info(mmc_dev(sdhci->mmc),
2822                                                 "Found T2T coeffs data\n");
2823                                         break;
2824                                 }
2825                                 t2t_coeffs++;
2826                         }
2827                         if (!coeffs_set) {
2828                                 dev_err(mmc_dev(sdhci->mmc),
2829                                         "T2T coeffs data missing\n");
2830                                 tuning_data->t2t_coeffs = NULL;
2831                                 return -ENODATA;
2832                         }
2833                 }
2834
2835                 coeffs_set = false;
2836                 /* Skip if tap hole coeffs are already found */
2837                 if (tuning_data->thole_coeffs == NULL || force_retuning) {
2838                         thole_coeffs = soc_data->tap_hole_coeffs;
2839                         freq_khz = tuning_data->freq_hz / 1000;
2840                         for (j = 0; j < soc_data->tap_hole_coeffs_count; j++) {
2841                                 if (!strcmp(dev_id, thole_coeffs->dev_id) &&
2842                                         (freq_khz == thole_coeffs->freq_khz)) {
2843                                         tuning_data->thole_coeffs =
2844                                                 thole_coeffs;
2845                                         coeffs_set = true;
2846                                         dev_info(mmc_dev(sdhci->mmc),
2847                                                 "%dMHz tap hole coeffs found\n",
2848                                                 (freq_khz / 1000));
2849                                         break;
2850                                 }
2851                                 thole_coeffs++;
2852                         }
2853
2854                         if (!coeffs_set) {
2855                                 dev_err(mmc_dev(sdhci->mmc),
2856                                         "%dMHz Tap hole coeffs data missing\n",
2857                                         (freq_khz / 1000));
2858                                 tuning_data->thole_coeffs = NULL;
2859                                 return -ENODATA;
2860                         }
2861                 }
2862         }
2863
2864         return 0;
2865 }
2866
2867 /*
2868  * Determines the numbers of frequencies required and then fills up the tuning
2869  * constraints for each of the frequencies. The data of lower frequency is
2870  * filled first and then the higher frequency data. Max supported frequencies
2871  * is currently two.
2872  */
2873 static int setup_freq_constraints(struct sdhci_host *sdhci,
2874         const unsigned int *freq_list)
2875 {
2876         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2877         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2878         struct tegra_tuning_data *tuning_data;
2879         int i, freq_count;
2880         u8 freq_band;
2881
2882         if ((sdhci->mmc->ios.timing != MMC_TIMING_UHS_SDR50) &&
2883                 (sdhci->mmc->caps2 & MMC_CAP2_FREQ_SCALING))
2884                 freq_count = DFS_FREQ_COUNT;
2885         else
2886                 freq_count = 1;
2887
2888         freq_band = sdhci_tegra_get_freq_point(sdhci);
2889         /* Fill up the req frequencies */
2890         switch (freq_count) {
2891         case 1:
2892                 tuning_data = &tegra_host->tuning_data[0];
2893                 tuning_data->freq_hz = sdhci->max_clk;
2894                 tuning_data->freq_band = freq_band;
2895                 tuning_data->constraints.vcore_mask =
2896                         tuning_vcore_constraints[freq_band].vcore_mask;
2897                 tuning_data->nr_voltages =
2898                         hweight32(tuning_data->constraints.vcore_mask);
2899         break;
2900         case 2:
2901                 tuning_data = &tegra_host->tuning_data[1];
2902                 tuning_data->freq_hz = sdhci->max_clk;
2903                 tuning_data->freq_band = freq_band;
2904                 tuning_data->constraints.vcore_mask =
2905                         tuning_vcore_constraints[freq_band].vcore_mask;
2906                 tuning_data->nr_voltages =
2907                         hweight32(tuning_data->constraints.vcore_mask);
2908
2909                 tuning_data = &tegra_host->tuning_data[0];
2910                 for (i = (freq_band - 1); i >= 0; i--) {
2911                         if (!freq_list[i])
2912                                 continue;
2913                         tuning_data->freq_hz = freq_list[i];
2914                         tuning_data->freq_band = i;
2915                         tuning_data->nr_voltages = 1;
2916                         tuning_data->constraints.vcore_mask =
2917                                 tuning_vcore_constraints[i].vcore_mask;
2918                         tuning_data->nr_voltages =
2919                                 hweight32(tuning_data->constraints.vcore_mask);
2920                 }
2921         break;
2922         default:
2923                 dev_err(mmc_dev(sdhci->mmc), "Unsupported freq count\n");
2924                 freq_count = -1;
2925         }
2926
2927         return freq_count;
2928 }
2929
2930 /*
2931  * Get the supported frequencies and other tuning related constraints for each
2932  * frequency. The supported frequencies should be determined from the list of
2933  * frequencies in the soc data and also consider the platform clock limits as
2934  * well as any DFS related restrictions.
2935  */
2936 static int sdhci_tegra_get_tuning_constraints(struct sdhci_host *sdhci,
2937                                                         bool force_retuning)
2938 {
2939         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2940         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2941         const unsigned int *freq_list;
2942         int err = 0;
2943
2944         /* A valid freq count means freq constraints are already set up */
2945         if (!tegra_host->tuning_freq_count || force_retuning) {
2946                 freq_list = tegra_host->soc_data->tuning_freq_list;
2947                 tegra_host->tuning_freq_count =
2948                         setup_freq_constraints(sdhci, freq_list);
2949                 if (tegra_host->tuning_freq_count < 0) {
2950                         dev_err(mmc_dev(sdhci->mmc),
2951                                 "Invalid tuning freq count\n");
2952                         return -EINVAL;
2953                 }
2954         }
2955
2956         err = find_tuning_coeffs_data(sdhci, force_retuning);
2957         if (err)
2958                 return err;
2959
2960         sdhci_tegra_dump_tuning_constraints(sdhci);
2961
2962         return err;
2963 }
2964
2965 /*
2966  * During boot, only boot voltage for vcore can be set. Check if the current
2967  * voltage is allowed to be used. Nominal and min override voltages can be
2968  * set once boot is done. This will be notified through late subsys init call.
2969  */
2970 static int sdhci_tegra_set_tuning_voltage(struct sdhci_host *sdhci,
2971         unsigned int voltage)
2972 {
2973         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
2974         struct sdhci_tegra *tegra_host = pltfm_host->priv;
2975         int err = 0;
2976         bool nom_emc_freq_set = false;
2977
2978         if (voltage && (voltage != tegra_host->boot_vcore_mv) &&
2979                 !vcore_overrides_allowed) {
2980                 SDHCI_TEGRA_DBG("%s: Override vcore %dmv not allowed\n",
2981                         mmc_hostname(sdhci->mmc), voltage);
2982                 return -EPERM;
2983         }
2984
2985         SDHCI_TEGRA_DBG("%s: Setting vcore override %d\n",
2986                 mmc_hostname(sdhci->mmc), voltage);
2987         /*
2988          * First clear any previous dvfs override settings. If dvfs overrides
2989          * are disabled, then print the error message but continue execution
2990          * rather than failing tuning altogether.
2991          */
2992         err = tegra_dvfs_override_core_voltage(pltfm_host->clk, 0);
2993         if ((err == -EPERM) || (err == -ENOSYS)) {
2994                 /*
2995                  * tegra_dvfs_override_core_voltage will return EPERM or ENOSYS,
2996                  * when DVFS override is not enabled. Continue tuning
2997                  * with default core voltage
2998                  */
2999                 SDHCI_TEGRA_DBG("dvfs overrides disabled. Nothing to clear\n");
3000                 err = 0;
3001         }
3002         if (!voltage)
3003                 return err;
3004
3005         /* EMC clock freq boost might be required for nominal core voltage */
3006         if ((voltage == tegra_host->nominal_vcore_mv) &&
3007                 tegra_host->plat->en_nominal_vcore_tuning &&
3008                 tegra_host->emc_clk) {
3009                 err = clk_set_rate(tegra_host->emc_clk,
3010                         SDMMC_EMC_NOM_VOLT_FREQ);
3011                 if (err)
3012                         dev_err(mmc_dev(sdhci->mmc),
3013                                 "Failed to set emc nom clk freq %d\n", err);
3014                 else
3015                         nom_emc_freq_set = true;
3016         }
3017
3018         /*
3019          * If dvfs overrides are disabled, then print the error message but
3020          * continue tuning execution rather than failing tuning altogether.
3021          */
3022         err = tegra_dvfs_override_core_voltage(pltfm_host->clk, voltage);
3023         if ((err == -EPERM) || (err == -ENOSYS)) {
3024                 /*
3025                  * tegra_dvfs_override_core_voltage will return EPERM or ENOSYS,
3026                  * when DVFS override is not enabled. Continue tuning
3027                  * with default core voltage
3028                  */
3029                 SDHCI_TEGRA_DBG("dvfs overrides disabled. No overrides set\n");
3030                 err = 0;
3031         } else if (err)
3032                 dev_err(mmc_dev(sdhci->mmc),
3033                         "failed to set vcore override %dmv\n", voltage);
3034
3035         /* Revert emc clock to normal freq */
3036         if (nom_emc_freq_set) {
3037                 err = clk_set_rate(tegra_host->emc_clk, SDMMC_EMC_MAX_FREQ);
3038                 if (err)
3039                         dev_err(mmc_dev(sdhci->mmc),
3040                                 "Failed to revert emc nom clk freq %d\n", err);
3041         }
3042
3043         return err;
3044 }
3045
3046 static int sdhci_tegra_run_tuning(struct sdhci_host *sdhci,
3047         struct tegra_tuning_data *tuning_data)
3048 {
3049         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3050         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3051         int err = 0;
3052         int voltage = 0;
3053         u8 i, vcore_mask = 0;
3054
3055         vcore_mask = tuning_data->constraints.vcore_mask;
3056         for (i = 0; i < tuning_data->nr_voltages; i++) {
3057                 voltage = get_tuning_voltage(tegra_host, &vcore_mask);
3058                 err = sdhci_tegra_set_tuning_voltage(sdhci, voltage);
3059                 if (err) {
3060                         dev_err(mmc_dev(sdhci->mmc),
3061                                 "Unable to set override voltage.\n");
3062                         return err;
3063                 }
3064
3065                 /* Get the tuning window info */
3066                 SDHCI_TEGRA_DBG("Getting tuning windows...\n");
3067                 err = sdhci_tegra_get_tap_window_data(sdhci, tuning_data);
3068                 if (err) {
3069                         dev_err(mmc_dev(sdhci->mmc),
3070                                 "Failed to get tap win %d\n", err);
3071                         return err;
3072                 }
3073                 SDHCI_TEGRA_DBG("%s: %d tuning window data obtained\n",
3074                         mmc_hostname(sdhci->mmc), tuning_data->freq_hz);
3075         }
3076         return err;
3077 }
3078
3079 static int sdhci_tegra_verify_best_tap(struct sdhci_host *sdhci)
3080 {
3081         struct tegra_tuning_data *tuning_data;
3082         int err = 0;
3083
3084         tuning_data = sdhci_tegra_get_tuning_data(sdhci, sdhci->max_clk);
3085         if ((tuning_data->best_tap_value < 0) ||
3086                 (tuning_data->best_tap_value > MAX_TAP_VALUES)) {
3087                 dev_err(mmc_dev(sdhci->mmc),
3088                         "Trying to verify invalid best tap value\n");
3089                 return -EINVAL;
3090         } else {
3091                 dev_err(mmc_dev(sdhci->mmc),
3092                         "%s: tuning freq %dhz, best tap %d\n",
3093                         __func__, tuning_data->freq_hz,
3094                         tuning_data->best_tap_value);
3095         }
3096
3097         /* Set the best tap value */
3098         sdhci_tegra_set_tap_delay(sdhci, tuning_data->best_tap_value);
3099
3100         /* Run tuning after setting the best tap value */
3101         err = sdhci_tegra_issue_tuning_cmd(sdhci);
3102         if (err)
3103                 dev_err(mmc_dev(sdhci->mmc),
3104                         "%dMHz best tap value verification failed %d\n",
3105                         tuning_data->freq_hz, err);
3106         return err;
3107 }
3108
3109 static int sdhci_tegra_execute_tuning(struct sdhci_host *sdhci, u32 opcode)
3110 {
3111         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3112         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3113         struct tegra_tuning_data *tuning_data;
3114         const struct sdhci_tegra_soc_data *soc_data = tegra_host->soc_data;
3115         int err;
3116         u16 ctrl_2;
3117         u32 misc_ctrl;
3118         u32 ier;
3119         u8 i, set_retuning = 0;
3120         bool force_retuning = false;
3121         bool enable_lb_clk;
3122
3123         /* Tuning is valid only in SDR104 and SDR50 modes */
3124         ctrl_2 = sdhci_readw(sdhci, SDHCI_HOST_CONTROL2);
3125         if (!(((ctrl_2 & SDHCI_CTRL_UHS_MASK) == SDHCI_CTRL_UHS_SDR104) ||
3126                 (((ctrl_2 & SDHCI_CTRL_UHS_MASK) == SDHCI_CTRL_UHS_SDR50) &&
3127                 (sdhci->flags & SDHCI_SDR50_NEEDS_TUNING))))
3128                         return 0;
3129
3130         /* Tuning should be done only for MMC_BUS_WIDTH_8 and MMC_BUS_WIDTH_4 */
3131         if (sdhci->mmc->ios.bus_width == MMC_BUS_WIDTH_8)
3132                 tegra_host->tuning_bsize = MMC_TUNING_BLOCK_SIZE_BUS_WIDTH_8;
3133         else if (sdhci->mmc->ios.bus_width == MMC_BUS_WIDTH_4)
3134                 tegra_host->tuning_bsize = MMC_TUNING_BLOCK_SIZE_BUS_WIDTH_4;
3135         else
3136                 return -EINVAL;
3137
3138         SDHCI_TEGRA_DBG("%s: Starting freq tuning\n", mmc_hostname(sdhci->mmc));
3139         enable_lb_clk = (soc_data->nvquirks &
3140                         NVQUIRK_DISABLE_EXTERNAL_LOOPBACK) &&
3141                         (tegra_host->instance == 2);
3142         if (enable_lb_clk) {
3143                 misc_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_MISC_CTRL);
3144                 misc_ctrl &= ~(1 <<
3145                         SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
3146                 sdhci_writel(sdhci, misc_ctrl, SDHCI_VNDR_MISC_CTRL);
3147         }
3148         mutex_lock(&tuning_mutex);
3149
3150         /* Set the tuning command to be used */
3151         tegra_host->tuning_opcode = opcode;
3152
3153         /*
3154          * Disable all interrupts signalling.Enable interrupt status
3155          * detection for buffer read ready and data crc. We use
3156          * polling for tuning as it involves less overhead.
3157          */
3158         ier = sdhci_readl(sdhci, SDHCI_INT_ENABLE);
3159         sdhci_writel(sdhci, 0, SDHCI_SIGNAL_ENABLE);
3160         sdhci_writel(sdhci, SDHCI_INT_DATA_AVAIL |
3161                 SDHCI_INT_DATA_CRC, SDHCI_INT_ENABLE);
3162
3163         /*
3164          * If tuning is already done and retune request is not set, then skip
3165          * best tap value calculation and use the old best tap value. If the
3166          * previous best tap value verification failed, force retuning.
3167          */
3168         if (tegra_host->tuning_status == TUNING_STATUS_DONE) {
3169                 err = sdhci_tegra_verify_best_tap(sdhci);
3170                 if (err) {
3171                         dev_err(mmc_dev(sdhci->mmc),
3172                                 "Prev best tap failed. Re-running tuning\n");
3173                         force_retuning = true;
3174                 } else {
3175                         goto out;
3176                 }
3177         }
3178
3179         if (tegra_host->force_retune == true) {
3180                 force_retuning = true;
3181                 tegra_host->force_retune = false;
3182         }
3183
3184         tegra_host->tuning_status = 0;
3185         err = sdhci_tegra_get_tuning_constraints(sdhci, force_retuning);
3186         if (err) {
3187                 dev_err(mmc_dev(sdhci->mmc),
3188                         "Failed to get tuning constraints\n");
3189                 goto out;
3190         }
3191
3192         for (i = 0; i < tegra_host->tuning_freq_count; i++) {
3193                 tuning_data = &tegra_host->tuning_data[i];
3194                 if (tuning_data->tuning_done && !force_retuning)
3195                         continue;
3196
3197                 SDHCI_TEGRA_DBG("%s: Setting tuning freq%d\n",
3198                         mmc_hostname(sdhci->mmc), tuning_data->freq_hz);
3199                 tegra_sdhci_set_clock(sdhci, tuning_data->freq_hz);
3200
3201                 SDHCI_TEGRA_DBG("%s: Calculating estimated tuning values\n",
3202                         mmc_hostname(sdhci->mmc));
3203                 err = calculate_estimated_tuning_values(tegra_host->speedo,
3204                         tuning_data, tegra_host->boot_vcore_mv);
3205                 if (err)
3206                         goto out;
3207
3208                 SDHCI_TEGRA_DBG("Running tuning...\n");
3209                 err = sdhci_tegra_run_tuning(sdhci, tuning_data);
3210                 if (err)
3211                         goto out;
3212
3213                 SDHCI_TEGRA_DBG("calculating best tap value\n");
3214                 err = sdhci_tegra_calculate_best_tap(sdhci, tuning_data);
3215                 if (err)
3216                         goto out;
3217
3218                 err = sdhci_tegra_verify_best_tap(sdhci);
3219                 if (!err && !set_retuning) {
3220                         tuning_data->tuning_done = true;
3221                         tegra_host->tuning_status |= TUNING_STATUS_DONE;
3222                 } else {
3223                         tegra_host->tuning_status |= TUNING_STATUS_RETUNE;
3224                 }
3225         }
3226 out:
3227         /* Release any override core voltages set */
3228         sdhci_tegra_set_tuning_voltage(sdhci, 0);
3229
3230         /* Enable interrupts. Enable full range for core voltage */
3231         sdhci_writel(sdhci, ier, SDHCI_INT_ENABLE);
3232         sdhci_writel(sdhci, ier, SDHCI_SIGNAL_ENABLE);
3233         mutex_unlock(&tuning_mutex);
3234
3235         SDHCI_TEGRA_DBG("%s: Freq tuning done\n", mmc_hostname(sdhci->mmc));
3236         if (enable_lb_clk) {
3237                 misc_ctrl = sdhci_readl(sdhci, SDHCI_VNDR_MISC_CTRL);
3238                 if (err) {
3239                         /* Tuning is failed and card will try to enumerate in
3240                          * Legacy High Speed mode. So, Enable External Loopback
3241                          * for SDMMC3.
3242                          */
3243                         misc_ctrl |= (1 <<
3244                                 SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
3245                 } else {
3246                         misc_ctrl &= ~(1 <<
3247                                 SDHCI_VNDR_MISC_CTRL_EN_EXT_LOOPBACK_SHIFT);
3248                 }
3249                 sdhci_writel(sdhci, misc_ctrl, SDHCI_VNDR_MISC_CTRL);
3250         }
3251         return err;
3252 }
3253
3254 static int __init sdhci_tegra_enable_vcore_override_tuning(void)
3255 {
3256         vcore_overrides_allowed = true;
3257         maintain_boot_voltage = false;
3258         return 0;
3259 }
3260 late_initcall(sdhci_tegra_enable_vcore_override_tuning);
3261
3262 static int tegra_sdhci_suspend(struct sdhci_host *sdhci)
3263 {
3264         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3265         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3266         int err = 0;
3267
3268         tegra_sdhci_set_clock(sdhci, 0);
3269
3270         /* Disable the power rails if any */
3271         if (tegra_host->card_present) {
3272                 err = tegra_sdhci_configure_regulators(tegra_host,
3273                         CONFIG_REG_DIS, 0, 0);
3274                 if (err)
3275                         dev_err(mmc_dev(sdhci->mmc),
3276                         "Regulators disable in suspend failed %d\n", err);
3277         }
3278         return err;
3279 }
3280
3281 static int tegra_sdhci_resume(struct sdhci_host *sdhci)
3282 {
3283         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3284         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3285         struct platform_device *pdev;
3286         struct tegra_sdhci_platform_data *plat;
3287         unsigned int signal_voltage = 0;
3288         int err;
3289
3290         pdev = to_platform_device(mmc_dev(sdhci->mmc));
3291         plat = pdev->dev.platform_data;
3292
3293         if (gpio_is_valid(plat->cd_gpio)) {
3294                 tegra_host->card_present =
3295                         (gpio_get_value_cansleep(plat->cd_gpio) == 0);
3296         }
3297
3298         /* Setting the min identification clock of freq 400KHz */
3299         tegra_sdhci_set_clock(sdhci, 400000);
3300
3301         /* Enable the power rails if any */
3302         if (tegra_host->card_present) {
3303                 err = tegra_sdhci_configure_regulators(tegra_host,
3304                         CONFIG_REG_EN, 0, 0);
3305                 if (err) {
3306                         dev_err(mmc_dev(sdhci->mmc),
3307                                 "Regulators enable in resume failed %d\n", err);
3308                         return err;
3309                 }
3310                 if (tegra_host->vdd_io_reg) {
3311                         if (plat->mmc_data.ocr_mask & SDHOST_1V8_OCR_MASK)
3312                                 signal_voltage = MMC_SIGNAL_VOLTAGE_180;
3313                         else
3314                                 signal_voltage = MMC_SIGNAL_VOLTAGE_330;
3315                         tegra_sdhci_signal_voltage_switch(sdhci,
3316                                 signal_voltage);
3317                 }
3318         }
3319
3320         /* Reset the controller and power on if MMC_KEEP_POWER flag is set*/
3321         if (sdhci->mmc->pm_flags & MMC_PM_KEEP_POWER) {
3322                 tegra_sdhci_reset(sdhci, SDHCI_RESET_ALL);
3323                 sdhci_writeb(sdhci, SDHCI_POWER_ON, SDHCI_POWER_CONTROL);
3324                 sdhci->pwr = 0;
3325
3326                 tegra_sdhci_do_calibration(sdhci, signal_voltage);
3327         }
3328
3329         return 0;
3330 }
3331
3332 static void tegra_sdhci_post_resume(struct sdhci_host *sdhci)
3333 {
3334         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3335         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3336
3337         /* Turn OFF the clocks if the device is not present */
3338         if ((!tegra_host->card_present || !sdhci->mmc->card) &&
3339                 tegra_host->clk_enabled)
3340                 tegra_sdhci_set_clock(sdhci, 0);
3341 }
3342
3343 /*
3344  * For tegra specific tuning, core voltage has to be fixed at different
3345  * voltages to get the tap values. Fixing the core voltage during tuning for one
3346  * device might affect transfers of other SDMMC devices. Check if tuning mutex
3347  * is locked before starting a data transfer. The new tuning procedure might
3348  * take at max 1.5s for completion for a single run. Taking DFS into count,
3349  * setting the max timeout for tuning mutex check a 3 secs. Since tuning is
3350  * run only during boot or the first time device is inserted, there wouldn't
3351  * be any delays in cmd/xfer execution once devices enumeration is done.
3352  */
3353 static void tegra_sdhci_get_bus(struct sdhci_host *sdhci)
3354 {
3355         unsigned int timeout = 300;
3356
3357         while (mutex_is_locked(&tuning_mutex)) {
3358                 msleep(10);
3359                 --timeout;
3360                 if (!timeout) {
3361                         dev_err(mmc_dev(sdhci->mmc),
3362                                 "Tuning mutex locked for long time\n");
3363                         return;
3364                 }
3365         };
3366 }
3367
3368 /*
3369  * The host/device can be powered off before the retuning request is handled in
3370  * case of SDIDO being off if Wifi is turned off, sd card removal etc. In such
3371  * cases, cancel the pending tuning timer and remove any core voltage
3372  * constraints that are set earlier.
3373  */
3374 static void tegra_sdhci_power_off(struct sdhci_host *sdhci, u8 power_mode)
3375 {
3376         int retuning_req_set = 0;
3377
3378         retuning_req_set = (timer_pending(&sdhci->tuning_timer) ||
3379                 (sdhci->flags & SDHCI_NEEDS_RETUNING));
3380
3381         if (retuning_req_set) {
3382                 del_timer_sync(&sdhci->tuning_timer);
3383
3384                 if (boot_volt_req_refcount)
3385                         --boot_volt_req_refcount;
3386
3387                 if (!boot_volt_req_refcount) {
3388                         sdhci_tegra_set_tuning_voltage(sdhci, 0);
3389                         SDHCI_TEGRA_DBG("%s: Release override as host is off\n",
3390                                 mmc_hostname(sdhci->mmc));
3391                 }
3392         }
3393 }
3394
3395 static int show_polling_period(void *data, u64 *value)
3396 {
3397         struct sdhci_host *host = (struct sdhci_host *)data;
3398
3399         if (host->mmc->dev_stats != NULL)
3400                 *value = host->mmc->dev_stats->polling_interval;
3401
3402         return 0;
3403 }
3404
3405 static int set_polling_period(void *data, u64 value)
3406 {
3407         struct sdhci_host *host = (struct sdhci_host *)data;
3408
3409         if (host->mmc->dev_stats != NULL) {
3410                 /* Limiting the maximum polling period to 1 sec */
3411                 if (value > 1000)
3412                         value = 1000;
3413                 host->mmc->dev_stats->polling_interval = value;
3414         }
3415
3416         return 0;
3417 }
3418 static int show_active_load_high_threshold(void *data, u64 *value)
3419 {
3420         struct sdhci_host *host = (struct sdhci_host *)data;
3421         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3422         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3423         struct tegra_freq_gov_data *gov_data = tegra_host->gov_data;
3424
3425         if (gov_data != NULL)
3426                 *value = gov_data->act_load_high_threshold;
3427
3428         return 0;
3429 }
3430
3431 static int set_active_load_high_threshold(void *data, u64 value)
3432 {
3433         struct sdhci_host *host = (struct sdhci_host *)data;
3434         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3435         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3436         struct tegra_freq_gov_data *gov_data = tegra_host->gov_data;
3437
3438         if (gov_data != NULL) {
3439                 /* Maximum threshold load percentage is 100.*/
3440                 if (value > 100)
3441                         value = 100;
3442                 gov_data->act_load_high_threshold = value;
3443         }
3444
3445         return 0;
3446 }
3447
3448 static int show_disableclkgating_value(void *data, u64 *value)
3449 {
3450         struct sdhci_host *host = (struct sdhci_host *)data;
3451         if (host != NULL) {
3452                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3453                 struct sdhci_tegra *tegra_host = pltfm_host->priv;
3454                 if (tegra_host != NULL)
3455                         *value = tegra_host->dbg_cfg.clk_ungated;
3456         }
3457         return 0;
3458 }
3459
3460 static int set_disableclkgating_value(void *data, u64 value)
3461 {
3462         struct sdhci_host *host = (struct sdhci_host *)data;
3463         if (host != NULL) {
3464                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3465                 if (pltfm_host != NULL) {
3466                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3467                         /* Set the CAPS2 register to reflect
3468                          * the clk gating value
3469                          */
3470                         if (tegra_host != NULL) {
3471                                 if (value) {
3472                                         host->mmc->ops->set_ios(host->mmc,
3473                                                 &host->mmc->ios);
3474                                         tegra_host->dbg_cfg.clk_ungated = true;
3475                                         host->mmc->caps2 &=
3476                                                 ~MMC_CAP2_CLOCK_GATING;
3477                                 } else {
3478                                         tegra_host->dbg_cfg.clk_ungated = false;
3479                                         host->mmc->caps2 |=
3480                                                 MMC_CAP2_CLOCK_GATING;
3481                                 }
3482                         }
3483                 }
3484         }
3485         return 0;
3486 }
3487
3488 static int set_trim_override_value(void *data, u64 value)
3489 {
3490         struct sdhci_host *host = (struct sdhci_host *)data;
3491         if (host != NULL) {
3492                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3493                 if (pltfm_host != NULL) {
3494                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3495                         if (tegra_host != NULL) {
3496                                 /* Make sure clock gating is disabled */
3497                                 if ((tegra_host->dbg_cfg.clk_ungated) &&
3498                                 (tegra_host->clk_enabled)) {
3499                                         sdhci_tegra_set_trim_delay(host, value);
3500                                         tegra_host->dbg_cfg.trim_val =
3501                                                 value;
3502                                 } else {
3503                                         pr_info("%s: Disable clock gating before setting value\n",
3504                                                 mmc_hostname(host->mmc));
3505                                 }
3506                         }
3507                 }
3508         }
3509         return 0;
3510 }
3511
3512 static int show_trim_override_value(void *data, u64 *value)
3513 {
3514         struct sdhci_host *host = (struct sdhci_host *)data;
3515         if (host != NULL) {
3516                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3517                 if (pltfm_host != NULL) {
3518                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3519                         if (tegra_host != NULL)
3520                                 *value = tegra_host->dbg_cfg.trim_val;
3521                 }
3522         }
3523         return 0;
3524 }
3525
3526 static int show_tap_override_value(void *data, u64 *value)
3527 {
3528         struct sdhci_host *host = (struct sdhci_host *)data;
3529         if (host != NULL) {
3530                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3531                 if (pltfm_host != NULL) {
3532                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3533                         if (tegra_host != NULL)
3534                                 *value = tegra_host->dbg_cfg.tap_val;
3535                 }
3536         }
3537         return 0;
3538 }
3539
3540 static int set_tap_override_value(void *data, u64 value)
3541 {
3542         struct sdhci_host *host = (struct sdhci_host *)data;
3543         if (host != NULL) {
3544                 struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3545                 if (pltfm_host != NULL) {
3546                         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3547                         if (tegra_host != NULL) {
3548                                 /* Make sure clock gating is disabled */
3549                                 if ((tegra_host->dbg_cfg.clk_ungated) &&
3550                                 (tegra_host->clk_enabled)) {
3551                                         sdhci_tegra_set_tap_delay(host, value);
3552                                         tegra_host->dbg_cfg.tap_val = value;
3553                                 } else {
3554                                         pr_info("%s: Disable clock gating before setting value\n",
3555                                                 mmc_hostname(host->mmc));
3556                                 }
3557                         }
3558                 }
3559         }
3560         return 0;
3561 }
3562 DEFINE_SIMPLE_ATTRIBUTE(sdhci_polling_period_fops, show_polling_period,
3563                 set_polling_period, "%llu\n");
3564 DEFINE_SIMPLE_ATTRIBUTE(sdhci_active_load_high_threshold_fops,
3565                 show_active_load_high_threshold,
3566                 set_active_load_high_threshold, "%llu\n");
3567 DEFINE_SIMPLE_ATTRIBUTE(sdhci_disable_clkgating_fops,
3568                 show_disableclkgating_value,
3569                 set_disableclkgating_value, "%llu\n");
3570 DEFINE_SIMPLE_ATTRIBUTE(sdhci_override_trim_data_fops,
3571                 show_trim_override_value,
3572                 set_trim_override_value, "%llu\n");
3573 DEFINE_SIMPLE_ATTRIBUTE(sdhci_override_tap_data_fops,
3574                 show_tap_override_value,
3575                 set_tap_override_value, "%llu\n");
3576
3577 static void sdhci_tegra_error_stats_debugfs(struct sdhci_host *host)
3578 {
3579         struct dentry *root = host->debugfs_root;
3580         struct dentry *dfs_root;
3581         unsigned saved_line;
3582
3583         if (!root) {
3584                 root = debugfs_create_dir(dev_name(mmc_dev(host->mmc)), NULL);
3585                 if (IS_ERR_OR_NULL(root)) {
3586                         saved_line = __LINE__;
3587                         goto err_root;
3588                 }
3589                 host->debugfs_root = root;
3590         }
3591
3592         dfs_root = debugfs_create_dir("dfs_stats_dir", root);
3593         if (IS_ERR_OR_NULL(dfs_root)) {
3594                 saved_line = __LINE__;
3595                 goto err_node;
3596         }
3597
3598         if (!debugfs_create_file("error_stats", S_IRUSR, root, host,
3599                                 &sdhci_host_fops)) {
3600                 saved_line = __LINE__;
3601                 goto err_node;
3602         }
3603         if (!debugfs_create_file("dfs_stats", S_IRUSR, dfs_root, host,
3604                                 &sdhci_host_dfs_fops)) {
3605                 saved_line = __LINE__;
3606                 goto err_node;
3607         }
3608         if (!debugfs_create_file("polling_period", 0644, dfs_root, (void *)host,
3609                                 &sdhci_polling_period_fops)) {
3610                 saved_line = __LINE__;
3611                 goto err_node;
3612         }
3613         if (!debugfs_create_file("active_load_high_threshold", 0644,
3614                                 dfs_root, (void *)host,
3615                                 &sdhci_active_load_high_threshold_fops)) {
3616                 saved_line = __LINE__;
3617                 goto err_node;
3618         }
3619
3620         dfs_root = debugfs_create_dir("override_data", root);
3621         if (IS_ERR_OR_NULL(dfs_root)) {
3622                 saved_line = __LINE__;
3623                 goto err_node;
3624         }
3625
3626         if (!debugfs_create_file("clk_gate_disabled", 0644,
3627                                 dfs_root, (void *)host,
3628                                 &sdhci_disable_clkgating_fops)) {
3629                 saved_line = __LINE__;
3630                 goto err_node;
3631         }
3632
3633         if (!debugfs_create_file("tap_value", 0644,
3634                                 dfs_root, (void *)host,
3635                                 &sdhci_override_tap_data_fops)) {
3636                 saved_line = __LINE__;
3637                 goto err_node;
3638         }
3639
3640         if (!debugfs_create_file("trim_value", 0644,
3641                                 dfs_root, (void *)host,
3642                                 &sdhci_override_trim_data_fops)) {
3643                 saved_line = __LINE__;
3644                 goto err_node;
3645         }
3646         if (IS_QUIRKS2_DELAYED_CLK_GATE(host)) {
3647                 host->clk_gate_tmout_ticks = -1;
3648                 if (!debugfs_create_u32("clk_gate_tmout_ticks",
3649                         S_IRUGO | S_IWUSR,
3650                         root, (u32 *)&host->clk_gate_tmout_ticks)) {
3651                         saved_line = __LINE__;
3652                         goto err_node;
3653                 }
3654         }
3655
3656         return;
3657
3658 err_node:
3659         debugfs_remove_recursive(root);
3660         host->debugfs_root = NULL;
3661 err_root:
3662         pr_err("%s %s: Failed to initialize debugfs functionality at line=%d\n", __func__,
3663                 mmc_hostname(host->mmc), saved_line);
3664         return;
3665 }
3666
3667 static ssize_t sdhci_handle_boost_mode_tap(struct device *dev,
3668         struct device_attribute *attr, const char *buf, size_t count)
3669 {
3670         int tap_cmd;
3671         struct mmc_card *card;
3672         char *p = (char *)buf;
3673         struct sdhci_host *host = dev_get_drvdata(dev);
3674         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3675         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3676         struct tegra_tuning_data *tuning_data;
3677         u32 present_state;
3678         u8 timeout;
3679         bool clk_set_for_tap_prog = false;
3680
3681         tap_cmd = memparse(p, &p);
3682
3683         card = host->mmc->card;
3684         if (!card)
3685                 return -ENODEV;
3686
3687         /* if not uhs -- no tuning and no tap value to set */
3688         if (!mmc_sd_card_uhs(card) && !mmc_card_hs200(card))
3689                 return count;
3690
3691         /* if no change in tap value -- just exit */
3692         if (tap_cmd == tegra_host->tap_cmd)
3693                 return count;
3694
3695         if ((tap_cmd != TAP_CMD_TRIM_DEFAULT_VOLTAGE) &&
3696                 (tap_cmd != TAP_CMD_TRIM_HIGH_VOLTAGE)) {
3697                 pr_info("echo 1 > cmd_state  # to set normal voltage\n");
3698                 pr_info("echo 2 > cmd_state  # to set high voltage\n");
3699                 return -EINVAL;
3700         }
3701
3702         tegra_host->tap_cmd = tap_cmd;
3703         tuning_data = sdhci_tegra_get_tuning_data(host, host->max_clk);
3704         /* Check if host clock is enabled */
3705         if (!tegra_host->clk_enabled) {
3706                 /* Nothing to do if the host is not powered ON */
3707                 if (host->mmc->ios.power_mode != MMC_POWER_ON)
3708                         return count;
3709                 else {
3710                         tegra_sdhci_set_clock(host, host->mmc->ios.clock);
3711                         clk_set_for_tap_prog = true;
3712                 }
3713         } else {
3714                 timeout = 10;
3715                 /* Wait for any on-going data transfers */
3716                 present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
3717                 while (present_state & (SDHCI_DOING_WRITE | SDHCI_DOING_READ)) {
3718                         if (!timeout)
3719                                 break;
3720                         timeout--;
3721                         mdelay(1);
3722                         present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
3723                 };
3724         }
3725         spin_lock(&host->lock);
3726         switch (tap_cmd) {
3727         case TAP_CMD_TRIM_DEFAULT_VOLTAGE:
3728                 /* set tap value for voltage range 1.1 to 1.25 */
3729                 sdhci_tegra_set_tap_delay(host, tuning_data->best_tap_value);
3730                 break;
3731
3732         case TAP_CMD_TRIM_HIGH_VOLTAGE:
3733                 /* set tap value for voltage range 1.25 to 1.39 */
3734                 sdhci_tegra_set_tap_delay(host,
3735                         tuning_data->nom_best_tap_value);
3736                 break;
3737         }
3738         spin_unlock(&host->lock);
3739         if (clk_set_for_tap_prog) {
3740                 tegra_sdhci_set_clock(host, 0);
3741                 clk_set_for_tap_prog = false;
3742         }
3743         return count;
3744 }
3745
3746 static ssize_t sdhci_show_turbo_mode(struct device *dev,
3747                         struct device_attribute *attr, char *buf)
3748 {
3749         struct sdhci_host *host = dev_get_drvdata(dev);
3750         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
3751         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3752
3753         return sprintf(buf, "%d\n", tegra_host->tap_cmd);
3754 }
3755
3756 static DEVICE_ATTR(cmd_state, 0644, sdhci_show_turbo_mode,
3757                         sdhci_handle_boost_mode_tap);
3758
3759 static int tegra_sdhci_reboot_notify(struct notifier_block *nb,
3760                                 unsigned long event, void *data)
3761 {
3762         struct sdhci_tegra *tegra_host =
3763                 container_of(nb, struct sdhci_tegra, reboot_notify);
3764         int err;
3765
3766         switch (event) {
3767         case SYS_RESTART:
3768         case SYS_POWER_OFF:
3769                 err = tegra_sdhci_configure_regulators(tegra_host,
3770                         CONFIG_REG_DIS, 0, 0);
3771                 if (err)
3772                         pr_err("Disable regulator in reboot notify failed %d\n",
3773                                 err);
3774                 return NOTIFY_OK;
3775         }
3776         return NOTIFY_DONE;
3777 }
3778
3779 void tegra_sdhci_ios_config_enter(struct sdhci_host *sdhci, struct mmc_ios *ios)
3780 {
3781         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3782         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3783         struct clk *new_mode_clk;
3784         bool change_clk = false;
3785
3786         /*
3787          * Tegra sdmmc controllers require clock to be enabled for any register
3788          * access. Set the minimum controller clock if no clock is requested.
3789          */
3790         if (!sdhci->clock && !ios->clock) {
3791                 tegra_sdhci_set_clock(sdhci, sdhci->mmc->f_min);
3792                 sdhci->clock = sdhci->mmc->f_min;
3793         } else if (ios->clock && (ios->clock != sdhci->clock)) {
3794                 tegra_sdhci_set_clock(sdhci, ios->clock);
3795         }
3796
3797         /*
3798          * Check for DDR50 mode setting and set ddr_clk if not already
3799          * done. Return if only one clock option is available.
3800          */
3801         if (!tegra_host->ddr_clk || !tegra_host->sdr_clk) {
3802                 return;
3803         } else {
3804                 if ((ios->timing == MMC_TIMING_UHS_DDR50) &&
3805                         !tegra_host->is_ddr_clk_set) {
3806                         change_clk = true;
3807                         new_mode_clk = tegra_host->ddr_clk;
3808                 } else if ((ios->timing != MMC_TIMING_UHS_DDR50) &&
3809                         tegra_host->is_ddr_clk_set) {
3810                         change_clk = true;
3811                         new_mode_clk = tegra_host->sdr_clk;
3812                 }
3813
3814                 if (change_clk) {
3815                         tegra_sdhci_set_clock(sdhci, 0);
3816                         pltfm_host->clk = new_mode_clk;
3817                         /* Restore the previous frequency */
3818                         tegra_sdhci_set_clock(sdhci, sdhci->max_clk);
3819                         tegra_host->is_ddr_clk_set =
3820                                 !tegra_host->is_ddr_clk_set;
3821                 }
3822         }
3823 }
3824
3825 void tegra_sdhci_ios_config_exit(struct sdhci_host *sdhci, struct mmc_ios *ios)
3826 {
3827         /*
3828          * Do any required handling for retuning requests before powering off
3829          * the host.
3830          */
3831         if (ios->power_mode == MMC_POWER_OFF)
3832                 tegra_sdhci_power_off(sdhci, ios->power_mode);
3833
3834         /*
3835          * In case of power off, turn off controller clock now as all the
3836          * required register accesses are already done.
3837          */
3838         if (!ios->clock && !sdhci->mmc->skip_host_clkgate)
3839                 tegra_sdhci_set_clock(sdhci, 0);
3840 }
3841
3842 static int tegra_sdhci_get_drive_strength(struct sdhci_host *sdhci,
3843                 unsigned int max_dtr, int host_drv, int card_drv)
3844 {
3845         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(sdhci);
3846         struct sdhci_tegra *tegra_host = pltfm_host->priv;
3847         const struct tegra_sdhci_platform_data *plat = tegra_host->plat;
3848
3849         return plat->default_drv_type;
3850 }
3851
3852 static const struct sdhci_ops tegra_sdhci_ops = {
3853         .get_ro     = tegra_sdhci_get_ro,
3854         .get_cd     = tegra_sdhci_get_cd,
3855         .read_l     = tegra_sdhci_readl,
3856         .read_w     = tegra_sdhci_readw,
3857         .write_l    = tegra_sdhci_writel,
3858         .write_w    = tegra_sdhci_writew,
3859         .platform_bus_width = tegra_sdhci_buswidth,
3860         .set_clock              = tegra_sdhci_set_clock,
3861         .suspend                = tegra_sdhci_suspend,
3862         .resume                 = tegra_sdhci_resume,
3863         .platform_resume        = tegra_sdhci_post_resume,
3864         .platform_reset_exit    = tegra_sdhci_reset_exit,
3865         .platform_get_bus       = tegra_sdhci_get_bus,
3866         .platform_ios_config_enter      = tegra_sdhci_ios_config_enter,
3867         .platform_ios_config_exit       = tegra_sdhci_ios_config_exit,
3868         .set_uhs_signaling      = tegra_sdhci_set_uhs_signaling,
3869         .switch_signal_voltage  = tegra_sdhci_signal_voltage_switch,
3870         .switch_signal_voltage_exit = tegra_sdhci_do_calibration,
3871         .execute_freq_tuning    = sdhci_tegra_execute_tuning,
3872         .sd_error_stats         = sdhci_tegra_sd_error_stats,
3873 #ifdef CONFIG_MMC_FREQ_SCALING
3874         .dfs_gov_init           = sdhci_tegra_freq_gov_init,
3875         .dfs_gov_get_target_freq        = sdhci_tegra_get_target_freq,
3876 #endif
3877         .get_drive_strength     = tegra_sdhci_get_drive_strength,
3878 };
3879
3880 static struct sdhci_pltfm_data sdhci_tegra11_pdata = {
3881         .quirks = TEGRA_SDHCI_QUIRKS,
3882         .quirks2 = TEGRA_SDHCI_QUIRKS2,
3883         .ops  = &tegra_sdhci_ops,
3884 };
3885
3886 static struct sdhci_tegra_soc_data soc_data_tegra11 = {
3887         .pdata = &sdhci_tegra11_pdata,
3888         .nvquirks = TEGRA_SDHCI_NVQUIRKS |
3889                     NVQUIRK_SET_DRIVE_STRENGTH |
3890                     NVQUIRK_SET_TRIM_DELAY |
3891                     NVQUIRK_ENABLE_DDR50 |
3892                     NVQUIRK_ENABLE_HS200 |
3893                     NVQUIRK_INFINITE_ERASE_TIMEOUT |
3894                     NVQUIRK_DISABLE_EXTERNAL_LOOPBACK |
3895                     NVQUIRK_DISABLE_SDMMC4_CALIB,
3896         .parent_clk_list = {"pll_p", "pll_c"},
3897         .tuning_freq_list = {81600000, 156000000, 200000000},
3898         .t2t_coeffs = t11x_tuning_coeffs,
3899         .t2t_coeffs_count = 3,
3900         .tap_hole_coeffs = t11x_tap_hole_coeffs,
3901         .tap_hole_coeffs_count = 12,
3902 };
3903
3904 static struct sdhci_pltfm_data sdhci_tegra12_pdata = {
3905         .quirks = TEGRA_SDHCI_QUIRKS,
3906         .quirks2 = TEGRA_SDHCI_QUIRKS2 |
3907                 SDHCI_QUIRK2_HOST_OFF_CARD_ON |
3908                 SDHCI_QUIRK2_SUPPORT_64BIT_DMA |
3909                 SDHCI_QUIRK2_USE_64BIT_ADDR,
3910         .ops  = &tegra_sdhci_ops,
3911 };
3912
3913 static struct sdhci_tegra_soc_data soc_data_tegra12 = {
3914         .pdata = &sdhci_tegra12_pdata,
3915         .nvquirks = TEGRA_SDHCI_NVQUIRKS |
3916                     NVQUIRK_SET_TRIM_DELAY |
3917                     NVQUIRK_ENABLE_DDR50 |
3918                     NVQUIRK_ENABLE_HS200 |
3919                     NVQUIRK_INFINITE_ERASE_TIMEOUT |
3920                     NVQUIRK_SET_PAD_E_INPUT_OR_E_PWRD |
3921                     NVQUIRK_HIGH_FREQ_TAP_PROCEDURE |
3922                     NVQUIRK_SET_CALIBRATION_OFFSETS |
3923                     NVQUIRK_DISABLE_EXTERNAL_LOOPBACK,
3924         .parent_clk_list = {"pll_p", "pll_c"},
3925         .tuning_freq_list = {81600000, 136000000, 200000000},
3926         .t2t_coeffs = t12x_tuning_coeffs,
3927         .t2t_coeffs_count = 3,
3928         .tap_hole_coeffs = t12x_tap_hole_coeffs,
3929         .tap_hole_coeffs_count = 12,
3930 };
3931
3932 static const struct of_device_id sdhci_tegra_dt_match[] = {
3933         { .compatible = "nvidia,tegra124-sdhci", .data = &soc_data_tegra12 },
3934         { .compatible = "nvidia,tegra114-sdhci", .data = &soc_data_tegra11 },
3935         {}
3936 };
3937 MODULE_DEVICE_TABLE(of, sdhci_dt_ids);
3938
3939 static struct tegra_sdhci_platform_data *sdhci_tegra_dt_parse_pdata(
3940                                                 struct platform_device *pdev)
3941 {
3942         int val;
3943         struct tegra_sdhci_platform_data *plat;
3944         struct device_node *np = pdev->dev.of_node;
3945         u32 bus_width;
3946
3947         if (!np)
3948                 return NULL;
3949
3950         plat = devm_kzalloc(&pdev->dev, sizeof(*plat), GFP_KERNEL);
3951         if (!plat) {
3952                 dev_err(&pdev->dev, "Can't allocate platform data\n");
3953                 return NULL;
3954         }
3955
3956         plat->cd_gpio = of_get_named_gpio(np, "cd-gpios", 0);
3957         plat->wp_gpio = of_get_named_gpio(np, "wp-gpios", 0);
3958         plat->power_gpio = of_get_named_gpio(np, "power-gpios", 0);
3959
3960         if (of_property_read_u32(np, "bus-width", &bus_width) == 0 &&
3961             bus_width == 8)
3962                 plat->is_8bit = 1;
3963
3964         of_property_read_u32(np, "tap-delay", &plat->tap_delay);
3965         of_property_read_u32(np, "trim-delay", &plat->trim_delay);
3966         of_property_read_u32(np, "ddr-clk-limit", &plat->ddr_clk_limit);
3967         of_property_read_u32(np, "max-clk-limit", &plat->max_clk_limit);
3968
3969         of_property_read_u32(np, "uhs_mask", &plat->uhs_mask);
3970
3971         if (of_find_property(np, "built-in", NULL))
3972                 plat->mmc_data.built_in = 1;
3973
3974         if (!of_property_read_u32(np, "mmc-ocr-mask", &val)) {
3975                 if (val == 0)
3976                         plat->mmc_data.ocr_mask = MMC_OCR_1V8_MASK;
3977                 else if (val == 1)
3978                         plat->mmc_data.ocr_mask = MMC_OCR_2V8_MASK;
3979                 else if (val == 2)
3980                         plat->mmc_data.ocr_mask = MMC_OCR_3V2_MASK;
3981                 else if (val == 3)
3982                         plat->mmc_data.ocr_mask = MMC_OCR_3V3_MASK;
3983         }
3984         return plat;
3985 }
3986
3987 static int sdhci_tegra_probe(struct platform_device *pdev)
3988 {
3989         const struct of_device_id *match;
3990         const struct sdhci_tegra_soc_data *soc_data;
3991         struct sdhci_host *host;
3992         struct sdhci_pltfm_host *pltfm_host;
3993         struct tegra_sdhci_platform_data *plat;
3994         struct sdhci_tegra *tegra_host;
3995         unsigned int low_freq;
3996         int rc;
3997         u8 i;
3998
3999         match = of_match_device(sdhci_tegra_dt_match, &pdev->dev);
4000         if (match) {
4001                 soc_data = match->data;
4002         } else {
4003                 /* Use id tables and remove the following chip defines */
4004 #if defined(CONFIG_ARCH_TEGRA_11x_SOC)
4005                 soc_data = &soc_data_tegra11;
4006 #else
4007                 soc_data = &soc_data_tegra12;
4008 #endif
4009         }
4010
4011         host = sdhci_pltfm_init(pdev, soc_data->pdata);
4012
4013         /* sdio delayed clock gate quirk in sdhci_host used */
4014         host->quirks2 |= SDHCI_QUIRK2_DELAYED_CLK_GATE;
4015
4016         if (IS_ERR(host))
4017                 return PTR_ERR(host);
4018
4019         pltfm_host = sdhci_priv(host);
4020
4021         plat = pdev->dev.platform_data;
4022
4023         if (plat == NULL)
4024                 plat = sdhci_tegra_dt_parse_pdata(pdev);
4025
4026         if (plat == NULL) {
4027                 dev_err(mmc_dev(host->mmc), "missing platform data\n");
4028                 rc = -ENXIO;
4029                 goto err_no_plat;
4030         }
4031
4032         tegra_host = devm_kzalloc(&pdev->dev, sizeof(*tegra_host), GFP_KERNEL);
4033         if (!tegra_host) {
4034                 dev_err(mmc_dev(host->mmc), "failed to allocate tegra_host\n");
4035                 rc = -ENOMEM;
4036                 goto err_no_plat;
4037         }
4038
4039         tegra_host->plat = plat;
4040         pdev->dev.platform_data = plat;
4041
4042         tegra_host->sd_stat_head = devm_kzalloc(&pdev->dev,
4043                 sizeof(struct sdhci_tegra_sd_stats), GFP_KERNEL);
4044         if (!tegra_host->sd_stat_head) {
4045                 dev_err(mmc_dev(host->mmc), "failed to allocate sd_stat_head\n");
4046                 rc = -ENOMEM;
4047                 goto err_power_req;
4048         }
4049
4050         tegra_host->soc_data = soc_data;
4051         pltfm_host->priv = tegra_host;
4052
4053         for (i = 0; i < ARRAY_SIZE(soc_data->parent_clk_list); i++) {
4054                 if (!soc_data->parent_clk_list[i])
4055                         continue;
4056                 if (!strcmp(soc_data->parent_clk_list[i], "pll_c")) {
4057                         pll_c = clk_get_sys(NULL, "pll_c");
4058                         if (IS_ERR(pll_c)) {
4059                                 rc = PTR_ERR(pll_c);
4060                                 dev_err(mmc_dev(host->mmc),
4061                                         "clk error in getting pll_c: %d\n", rc);
4062                         }
4063                         pll_c_rate = clk_get_rate(pll_c);
4064                 }
4065
4066                 if (!strcmp(soc_data->parent_clk_list[i], "pll_p")) {
4067                         pll_p = clk_get_sys(NULL, "pll_p");
4068                         if (IS_ERR(pll_p)) {
4069                                 rc = PTR_ERR(pll_p);
4070                                 dev_err(mmc_dev(host->mmc),
4071                                         "clk error in getting pll_p: %d\n", rc);
4072                         }
4073                         pll_p_rate = clk_get_rate(pll_p);
4074                 }
4075         }
4076
4077 #ifdef CONFIG_MMC_EMBEDDED_SDIO
4078         if (plat->mmc_data.embedded_sdio)
4079                 mmc_set_embedded_sdio_data(host->mmc,
4080                         &plat->mmc_data.embedded_sdio->cis,
4081                         &plat->mmc_data.embedded_sdio->cccr,
4082                         plat->mmc_data.embedded_sdio->funcs,
4083                         plat->mmc_data.embedded_sdio->num_funcs);
4084 #endif
4085
4086         if (gpio_is_valid(plat->power_gpio)) {
4087                 rc = gpio_request(plat->power_gpio, "sdhci_power");
4088                 if (rc) {
4089                         dev_err(mmc_dev(host->mmc),
4090                                 "failed to allocate power gpio\n");
4091                         goto err_power_req;
4092                 }
4093                 gpio_direction_output(plat->power_gpio, 1);
4094         }
4095
4096         if (gpio_is_valid(plat->cd_gpio)) {
4097                 rc = gpio_request(plat->cd_gpio, "sdhci_cd");
4098                 if (rc) {
4099                         dev_err(mmc_dev(host->mmc),
4100                                 "failed to allocate cd gpio\n");
4101                         goto err_cd_req;
4102                 }
4103                 gpio_direction_input(plat->cd_gpio);
4104
4105                 tegra_host->card_present =
4106                         (gpio_get_value_cansleep(plat->cd_gpio) == 0);
4107
4108         } else if (plat->mmc_data.register_status_notify) {
4109                 plat->mmc_data.register_status_notify(sdhci_status_notify_cb, host);
4110         }
4111
4112         if (plat->mmc_data.status) {
4113                 plat->mmc_data.card_present = plat->mmc_data.status(mmc_dev(host->mmc));
4114         }
4115
4116         if (gpio_is_valid(plat->wp_gpio)) {
4117                 rc = gpio_request(plat->wp_gpio, "sdhci_wp");
4118                 if (rc) {
4119                         dev_err(mmc_dev(host->mmc),
4120                                 "failed to allocate wp gpio\n");
4121                         goto err_wp_req;
4122                 }
4123                 gpio_direction_input(plat->wp_gpio);
4124         }
4125
4126         /*
4127          * If there is no card detect gpio, assume that the
4128          * card is always present.
4129          */
4130         if (!gpio_is_valid(plat->cd_gpio))
4131                 tegra_host->card_present = 1;
4132
4133         if (plat->mmc_data.ocr_mask & SDHOST_1V8_OCR_MASK) {
4134                 tegra_host->vddio_min_uv = SDHOST_LOW_VOLT_MIN;
4135                 tegra_host->vddio_max_uv = SDHOST_LOW_VOLT_MAX;
4136         } else if (plat->mmc_data.ocr_mask & MMC_OCR_2V8_MASK) {
4137                         tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_2V8;
4138                         tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4139         } else if (plat->mmc_data.ocr_mask & MMC_OCR_3V2_MASK) {
4140                         tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_3V2;
4141                         tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4142         } else if (plat->mmc_data.ocr_mask & MMC_OCR_3V3_MASK) {
4143                         tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_3V3;
4144                         tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4145         } else {
4146                 /*
4147                  * Set the minV and maxV to default
4148                  * voltage range of 2.7V - 3.6V
4149                  */
4150                 tegra_host->vddio_min_uv = SDHOST_HIGH_VOLT_MIN;
4151                 tegra_host->vddio_max_uv = SDHOST_HIGH_VOLT_MAX;
4152         }
4153
4154         tegra_host->vdd_io_reg = regulator_get(mmc_dev(host->mmc),
4155                                                         "vddio_sdmmc");
4156         if (IS_ERR_OR_NULL(tegra_host->vdd_io_reg)) {
4157                 dev_info(mmc_dev(host->mmc), "%s regulator not found: %ld."
4158                         "Assuming vddio_sdmmc is not required.\n",
4159                         "vddio_sdmmc", PTR_ERR(tegra_host->vdd_io_reg));
4160                 tegra_host->vdd_io_reg = NULL;
4161         } else {
4162                 rc = tegra_sdhci_configure_regulators(tegra_host,
4163                         CONFIG_REG_SET_VOLT,
4164                         tegra_host->vddio_min_uv,
4165                         tegra_host->vddio_max_uv);
4166                 if (rc) {
4167                         dev_err(mmc_dev(host->mmc),
4168                                 "Init volt(%duV-%duV) setting failed %d\n",
4169                                 tegra_host->vddio_min_uv,
4170                                 tegra_host->vddio_max_uv, rc);
4171                         regulator_put(tegra_host->vdd_io_reg);
4172                         tegra_host->vdd_io_reg = NULL;
4173                 }
4174         }
4175
4176         tegra_host->vdd_slot_reg = regulator_get(mmc_dev(host->mmc),
4177                                                         "vddio_sd_slot");
4178         if (IS_ERR_OR_NULL(tegra_host->vdd_slot_reg)) {
4179                 dev_info(mmc_dev(host->mmc), "%s regulator not found: %ld."
4180                         " Assuming vddio_sd_slot is not required.\n",
4181                         "vddio_sd_slot", PTR_ERR(tegra_host->vdd_slot_reg));
4182                 tegra_host->vdd_slot_reg = NULL;
4183         }
4184
4185         if (tegra_host->card_present) {
4186                 rc = tegra_sdhci_configure_regulators(tegra_host, CONFIG_REG_EN,
4187                         0, 0);
4188                 if (rc) {
4189                         dev_err(mmc_dev(host->mmc),
4190                                 "Enable regulators failed in probe %d\n", rc);
4191                         goto err_clk_get;
4192                 }
4193         }
4194
4195         tegra_pd_add_device(&pdev->dev);
4196         pm_runtime_enable(&pdev->dev);
4197
4198         /* Get the ddr clock */
4199         tegra_host->ddr_clk = clk_get(mmc_dev(host->mmc), "ddr");
4200         if (IS_ERR(tegra_host->ddr_clk)) {
4201                 dev_err(mmc_dev(host->mmc), "ddr clk err\n");
4202                 tegra_host->ddr_clk = NULL;
4203         }
4204
4205         /* Get high speed clock */
4206         tegra_host->sdr_clk = clk_get(mmc_dev(host->mmc), NULL);
4207         if (IS_ERR(tegra_host->sdr_clk)) {
4208                 dev_err(mmc_dev(host->mmc), "sdr clk err\n");
4209                 tegra_host->sdr_clk = NULL;
4210                 /* If both ddr and sdr clks are missing, then fail probe */
4211                 if (!tegra_host->ddr_clk && !tegra_host->sdr_clk) {
4212                         dev_err(mmc_dev(host->mmc),
4213                                 "Failed to get ddr and sdr clks\n");
4214                         rc = -EINVAL;
4215                         goto err_clk_get;
4216                 }
4217         }
4218
4219         if (tegra_host->sdr_clk) {
4220                 pltfm_host->clk = tegra_host->sdr_clk;
4221                 tegra_host->is_ddr_clk_set = false;
4222         } else {
4223                 pltfm_host->clk = tegra_host->ddr_clk;
4224                 tegra_host->is_ddr_clk_set = true;
4225         }
4226
4227         if (clk_get_parent(pltfm_host->clk) == pll_c)
4228                 tegra_host->is_parent_pllc = true;
4229
4230         pm_runtime_get_sync(&pdev->dev);
4231         rc = clk_prepare_enable(pltfm_host->clk);
4232         if (rc != 0)
4233                 goto err_clk_put;
4234
4235         tegra_host->emc_clk = devm_clk_get(mmc_dev(host->mmc), "emc");
4236         if (IS_ERR_OR_NULL(tegra_host->emc_clk)) {
4237                 dev_err(mmc_dev(host->mmc), "Can't get emc clk\n");
4238                 tegra_host->emc_clk = NULL;
4239         } else {
4240                 clk_set_rate(tegra_host->emc_clk, SDMMC_EMC_MAX_FREQ);
4241         }
4242
4243         tegra_host->sclk = devm_clk_get(mmc_dev(host->mmc), "sclk");
4244         if (IS_ERR_OR_NULL(tegra_host->sclk)) {
4245                 dev_err(mmc_dev(host->mmc), "Can't get sclk clock\n");
4246                 tegra_host->sclk = NULL;
4247         } else {
4248                 clk_set_rate(tegra_host->sclk, SDMMC_AHB_MAX_FREQ);
4249         }
4250         pltfm_host->priv = tegra_host;
4251         tegra_host->clk_enabled = true;
4252         host->is_clk_on = tegra_host->clk_enabled;
4253         mutex_init(&tegra_host->set_clock_mutex);
4254
4255         tegra_host->max_clk_limit = plat->max_clk_limit;
4256         tegra_host->ddr_clk_limit = plat->ddr_clk_limit;
4257         tegra_host->instance = pdev->id;
4258         tegra_host->tap_cmd = TAP_CMD_TRIM_DEFAULT_VOLTAGE;
4259         tegra_host->speedo = plat->cpu_speedo;
4260         dev_info(mmc_dev(host->mmc), "Speedo value %d\n", tegra_host->speedo);
4261         host->mmc->pm_caps |= plat->pm_caps;
4262         host->mmc->pm_flags |= plat->pm_flags;
4263
4264         host->mmc->caps |= MMC_CAP_ERASE;
4265         /* enable 1/8V DDR capable */
4266         host->mmc->caps |= MMC_CAP_1_8V_DDR;
4267         if (plat->is_8bit)
4268                 host->mmc->caps |= MMC_CAP_8_BIT_DATA;
4269         host->mmc->caps |= MMC_CAP_SDIO_IRQ;
4270         host->mmc->pm_caps |= MMC_PM_KEEP_POWER | MMC_PM_IGNORE_PM_NOTIFY;
4271         if (plat->mmc_data.built_in) {
4272                 host->mmc->caps |= MMC_CAP_NONREMOVABLE;
4273         }
4274         host->mmc->pm_flags |= MMC_PM_IGNORE_PM_NOTIFY;
4275
4276         /* disable access to boot partitions */
4277         host->mmc->caps2 |= MMC_CAP2_BOOTPART_NOACC;
4278
4279 #if !defined(CONFIG_ARCH_TEGRA_2x_SOC) && !defined(CONFIG_ARCH_TEGRA_3x_SOC)
4280         if (soc_data->nvquirks & NVQUIRK_ENABLE_HS200)
4281                 host->mmc->caps2 |= MMC_CAP2_HS200;
4282 #ifdef CONFIG_TEGRA_FPGA_PLATFORM
4283         /* Enable HS200 mode */
4284         host->mmc->caps2 |= MMC_CAP2_HS200;
4285 #else
4286         host->mmc->caps2 |= MMC_CAP2_CACHE_CTRL;
4287         host->mmc->caps |= MMC_CAP_CMD23;
4288         host->mmc->caps2 |= MMC_CAP2_PACKED_CMD;
4289 #endif
4290 #endif
4291
4292         /*
4293          * Enable dyamic frequency scaling support only if the platform clock
4294          * limit is higher than the lowest supported frequency by tuning.
4295          */
4296         for (i = 0; i < TUNING_FREQ_COUNT; i++) {
4297                 low_freq = soc_data->tuning_freq_list[i];
4298                 if (low_freq)
4299                         break;
4300         }
4301         if (plat->en_freq_scaling && (plat->max_clk_limit > low_freq))
4302                 host->mmc->caps2 |= MMC_CAP2_FREQ_SCALING;
4303
4304         if (!plat->disable_clock_gate)
4305                 host->mmc->caps2 |= MMC_CAP2_CLOCK_GATING;
4306
4307         if (plat->nominal_vcore_mv)
4308                 tegra_host->nominal_vcore_mv = plat->nominal_vcore_mv;
4309         if (plat->min_vcore_override_mv)
4310                 tegra_host->min_vcore_override_mv = plat->min_vcore_override_mv;
4311         if (plat->boot_vcore_mv)
4312                 tegra_host->boot_vcore_mv = plat->boot_vcore_mv;
4313         dev_info(mmc_dev(host->mmc),
4314                 "Tuning constraints: nom_mv %d, boot_mv %d, min_or_mv %d\n",
4315                 tegra_host->nominal_vcore_mv, tegra_host->boot_vcore_mv,
4316                 tegra_host->min_vcore_override_mv);
4317
4318         /*
4319          * If nominal voltage is equal to boot voltage, there is no need for
4320          * nominal voltage tuning.
4321          */
4322         if (plat->nominal_vcore_mv <= plat->boot_vcore_mv)
4323                 plat->en_nominal_vcore_tuning = false;
4324
4325         INIT_DELAYED_WORK(&host->delayed_clk_gate_wrk, delayed_clk_gate_cb);
4326         rc = sdhci_add_host(host);
4327         if (rc)
4328                 goto err_add_host;
4329
4330         if (gpio_is_valid(plat->cd_gpio)) {
4331                 rc = request_threaded_irq(gpio_to_irq(plat->cd_gpio), NULL,
4332                         carddetect_irq,
4333                         IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING | IRQF_ONESHOT,
4334                         mmc_hostname(host->mmc), host);
4335                 if (rc) {
4336                         dev_err(mmc_dev(host->mmc), "request irq error\n");
4337                         goto err_cd_irq_req;
4338                 }
4339                 if (!plat->cd_wakeup_incapable) {
4340                         rc = enable_irq_wake(gpio_to_irq(plat->cd_gpio));
4341                         if (rc < 0)
4342                                 dev_err(mmc_dev(host->mmc),
4343                                         "SD card wake-up event registration "
4344                                         "failed with error: %d\n", rc);
4345                 }
4346         }
4347         sdhci_tegra_error_stats_debugfs(host);
4348         device_create_file(&pdev->dev, &dev_attr_cmd_state);
4349
4350         /* Enable async suspend/resume to reduce LP0 latency */
4351         device_enable_async_suspend(&pdev->dev);
4352
4353         if (plat->power_off_rail) {
4354                 tegra_host->reboot_notify.notifier_call =
4355                         tegra_sdhci_reboot_notify;
4356                 register_reboot_notifier(&tegra_host->reboot_notify);
4357         }
4358 #ifdef CONFIG_DEBUG_FS
4359         tegra_host->dbg_cfg.tap_val =
4360                 plat->tap_delay;
4361         tegra_host->dbg_cfg.trim_val =
4362                 plat->ddr_trim_delay;
4363         tegra_host->dbg_cfg.clk_ungated =
4364                 plat->disable_clock_gate;
4365 #endif
4366         return 0;
4367
4368 err_cd_irq_req:
4369         if (gpio_is_valid(plat->cd_gpio))
4370                 gpio_free(plat->cd_gpio);
4371 err_add_host:
4372         if (tegra_host->is_ddr_clk_set)
4373                 clk_disable_unprepare(tegra_host->ddr_clk);
4374         else
4375                 clk_disable_unprepare(tegra_host->sdr_clk);
4376         pm_runtime_put_sync(&pdev->dev);
4377 err_clk_put:
4378         if (tegra_host->ddr_clk)
4379                 clk_put(tegra_host->ddr_clk);
4380         if (tegra_host->sdr_clk)
4381                 clk_put(tegra_host->sdr_clk);
4382 err_clk_get:
4383         if (gpio_is_valid(plat->wp_gpio))
4384                 gpio_free(plat->wp_gpio);
4385 err_wp_req:
4386         if (gpio_is_valid(plat->cd_gpio))
4387                 free_irq(gpio_to_irq(plat->cd_gpio), host);
4388 err_cd_req:
4389         if (gpio_is_valid(plat->power_gpio))
4390                 gpio_free(plat->power_gpio);
4391 err_power_req:
4392 err_no_plat:
4393         sdhci_pltfm_free(pdev);
4394         return rc;
4395 }
4396
4397 static int sdhci_tegra_remove(struct platform_device *pdev)
4398 {
4399         struct sdhci_host *host = platform_get_drvdata(pdev);
4400         struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
4401         struct sdhci_tegra *tegra_host = pltfm_host->priv;
4402         const struct tegra_sdhci_platform_data *plat = tegra_host->plat;
4403         int dead = (readl(host->ioaddr + SDHCI_INT_STATUS) == 0xffffffff);
4404         int rc = 0;
4405
4406         sdhci_remove_host(host, dead);
4407
4408         disable_irq_wake(gpio_to_irq(plat->cd_gpio));
4409
4410         rc = tegra_sdhci_configure_regulators(tegra_host, CONFIG_REG_DIS, 0, 0);
4411         if (rc)
4412                 dev_err(mmc_dev(host->mmc),
4413                         "Regulator disable in remove failed %d\n", rc);
4414
4415         if (tegra_host->vdd_slot_reg)
4416                 regulator_put(tegra_host->vdd_slot_reg);
4417         if (tegra_host->vdd_io_reg)
4418                 regulator_put(tegra_host->vdd_io_reg);
4419
4420         if (gpio_is_valid(plat->wp_gpio))
4421                 gpio_free(plat->wp_gpio);
4422
4423         if (gpio_is_valid(plat->cd_gpio)) {
4424                 free_irq(gpio_to_irq(plat->cd_gpio), host);
4425                 gpio_free(plat->cd_gpio);
4426         }
4427
4428         if (gpio_is_valid(plat->power_gpio))
4429                 gpio_free(plat->power_gpio);
4430
4431         if (tegra_host->clk_enabled) {
4432                 if (tegra_host->is_ddr_clk_set)
4433                         clk_disable_unprepare(tegra_host->ddr_clk);
4434                 else
4435                         clk_disable_unprepare(tegra_host->sdr_clk);
4436                 pm_runtime_put_sync(&pdev->dev);
4437         }
4438
4439         if (tegra_host->ddr_clk)
4440                 clk_put(tegra_host->ddr_clk);
4441         if (tegra_host->sdr_clk)
4442                 clk_put(tegra_host->sdr_clk);
4443
4444         if (tegra_host->emc_clk && tegra_host->is_sdmmc_emc_clk_on)
4445                 clk_disable_unprepare(tegra_host->emc_clk);
4446         if (tegra_host->sclk && tegra_host->is_sdmmc_sclk_on)
4447                 clk_disable_unprepare(tegra_host->sclk);
4448         if (plat->power_off_rail)
4449                 unregister_reboot_notifier(&tegra_host->reboot_notify);
4450
4451         sdhci_pltfm_free(pdev);
4452
4453         return rc;
4454 }
4455
4456 static struct platform_driver sdhci_tegra_driver = {
4457         .driver         = {
4458                 .name   = "sdhci-tegra",
4459                 .owner  = THIS_MODULE,
4460                 .of_match_table = sdhci_tegra_dt_match,
4461                 .pm     = SDHCI_PLTFM_PMOPS,
4462         },
4463         .probe          = sdhci_tegra_probe,
4464         .remove         = sdhci_tegra_remove,
4465 };
4466
4467 module_platform_driver(sdhci_tegra_driver);
4468
4469 MODULE_DESCRIPTION("SDHCI driver for Tegra");
4470 MODULE_AUTHOR("Google, Inc.");
4471 MODULE_LICENSE("GPL v2");