1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * Universal Flash Storage Host controller driver Core 4 * Copyright (C) 2011-2013 Samsung India Software Operations 5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved. 6 * 7 * Authors: 8 * Santosh Yaraganavi <santosh.sy@samsung.com> 9 * Vinayak Holikatti <h.vinayak@samsung.com> 10 */ 11 12 #include <linux/async.h> 13 #include <linux/devfreq.h> 14 #include <linux/nls.h> 15 #include <linux/of.h> 16 #include <linux/bitfield.h> 17 #include <linux/blk-pm.h> 18 #include <linux/blkdev.h> 19 #include <linux/clk.h> 20 #include <linux/delay.h> 21 #include <linux/interrupt.h> 22 #include <linux/module.h> 23 #include <linux/regulator/consumer.h> 24 #include <linux/sched/clock.h> 25 #include <scsi/scsi_cmnd.h> 26 #include <scsi/scsi_dbg.h> 27 #include <scsi/scsi_driver.h> 28 #include <scsi/scsi_eh.h> 29 #include "ufshcd-priv.h" 30 #include <ufs/ufs_quirks.h> 31 #include <ufs/unipro.h> 32 #include "ufs-sysfs.h" 33 #include "ufs-debugfs.h" 34 #include "ufs-fault-injection.h" 35 #include "ufs_bsg.h" 36 #include "ufshcd-crypto.h" 37 #include "ufshpb.h" 38 #include <asm/unaligned.h> 39 40 #define CREATE_TRACE_POINTS 41 #include <trace/events/ufs.h> 42 43 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\ 44 UTP_TASK_REQ_COMPL |\ 45 UFSHCD_ERROR_MASK) 46 47 #define UFSHCD_ENABLE_MCQ_INTRS (UTP_TASK_REQ_COMPL |\ 48 UFSHCD_ERROR_MASK |\ 49 MCQ_CQ_EVENT_STATUS) 50 51 52 /* UIC command timeout, unit: ms */ 53 #define UIC_CMD_TIMEOUT 500 54 55 /* NOP OUT retries waiting for NOP IN response */ 56 #define NOP_OUT_RETRIES 10 57 /* Timeout after 50 msecs if NOP OUT hangs without response */ 58 #define NOP_OUT_TIMEOUT 50 /* msecs */ 59 60 /* Query request retries */ 61 #define QUERY_REQ_RETRIES 3 62 /* Query request timeout */ 63 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */ 64 65 /* Advanced RPMB request timeout */ 66 #define ADVANCED_RPMB_REQ_TIMEOUT 3000 /* 3 seconds */ 67 68 /* Task management command timeout */ 69 #define TM_CMD_TIMEOUT 100 /* msecs */ 70 71 /* maximum number of retries for a general UIC command */ 72 #define UFS_UIC_COMMAND_RETRIES 3 73 74 /* maximum number of link-startup retries */ 75 #define DME_LINKSTARTUP_RETRIES 3 76 77 /* maximum number of reset retries before giving up */ 78 #define MAX_HOST_RESET_RETRIES 5 79 80 /* Maximum number of error handler retries before giving up */ 81 #define MAX_ERR_HANDLER_RETRIES 5 82 83 /* Expose the flag value from utp_upiu_query.value */ 84 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF 85 86 /* Interrupt aggregation default timeout, unit: 40us */ 87 #define INT_AGGR_DEF_TO 0x02 88 89 /* default delay of autosuspend: 2000 ms */ 90 #define RPM_AUTOSUSPEND_DELAY_MS 2000 91 92 /* Default delay of RPM device flush delayed work */ 93 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000 94 95 /* Default value of wait time before gating device ref clock */ 96 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */ 97 98 /* Polling time to wait for fDeviceInit */ 99 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */ 100 101 /* UFSHC 4.0 compliant HC support this mode. */ 102 static bool use_mcq_mode = true; 103 104 static bool is_mcq_supported(struct ufs_hba *hba) 105 { 106 return hba->mcq_sup && use_mcq_mode; 107 } 108 109 module_param(use_mcq_mode, bool, 0644); 110 MODULE_PARM_DESC(use_mcq_mode, "Control MCQ mode for controllers starting from UFSHCI 4.0. 1 - enable MCQ, 0 - disable MCQ. MCQ is enabled by default"); 111 112 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \ 113 ({ \ 114 int _ret; \ 115 if (_on) \ 116 _ret = ufshcd_enable_vreg(_dev, _vreg); \ 117 else \ 118 _ret = ufshcd_disable_vreg(_dev, _vreg); \ 119 _ret; \ 120 }) 121 122 #define ufshcd_hex_dump(prefix_str, buf, len) do { \ 123 size_t __len = (len); \ 124 print_hex_dump(KERN_ERR, prefix_str, \ 125 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\ 126 16, 4, buf, __len, false); \ 127 } while (0) 128 129 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len, 130 const char *prefix) 131 { 132 u32 *regs; 133 size_t pos; 134 135 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */ 136 return -EINVAL; 137 138 regs = kzalloc(len, GFP_ATOMIC); 139 if (!regs) 140 return -ENOMEM; 141 142 for (pos = 0; pos < len; pos += 4) { 143 if (offset == 0 && 144 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER && 145 pos <= REG_UIC_ERROR_CODE_DME) 146 continue; 147 regs[pos / 4] = ufshcd_readl(hba, offset + pos); 148 } 149 150 ufshcd_hex_dump(prefix, regs, len); 151 kfree(regs); 152 153 return 0; 154 } 155 EXPORT_SYMBOL_GPL(ufshcd_dump_regs); 156 157 enum { 158 UFSHCD_MAX_CHANNEL = 0, 159 UFSHCD_MAX_ID = 1, 160 UFSHCD_NUM_RESERVED = 1, 161 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED, 162 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED, 163 }; 164 165 static const char *const ufshcd_state_name[] = { 166 [UFSHCD_STATE_RESET] = "reset", 167 [UFSHCD_STATE_OPERATIONAL] = "operational", 168 [UFSHCD_STATE_ERROR] = "error", 169 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal", 170 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal", 171 }; 172 173 /* UFSHCD error handling flags */ 174 enum { 175 UFSHCD_EH_IN_PROGRESS = (1 << 0), 176 }; 177 178 /* UFSHCD UIC layer error flags */ 179 enum { 180 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */ 181 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */ 182 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */ 183 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */ 184 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */ 185 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */ 186 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */ 187 }; 188 189 #define ufshcd_set_eh_in_progress(h) \ 190 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS) 191 #define ufshcd_eh_in_progress(h) \ 192 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS) 193 #define ufshcd_clear_eh_in_progress(h) \ 194 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS) 195 196 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = { 197 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE}, 198 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE}, 199 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE}, 200 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE}, 201 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE}, 202 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE}, 203 /* 204 * For DeepSleep, the link is first put in hibern8 and then off. 205 * Leaving the link in hibern8 is not supported. 206 */ 207 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE}, 208 }; 209 210 static inline enum ufs_dev_pwr_mode 211 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl) 212 { 213 return ufs_pm_lvl_states[lvl].dev_state; 214 } 215 216 static inline enum uic_link_state 217 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl) 218 { 219 return ufs_pm_lvl_states[lvl].link_state; 220 } 221 222 static inline enum ufs_pm_level 223 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state, 224 enum uic_link_state link_state) 225 { 226 enum ufs_pm_level lvl; 227 228 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) { 229 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) && 230 (ufs_pm_lvl_states[lvl].link_state == link_state)) 231 return lvl; 232 } 233 234 /* if no match found, return the level 0 */ 235 return UFS_PM_LVL_0; 236 } 237 238 static const struct ufs_dev_quirk ufs_fixups[] = { 239 /* UFS cards deviations table */ 240 { .wmanufacturerid = UFS_VENDOR_MICRON, 241 .model = UFS_ANY_MODEL, 242 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM | 243 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ }, 244 { .wmanufacturerid = UFS_VENDOR_SAMSUNG, 245 .model = UFS_ANY_MODEL, 246 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM | 247 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE | 248 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS }, 249 { .wmanufacturerid = UFS_VENDOR_SKHYNIX, 250 .model = UFS_ANY_MODEL, 251 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME }, 252 { .wmanufacturerid = UFS_VENDOR_SKHYNIX, 253 .model = "hB8aL1" /*H28U62301AMR*/, 254 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME }, 255 { .wmanufacturerid = UFS_VENDOR_TOSHIBA, 256 .model = UFS_ANY_MODEL, 257 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM }, 258 { .wmanufacturerid = UFS_VENDOR_TOSHIBA, 259 .model = "THGLF2G9C8KBADG", 260 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE }, 261 { .wmanufacturerid = UFS_VENDOR_TOSHIBA, 262 .model = "THGLF2G9D8KBADG", 263 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE }, 264 {} 265 }; 266 267 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba); 268 static void ufshcd_async_scan(void *data, async_cookie_t cookie); 269 static int ufshcd_reset_and_restore(struct ufs_hba *hba); 270 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd); 271 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag); 272 static void ufshcd_hba_exit(struct ufs_hba *hba); 273 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params); 274 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on); 275 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba); 276 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba); 277 static void ufshcd_resume_clkscaling(struct ufs_hba *hba); 278 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba); 279 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba); 280 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up); 281 static irqreturn_t ufshcd_intr(int irq, void *__hba); 282 static int ufshcd_change_power_mode(struct ufs_hba *hba, 283 struct ufs_pa_layer_attr *pwr_mode); 284 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on); 285 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on); 286 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba, 287 struct ufs_vreg *vreg); 288 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag); 289 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba, 290 bool enable); 291 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba); 292 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba); 293 294 static inline void ufshcd_enable_irq(struct ufs_hba *hba) 295 { 296 if (!hba->is_irq_enabled) { 297 enable_irq(hba->irq); 298 hba->is_irq_enabled = true; 299 } 300 } 301 302 static inline void ufshcd_disable_irq(struct ufs_hba *hba) 303 { 304 if (hba->is_irq_enabled) { 305 disable_irq(hba->irq); 306 hba->is_irq_enabled = false; 307 } 308 } 309 310 static void ufshcd_configure_wb(struct ufs_hba *hba) 311 { 312 if (!ufshcd_is_wb_allowed(hba)) 313 return; 314 315 ufshcd_wb_toggle(hba, true); 316 317 ufshcd_wb_toggle_buf_flush_during_h8(hba, true); 318 319 if (ufshcd_is_wb_buf_flush_allowed(hba)) 320 ufshcd_wb_toggle_buf_flush(hba, true); 321 } 322 323 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba) 324 { 325 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt)) 326 scsi_unblock_requests(hba->host); 327 } 328 329 static void ufshcd_scsi_block_requests(struct ufs_hba *hba) 330 { 331 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1) 332 scsi_block_requests(hba->host); 333 } 334 335 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag, 336 enum ufs_trace_str_t str_t) 337 { 338 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr; 339 struct utp_upiu_header *header; 340 341 if (!trace_ufshcd_upiu_enabled()) 342 return; 343 344 if (str_t == UFS_CMD_SEND) 345 header = &rq->header; 346 else 347 header = &hba->lrb[tag].ucd_rsp_ptr->header; 348 349 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb, 350 UFS_TSF_CDB); 351 } 352 353 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, 354 enum ufs_trace_str_t str_t, 355 struct utp_upiu_req *rq_rsp) 356 { 357 if (!trace_ufshcd_upiu_enabled()) 358 return; 359 360 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header, 361 &rq_rsp->qr, UFS_TSF_OSF); 362 } 363 364 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag, 365 enum ufs_trace_str_t str_t) 366 { 367 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag]; 368 369 if (!trace_ufshcd_upiu_enabled()) 370 return; 371 372 if (str_t == UFS_TM_SEND) 373 trace_ufshcd_upiu(dev_name(hba->dev), str_t, 374 &descp->upiu_req.req_header, 375 &descp->upiu_req.input_param1, 376 UFS_TSF_TM_INPUT); 377 else 378 trace_ufshcd_upiu(dev_name(hba->dev), str_t, 379 &descp->upiu_rsp.rsp_header, 380 &descp->upiu_rsp.output_param1, 381 UFS_TSF_TM_OUTPUT); 382 } 383 384 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba, 385 const struct uic_command *ucmd, 386 enum ufs_trace_str_t str_t) 387 { 388 u32 cmd; 389 390 if (!trace_ufshcd_uic_command_enabled()) 391 return; 392 393 if (str_t == UFS_CMD_SEND) 394 cmd = ucmd->command; 395 else 396 cmd = ufshcd_readl(hba, REG_UIC_COMMAND); 397 398 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd, 399 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1), 400 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2), 401 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3)); 402 } 403 404 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag, 405 enum ufs_trace_str_t str_t) 406 { 407 u64 lba = 0; 408 u8 opcode = 0, group_id = 0; 409 u32 doorbell = 0; 410 u32 intr; 411 int hwq_id = -1; 412 struct ufshcd_lrb *lrbp = &hba->lrb[tag]; 413 struct scsi_cmnd *cmd = lrbp->cmd; 414 struct request *rq = scsi_cmd_to_rq(cmd); 415 int transfer_len = -1; 416 417 if (!cmd) 418 return; 419 420 /* trace UPIU also */ 421 ufshcd_add_cmd_upiu_trace(hba, tag, str_t); 422 if (!trace_ufshcd_command_enabled()) 423 return; 424 425 opcode = cmd->cmnd[0]; 426 427 if (opcode == READ_10 || opcode == WRITE_10) { 428 /* 429 * Currently we only fully trace read(10) and write(10) commands 430 */ 431 transfer_len = 432 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len); 433 lba = scsi_get_lba(cmd); 434 if (opcode == WRITE_10) 435 group_id = lrbp->cmd->cmnd[6]; 436 } else if (opcode == UNMAP) { 437 /* 438 * The number of Bytes to be unmapped beginning with the lba. 439 */ 440 transfer_len = blk_rq_bytes(rq); 441 lba = scsi_get_lba(cmd); 442 } 443 444 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS); 445 446 if (is_mcq_enabled(hba)) { 447 struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq); 448 449 hwq_id = hwq->id; 450 } else { 451 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 452 } 453 trace_ufshcd_command(dev_name(hba->dev), str_t, tag, 454 doorbell, hwq_id, transfer_len, intr, lba, opcode, group_id); 455 } 456 457 static void ufshcd_print_clk_freqs(struct ufs_hba *hba) 458 { 459 struct ufs_clk_info *clki; 460 struct list_head *head = &hba->clk_list_head; 461 462 if (list_empty(head)) 463 return; 464 465 list_for_each_entry(clki, head, list) { 466 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq && 467 clki->max_freq) 468 dev_err(hba->dev, "clk: %s, rate: %u\n", 469 clki->name, clki->curr_freq); 470 } 471 } 472 473 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id, 474 const char *err_name) 475 { 476 int i; 477 bool found = false; 478 const struct ufs_event_hist *e; 479 480 if (id >= UFS_EVT_CNT) 481 return; 482 483 e = &hba->ufs_stats.event[id]; 484 485 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) { 486 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH; 487 488 if (e->tstamp[p] == 0) 489 continue; 490 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p, 491 e->val[p], div_u64(e->tstamp[p], 1000)); 492 found = true; 493 } 494 495 if (!found) 496 dev_err(hba->dev, "No record of %s\n", err_name); 497 else 498 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt); 499 } 500 501 static void ufshcd_print_evt_hist(struct ufs_hba *hba) 502 { 503 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: "); 504 505 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err"); 506 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err"); 507 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err"); 508 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err"); 509 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err"); 510 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR, 511 "auto_hibern8_err"); 512 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err"); 513 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL, 514 "link_startup_fail"); 515 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail"); 516 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR, 517 "suspend_fail"); 518 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail"); 519 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR, 520 "wlun suspend_fail"); 521 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset"); 522 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset"); 523 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort"); 524 525 ufshcd_vops_dbg_register_dump(hba); 526 } 527 528 static 529 void ufshcd_print_tr(struct ufs_hba *hba, int tag, bool pr_prdt) 530 { 531 const struct ufshcd_lrb *lrbp; 532 int prdt_length; 533 534 lrbp = &hba->lrb[tag]; 535 536 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n", 537 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000)); 538 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n", 539 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000)); 540 dev_err(hba->dev, 541 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n", 542 tag, (u64)lrbp->utrd_dma_addr); 543 544 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr, 545 sizeof(struct utp_transfer_req_desc)); 546 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag, 547 (u64)lrbp->ucd_req_dma_addr); 548 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr, 549 sizeof(struct utp_upiu_req)); 550 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag, 551 (u64)lrbp->ucd_rsp_dma_addr); 552 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr, 553 sizeof(struct utp_upiu_rsp)); 554 555 prdt_length = le16_to_cpu( 556 lrbp->utr_descriptor_ptr->prd_table_length); 557 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) 558 prdt_length /= ufshcd_sg_entry_size(hba); 559 560 dev_err(hba->dev, 561 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n", 562 tag, prdt_length, 563 (u64)lrbp->ucd_prdt_dma_addr); 564 565 if (pr_prdt) 566 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr, 567 ufshcd_sg_entry_size(hba) * prdt_length); 568 } 569 570 static bool ufshcd_print_tr_iter(struct request *req, void *priv) 571 { 572 struct scsi_device *sdev = req->q->queuedata; 573 struct Scsi_Host *shost = sdev->host; 574 struct ufs_hba *hba = shost_priv(shost); 575 576 ufshcd_print_tr(hba, req->tag, *(bool *)priv); 577 578 return true; 579 } 580 581 /** 582 * ufshcd_print_trs_all - print trs for all started requests. 583 * @hba: per-adapter instance. 584 * @pr_prdt: need to print prdt or not. 585 */ 586 static void ufshcd_print_trs_all(struct ufs_hba *hba, bool pr_prdt) 587 { 588 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_print_tr_iter, &pr_prdt); 589 } 590 591 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap) 592 { 593 int tag; 594 595 for_each_set_bit(tag, &bitmap, hba->nutmrs) { 596 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag]; 597 598 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag); 599 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp)); 600 } 601 } 602 603 static void ufshcd_print_host_state(struct ufs_hba *hba) 604 { 605 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun; 606 607 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state); 608 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n", 609 hba->outstanding_reqs, hba->outstanding_tasks); 610 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n", 611 hba->saved_err, hba->saved_uic_err); 612 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n", 613 hba->curr_dev_pwr_mode, hba->uic_link_state); 614 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n", 615 hba->pm_op_in_progress, hba->is_sys_suspended); 616 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n", 617 hba->auto_bkops_enabled, hba->host->host_self_blocked); 618 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state); 619 dev_err(hba->dev, 620 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n", 621 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000), 622 hba->ufs_stats.hibern8_exit_cnt); 623 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n", 624 div_u64(hba->ufs_stats.last_intr_ts, 1000), 625 hba->ufs_stats.last_intr_status); 626 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n", 627 hba->eh_flags, hba->req_abort_count); 628 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n", 629 hba->ufs_version, hba->capabilities, hba->caps); 630 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks, 631 hba->dev_quirks); 632 if (sdev_ufs) 633 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n", 634 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev); 635 636 ufshcd_print_clk_freqs(hba); 637 } 638 639 /** 640 * ufshcd_print_pwr_info - print power params as saved in hba 641 * power info 642 * @hba: per-adapter instance 643 */ 644 static void ufshcd_print_pwr_info(struct ufs_hba *hba) 645 { 646 static const char * const names[] = { 647 "INVALID MODE", 648 "FAST MODE", 649 "SLOW_MODE", 650 "INVALID MODE", 651 "FASTAUTO_MODE", 652 "SLOWAUTO_MODE", 653 "INVALID MODE", 654 }; 655 656 /* 657 * Using dev_dbg to avoid messages during runtime PM to avoid 658 * never-ending cycles of messages written back to storage by user space 659 * causing runtime resume, causing more messages and so on. 660 */ 661 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n", 662 __func__, 663 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx, 664 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx, 665 names[hba->pwr_info.pwr_rx], 666 names[hba->pwr_info.pwr_tx], 667 hba->pwr_info.hs_rate); 668 } 669 670 static void ufshcd_device_reset(struct ufs_hba *hba) 671 { 672 int err; 673 674 err = ufshcd_vops_device_reset(hba); 675 676 if (!err) { 677 ufshcd_set_ufs_dev_active(hba); 678 if (ufshcd_is_wb_allowed(hba)) { 679 hba->dev_info.wb_enabled = false; 680 hba->dev_info.wb_buf_flush_enabled = false; 681 } 682 } 683 if (err != -EOPNOTSUPP) 684 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err); 685 } 686 687 void ufshcd_delay_us(unsigned long us, unsigned long tolerance) 688 { 689 if (!us) 690 return; 691 692 if (us < 10) 693 udelay(us); 694 else 695 usleep_range(us, us + tolerance); 696 } 697 EXPORT_SYMBOL_GPL(ufshcd_delay_us); 698 699 /** 700 * ufshcd_wait_for_register - wait for register value to change 701 * @hba: per-adapter interface 702 * @reg: mmio register offset 703 * @mask: mask to apply to the read register value 704 * @val: value to wait for 705 * @interval_us: polling interval in microseconds 706 * @timeout_ms: timeout in milliseconds 707 * 708 * Return: 709 * -ETIMEDOUT on error, zero on success. 710 */ 711 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask, 712 u32 val, unsigned long interval_us, 713 unsigned long timeout_ms) 714 { 715 int err = 0; 716 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms); 717 718 /* ignore bits that we don't intend to wait on */ 719 val = val & mask; 720 721 while ((ufshcd_readl(hba, reg) & mask) != val) { 722 usleep_range(interval_us, interval_us + 50); 723 if (time_after(jiffies, timeout)) { 724 if ((ufshcd_readl(hba, reg) & mask) != val) 725 err = -ETIMEDOUT; 726 break; 727 } 728 } 729 730 return err; 731 } 732 733 /** 734 * ufshcd_get_intr_mask - Get the interrupt bit mask 735 * @hba: Pointer to adapter instance 736 * 737 * Returns interrupt bit mask per version 738 */ 739 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba) 740 { 741 if (hba->ufs_version == ufshci_version(1, 0)) 742 return INTERRUPT_MASK_ALL_VER_10; 743 if (hba->ufs_version <= ufshci_version(2, 0)) 744 return INTERRUPT_MASK_ALL_VER_11; 745 746 return INTERRUPT_MASK_ALL_VER_21; 747 } 748 749 /** 750 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA 751 * @hba: Pointer to adapter instance 752 * 753 * Returns UFSHCI version supported by the controller 754 */ 755 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba) 756 { 757 u32 ufshci_ver; 758 759 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION) 760 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba); 761 else 762 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION); 763 764 /* 765 * UFSHCI v1.x uses a different version scheme, in order 766 * to allow the use of comparisons with the ufshci_version 767 * function, we convert it to the same scheme as ufs 2.0+. 768 */ 769 if (ufshci_ver & 0x00010000) 770 return ufshci_version(1, ufshci_ver & 0x00000100); 771 772 return ufshci_ver; 773 } 774 775 /** 776 * ufshcd_is_device_present - Check if any device connected to 777 * the host controller 778 * @hba: pointer to adapter instance 779 * 780 * Returns true if device present, false if no device detected 781 */ 782 static inline bool ufshcd_is_device_present(struct ufs_hba *hba) 783 { 784 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT; 785 } 786 787 /** 788 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status 789 * @lrbp: pointer to local command reference block 790 * @cqe: pointer to the completion queue entry 791 * 792 * This function is used to get the OCS field from UTRD 793 * Returns the OCS field in the UTRD 794 */ 795 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp, 796 struct cq_entry *cqe) 797 { 798 if (cqe) 799 return le32_to_cpu(cqe->status) & MASK_OCS; 800 801 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS; 802 } 803 804 /** 805 * ufshcd_utrl_clear() - Clear requests from the controller request list. 806 * @hba: per adapter instance 807 * @mask: mask with one bit set for each request to be cleared 808 */ 809 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask) 810 { 811 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR) 812 mask = ~mask; 813 /* 814 * From the UFSHCI specification: "UTP Transfer Request List CLear 815 * Register (UTRLCLR): This field is bit significant. Each bit 816 * corresponds to a slot in the UTP Transfer Request List, where bit 0 817 * corresponds to request slot 0. A bit in this field is set to ‘0’ 818 * by host software to indicate to the host controller that a transfer 819 * request slot is cleared. The host controller 820 * shall free up any resources associated to the request slot 821 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The 822 * host software indicates no change to request slots by setting the 823 * associated bits in this field to ‘1’. Bits in this field shall only 824 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’." 825 */ 826 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR); 827 } 828 829 /** 830 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register 831 * @hba: per adapter instance 832 * @pos: position of the bit to be cleared 833 */ 834 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos) 835 { 836 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR) 837 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR); 838 else 839 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR); 840 } 841 842 /** 843 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY 844 * @reg: Register value of host controller status 845 * 846 * Returns integer, 0 on Success and positive value if failed 847 */ 848 static inline int ufshcd_get_lists_status(u32 reg) 849 { 850 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY); 851 } 852 853 /** 854 * ufshcd_get_uic_cmd_result - Get the UIC command result 855 * @hba: Pointer to adapter instance 856 * 857 * This function gets the result of UIC command completion 858 * Returns 0 on success, non zero value on error 859 */ 860 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba) 861 { 862 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) & 863 MASK_UIC_COMMAND_RESULT; 864 } 865 866 /** 867 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command 868 * @hba: Pointer to adapter instance 869 * 870 * This function gets UIC command argument3 871 * Returns 0 on success, non zero value on error 872 */ 873 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba) 874 { 875 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3); 876 } 877 878 /** 879 * ufshcd_get_req_rsp - returns the TR response transaction type 880 * @ucd_rsp_ptr: pointer to response UPIU 881 */ 882 static inline int 883 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr) 884 { 885 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24; 886 } 887 888 /** 889 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU 890 * @ucd_rsp_ptr: pointer to response UPIU 891 * 892 * This function gets the response status and scsi_status from response UPIU 893 * Returns the response result code. 894 */ 895 static inline int 896 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr) 897 { 898 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT; 899 } 900 901 /* 902 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length 903 * from response UPIU 904 * @ucd_rsp_ptr: pointer to response UPIU 905 * 906 * Return the data segment length. 907 */ 908 static inline unsigned int 909 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr) 910 { 911 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) & 912 MASK_RSP_UPIU_DATA_SEG_LEN; 913 } 914 915 /** 916 * ufshcd_is_exception_event - Check if the device raised an exception event 917 * @ucd_rsp_ptr: pointer to response UPIU 918 * 919 * The function checks if the device raised an exception event indicated in 920 * the Device Information field of response UPIU. 921 * 922 * Returns true if exception is raised, false otherwise. 923 */ 924 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr) 925 { 926 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) & 927 MASK_RSP_EXCEPTION_EVENT; 928 } 929 930 /** 931 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values. 932 * @hba: per adapter instance 933 */ 934 static inline void 935 ufshcd_reset_intr_aggr(struct ufs_hba *hba) 936 { 937 ufshcd_writel(hba, INT_AGGR_ENABLE | 938 INT_AGGR_COUNTER_AND_TIMER_RESET, 939 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL); 940 } 941 942 /** 943 * ufshcd_config_intr_aggr - Configure interrupt aggregation values. 944 * @hba: per adapter instance 945 * @cnt: Interrupt aggregation counter threshold 946 * @tmout: Interrupt aggregation timeout value 947 */ 948 static inline void 949 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout) 950 { 951 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE | 952 INT_AGGR_COUNTER_THLD_VAL(cnt) | 953 INT_AGGR_TIMEOUT_VAL(tmout), 954 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL); 955 } 956 957 /** 958 * ufshcd_disable_intr_aggr - Disables interrupt aggregation. 959 * @hba: per adapter instance 960 */ 961 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba) 962 { 963 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL); 964 } 965 966 /** 967 * ufshcd_enable_run_stop_reg - Enable run-stop registers, 968 * When run-stop registers are set to 1, it indicates the 969 * host controller that it can process the requests 970 * @hba: per adapter instance 971 */ 972 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba) 973 { 974 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT, 975 REG_UTP_TASK_REQ_LIST_RUN_STOP); 976 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT, 977 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP); 978 } 979 980 /** 981 * ufshcd_hba_start - Start controller initialization sequence 982 * @hba: per adapter instance 983 */ 984 static inline void ufshcd_hba_start(struct ufs_hba *hba) 985 { 986 u32 val = CONTROLLER_ENABLE; 987 988 if (ufshcd_crypto_enable(hba)) 989 val |= CRYPTO_GENERAL_ENABLE; 990 991 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE); 992 } 993 994 /** 995 * ufshcd_is_hba_active - Get controller state 996 * @hba: per adapter instance 997 * 998 * Returns true if and only if the controller is active. 999 */ 1000 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba) 1001 { 1002 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE; 1003 } 1004 1005 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba) 1006 { 1007 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */ 1008 if (hba->ufs_version <= ufshci_version(1, 1)) 1009 return UFS_UNIPRO_VER_1_41; 1010 else 1011 return UFS_UNIPRO_VER_1_6; 1012 } 1013 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver); 1014 1015 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba) 1016 { 1017 /* 1018 * If both host and device support UniPro ver1.6 or later, PA layer 1019 * parameters tuning happens during link startup itself. 1020 * 1021 * We can manually tune PA layer parameters if either host or device 1022 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning 1023 * logic simple, we will only do manual tuning if local unipro version 1024 * doesn't support ver1.6 or later. 1025 */ 1026 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6; 1027 } 1028 1029 /** 1030 * ufshcd_set_clk_freq - set UFS controller clock frequencies 1031 * @hba: per adapter instance 1032 * @scale_up: If True, set max possible frequency othewise set low frequency 1033 * 1034 * Returns 0 if successful 1035 * Returns < 0 for any other errors 1036 */ 1037 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up) 1038 { 1039 int ret = 0; 1040 struct ufs_clk_info *clki; 1041 struct list_head *head = &hba->clk_list_head; 1042 1043 if (list_empty(head)) 1044 goto out; 1045 1046 list_for_each_entry(clki, head, list) { 1047 if (!IS_ERR_OR_NULL(clki->clk)) { 1048 if (scale_up && clki->max_freq) { 1049 if (clki->curr_freq == clki->max_freq) 1050 continue; 1051 1052 ret = clk_set_rate(clki->clk, clki->max_freq); 1053 if (ret) { 1054 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n", 1055 __func__, clki->name, 1056 clki->max_freq, ret); 1057 break; 1058 } 1059 trace_ufshcd_clk_scaling(dev_name(hba->dev), 1060 "scaled up", clki->name, 1061 clki->curr_freq, 1062 clki->max_freq); 1063 1064 clki->curr_freq = clki->max_freq; 1065 1066 } else if (!scale_up && clki->min_freq) { 1067 if (clki->curr_freq == clki->min_freq) 1068 continue; 1069 1070 ret = clk_set_rate(clki->clk, clki->min_freq); 1071 if (ret) { 1072 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n", 1073 __func__, clki->name, 1074 clki->min_freq, ret); 1075 break; 1076 } 1077 trace_ufshcd_clk_scaling(dev_name(hba->dev), 1078 "scaled down", clki->name, 1079 clki->curr_freq, 1080 clki->min_freq); 1081 clki->curr_freq = clki->min_freq; 1082 } 1083 } 1084 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__, 1085 clki->name, clk_get_rate(clki->clk)); 1086 } 1087 1088 out: 1089 return ret; 1090 } 1091 1092 /** 1093 * ufshcd_scale_clks - scale up or scale down UFS controller clocks 1094 * @hba: per adapter instance 1095 * @scale_up: True if scaling up and false if scaling down 1096 * 1097 * Returns 0 if successful 1098 * Returns < 0 for any other errors 1099 */ 1100 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up) 1101 { 1102 int ret = 0; 1103 ktime_t start = ktime_get(); 1104 1105 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE); 1106 if (ret) 1107 goto out; 1108 1109 ret = ufshcd_set_clk_freq(hba, scale_up); 1110 if (ret) 1111 goto out; 1112 1113 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE); 1114 if (ret) 1115 ufshcd_set_clk_freq(hba, !scale_up); 1116 1117 out: 1118 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev), 1119 (scale_up ? "up" : "down"), 1120 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 1121 return ret; 1122 } 1123 1124 /** 1125 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not 1126 * @hba: per adapter instance 1127 * @scale_up: True if scaling up and false if scaling down 1128 * 1129 * Returns true if scaling is required, false otherwise. 1130 */ 1131 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba, 1132 bool scale_up) 1133 { 1134 struct ufs_clk_info *clki; 1135 struct list_head *head = &hba->clk_list_head; 1136 1137 if (list_empty(head)) 1138 return false; 1139 1140 list_for_each_entry(clki, head, list) { 1141 if (!IS_ERR_OR_NULL(clki->clk)) { 1142 if (scale_up && clki->max_freq) { 1143 if (clki->curr_freq == clki->max_freq) 1144 continue; 1145 return true; 1146 } else if (!scale_up && clki->min_freq) { 1147 if (clki->curr_freq == clki->min_freq) 1148 continue; 1149 return true; 1150 } 1151 } 1152 } 1153 1154 return false; 1155 } 1156 1157 /* 1158 * Determine the number of pending commands by counting the bits in the SCSI 1159 * device budget maps. This approach has been selected because a bit is set in 1160 * the budget map before scsi_host_queue_ready() checks the host_self_blocked 1161 * flag. The host_self_blocked flag can be modified by calling 1162 * scsi_block_requests() or scsi_unblock_requests(). 1163 */ 1164 static u32 ufshcd_pending_cmds(struct ufs_hba *hba) 1165 { 1166 const struct scsi_device *sdev; 1167 u32 pending = 0; 1168 1169 lockdep_assert_held(hba->host->host_lock); 1170 __shost_for_each_device(sdev, hba->host) 1171 pending += sbitmap_weight(&sdev->budget_map); 1172 1173 return pending; 1174 } 1175 1176 /* 1177 * Wait until all pending SCSI commands and TMFs have finished or the timeout 1178 * has expired. 1179 * 1180 * Return: 0 upon success; -EBUSY upon timeout. 1181 */ 1182 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba, 1183 u64 wait_timeout_us) 1184 { 1185 unsigned long flags; 1186 int ret = 0; 1187 u32 tm_doorbell; 1188 u32 tr_pending; 1189 bool timeout = false, do_last_check = false; 1190 ktime_t start; 1191 1192 ufshcd_hold(hba, false); 1193 spin_lock_irqsave(hba->host->host_lock, flags); 1194 /* 1195 * Wait for all the outstanding tasks/transfer requests. 1196 * Verify by checking the doorbell registers are clear. 1197 */ 1198 start = ktime_get(); 1199 do { 1200 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) { 1201 ret = -EBUSY; 1202 goto out; 1203 } 1204 1205 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL); 1206 tr_pending = ufshcd_pending_cmds(hba); 1207 if (!tm_doorbell && !tr_pending) { 1208 timeout = false; 1209 break; 1210 } else if (do_last_check) { 1211 break; 1212 } 1213 1214 spin_unlock_irqrestore(hba->host->host_lock, flags); 1215 io_schedule_timeout(msecs_to_jiffies(20)); 1216 if (ktime_to_us(ktime_sub(ktime_get(), start)) > 1217 wait_timeout_us) { 1218 timeout = true; 1219 /* 1220 * We might have scheduled out for long time so make 1221 * sure to check if doorbells are cleared by this time 1222 * or not. 1223 */ 1224 do_last_check = true; 1225 } 1226 spin_lock_irqsave(hba->host->host_lock, flags); 1227 } while (tm_doorbell || tr_pending); 1228 1229 if (timeout) { 1230 dev_err(hba->dev, 1231 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n", 1232 __func__, tm_doorbell, tr_pending); 1233 ret = -EBUSY; 1234 } 1235 out: 1236 spin_unlock_irqrestore(hba->host->host_lock, flags); 1237 ufshcd_release(hba); 1238 return ret; 1239 } 1240 1241 /** 1242 * ufshcd_scale_gear - scale up/down UFS gear 1243 * @hba: per adapter instance 1244 * @scale_up: True for scaling up gear and false for scaling down 1245 * 1246 * Returns 0 for success, 1247 * Returns -EBUSY if scaling can't happen at this time 1248 * Returns non-zero for any other errors 1249 */ 1250 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up) 1251 { 1252 int ret = 0; 1253 struct ufs_pa_layer_attr new_pwr_info; 1254 1255 if (scale_up) { 1256 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info, 1257 sizeof(struct ufs_pa_layer_attr)); 1258 } else { 1259 memcpy(&new_pwr_info, &hba->pwr_info, 1260 sizeof(struct ufs_pa_layer_attr)); 1261 1262 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear || 1263 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) { 1264 /* save the current power mode */ 1265 memcpy(&hba->clk_scaling.saved_pwr_info, 1266 &hba->pwr_info, 1267 sizeof(struct ufs_pa_layer_attr)); 1268 1269 /* scale down gear */ 1270 new_pwr_info.gear_tx = hba->clk_scaling.min_gear; 1271 new_pwr_info.gear_rx = hba->clk_scaling.min_gear; 1272 } 1273 } 1274 1275 /* check if the power mode needs to be changed or not? */ 1276 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info); 1277 if (ret) 1278 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)", 1279 __func__, ret, 1280 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx, 1281 new_pwr_info.gear_tx, new_pwr_info.gear_rx); 1282 1283 return ret; 1284 } 1285 1286 /* 1287 * Wait until all pending SCSI commands and TMFs have finished or the timeout 1288 * has expired. 1289 * 1290 * Return: 0 upon success; -EBUSY upon timeout. 1291 */ 1292 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us) 1293 { 1294 int ret = 0; 1295 /* 1296 * make sure that there are no outstanding requests when 1297 * clock scaling is in progress 1298 */ 1299 ufshcd_scsi_block_requests(hba); 1300 mutex_lock(&hba->wb_mutex); 1301 down_write(&hba->clk_scaling_lock); 1302 1303 if (!hba->clk_scaling.is_allowed || 1304 ufshcd_wait_for_doorbell_clr(hba, timeout_us)) { 1305 ret = -EBUSY; 1306 up_write(&hba->clk_scaling_lock); 1307 mutex_unlock(&hba->wb_mutex); 1308 ufshcd_scsi_unblock_requests(hba); 1309 goto out; 1310 } 1311 1312 /* let's not get into low power until clock scaling is completed */ 1313 ufshcd_hold(hba, false); 1314 1315 out: 1316 return ret; 1317 } 1318 1319 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up) 1320 { 1321 up_write(&hba->clk_scaling_lock); 1322 1323 /* Enable Write Booster if we have scaled up else disable it */ 1324 if (ufshcd_enable_wb_if_scaling_up(hba) && !err) 1325 ufshcd_wb_toggle(hba, scale_up); 1326 1327 mutex_unlock(&hba->wb_mutex); 1328 1329 ufshcd_scsi_unblock_requests(hba); 1330 ufshcd_release(hba); 1331 } 1332 1333 /** 1334 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear 1335 * @hba: per adapter instance 1336 * @scale_up: True for scaling up and false for scalin down 1337 * 1338 * Returns 0 for success, 1339 * Returns -EBUSY if scaling can't happen at this time 1340 * Returns non-zero for any other errors 1341 */ 1342 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up) 1343 { 1344 int ret = 0; 1345 1346 ret = ufshcd_clock_scaling_prepare(hba, 1 * USEC_PER_SEC); 1347 if (ret) 1348 return ret; 1349 1350 /* scale down the gear before scaling down clocks */ 1351 if (!scale_up) { 1352 ret = ufshcd_scale_gear(hba, false); 1353 if (ret) 1354 goto out_unprepare; 1355 } 1356 1357 ret = ufshcd_scale_clks(hba, scale_up); 1358 if (ret) { 1359 if (!scale_up) 1360 ufshcd_scale_gear(hba, true); 1361 goto out_unprepare; 1362 } 1363 1364 /* scale up the gear after scaling up clocks */ 1365 if (scale_up) { 1366 ret = ufshcd_scale_gear(hba, true); 1367 if (ret) { 1368 ufshcd_scale_clks(hba, false); 1369 goto out_unprepare; 1370 } 1371 } 1372 1373 out_unprepare: 1374 ufshcd_clock_scaling_unprepare(hba, ret, scale_up); 1375 return ret; 1376 } 1377 1378 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work) 1379 { 1380 struct ufs_hba *hba = container_of(work, struct ufs_hba, 1381 clk_scaling.suspend_work); 1382 unsigned long irq_flags; 1383 1384 spin_lock_irqsave(hba->host->host_lock, irq_flags); 1385 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) { 1386 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1387 return; 1388 } 1389 hba->clk_scaling.is_suspended = true; 1390 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1391 1392 __ufshcd_suspend_clkscaling(hba); 1393 } 1394 1395 static void ufshcd_clk_scaling_resume_work(struct work_struct *work) 1396 { 1397 struct ufs_hba *hba = container_of(work, struct ufs_hba, 1398 clk_scaling.resume_work); 1399 unsigned long irq_flags; 1400 1401 spin_lock_irqsave(hba->host->host_lock, irq_flags); 1402 if (!hba->clk_scaling.is_suspended) { 1403 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1404 return; 1405 } 1406 hba->clk_scaling.is_suspended = false; 1407 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1408 1409 devfreq_resume_device(hba->devfreq); 1410 } 1411 1412 static int ufshcd_devfreq_target(struct device *dev, 1413 unsigned long *freq, u32 flags) 1414 { 1415 int ret = 0; 1416 struct ufs_hba *hba = dev_get_drvdata(dev); 1417 ktime_t start; 1418 bool scale_up, sched_clk_scaling_suspend_work = false; 1419 struct list_head *clk_list = &hba->clk_list_head; 1420 struct ufs_clk_info *clki; 1421 unsigned long irq_flags; 1422 1423 if (!ufshcd_is_clkscaling_supported(hba)) 1424 return -EINVAL; 1425 1426 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list); 1427 /* Override with the closest supported frequency */ 1428 *freq = (unsigned long) clk_round_rate(clki->clk, *freq); 1429 spin_lock_irqsave(hba->host->host_lock, irq_flags); 1430 if (ufshcd_eh_in_progress(hba)) { 1431 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1432 return 0; 1433 } 1434 1435 if (!hba->clk_scaling.active_reqs) 1436 sched_clk_scaling_suspend_work = true; 1437 1438 if (list_empty(clk_list)) { 1439 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1440 goto out; 1441 } 1442 1443 /* Decide based on the rounded-off frequency and update */ 1444 scale_up = *freq == clki->max_freq; 1445 if (!scale_up) 1446 *freq = clki->min_freq; 1447 /* Update the frequency */ 1448 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) { 1449 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1450 ret = 0; 1451 goto out; /* no state change required */ 1452 } 1453 spin_unlock_irqrestore(hba->host->host_lock, irq_flags); 1454 1455 start = ktime_get(); 1456 ret = ufshcd_devfreq_scale(hba, scale_up); 1457 1458 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev), 1459 (scale_up ? "up" : "down"), 1460 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 1461 1462 out: 1463 if (sched_clk_scaling_suspend_work) 1464 queue_work(hba->clk_scaling.workq, 1465 &hba->clk_scaling.suspend_work); 1466 1467 return ret; 1468 } 1469 1470 static int ufshcd_devfreq_get_dev_status(struct device *dev, 1471 struct devfreq_dev_status *stat) 1472 { 1473 struct ufs_hba *hba = dev_get_drvdata(dev); 1474 struct ufs_clk_scaling *scaling = &hba->clk_scaling; 1475 unsigned long flags; 1476 struct list_head *clk_list = &hba->clk_list_head; 1477 struct ufs_clk_info *clki; 1478 ktime_t curr_t; 1479 1480 if (!ufshcd_is_clkscaling_supported(hba)) 1481 return -EINVAL; 1482 1483 memset(stat, 0, sizeof(*stat)); 1484 1485 spin_lock_irqsave(hba->host->host_lock, flags); 1486 curr_t = ktime_get(); 1487 if (!scaling->window_start_t) 1488 goto start_window; 1489 1490 clki = list_first_entry(clk_list, struct ufs_clk_info, list); 1491 /* 1492 * If current frequency is 0, then the ondemand governor considers 1493 * there's no initial frequency set. And it always requests to set 1494 * to max. frequency. 1495 */ 1496 stat->current_frequency = clki->curr_freq; 1497 if (scaling->is_busy_started) 1498 scaling->tot_busy_t += ktime_us_delta(curr_t, 1499 scaling->busy_start_t); 1500 1501 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t); 1502 stat->busy_time = scaling->tot_busy_t; 1503 start_window: 1504 scaling->window_start_t = curr_t; 1505 scaling->tot_busy_t = 0; 1506 1507 if (scaling->active_reqs) { 1508 scaling->busy_start_t = curr_t; 1509 scaling->is_busy_started = true; 1510 } else { 1511 scaling->busy_start_t = 0; 1512 scaling->is_busy_started = false; 1513 } 1514 spin_unlock_irqrestore(hba->host->host_lock, flags); 1515 return 0; 1516 } 1517 1518 static int ufshcd_devfreq_init(struct ufs_hba *hba) 1519 { 1520 struct list_head *clk_list = &hba->clk_list_head; 1521 struct ufs_clk_info *clki; 1522 struct devfreq *devfreq; 1523 int ret; 1524 1525 /* Skip devfreq if we don't have any clocks in the list */ 1526 if (list_empty(clk_list)) 1527 return 0; 1528 1529 clki = list_first_entry(clk_list, struct ufs_clk_info, list); 1530 dev_pm_opp_add(hba->dev, clki->min_freq, 0); 1531 dev_pm_opp_add(hba->dev, clki->max_freq, 0); 1532 1533 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile, 1534 &hba->vps->ondemand_data); 1535 devfreq = devfreq_add_device(hba->dev, 1536 &hba->vps->devfreq_profile, 1537 DEVFREQ_GOV_SIMPLE_ONDEMAND, 1538 &hba->vps->ondemand_data); 1539 if (IS_ERR(devfreq)) { 1540 ret = PTR_ERR(devfreq); 1541 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret); 1542 1543 dev_pm_opp_remove(hba->dev, clki->min_freq); 1544 dev_pm_opp_remove(hba->dev, clki->max_freq); 1545 return ret; 1546 } 1547 1548 hba->devfreq = devfreq; 1549 1550 return 0; 1551 } 1552 1553 static void ufshcd_devfreq_remove(struct ufs_hba *hba) 1554 { 1555 struct list_head *clk_list = &hba->clk_list_head; 1556 struct ufs_clk_info *clki; 1557 1558 if (!hba->devfreq) 1559 return; 1560 1561 devfreq_remove_device(hba->devfreq); 1562 hba->devfreq = NULL; 1563 1564 clki = list_first_entry(clk_list, struct ufs_clk_info, list); 1565 dev_pm_opp_remove(hba->dev, clki->min_freq); 1566 dev_pm_opp_remove(hba->dev, clki->max_freq); 1567 } 1568 1569 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba) 1570 { 1571 unsigned long flags; 1572 1573 devfreq_suspend_device(hba->devfreq); 1574 spin_lock_irqsave(hba->host->host_lock, flags); 1575 hba->clk_scaling.window_start_t = 0; 1576 spin_unlock_irqrestore(hba->host->host_lock, flags); 1577 } 1578 1579 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba) 1580 { 1581 unsigned long flags; 1582 bool suspend = false; 1583 1584 cancel_work_sync(&hba->clk_scaling.suspend_work); 1585 cancel_work_sync(&hba->clk_scaling.resume_work); 1586 1587 spin_lock_irqsave(hba->host->host_lock, flags); 1588 if (!hba->clk_scaling.is_suspended) { 1589 suspend = true; 1590 hba->clk_scaling.is_suspended = true; 1591 } 1592 spin_unlock_irqrestore(hba->host->host_lock, flags); 1593 1594 if (suspend) 1595 __ufshcd_suspend_clkscaling(hba); 1596 } 1597 1598 static void ufshcd_resume_clkscaling(struct ufs_hba *hba) 1599 { 1600 unsigned long flags; 1601 bool resume = false; 1602 1603 spin_lock_irqsave(hba->host->host_lock, flags); 1604 if (hba->clk_scaling.is_suspended) { 1605 resume = true; 1606 hba->clk_scaling.is_suspended = false; 1607 } 1608 spin_unlock_irqrestore(hba->host->host_lock, flags); 1609 1610 if (resume) 1611 devfreq_resume_device(hba->devfreq); 1612 } 1613 1614 static ssize_t ufshcd_clkscale_enable_show(struct device *dev, 1615 struct device_attribute *attr, char *buf) 1616 { 1617 struct ufs_hba *hba = dev_get_drvdata(dev); 1618 1619 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled); 1620 } 1621 1622 static ssize_t ufshcd_clkscale_enable_store(struct device *dev, 1623 struct device_attribute *attr, const char *buf, size_t count) 1624 { 1625 struct ufs_hba *hba = dev_get_drvdata(dev); 1626 u32 value; 1627 int err = 0; 1628 1629 if (kstrtou32(buf, 0, &value)) 1630 return -EINVAL; 1631 1632 down(&hba->host_sem); 1633 if (!ufshcd_is_user_access_allowed(hba)) { 1634 err = -EBUSY; 1635 goto out; 1636 } 1637 1638 value = !!value; 1639 if (value == hba->clk_scaling.is_enabled) 1640 goto out; 1641 1642 ufshcd_rpm_get_sync(hba); 1643 ufshcd_hold(hba, false); 1644 1645 hba->clk_scaling.is_enabled = value; 1646 1647 if (value) { 1648 ufshcd_resume_clkscaling(hba); 1649 } else { 1650 ufshcd_suspend_clkscaling(hba); 1651 err = ufshcd_devfreq_scale(hba, true); 1652 if (err) 1653 dev_err(hba->dev, "%s: failed to scale clocks up %d\n", 1654 __func__, err); 1655 } 1656 1657 ufshcd_release(hba); 1658 ufshcd_rpm_put_sync(hba); 1659 out: 1660 up(&hba->host_sem); 1661 return err ? err : count; 1662 } 1663 1664 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba) 1665 { 1666 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show; 1667 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store; 1668 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr); 1669 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable"; 1670 hba->clk_scaling.enable_attr.attr.mode = 0644; 1671 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr)) 1672 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n"); 1673 } 1674 1675 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba) 1676 { 1677 if (hba->clk_scaling.enable_attr.attr.name) 1678 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr); 1679 } 1680 1681 static void ufshcd_init_clk_scaling(struct ufs_hba *hba) 1682 { 1683 char wq_name[sizeof("ufs_clkscaling_00")]; 1684 1685 if (!ufshcd_is_clkscaling_supported(hba)) 1686 return; 1687 1688 if (!hba->clk_scaling.min_gear) 1689 hba->clk_scaling.min_gear = UFS_HS_G1; 1690 1691 INIT_WORK(&hba->clk_scaling.suspend_work, 1692 ufshcd_clk_scaling_suspend_work); 1693 INIT_WORK(&hba->clk_scaling.resume_work, 1694 ufshcd_clk_scaling_resume_work); 1695 1696 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d", 1697 hba->host->host_no); 1698 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name); 1699 1700 hba->clk_scaling.is_initialized = true; 1701 } 1702 1703 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba) 1704 { 1705 if (!hba->clk_scaling.is_initialized) 1706 return; 1707 1708 ufshcd_remove_clk_scaling_sysfs(hba); 1709 destroy_workqueue(hba->clk_scaling.workq); 1710 ufshcd_devfreq_remove(hba); 1711 hba->clk_scaling.is_initialized = false; 1712 } 1713 1714 static void ufshcd_ungate_work(struct work_struct *work) 1715 { 1716 int ret; 1717 unsigned long flags; 1718 struct ufs_hba *hba = container_of(work, struct ufs_hba, 1719 clk_gating.ungate_work); 1720 1721 cancel_delayed_work_sync(&hba->clk_gating.gate_work); 1722 1723 spin_lock_irqsave(hba->host->host_lock, flags); 1724 if (hba->clk_gating.state == CLKS_ON) { 1725 spin_unlock_irqrestore(hba->host->host_lock, flags); 1726 goto unblock_reqs; 1727 } 1728 1729 spin_unlock_irqrestore(hba->host->host_lock, flags); 1730 ufshcd_hba_vreg_set_hpm(hba); 1731 ufshcd_setup_clocks(hba, true); 1732 1733 ufshcd_enable_irq(hba); 1734 1735 /* Exit from hibern8 */ 1736 if (ufshcd_can_hibern8_during_gating(hba)) { 1737 /* Prevent gating in this path */ 1738 hba->clk_gating.is_suspended = true; 1739 if (ufshcd_is_link_hibern8(hba)) { 1740 ret = ufshcd_uic_hibern8_exit(hba); 1741 if (ret) 1742 dev_err(hba->dev, "%s: hibern8 exit failed %d\n", 1743 __func__, ret); 1744 else 1745 ufshcd_set_link_active(hba); 1746 } 1747 hba->clk_gating.is_suspended = false; 1748 } 1749 unblock_reqs: 1750 ufshcd_scsi_unblock_requests(hba); 1751 } 1752 1753 /** 1754 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release. 1755 * Also, exit from hibern8 mode and set the link as active. 1756 * @hba: per adapter instance 1757 * @async: This indicates whether caller should ungate clocks asynchronously. 1758 */ 1759 int ufshcd_hold(struct ufs_hba *hba, bool async) 1760 { 1761 int rc = 0; 1762 bool flush_result; 1763 unsigned long flags; 1764 1765 if (!ufshcd_is_clkgating_allowed(hba) || 1766 !hba->clk_gating.is_initialized) 1767 goto out; 1768 spin_lock_irqsave(hba->host->host_lock, flags); 1769 hba->clk_gating.active_reqs++; 1770 1771 start: 1772 switch (hba->clk_gating.state) { 1773 case CLKS_ON: 1774 /* 1775 * Wait for the ungate work to complete if in progress. 1776 * Though the clocks may be in ON state, the link could 1777 * still be in hibner8 state if hibern8 is allowed 1778 * during clock gating. 1779 * Make sure we exit hibern8 state also in addition to 1780 * clocks being ON. 1781 */ 1782 if (ufshcd_can_hibern8_during_gating(hba) && 1783 ufshcd_is_link_hibern8(hba)) { 1784 if (async) { 1785 rc = -EAGAIN; 1786 hba->clk_gating.active_reqs--; 1787 break; 1788 } 1789 spin_unlock_irqrestore(hba->host->host_lock, flags); 1790 flush_result = flush_work(&hba->clk_gating.ungate_work); 1791 if (hba->clk_gating.is_suspended && !flush_result) 1792 goto out; 1793 spin_lock_irqsave(hba->host->host_lock, flags); 1794 goto start; 1795 } 1796 break; 1797 case REQ_CLKS_OFF: 1798 if (cancel_delayed_work(&hba->clk_gating.gate_work)) { 1799 hba->clk_gating.state = CLKS_ON; 1800 trace_ufshcd_clk_gating(dev_name(hba->dev), 1801 hba->clk_gating.state); 1802 break; 1803 } 1804 /* 1805 * If we are here, it means gating work is either done or 1806 * currently running. Hence, fall through to cancel gating 1807 * work and to enable clocks. 1808 */ 1809 fallthrough; 1810 case CLKS_OFF: 1811 hba->clk_gating.state = REQ_CLKS_ON; 1812 trace_ufshcd_clk_gating(dev_name(hba->dev), 1813 hba->clk_gating.state); 1814 if (queue_work(hba->clk_gating.clk_gating_workq, 1815 &hba->clk_gating.ungate_work)) 1816 ufshcd_scsi_block_requests(hba); 1817 /* 1818 * fall through to check if we should wait for this 1819 * work to be done or not. 1820 */ 1821 fallthrough; 1822 case REQ_CLKS_ON: 1823 if (async) { 1824 rc = -EAGAIN; 1825 hba->clk_gating.active_reqs--; 1826 break; 1827 } 1828 1829 spin_unlock_irqrestore(hba->host->host_lock, flags); 1830 flush_work(&hba->clk_gating.ungate_work); 1831 /* Make sure state is CLKS_ON before returning */ 1832 spin_lock_irqsave(hba->host->host_lock, flags); 1833 goto start; 1834 default: 1835 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n", 1836 __func__, hba->clk_gating.state); 1837 break; 1838 } 1839 spin_unlock_irqrestore(hba->host->host_lock, flags); 1840 out: 1841 return rc; 1842 } 1843 EXPORT_SYMBOL_GPL(ufshcd_hold); 1844 1845 static void ufshcd_gate_work(struct work_struct *work) 1846 { 1847 struct ufs_hba *hba = container_of(work, struct ufs_hba, 1848 clk_gating.gate_work.work); 1849 unsigned long flags; 1850 int ret; 1851 1852 spin_lock_irqsave(hba->host->host_lock, flags); 1853 /* 1854 * In case you are here to cancel this work the gating state 1855 * would be marked as REQ_CLKS_ON. In this case save time by 1856 * skipping the gating work and exit after changing the clock 1857 * state to CLKS_ON. 1858 */ 1859 if (hba->clk_gating.is_suspended || 1860 (hba->clk_gating.state != REQ_CLKS_OFF)) { 1861 hba->clk_gating.state = CLKS_ON; 1862 trace_ufshcd_clk_gating(dev_name(hba->dev), 1863 hba->clk_gating.state); 1864 goto rel_lock; 1865 } 1866 1867 if (hba->clk_gating.active_reqs 1868 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL 1869 || hba->outstanding_reqs || hba->outstanding_tasks 1870 || hba->active_uic_cmd || hba->uic_async_done) 1871 goto rel_lock; 1872 1873 spin_unlock_irqrestore(hba->host->host_lock, flags); 1874 1875 /* put the link into hibern8 mode before turning off clocks */ 1876 if (ufshcd_can_hibern8_during_gating(hba)) { 1877 ret = ufshcd_uic_hibern8_enter(hba); 1878 if (ret) { 1879 hba->clk_gating.state = CLKS_ON; 1880 dev_err(hba->dev, "%s: hibern8 enter failed %d\n", 1881 __func__, ret); 1882 trace_ufshcd_clk_gating(dev_name(hba->dev), 1883 hba->clk_gating.state); 1884 goto out; 1885 } 1886 ufshcd_set_link_hibern8(hba); 1887 } 1888 1889 ufshcd_disable_irq(hba); 1890 1891 ufshcd_setup_clocks(hba, false); 1892 1893 /* Put the host controller in low power mode if possible */ 1894 ufshcd_hba_vreg_set_lpm(hba); 1895 /* 1896 * In case you are here to cancel this work the gating state 1897 * would be marked as REQ_CLKS_ON. In this case keep the state 1898 * as REQ_CLKS_ON which would anyway imply that clocks are off 1899 * and a request to turn them on is pending. By doing this way, 1900 * we keep the state machine in tact and this would ultimately 1901 * prevent from doing cancel work multiple times when there are 1902 * new requests arriving before the current cancel work is done. 1903 */ 1904 spin_lock_irqsave(hba->host->host_lock, flags); 1905 if (hba->clk_gating.state == REQ_CLKS_OFF) { 1906 hba->clk_gating.state = CLKS_OFF; 1907 trace_ufshcd_clk_gating(dev_name(hba->dev), 1908 hba->clk_gating.state); 1909 } 1910 rel_lock: 1911 spin_unlock_irqrestore(hba->host->host_lock, flags); 1912 out: 1913 return; 1914 } 1915 1916 /* host lock must be held before calling this variant */ 1917 static void __ufshcd_release(struct ufs_hba *hba) 1918 { 1919 if (!ufshcd_is_clkgating_allowed(hba)) 1920 return; 1921 1922 hba->clk_gating.active_reqs--; 1923 1924 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended || 1925 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL || 1926 hba->outstanding_tasks || !hba->clk_gating.is_initialized || 1927 hba->active_uic_cmd || hba->uic_async_done || 1928 hba->clk_gating.state == CLKS_OFF) 1929 return; 1930 1931 hba->clk_gating.state = REQ_CLKS_OFF; 1932 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state); 1933 queue_delayed_work(hba->clk_gating.clk_gating_workq, 1934 &hba->clk_gating.gate_work, 1935 msecs_to_jiffies(hba->clk_gating.delay_ms)); 1936 } 1937 1938 void ufshcd_release(struct ufs_hba *hba) 1939 { 1940 unsigned long flags; 1941 1942 spin_lock_irqsave(hba->host->host_lock, flags); 1943 __ufshcd_release(hba); 1944 spin_unlock_irqrestore(hba->host->host_lock, flags); 1945 } 1946 EXPORT_SYMBOL_GPL(ufshcd_release); 1947 1948 static ssize_t ufshcd_clkgate_delay_show(struct device *dev, 1949 struct device_attribute *attr, char *buf) 1950 { 1951 struct ufs_hba *hba = dev_get_drvdata(dev); 1952 1953 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms); 1954 } 1955 1956 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value) 1957 { 1958 struct ufs_hba *hba = dev_get_drvdata(dev); 1959 unsigned long flags; 1960 1961 spin_lock_irqsave(hba->host->host_lock, flags); 1962 hba->clk_gating.delay_ms = value; 1963 spin_unlock_irqrestore(hba->host->host_lock, flags); 1964 } 1965 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set); 1966 1967 static ssize_t ufshcd_clkgate_delay_store(struct device *dev, 1968 struct device_attribute *attr, const char *buf, size_t count) 1969 { 1970 unsigned long value; 1971 1972 if (kstrtoul(buf, 0, &value)) 1973 return -EINVAL; 1974 1975 ufshcd_clkgate_delay_set(dev, value); 1976 return count; 1977 } 1978 1979 static ssize_t ufshcd_clkgate_enable_show(struct device *dev, 1980 struct device_attribute *attr, char *buf) 1981 { 1982 struct ufs_hba *hba = dev_get_drvdata(dev); 1983 1984 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled); 1985 } 1986 1987 static ssize_t ufshcd_clkgate_enable_store(struct device *dev, 1988 struct device_attribute *attr, const char *buf, size_t count) 1989 { 1990 struct ufs_hba *hba = dev_get_drvdata(dev); 1991 unsigned long flags; 1992 u32 value; 1993 1994 if (kstrtou32(buf, 0, &value)) 1995 return -EINVAL; 1996 1997 value = !!value; 1998 1999 spin_lock_irqsave(hba->host->host_lock, flags); 2000 if (value == hba->clk_gating.is_enabled) 2001 goto out; 2002 2003 if (value) 2004 __ufshcd_release(hba); 2005 else 2006 hba->clk_gating.active_reqs++; 2007 2008 hba->clk_gating.is_enabled = value; 2009 out: 2010 spin_unlock_irqrestore(hba->host->host_lock, flags); 2011 return count; 2012 } 2013 2014 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba) 2015 { 2016 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show; 2017 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store; 2018 sysfs_attr_init(&hba->clk_gating.delay_attr.attr); 2019 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms"; 2020 hba->clk_gating.delay_attr.attr.mode = 0644; 2021 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr)) 2022 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n"); 2023 2024 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show; 2025 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store; 2026 sysfs_attr_init(&hba->clk_gating.enable_attr.attr); 2027 hba->clk_gating.enable_attr.attr.name = "clkgate_enable"; 2028 hba->clk_gating.enable_attr.attr.mode = 0644; 2029 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr)) 2030 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n"); 2031 } 2032 2033 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba) 2034 { 2035 if (hba->clk_gating.delay_attr.attr.name) 2036 device_remove_file(hba->dev, &hba->clk_gating.delay_attr); 2037 if (hba->clk_gating.enable_attr.attr.name) 2038 device_remove_file(hba->dev, &hba->clk_gating.enable_attr); 2039 } 2040 2041 static void ufshcd_init_clk_gating(struct ufs_hba *hba) 2042 { 2043 char wq_name[sizeof("ufs_clk_gating_00")]; 2044 2045 if (!ufshcd_is_clkgating_allowed(hba)) 2046 return; 2047 2048 hba->clk_gating.state = CLKS_ON; 2049 2050 hba->clk_gating.delay_ms = 150; 2051 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work); 2052 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work); 2053 2054 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d", 2055 hba->host->host_no); 2056 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name, 2057 WQ_MEM_RECLAIM | WQ_HIGHPRI); 2058 2059 ufshcd_init_clk_gating_sysfs(hba); 2060 2061 hba->clk_gating.is_enabled = true; 2062 hba->clk_gating.is_initialized = true; 2063 } 2064 2065 static void ufshcd_exit_clk_gating(struct ufs_hba *hba) 2066 { 2067 if (!hba->clk_gating.is_initialized) 2068 return; 2069 2070 ufshcd_remove_clk_gating_sysfs(hba); 2071 2072 /* Ungate the clock if necessary. */ 2073 ufshcd_hold(hba, false); 2074 hba->clk_gating.is_initialized = false; 2075 ufshcd_release(hba); 2076 2077 destroy_workqueue(hba->clk_gating.clk_gating_workq); 2078 } 2079 2080 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba) 2081 { 2082 bool queue_resume_work = false; 2083 ktime_t curr_t = ktime_get(); 2084 unsigned long flags; 2085 2086 if (!ufshcd_is_clkscaling_supported(hba)) 2087 return; 2088 2089 spin_lock_irqsave(hba->host->host_lock, flags); 2090 if (!hba->clk_scaling.active_reqs++) 2091 queue_resume_work = true; 2092 2093 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) { 2094 spin_unlock_irqrestore(hba->host->host_lock, flags); 2095 return; 2096 } 2097 2098 if (queue_resume_work) 2099 queue_work(hba->clk_scaling.workq, 2100 &hba->clk_scaling.resume_work); 2101 2102 if (!hba->clk_scaling.window_start_t) { 2103 hba->clk_scaling.window_start_t = curr_t; 2104 hba->clk_scaling.tot_busy_t = 0; 2105 hba->clk_scaling.is_busy_started = false; 2106 } 2107 2108 if (!hba->clk_scaling.is_busy_started) { 2109 hba->clk_scaling.busy_start_t = curr_t; 2110 hba->clk_scaling.is_busy_started = true; 2111 } 2112 spin_unlock_irqrestore(hba->host->host_lock, flags); 2113 } 2114 2115 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba) 2116 { 2117 struct ufs_clk_scaling *scaling = &hba->clk_scaling; 2118 unsigned long flags; 2119 2120 if (!ufshcd_is_clkscaling_supported(hba)) 2121 return; 2122 2123 spin_lock_irqsave(hba->host->host_lock, flags); 2124 hba->clk_scaling.active_reqs--; 2125 if (!scaling->active_reqs && scaling->is_busy_started) { 2126 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(), 2127 scaling->busy_start_t)); 2128 scaling->busy_start_t = 0; 2129 scaling->is_busy_started = false; 2130 } 2131 spin_unlock_irqrestore(hba->host->host_lock, flags); 2132 } 2133 2134 static inline int ufshcd_monitor_opcode2dir(u8 opcode) 2135 { 2136 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16) 2137 return READ; 2138 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16) 2139 return WRITE; 2140 else 2141 return -EINVAL; 2142 } 2143 2144 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba, 2145 struct ufshcd_lrb *lrbp) 2146 { 2147 const struct ufs_hba_monitor *m = &hba->monitor; 2148 2149 return (m->enabled && lrbp && lrbp->cmd && 2150 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) && 2151 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp)); 2152 } 2153 2154 static void ufshcd_start_monitor(struct ufs_hba *hba, 2155 const struct ufshcd_lrb *lrbp) 2156 { 2157 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd); 2158 unsigned long flags; 2159 2160 spin_lock_irqsave(hba->host->host_lock, flags); 2161 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0) 2162 hba->monitor.busy_start_ts[dir] = ktime_get(); 2163 spin_unlock_irqrestore(hba->host->host_lock, flags); 2164 } 2165 2166 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp) 2167 { 2168 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd); 2169 unsigned long flags; 2170 2171 spin_lock_irqsave(hba->host->host_lock, flags); 2172 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) { 2173 const struct request *req = scsi_cmd_to_rq(lrbp->cmd); 2174 struct ufs_hba_monitor *m = &hba->monitor; 2175 ktime_t now, inc, lat; 2176 2177 now = lrbp->compl_time_stamp; 2178 inc = ktime_sub(now, m->busy_start_ts[dir]); 2179 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc); 2180 m->nr_sec_rw[dir] += blk_rq_sectors(req); 2181 2182 /* Update latencies */ 2183 m->nr_req[dir]++; 2184 lat = ktime_sub(now, lrbp->issue_time_stamp); 2185 m->lat_sum[dir] += lat; 2186 if (m->lat_max[dir] < lat || !m->lat_max[dir]) 2187 m->lat_max[dir] = lat; 2188 if (m->lat_min[dir] > lat || !m->lat_min[dir]) 2189 m->lat_min[dir] = lat; 2190 2191 m->nr_queued[dir]--; 2192 /* Push forward the busy start of monitor */ 2193 m->busy_start_ts[dir] = now; 2194 } 2195 spin_unlock_irqrestore(hba->host->host_lock, flags); 2196 } 2197 2198 /** 2199 * ufshcd_send_command - Send SCSI or device management commands 2200 * @hba: per adapter instance 2201 * @task_tag: Task tag of the command 2202 * @hwq: pointer to hardware queue instance 2203 */ 2204 static inline 2205 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag, 2206 struct ufs_hw_queue *hwq) 2207 { 2208 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag]; 2209 unsigned long flags; 2210 2211 lrbp->issue_time_stamp = ktime_get(); 2212 lrbp->issue_time_stamp_local_clock = local_clock(); 2213 lrbp->compl_time_stamp = ktime_set(0, 0); 2214 lrbp->compl_time_stamp_local_clock = 0; 2215 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND); 2216 ufshcd_clk_scaling_start_busy(hba); 2217 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp))) 2218 ufshcd_start_monitor(hba, lrbp); 2219 2220 if (is_mcq_enabled(hba)) { 2221 int utrd_size = sizeof(struct utp_transfer_req_desc); 2222 struct utp_transfer_req_desc *src = lrbp->utr_descriptor_ptr; 2223 struct utp_transfer_req_desc *dest = hwq->sqe_base_addr + hwq->sq_tail_slot; 2224 2225 spin_lock(&hwq->sq_lock); 2226 memcpy(dest, src, utrd_size); 2227 ufshcd_inc_sq_tail(hwq); 2228 spin_unlock(&hwq->sq_lock); 2229 } else { 2230 spin_lock_irqsave(&hba->outstanding_lock, flags); 2231 if (hba->vops && hba->vops->setup_xfer_req) 2232 hba->vops->setup_xfer_req(hba, lrbp->task_tag, 2233 !!lrbp->cmd); 2234 __set_bit(lrbp->task_tag, &hba->outstanding_reqs); 2235 ufshcd_writel(hba, 1 << lrbp->task_tag, 2236 REG_UTP_TRANSFER_REQ_DOOR_BELL); 2237 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 2238 } 2239 } 2240 2241 /** 2242 * ufshcd_copy_sense_data - Copy sense data in case of check condition 2243 * @lrbp: pointer to local reference block 2244 */ 2245 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp) 2246 { 2247 u8 *const sense_buffer = lrbp->cmd->sense_buffer; 2248 int len; 2249 2250 if (sense_buffer && 2251 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) { 2252 int len_to_copy; 2253 2254 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len); 2255 len_to_copy = min_t(int, UFS_SENSE_SIZE, len); 2256 2257 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data, 2258 len_to_copy); 2259 } 2260 } 2261 2262 /** 2263 * ufshcd_copy_query_response() - Copy the Query Response and the data 2264 * descriptor 2265 * @hba: per adapter instance 2266 * @lrbp: pointer to local reference block 2267 */ 2268 static 2269 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 2270 { 2271 struct ufs_query_res *query_res = &hba->dev_cmd.query.response; 2272 2273 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE); 2274 2275 /* Get the descriptor */ 2276 if (hba->dev_cmd.query.descriptor && 2277 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) { 2278 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + 2279 GENERAL_UPIU_REQUEST_SIZE; 2280 u16 resp_len; 2281 u16 buf_len; 2282 2283 /* data segment length */ 2284 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) & 2285 MASK_QUERY_DATA_SEG_LEN; 2286 buf_len = be16_to_cpu( 2287 hba->dev_cmd.query.request.upiu_req.length); 2288 if (likely(buf_len >= resp_len)) { 2289 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len); 2290 } else { 2291 dev_warn(hba->dev, 2292 "%s: rsp size %d is bigger than buffer size %d", 2293 __func__, resp_len, buf_len); 2294 return -EINVAL; 2295 } 2296 } 2297 2298 return 0; 2299 } 2300 2301 /** 2302 * ufshcd_hba_capabilities - Read controller capabilities 2303 * @hba: per adapter instance 2304 * 2305 * Return: 0 on success, negative on error. 2306 */ 2307 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba) 2308 { 2309 int err; 2310 2311 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES); 2312 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS) 2313 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT; 2314 2315 /* nutrs and nutmrs are 0 based values */ 2316 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1; 2317 hba->nutmrs = 2318 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1; 2319 hba->reserved_slot = hba->nutrs - 1; 2320 2321 /* Read crypto capabilities */ 2322 err = ufshcd_hba_init_crypto_capabilities(hba); 2323 if (err) { 2324 dev_err(hba->dev, "crypto setup failed\n"); 2325 return err; 2326 } 2327 2328 hba->mcq_sup = FIELD_GET(MASK_MCQ_SUPPORT, hba->capabilities); 2329 if (!hba->mcq_sup) 2330 return 0; 2331 2332 hba->mcq_capabilities = ufshcd_readl(hba, REG_MCQCAP); 2333 hba->ext_iid_sup = FIELD_GET(MASK_EXT_IID_SUPPORT, 2334 hba->mcq_capabilities); 2335 2336 return 0; 2337 } 2338 2339 /** 2340 * ufshcd_ready_for_uic_cmd - Check if controller is ready 2341 * to accept UIC commands 2342 * @hba: per adapter instance 2343 * Return true on success, else false 2344 */ 2345 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba) 2346 { 2347 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY; 2348 } 2349 2350 /** 2351 * ufshcd_get_upmcrs - Get the power mode change request status 2352 * @hba: Pointer to adapter instance 2353 * 2354 * This function gets the UPMCRS field of HCS register 2355 * Returns value of UPMCRS field 2356 */ 2357 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba) 2358 { 2359 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7; 2360 } 2361 2362 /** 2363 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer 2364 * @hba: per adapter instance 2365 * @uic_cmd: UIC command 2366 */ 2367 static inline void 2368 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd) 2369 { 2370 lockdep_assert_held(&hba->uic_cmd_mutex); 2371 2372 WARN_ON(hba->active_uic_cmd); 2373 2374 hba->active_uic_cmd = uic_cmd; 2375 2376 /* Write Args */ 2377 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1); 2378 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2); 2379 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3); 2380 2381 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND); 2382 2383 /* Write UIC Cmd */ 2384 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK, 2385 REG_UIC_COMMAND); 2386 } 2387 2388 /** 2389 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command 2390 * @hba: per adapter instance 2391 * @uic_cmd: UIC command 2392 * 2393 * Returns 0 only if success. 2394 */ 2395 static int 2396 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd) 2397 { 2398 int ret; 2399 unsigned long flags; 2400 2401 lockdep_assert_held(&hba->uic_cmd_mutex); 2402 2403 if (wait_for_completion_timeout(&uic_cmd->done, 2404 msecs_to_jiffies(UIC_CMD_TIMEOUT))) { 2405 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT; 2406 } else { 2407 ret = -ETIMEDOUT; 2408 dev_err(hba->dev, 2409 "uic cmd 0x%x with arg3 0x%x completion timeout\n", 2410 uic_cmd->command, uic_cmd->argument3); 2411 2412 if (!uic_cmd->cmd_active) { 2413 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n", 2414 __func__); 2415 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT; 2416 } 2417 } 2418 2419 spin_lock_irqsave(hba->host->host_lock, flags); 2420 hba->active_uic_cmd = NULL; 2421 spin_unlock_irqrestore(hba->host->host_lock, flags); 2422 2423 return ret; 2424 } 2425 2426 /** 2427 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result 2428 * @hba: per adapter instance 2429 * @uic_cmd: UIC command 2430 * @completion: initialize the completion only if this is set to true 2431 * 2432 * Returns 0 only if success. 2433 */ 2434 static int 2435 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd, 2436 bool completion) 2437 { 2438 lockdep_assert_held(&hba->uic_cmd_mutex); 2439 lockdep_assert_held(hba->host->host_lock); 2440 2441 if (!ufshcd_ready_for_uic_cmd(hba)) { 2442 dev_err(hba->dev, 2443 "Controller not ready to accept UIC commands\n"); 2444 return -EIO; 2445 } 2446 2447 if (completion) 2448 init_completion(&uic_cmd->done); 2449 2450 uic_cmd->cmd_active = 1; 2451 ufshcd_dispatch_uic_cmd(hba, uic_cmd); 2452 2453 return 0; 2454 } 2455 2456 /** 2457 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result 2458 * @hba: per adapter instance 2459 * @uic_cmd: UIC command 2460 * 2461 * Returns 0 only if success. 2462 */ 2463 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd) 2464 { 2465 int ret; 2466 unsigned long flags; 2467 2468 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD) 2469 return 0; 2470 2471 ufshcd_hold(hba, false); 2472 mutex_lock(&hba->uic_cmd_mutex); 2473 ufshcd_add_delay_before_dme_cmd(hba); 2474 2475 spin_lock_irqsave(hba->host->host_lock, flags); 2476 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true); 2477 spin_unlock_irqrestore(hba->host->host_lock, flags); 2478 if (!ret) 2479 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd); 2480 2481 mutex_unlock(&hba->uic_cmd_mutex); 2482 2483 ufshcd_release(hba); 2484 return ret; 2485 } 2486 2487 /** 2488 * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format) 2489 * @hba: per-adapter instance 2490 * @lrbp: pointer to local reference block 2491 * @sg_entries: The number of sg lists actually used 2492 * @sg_list: Pointer to SG list 2493 */ 2494 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries, 2495 struct scatterlist *sg_list) 2496 { 2497 struct ufshcd_sg_entry *prd; 2498 struct scatterlist *sg; 2499 int i; 2500 2501 if (sg_entries) { 2502 2503 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) 2504 lrbp->utr_descriptor_ptr->prd_table_length = 2505 cpu_to_le16(sg_entries * ufshcd_sg_entry_size(hba)); 2506 else 2507 lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries); 2508 2509 prd = lrbp->ucd_prdt_ptr; 2510 2511 for_each_sg(sg_list, sg, sg_entries, i) { 2512 const unsigned int len = sg_dma_len(sg); 2513 2514 /* 2515 * From the UFSHCI spec: "Data Byte Count (DBC): A '0' 2516 * based value that indicates the length, in bytes, of 2517 * the data block. A maximum of length of 256KB may 2518 * exist for any entry. Bits 1:0 of this field shall be 2519 * 11b to indicate Dword granularity. A value of '3' 2520 * indicates 4 bytes, '7' indicates 8 bytes, etc." 2521 */ 2522 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len); 2523 prd->size = cpu_to_le32(len - 1); 2524 prd->addr = cpu_to_le64(sg->dma_address); 2525 prd->reserved = 0; 2526 prd = (void *)prd + ufshcd_sg_entry_size(hba); 2527 } 2528 } else { 2529 lrbp->utr_descriptor_ptr->prd_table_length = 0; 2530 } 2531 } 2532 2533 /** 2534 * ufshcd_map_sg - Map scatter-gather list to prdt 2535 * @hba: per adapter instance 2536 * @lrbp: pointer to local reference block 2537 * 2538 * Returns 0 in case of success, non-zero value in case of failure 2539 */ 2540 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 2541 { 2542 struct scsi_cmnd *cmd = lrbp->cmd; 2543 int sg_segments = scsi_dma_map(cmd); 2544 2545 if (sg_segments < 0) 2546 return sg_segments; 2547 2548 ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd)); 2549 2550 return 0; 2551 } 2552 2553 /** 2554 * ufshcd_enable_intr - enable interrupts 2555 * @hba: per adapter instance 2556 * @intrs: interrupt bits 2557 */ 2558 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs) 2559 { 2560 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE); 2561 2562 if (hba->ufs_version == ufshci_version(1, 0)) { 2563 u32 rw; 2564 rw = set & INTERRUPT_MASK_RW_VER_10; 2565 set = rw | ((set ^ intrs) & intrs); 2566 } else { 2567 set |= intrs; 2568 } 2569 2570 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE); 2571 } 2572 2573 /** 2574 * ufshcd_disable_intr - disable interrupts 2575 * @hba: per adapter instance 2576 * @intrs: interrupt bits 2577 */ 2578 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs) 2579 { 2580 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE); 2581 2582 if (hba->ufs_version == ufshci_version(1, 0)) { 2583 u32 rw; 2584 rw = (set & INTERRUPT_MASK_RW_VER_10) & 2585 ~(intrs & INTERRUPT_MASK_RW_VER_10); 2586 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10); 2587 2588 } else { 2589 set &= ~intrs; 2590 } 2591 2592 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE); 2593 } 2594 2595 /** 2596 * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request 2597 * descriptor according to request 2598 * @lrbp: pointer to local reference block 2599 * @upiu_flags: flags required in the header 2600 * @cmd_dir: requests data direction 2601 * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments) 2602 */ 2603 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp, u8 *upiu_flags, 2604 enum dma_data_direction cmd_dir, int ehs_length) 2605 { 2606 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr; 2607 u32 data_direction; 2608 u32 dword_0; 2609 u32 dword_1 = 0; 2610 u32 dword_3 = 0; 2611 2612 if (cmd_dir == DMA_FROM_DEVICE) { 2613 data_direction = UTP_DEVICE_TO_HOST; 2614 *upiu_flags = UPIU_CMD_FLAGS_READ; 2615 } else if (cmd_dir == DMA_TO_DEVICE) { 2616 data_direction = UTP_HOST_TO_DEVICE; 2617 *upiu_flags = UPIU_CMD_FLAGS_WRITE; 2618 } else { 2619 data_direction = UTP_NO_DATA_TRANSFER; 2620 *upiu_flags = UPIU_CMD_FLAGS_NONE; 2621 } 2622 2623 dword_0 = data_direction | (lrbp->command_type << UPIU_COMMAND_TYPE_OFFSET) | 2624 ehs_length << 8; 2625 if (lrbp->intr_cmd) 2626 dword_0 |= UTP_REQ_DESC_INT_CMD; 2627 2628 /* Prepare crypto related dwords */ 2629 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3); 2630 2631 /* Transfer request descriptor header fields */ 2632 req_desc->header.dword_0 = cpu_to_le32(dword_0); 2633 req_desc->header.dword_1 = cpu_to_le32(dword_1); 2634 /* 2635 * assigning invalid value for command status. Controller 2636 * updates OCS on command completion, with the command 2637 * status 2638 */ 2639 req_desc->header.dword_2 = 2640 cpu_to_le32(OCS_INVALID_COMMAND_STATUS); 2641 req_desc->header.dword_3 = cpu_to_le32(dword_3); 2642 2643 req_desc->prd_table_length = 0; 2644 } 2645 2646 /** 2647 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc, 2648 * for scsi commands 2649 * @lrbp: local reference block pointer 2650 * @upiu_flags: flags 2651 */ 2652 static 2653 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags) 2654 { 2655 struct scsi_cmnd *cmd = lrbp->cmd; 2656 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr; 2657 unsigned short cdb_len; 2658 2659 /* command descriptor fields */ 2660 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD( 2661 UPIU_TRANSACTION_COMMAND, upiu_flags, 2662 lrbp->lun, lrbp->task_tag); 2663 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD( 2664 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0); 2665 2666 /* Total EHS length and Data segment length will be zero */ 2667 ucd_req_ptr->header.dword_2 = 0; 2668 2669 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length); 2670 2671 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE); 2672 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE); 2673 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len); 2674 2675 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp)); 2676 } 2677 2678 /** 2679 * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request 2680 * @hba: UFS hba 2681 * @lrbp: local reference block pointer 2682 * @upiu_flags: flags 2683 */ 2684 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba, 2685 struct ufshcd_lrb *lrbp, u8 upiu_flags) 2686 { 2687 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr; 2688 struct ufs_query *query = &hba->dev_cmd.query; 2689 u16 len = be16_to_cpu(query->request.upiu_req.length); 2690 2691 /* Query request header */ 2692 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD( 2693 UPIU_TRANSACTION_QUERY_REQ, upiu_flags, 2694 lrbp->lun, lrbp->task_tag); 2695 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD( 2696 0, query->request.query_func, 0, 0); 2697 2698 /* Data segment length only need for WRITE_DESC */ 2699 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC) 2700 ucd_req_ptr->header.dword_2 = 2701 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len); 2702 else 2703 ucd_req_ptr->header.dword_2 = 0; 2704 2705 /* Copy the Query Request buffer as is */ 2706 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req, 2707 QUERY_OSF_SIZE); 2708 2709 /* Copy the Descriptor */ 2710 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC) 2711 memcpy(ucd_req_ptr + 1, query->descriptor, len); 2712 2713 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp)); 2714 } 2715 2716 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp) 2717 { 2718 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr; 2719 2720 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req)); 2721 2722 /* command descriptor fields */ 2723 ucd_req_ptr->header.dword_0 = 2724 UPIU_HEADER_DWORD( 2725 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag); 2726 /* clear rest of the fields of basic header */ 2727 ucd_req_ptr->header.dword_1 = 0; 2728 ucd_req_ptr->header.dword_2 = 0; 2729 2730 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp)); 2731 } 2732 2733 /** 2734 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU) 2735 * for Device Management Purposes 2736 * @hba: per adapter instance 2737 * @lrbp: pointer to local reference block 2738 */ 2739 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba, 2740 struct ufshcd_lrb *lrbp) 2741 { 2742 u8 upiu_flags; 2743 int ret = 0; 2744 2745 if (hba->ufs_version <= ufshci_version(1, 1)) 2746 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE; 2747 else 2748 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE; 2749 2750 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0); 2751 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY) 2752 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags); 2753 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP) 2754 ufshcd_prepare_utp_nop_upiu(lrbp); 2755 else 2756 ret = -EINVAL; 2757 2758 return ret; 2759 } 2760 2761 /** 2762 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU) 2763 * for SCSI Purposes 2764 * @hba: per adapter instance 2765 * @lrbp: pointer to local reference block 2766 */ 2767 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 2768 { 2769 u8 upiu_flags; 2770 int ret = 0; 2771 2772 if (hba->ufs_version <= ufshci_version(1, 1)) 2773 lrbp->command_type = UTP_CMD_TYPE_SCSI; 2774 else 2775 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE; 2776 2777 if (likely(lrbp->cmd)) { 2778 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, lrbp->cmd->sc_data_direction, 0); 2779 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags); 2780 } else { 2781 ret = -EINVAL; 2782 } 2783 2784 return ret; 2785 } 2786 2787 /** 2788 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID 2789 * @upiu_wlun_id: UPIU W-LUN id 2790 * 2791 * Returns SCSI W-LUN id 2792 */ 2793 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id) 2794 { 2795 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE; 2796 } 2797 2798 static inline bool is_device_wlun(struct scsi_device *sdev) 2799 { 2800 return sdev->lun == 2801 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN); 2802 } 2803 2804 /* 2805 * Associate the UFS controller queue with the default and poll HCTX types. 2806 * Initialize the mq_map[] arrays. 2807 */ 2808 static void ufshcd_map_queues(struct Scsi_Host *shost) 2809 { 2810 struct ufs_hba *hba = shost_priv(shost); 2811 int i, queue_offset = 0; 2812 2813 if (!is_mcq_supported(hba)) { 2814 hba->nr_queues[HCTX_TYPE_DEFAULT] = 1; 2815 hba->nr_queues[HCTX_TYPE_READ] = 0; 2816 hba->nr_queues[HCTX_TYPE_POLL] = 1; 2817 hba->nr_hw_queues = 1; 2818 } 2819 2820 for (i = 0; i < shost->nr_maps; i++) { 2821 struct blk_mq_queue_map *map = &shost->tag_set.map[i]; 2822 2823 map->nr_queues = hba->nr_queues[i]; 2824 if (!map->nr_queues) 2825 continue; 2826 map->queue_offset = queue_offset; 2827 if (i == HCTX_TYPE_POLL && !is_mcq_supported(hba)) 2828 map->queue_offset = 0; 2829 2830 blk_mq_map_queues(map); 2831 queue_offset += map->nr_queues; 2832 } 2833 } 2834 2835 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i) 2836 { 2837 struct utp_transfer_cmd_desc *cmd_descp = (void *)hba->ucdl_base_addr + 2838 i * sizeof_utp_transfer_cmd_desc(hba); 2839 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr; 2840 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr + 2841 i * sizeof_utp_transfer_cmd_desc(hba); 2842 u16 response_offset = offsetof(struct utp_transfer_cmd_desc, 2843 response_upiu); 2844 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table); 2845 2846 lrb->utr_descriptor_ptr = utrdlp + i; 2847 lrb->utrd_dma_addr = hba->utrdl_dma_addr + 2848 i * sizeof(struct utp_transfer_req_desc); 2849 lrb->ucd_req_ptr = (struct utp_upiu_req *)cmd_descp->command_upiu; 2850 lrb->ucd_req_dma_addr = cmd_desc_element_addr; 2851 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp->response_upiu; 2852 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset; 2853 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp->prd_table; 2854 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset; 2855 } 2856 2857 /** 2858 * ufshcd_queuecommand - main entry point for SCSI requests 2859 * @host: SCSI host pointer 2860 * @cmd: command from SCSI Midlayer 2861 * 2862 * Returns 0 for success, non-zero in case of failure 2863 */ 2864 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd) 2865 { 2866 struct ufs_hba *hba = shost_priv(host); 2867 int tag = scsi_cmd_to_rq(cmd)->tag; 2868 struct ufshcd_lrb *lrbp; 2869 int err = 0; 2870 struct ufs_hw_queue *hwq = NULL; 2871 2872 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag); 2873 2874 /* 2875 * Allows the UFS error handler to wait for prior ufshcd_queuecommand() 2876 * calls. 2877 */ 2878 rcu_read_lock(); 2879 2880 switch (hba->ufshcd_state) { 2881 case UFSHCD_STATE_OPERATIONAL: 2882 break; 2883 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL: 2884 /* 2885 * SCSI error handler can call ->queuecommand() while UFS error 2886 * handler is in progress. Error interrupts could change the 2887 * state from UFSHCD_STATE_RESET to 2888 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests 2889 * being issued in that case. 2890 */ 2891 if (ufshcd_eh_in_progress(hba)) { 2892 err = SCSI_MLQUEUE_HOST_BUSY; 2893 goto out; 2894 } 2895 break; 2896 case UFSHCD_STATE_EH_SCHEDULED_FATAL: 2897 /* 2898 * pm_runtime_get_sync() is used at error handling preparation 2899 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's 2900 * PM ops, it can never be finished if we let SCSI layer keep 2901 * retrying it, which gets err handler stuck forever. Neither 2902 * can we let the scsi cmd pass through, because UFS is in bad 2903 * state, the scsi cmd may eventually time out, which will get 2904 * err handler blocked for too long. So, just fail the scsi cmd 2905 * sent from PM ops, err handler can recover PM error anyways. 2906 */ 2907 if (hba->pm_op_in_progress) { 2908 hba->force_reset = true; 2909 set_host_byte(cmd, DID_BAD_TARGET); 2910 scsi_done(cmd); 2911 goto out; 2912 } 2913 fallthrough; 2914 case UFSHCD_STATE_RESET: 2915 err = SCSI_MLQUEUE_HOST_BUSY; 2916 goto out; 2917 case UFSHCD_STATE_ERROR: 2918 set_host_byte(cmd, DID_ERROR); 2919 scsi_done(cmd); 2920 goto out; 2921 } 2922 2923 hba->req_abort_count = 0; 2924 2925 err = ufshcd_hold(hba, true); 2926 if (err) { 2927 err = SCSI_MLQUEUE_HOST_BUSY; 2928 goto out; 2929 } 2930 WARN_ON(ufshcd_is_clkgating_allowed(hba) && 2931 (hba->clk_gating.state != CLKS_ON)); 2932 2933 lrbp = &hba->lrb[tag]; 2934 WARN_ON(lrbp->cmd); 2935 lrbp->cmd = cmd; 2936 lrbp->task_tag = tag; 2937 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun); 2938 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba); 2939 2940 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp); 2941 2942 lrbp->req_abort_skip = false; 2943 2944 ufshpb_prep(hba, lrbp); 2945 2946 ufshcd_comp_scsi_upiu(hba, lrbp); 2947 2948 err = ufshcd_map_sg(hba, lrbp); 2949 if (err) { 2950 lrbp->cmd = NULL; 2951 ufshcd_release(hba); 2952 goto out; 2953 } 2954 2955 if (is_mcq_enabled(hba)) 2956 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd)); 2957 2958 ufshcd_send_command(hba, tag, hwq); 2959 2960 out: 2961 rcu_read_unlock(); 2962 2963 if (ufs_trigger_eh()) { 2964 unsigned long flags; 2965 2966 spin_lock_irqsave(hba->host->host_lock, flags); 2967 ufshcd_schedule_eh_work(hba); 2968 spin_unlock_irqrestore(hba->host->host_lock, flags); 2969 } 2970 2971 return err; 2972 } 2973 2974 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba, 2975 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag) 2976 { 2977 lrbp->cmd = NULL; 2978 lrbp->task_tag = tag; 2979 lrbp->lun = 0; /* device management cmd is not specific to any LUN */ 2980 lrbp->intr_cmd = true; /* No interrupt aggregation */ 2981 ufshcd_prepare_lrbp_crypto(NULL, lrbp); 2982 hba->dev_cmd.type = cmd_type; 2983 2984 return ufshcd_compose_devman_upiu(hba, lrbp); 2985 } 2986 2987 /* 2988 * Clear all the requests from the controller for which a bit has been set in 2989 * @mask and wait until the controller confirms that these requests have been 2990 * cleared. 2991 */ 2992 static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask) 2993 { 2994 unsigned long flags; 2995 2996 /* clear outstanding transaction before retry */ 2997 spin_lock_irqsave(hba->host->host_lock, flags); 2998 ufshcd_utrl_clear(hba, mask); 2999 spin_unlock_irqrestore(hba->host->host_lock, flags); 3000 3001 /* 3002 * wait for h/w to clear corresponding bit in door-bell. 3003 * max. wait is 1 sec. 3004 */ 3005 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL, 3006 mask, ~mask, 1000, 1000); 3007 } 3008 3009 static int 3010 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 3011 { 3012 struct ufs_query_res *query_res = &hba->dev_cmd.query.response; 3013 3014 /* Get the UPIU response */ 3015 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >> 3016 UPIU_RSP_CODE_OFFSET; 3017 return query_res->response; 3018 } 3019 3020 /** 3021 * ufshcd_dev_cmd_completion() - handles device management command responses 3022 * @hba: per adapter instance 3023 * @lrbp: pointer to local reference block 3024 */ 3025 static int 3026 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 3027 { 3028 int resp; 3029 int err = 0; 3030 3031 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0); 3032 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr); 3033 3034 switch (resp) { 3035 case UPIU_TRANSACTION_NOP_IN: 3036 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) { 3037 err = -EINVAL; 3038 dev_err(hba->dev, "%s: unexpected response %x\n", 3039 __func__, resp); 3040 } 3041 break; 3042 case UPIU_TRANSACTION_QUERY_RSP: 3043 err = ufshcd_check_query_response(hba, lrbp); 3044 if (!err) 3045 err = ufshcd_copy_query_response(hba, lrbp); 3046 break; 3047 case UPIU_TRANSACTION_REJECT_UPIU: 3048 /* TODO: handle Reject UPIU Response */ 3049 err = -EPERM; 3050 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n", 3051 __func__); 3052 break; 3053 case UPIU_TRANSACTION_RESPONSE: 3054 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) { 3055 err = -EINVAL; 3056 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp); 3057 } 3058 break; 3059 default: 3060 err = -EINVAL; 3061 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n", 3062 __func__, resp); 3063 break; 3064 } 3065 3066 return err; 3067 } 3068 3069 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba, 3070 struct ufshcd_lrb *lrbp, int max_timeout) 3071 { 3072 unsigned long time_left = msecs_to_jiffies(max_timeout); 3073 unsigned long flags; 3074 bool pending; 3075 int err; 3076 3077 retry: 3078 time_left = wait_for_completion_timeout(hba->dev_cmd.complete, 3079 time_left); 3080 3081 if (likely(time_left)) { 3082 /* 3083 * The completion handler called complete() and the caller of 3084 * this function still owns the @lrbp tag so the code below does 3085 * not trigger any race conditions. 3086 */ 3087 hba->dev_cmd.complete = NULL; 3088 err = ufshcd_get_tr_ocs(lrbp, hba->dev_cmd.cqe); 3089 if (!err) 3090 err = ufshcd_dev_cmd_completion(hba, lrbp); 3091 } else { 3092 err = -ETIMEDOUT; 3093 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n", 3094 __func__, lrbp->task_tag); 3095 if (ufshcd_clear_cmds(hba, 1U << lrbp->task_tag) == 0) { 3096 /* successfully cleared the command, retry if needed */ 3097 err = -EAGAIN; 3098 /* 3099 * Since clearing the command succeeded we also need to 3100 * clear the task tag bit from the outstanding_reqs 3101 * variable. 3102 */ 3103 spin_lock_irqsave(&hba->outstanding_lock, flags); 3104 pending = test_bit(lrbp->task_tag, 3105 &hba->outstanding_reqs); 3106 if (pending) { 3107 hba->dev_cmd.complete = NULL; 3108 __clear_bit(lrbp->task_tag, 3109 &hba->outstanding_reqs); 3110 } 3111 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 3112 3113 if (!pending) { 3114 /* 3115 * The completion handler ran while we tried to 3116 * clear the command. 3117 */ 3118 time_left = 1; 3119 goto retry; 3120 } 3121 } else { 3122 dev_err(hba->dev, "%s: failed to clear tag %d\n", 3123 __func__, lrbp->task_tag); 3124 3125 spin_lock_irqsave(&hba->outstanding_lock, flags); 3126 pending = test_bit(lrbp->task_tag, 3127 &hba->outstanding_reqs); 3128 if (pending) 3129 hba->dev_cmd.complete = NULL; 3130 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 3131 3132 if (!pending) { 3133 /* 3134 * The completion handler ran while we tried to 3135 * clear the command. 3136 */ 3137 time_left = 1; 3138 goto retry; 3139 } 3140 } 3141 } 3142 3143 return err; 3144 } 3145 3146 /** 3147 * ufshcd_exec_dev_cmd - API for sending device management requests 3148 * @hba: UFS hba 3149 * @cmd_type: specifies the type (NOP, Query...) 3150 * @timeout: timeout in milliseconds 3151 * 3152 * NOTE: Since there is only one available tag for device management commands, 3153 * it is expected you hold the hba->dev_cmd.lock mutex. 3154 */ 3155 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba, 3156 enum dev_cmd_type cmd_type, int timeout) 3157 { 3158 DECLARE_COMPLETION_ONSTACK(wait); 3159 const u32 tag = hba->reserved_slot; 3160 struct ufshcd_lrb *lrbp; 3161 int err; 3162 3163 /* Protects use of hba->reserved_slot. */ 3164 lockdep_assert_held(&hba->dev_cmd.lock); 3165 3166 down_read(&hba->clk_scaling_lock); 3167 3168 lrbp = &hba->lrb[tag]; 3169 WARN_ON(lrbp->cmd); 3170 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag); 3171 if (unlikely(err)) 3172 goto out; 3173 3174 hba->dev_cmd.complete = &wait; 3175 hba->dev_cmd.cqe = NULL; 3176 3177 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr); 3178 3179 ufshcd_send_command(hba, tag, hba->dev_cmd_queue); 3180 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout); 3181 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP, 3182 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr); 3183 3184 out: 3185 up_read(&hba->clk_scaling_lock); 3186 return err; 3187 } 3188 3189 /** 3190 * ufshcd_init_query() - init the query response and request parameters 3191 * @hba: per-adapter instance 3192 * @request: address of the request pointer to be initialized 3193 * @response: address of the response pointer to be initialized 3194 * @opcode: operation to perform 3195 * @idn: flag idn to access 3196 * @index: LU number to access 3197 * @selector: query/flag/descriptor further identification 3198 */ 3199 static inline void ufshcd_init_query(struct ufs_hba *hba, 3200 struct ufs_query_req **request, struct ufs_query_res **response, 3201 enum query_opcode opcode, u8 idn, u8 index, u8 selector) 3202 { 3203 *request = &hba->dev_cmd.query.request; 3204 *response = &hba->dev_cmd.query.response; 3205 memset(*request, 0, sizeof(struct ufs_query_req)); 3206 memset(*response, 0, sizeof(struct ufs_query_res)); 3207 (*request)->upiu_req.opcode = opcode; 3208 (*request)->upiu_req.idn = idn; 3209 (*request)->upiu_req.index = index; 3210 (*request)->upiu_req.selector = selector; 3211 } 3212 3213 static int ufshcd_query_flag_retry(struct ufs_hba *hba, 3214 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res) 3215 { 3216 int ret; 3217 int retries; 3218 3219 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) { 3220 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res); 3221 if (ret) 3222 dev_dbg(hba->dev, 3223 "%s: failed with error %d, retries %d\n", 3224 __func__, ret, retries); 3225 else 3226 break; 3227 } 3228 3229 if (ret) 3230 dev_err(hba->dev, 3231 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n", 3232 __func__, opcode, idn, ret, retries); 3233 return ret; 3234 } 3235 3236 /** 3237 * ufshcd_query_flag() - API function for sending flag query requests 3238 * @hba: per-adapter instance 3239 * @opcode: flag query to perform 3240 * @idn: flag idn to access 3241 * @index: flag index to access 3242 * @flag_res: the flag value after the query request completes 3243 * 3244 * Returns 0 for success, non-zero in case of failure 3245 */ 3246 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode, 3247 enum flag_idn idn, u8 index, bool *flag_res) 3248 { 3249 struct ufs_query_req *request = NULL; 3250 struct ufs_query_res *response = NULL; 3251 int err, selector = 0; 3252 int timeout = QUERY_REQ_TIMEOUT; 3253 3254 BUG_ON(!hba); 3255 3256 ufshcd_hold(hba, false); 3257 mutex_lock(&hba->dev_cmd.lock); 3258 ufshcd_init_query(hba, &request, &response, opcode, idn, index, 3259 selector); 3260 3261 switch (opcode) { 3262 case UPIU_QUERY_OPCODE_SET_FLAG: 3263 case UPIU_QUERY_OPCODE_CLEAR_FLAG: 3264 case UPIU_QUERY_OPCODE_TOGGLE_FLAG: 3265 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST; 3266 break; 3267 case UPIU_QUERY_OPCODE_READ_FLAG: 3268 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST; 3269 if (!flag_res) { 3270 /* No dummy reads */ 3271 dev_err(hba->dev, "%s: Invalid argument for read request\n", 3272 __func__); 3273 err = -EINVAL; 3274 goto out_unlock; 3275 } 3276 break; 3277 default: 3278 dev_err(hba->dev, 3279 "%s: Expected query flag opcode but got = %d\n", 3280 __func__, opcode); 3281 err = -EINVAL; 3282 goto out_unlock; 3283 } 3284 3285 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout); 3286 3287 if (err) { 3288 dev_err(hba->dev, 3289 "%s: Sending flag query for idn %d failed, err = %d\n", 3290 __func__, idn, err); 3291 goto out_unlock; 3292 } 3293 3294 if (flag_res) 3295 *flag_res = (be32_to_cpu(response->upiu_res.value) & 3296 MASK_QUERY_UPIU_FLAG_LOC) & 0x1; 3297 3298 out_unlock: 3299 mutex_unlock(&hba->dev_cmd.lock); 3300 ufshcd_release(hba); 3301 return err; 3302 } 3303 3304 /** 3305 * ufshcd_query_attr - API function for sending attribute requests 3306 * @hba: per-adapter instance 3307 * @opcode: attribute opcode 3308 * @idn: attribute idn to access 3309 * @index: index field 3310 * @selector: selector field 3311 * @attr_val: the attribute value after the query request completes 3312 * 3313 * Returns 0 for success, non-zero in case of failure 3314 */ 3315 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode, 3316 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val) 3317 { 3318 struct ufs_query_req *request = NULL; 3319 struct ufs_query_res *response = NULL; 3320 int err; 3321 3322 BUG_ON(!hba); 3323 3324 if (!attr_val) { 3325 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n", 3326 __func__, opcode); 3327 return -EINVAL; 3328 } 3329 3330 ufshcd_hold(hba, false); 3331 3332 mutex_lock(&hba->dev_cmd.lock); 3333 ufshcd_init_query(hba, &request, &response, opcode, idn, index, 3334 selector); 3335 3336 switch (opcode) { 3337 case UPIU_QUERY_OPCODE_WRITE_ATTR: 3338 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST; 3339 request->upiu_req.value = cpu_to_be32(*attr_val); 3340 break; 3341 case UPIU_QUERY_OPCODE_READ_ATTR: 3342 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST; 3343 break; 3344 default: 3345 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n", 3346 __func__, opcode); 3347 err = -EINVAL; 3348 goto out_unlock; 3349 } 3350 3351 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT); 3352 3353 if (err) { 3354 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n", 3355 __func__, opcode, idn, index, err); 3356 goto out_unlock; 3357 } 3358 3359 *attr_val = be32_to_cpu(response->upiu_res.value); 3360 3361 out_unlock: 3362 mutex_unlock(&hba->dev_cmd.lock); 3363 ufshcd_release(hba); 3364 return err; 3365 } 3366 3367 /** 3368 * ufshcd_query_attr_retry() - API function for sending query 3369 * attribute with retries 3370 * @hba: per-adapter instance 3371 * @opcode: attribute opcode 3372 * @idn: attribute idn to access 3373 * @index: index field 3374 * @selector: selector field 3375 * @attr_val: the attribute value after the query request 3376 * completes 3377 * 3378 * Returns 0 for success, non-zero in case of failure 3379 */ 3380 int ufshcd_query_attr_retry(struct ufs_hba *hba, 3381 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector, 3382 u32 *attr_val) 3383 { 3384 int ret = 0; 3385 u32 retries; 3386 3387 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) { 3388 ret = ufshcd_query_attr(hba, opcode, idn, index, 3389 selector, attr_val); 3390 if (ret) 3391 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n", 3392 __func__, ret, retries); 3393 else 3394 break; 3395 } 3396 3397 if (ret) 3398 dev_err(hba->dev, 3399 "%s: query attribute, idn %d, failed with error %d after %d retries\n", 3400 __func__, idn, ret, QUERY_REQ_RETRIES); 3401 return ret; 3402 } 3403 3404 static int __ufshcd_query_descriptor(struct ufs_hba *hba, 3405 enum query_opcode opcode, enum desc_idn idn, u8 index, 3406 u8 selector, u8 *desc_buf, int *buf_len) 3407 { 3408 struct ufs_query_req *request = NULL; 3409 struct ufs_query_res *response = NULL; 3410 int err; 3411 3412 BUG_ON(!hba); 3413 3414 if (!desc_buf) { 3415 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n", 3416 __func__, opcode); 3417 return -EINVAL; 3418 } 3419 3420 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) { 3421 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n", 3422 __func__, *buf_len); 3423 return -EINVAL; 3424 } 3425 3426 ufshcd_hold(hba, false); 3427 3428 mutex_lock(&hba->dev_cmd.lock); 3429 ufshcd_init_query(hba, &request, &response, opcode, idn, index, 3430 selector); 3431 hba->dev_cmd.query.descriptor = desc_buf; 3432 request->upiu_req.length = cpu_to_be16(*buf_len); 3433 3434 switch (opcode) { 3435 case UPIU_QUERY_OPCODE_WRITE_DESC: 3436 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST; 3437 break; 3438 case UPIU_QUERY_OPCODE_READ_DESC: 3439 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST; 3440 break; 3441 default: 3442 dev_err(hba->dev, 3443 "%s: Expected query descriptor opcode but got = 0x%.2x\n", 3444 __func__, opcode); 3445 err = -EINVAL; 3446 goto out_unlock; 3447 } 3448 3449 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT); 3450 3451 if (err) { 3452 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n", 3453 __func__, opcode, idn, index, err); 3454 goto out_unlock; 3455 } 3456 3457 *buf_len = be16_to_cpu(response->upiu_res.length); 3458 3459 out_unlock: 3460 hba->dev_cmd.query.descriptor = NULL; 3461 mutex_unlock(&hba->dev_cmd.lock); 3462 ufshcd_release(hba); 3463 return err; 3464 } 3465 3466 /** 3467 * ufshcd_query_descriptor_retry - API function for sending descriptor requests 3468 * @hba: per-adapter instance 3469 * @opcode: attribute opcode 3470 * @idn: attribute idn to access 3471 * @index: index field 3472 * @selector: selector field 3473 * @desc_buf: the buffer that contains the descriptor 3474 * @buf_len: length parameter passed to the device 3475 * 3476 * Returns 0 for success, non-zero in case of failure. 3477 * The buf_len parameter will contain, on return, the length parameter 3478 * received on the response. 3479 */ 3480 int ufshcd_query_descriptor_retry(struct ufs_hba *hba, 3481 enum query_opcode opcode, 3482 enum desc_idn idn, u8 index, 3483 u8 selector, 3484 u8 *desc_buf, int *buf_len) 3485 { 3486 int err; 3487 int retries; 3488 3489 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) { 3490 err = __ufshcd_query_descriptor(hba, opcode, idn, index, 3491 selector, desc_buf, buf_len); 3492 if (!err || err == -EINVAL) 3493 break; 3494 } 3495 3496 return err; 3497 } 3498 3499 /** 3500 * ufshcd_read_desc_param - read the specified descriptor parameter 3501 * @hba: Pointer to adapter instance 3502 * @desc_id: descriptor idn value 3503 * @desc_index: descriptor index 3504 * @param_offset: offset of the parameter to read 3505 * @param_read_buf: pointer to buffer where parameter would be read 3506 * @param_size: sizeof(param_read_buf) 3507 * 3508 * Return 0 in case of success, non-zero otherwise 3509 */ 3510 int ufshcd_read_desc_param(struct ufs_hba *hba, 3511 enum desc_idn desc_id, 3512 int desc_index, 3513 u8 param_offset, 3514 u8 *param_read_buf, 3515 u8 param_size) 3516 { 3517 int ret; 3518 u8 *desc_buf; 3519 int buff_len = QUERY_DESC_MAX_SIZE; 3520 bool is_kmalloc = true; 3521 3522 /* Safety check */ 3523 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size) 3524 return -EINVAL; 3525 3526 /* Check whether we need temp memory */ 3527 if (param_offset != 0 || param_size < buff_len) { 3528 desc_buf = kzalloc(buff_len, GFP_KERNEL); 3529 if (!desc_buf) 3530 return -ENOMEM; 3531 } else { 3532 desc_buf = param_read_buf; 3533 is_kmalloc = false; 3534 } 3535 3536 /* Request for full descriptor */ 3537 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC, 3538 desc_id, desc_index, 0, 3539 desc_buf, &buff_len); 3540 if (ret) { 3541 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n", 3542 __func__, desc_id, desc_index, param_offset, ret); 3543 goto out; 3544 } 3545 3546 /* Update descriptor length */ 3547 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET]; 3548 3549 if (param_offset >= buff_len) { 3550 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n", 3551 __func__, param_offset, desc_id, buff_len); 3552 ret = -EINVAL; 3553 goto out; 3554 } 3555 3556 /* Sanity check */ 3557 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) { 3558 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n", 3559 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]); 3560 ret = -EINVAL; 3561 goto out; 3562 } 3563 3564 if (is_kmalloc) { 3565 /* Make sure we don't copy more data than available */ 3566 if (param_offset >= buff_len) 3567 ret = -EINVAL; 3568 else 3569 memcpy(param_read_buf, &desc_buf[param_offset], 3570 min_t(u32, param_size, buff_len - param_offset)); 3571 } 3572 out: 3573 if (is_kmalloc) 3574 kfree(desc_buf); 3575 return ret; 3576 } 3577 3578 /** 3579 * struct uc_string_id - unicode string 3580 * 3581 * @len: size of this descriptor inclusive 3582 * @type: descriptor type 3583 * @uc: unicode string character 3584 */ 3585 struct uc_string_id { 3586 u8 len; 3587 u8 type; 3588 wchar_t uc[]; 3589 } __packed; 3590 3591 /* replace non-printable or non-ASCII characters with spaces */ 3592 static inline char ufshcd_remove_non_printable(u8 ch) 3593 { 3594 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' '; 3595 } 3596 3597 /** 3598 * ufshcd_read_string_desc - read string descriptor 3599 * @hba: pointer to adapter instance 3600 * @desc_index: descriptor index 3601 * @buf: pointer to buffer where descriptor would be read, 3602 * the caller should free the memory. 3603 * @ascii: if true convert from unicode to ascii characters 3604 * null terminated string. 3605 * 3606 * Return: 3607 * * string size on success. 3608 * * -ENOMEM: on allocation failure 3609 * * -EINVAL: on a wrong parameter 3610 */ 3611 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, 3612 u8 **buf, bool ascii) 3613 { 3614 struct uc_string_id *uc_str; 3615 u8 *str; 3616 int ret; 3617 3618 if (!buf) 3619 return -EINVAL; 3620 3621 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL); 3622 if (!uc_str) 3623 return -ENOMEM; 3624 3625 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0, 3626 (u8 *)uc_str, QUERY_DESC_MAX_SIZE); 3627 if (ret < 0) { 3628 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n", 3629 QUERY_REQ_RETRIES, ret); 3630 str = NULL; 3631 goto out; 3632 } 3633 3634 if (uc_str->len <= QUERY_DESC_HDR_SIZE) { 3635 dev_dbg(hba->dev, "String Desc is of zero length\n"); 3636 str = NULL; 3637 ret = 0; 3638 goto out; 3639 } 3640 3641 if (ascii) { 3642 ssize_t ascii_len; 3643 int i; 3644 /* remove header and divide by 2 to move from UTF16 to UTF8 */ 3645 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1; 3646 str = kzalloc(ascii_len, GFP_KERNEL); 3647 if (!str) { 3648 ret = -ENOMEM; 3649 goto out; 3650 } 3651 3652 /* 3653 * the descriptor contains string in UTF16 format 3654 * we need to convert to utf-8 so it can be displayed 3655 */ 3656 ret = utf16s_to_utf8s(uc_str->uc, 3657 uc_str->len - QUERY_DESC_HDR_SIZE, 3658 UTF16_BIG_ENDIAN, str, ascii_len); 3659 3660 /* replace non-printable or non-ASCII characters with spaces */ 3661 for (i = 0; i < ret; i++) 3662 str[i] = ufshcd_remove_non_printable(str[i]); 3663 3664 str[ret++] = '\0'; 3665 3666 } else { 3667 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL); 3668 if (!str) { 3669 ret = -ENOMEM; 3670 goto out; 3671 } 3672 ret = uc_str->len; 3673 } 3674 out: 3675 *buf = str; 3676 kfree(uc_str); 3677 return ret; 3678 } 3679 3680 /** 3681 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter 3682 * @hba: Pointer to adapter instance 3683 * @lun: lun id 3684 * @param_offset: offset of the parameter to read 3685 * @param_read_buf: pointer to buffer where parameter would be read 3686 * @param_size: sizeof(param_read_buf) 3687 * 3688 * Return 0 in case of success, non-zero otherwise 3689 */ 3690 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba, 3691 int lun, 3692 enum unit_desc_param param_offset, 3693 u8 *param_read_buf, 3694 u32 param_size) 3695 { 3696 /* 3697 * Unit descriptors are only available for general purpose LUs (LUN id 3698 * from 0 to 7) and RPMB Well known LU. 3699 */ 3700 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun)) 3701 return -EOPNOTSUPP; 3702 3703 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun, 3704 param_offset, param_read_buf, param_size); 3705 } 3706 3707 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba) 3708 { 3709 int err = 0; 3710 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US; 3711 3712 if (hba->dev_info.wspecversion >= 0x300) { 3713 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 3714 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0, 3715 &gating_wait); 3716 if (err) 3717 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n", 3718 err, gating_wait); 3719 3720 if (gating_wait == 0) { 3721 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US; 3722 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n", 3723 gating_wait); 3724 } 3725 3726 hba->dev_info.clk_gating_wait_us = gating_wait; 3727 } 3728 3729 return err; 3730 } 3731 3732 /** 3733 * ufshcd_memory_alloc - allocate memory for host memory space data structures 3734 * @hba: per adapter instance 3735 * 3736 * 1. Allocate DMA memory for Command Descriptor array 3737 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT 3738 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL). 3739 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List 3740 * (UTMRDL) 3741 * 4. Allocate memory for local reference block(lrb). 3742 * 3743 * Returns 0 for success, non-zero in case of failure 3744 */ 3745 static int ufshcd_memory_alloc(struct ufs_hba *hba) 3746 { 3747 size_t utmrdl_size, utrdl_size, ucdl_size; 3748 3749 /* Allocate memory for UTP command descriptors */ 3750 ucdl_size = sizeof_utp_transfer_cmd_desc(hba) * hba->nutrs; 3751 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev, 3752 ucdl_size, 3753 &hba->ucdl_dma_addr, 3754 GFP_KERNEL); 3755 3756 /* 3757 * UFSHCI requires UTP command descriptor to be 128 byte aligned. 3758 */ 3759 if (!hba->ucdl_base_addr || 3760 WARN_ON(hba->ucdl_dma_addr & (128 - 1))) { 3761 dev_err(hba->dev, 3762 "Command Descriptor Memory allocation failed\n"); 3763 goto out; 3764 } 3765 3766 /* 3767 * Allocate memory for UTP Transfer descriptors 3768 * UFSHCI requires 1024 byte alignment of UTRD 3769 */ 3770 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs); 3771 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev, 3772 utrdl_size, 3773 &hba->utrdl_dma_addr, 3774 GFP_KERNEL); 3775 if (!hba->utrdl_base_addr || 3776 WARN_ON(hba->utrdl_dma_addr & (1024 - 1))) { 3777 dev_err(hba->dev, 3778 "Transfer Descriptor Memory allocation failed\n"); 3779 goto out; 3780 } 3781 3782 /* 3783 * Skip utmrdl allocation; it may have been 3784 * allocated during first pass and not released during 3785 * MCQ memory allocation. 3786 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq() 3787 */ 3788 if (hba->utmrdl_base_addr) 3789 goto skip_utmrdl; 3790 /* 3791 * Allocate memory for UTP Task Management descriptors 3792 * UFSHCI requires 1024 byte alignment of UTMRD 3793 */ 3794 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs; 3795 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev, 3796 utmrdl_size, 3797 &hba->utmrdl_dma_addr, 3798 GFP_KERNEL); 3799 if (!hba->utmrdl_base_addr || 3800 WARN_ON(hba->utmrdl_dma_addr & (1024 - 1))) { 3801 dev_err(hba->dev, 3802 "Task Management Descriptor Memory allocation failed\n"); 3803 goto out; 3804 } 3805 3806 skip_utmrdl: 3807 /* Allocate memory for local reference block */ 3808 hba->lrb = devm_kcalloc(hba->dev, 3809 hba->nutrs, sizeof(struct ufshcd_lrb), 3810 GFP_KERNEL); 3811 if (!hba->lrb) { 3812 dev_err(hba->dev, "LRB Memory allocation failed\n"); 3813 goto out; 3814 } 3815 return 0; 3816 out: 3817 return -ENOMEM; 3818 } 3819 3820 /** 3821 * ufshcd_host_memory_configure - configure local reference block with 3822 * memory offsets 3823 * @hba: per adapter instance 3824 * 3825 * Configure Host memory space 3826 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA 3827 * address. 3828 * 2. Update each UTRD with Response UPIU offset, Response UPIU length 3829 * and PRDT offset. 3830 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT 3831 * into local reference block. 3832 */ 3833 static void ufshcd_host_memory_configure(struct ufs_hba *hba) 3834 { 3835 struct utp_transfer_req_desc *utrdlp; 3836 dma_addr_t cmd_desc_dma_addr; 3837 dma_addr_t cmd_desc_element_addr; 3838 u16 response_offset; 3839 u16 prdt_offset; 3840 int cmd_desc_size; 3841 int i; 3842 3843 utrdlp = hba->utrdl_base_addr; 3844 3845 response_offset = 3846 offsetof(struct utp_transfer_cmd_desc, response_upiu); 3847 prdt_offset = 3848 offsetof(struct utp_transfer_cmd_desc, prd_table); 3849 3850 cmd_desc_size = sizeof_utp_transfer_cmd_desc(hba); 3851 cmd_desc_dma_addr = hba->ucdl_dma_addr; 3852 3853 for (i = 0; i < hba->nutrs; i++) { 3854 /* Configure UTRD with command descriptor base address */ 3855 cmd_desc_element_addr = 3856 (cmd_desc_dma_addr + (cmd_desc_size * i)); 3857 utrdlp[i].command_desc_base_addr_lo = 3858 cpu_to_le32(lower_32_bits(cmd_desc_element_addr)); 3859 utrdlp[i].command_desc_base_addr_hi = 3860 cpu_to_le32(upper_32_bits(cmd_desc_element_addr)); 3861 3862 /* Response upiu and prdt offset should be in double words */ 3863 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) { 3864 utrdlp[i].response_upiu_offset = 3865 cpu_to_le16(response_offset); 3866 utrdlp[i].prd_table_offset = 3867 cpu_to_le16(prdt_offset); 3868 utrdlp[i].response_upiu_length = 3869 cpu_to_le16(ALIGNED_UPIU_SIZE); 3870 } else { 3871 utrdlp[i].response_upiu_offset = 3872 cpu_to_le16(response_offset >> 2); 3873 utrdlp[i].prd_table_offset = 3874 cpu_to_le16(prdt_offset >> 2); 3875 utrdlp[i].response_upiu_length = 3876 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2); 3877 } 3878 3879 ufshcd_init_lrb(hba, &hba->lrb[i], i); 3880 } 3881 } 3882 3883 /** 3884 * ufshcd_dme_link_startup - Notify Unipro to perform link startup 3885 * @hba: per adapter instance 3886 * 3887 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer, 3888 * in order to initialize the Unipro link startup procedure. 3889 * Once the Unipro links are up, the device connected to the controller 3890 * is detected. 3891 * 3892 * Returns 0 on success, non-zero value on failure 3893 */ 3894 static int ufshcd_dme_link_startup(struct ufs_hba *hba) 3895 { 3896 struct uic_command uic_cmd = {0}; 3897 int ret; 3898 3899 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP; 3900 3901 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 3902 if (ret) 3903 dev_dbg(hba->dev, 3904 "dme-link-startup: error code %d\n", ret); 3905 return ret; 3906 } 3907 /** 3908 * ufshcd_dme_reset - UIC command for DME_RESET 3909 * @hba: per adapter instance 3910 * 3911 * DME_RESET command is issued in order to reset UniPro stack. 3912 * This function now deals with cold reset. 3913 * 3914 * Returns 0 on success, non-zero value on failure 3915 */ 3916 static int ufshcd_dme_reset(struct ufs_hba *hba) 3917 { 3918 struct uic_command uic_cmd = {0}; 3919 int ret; 3920 3921 uic_cmd.command = UIC_CMD_DME_RESET; 3922 3923 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 3924 if (ret) 3925 dev_err(hba->dev, 3926 "dme-reset: error code %d\n", ret); 3927 3928 return ret; 3929 } 3930 3931 int ufshcd_dme_configure_adapt(struct ufs_hba *hba, 3932 int agreed_gear, 3933 int adapt_val) 3934 { 3935 int ret; 3936 3937 if (agreed_gear < UFS_HS_G4) 3938 adapt_val = PA_NO_ADAPT; 3939 3940 ret = ufshcd_dme_set(hba, 3941 UIC_ARG_MIB(PA_TXHSADAPTTYPE), 3942 adapt_val); 3943 return ret; 3944 } 3945 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt); 3946 3947 /** 3948 * ufshcd_dme_enable - UIC command for DME_ENABLE 3949 * @hba: per adapter instance 3950 * 3951 * DME_ENABLE command is issued in order to enable UniPro stack. 3952 * 3953 * Returns 0 on success, non-zero value on failure 3954 */ 3955 static int ufshcd_dme_enable(struct ufs_hba *hba) 3956 { 3957 struct uic_command uic_cmd = {0}; 3958 int ret; 3959 3960 uic_cmd.command = UIC_CMD_DME_ENABLE; 3961 3962 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 3963 if (ret) 3964 dev_err(hba->dev, 3965 "dme-enable: error code %d\n", ret); 3966 3967 return ret; 3968 } 3969 3970 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba) 3971 { 3972 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000 3973 unsigned long min_sleep_time_us; 3974 3975 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS)) 3976 return; 3977 3978 /* 3979 * last_dme_cmd_tstamp will be 0 only for 1st call to 3980 * this function 3981 */ 3982 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) { 3983 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US; 3984 } else { 3985 unsigned long delta = 3986 (unsigned long) ktime_to_us( 3987 ktime_sub(ktime_get(), 3988 hba->last_dme_cmd_tstamp)); 3989 3990 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US) 3991 min_sleep_time_us = 3992 MIN_DELAY_BEFORE_DME_CMDS_US - delta; 3993 else 3994 return; /* no more delay required */ 3995 } 3996 3997 /* allow sleep for extra 50us if needed */ 3998 usleep_range(min_sleep_time_us, min_sleep_time_us + 50); 3999 } 4000 4001 /** 4002 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET 4003 * @hba: per adapter instance 4004 * @attr_sel: uic command argument1 4005 * @attr_set: attribute set type as uic command argument2 4006 * @mib_val: setting value as uic command argument3 4007 * @peer: indicate whether peer or local 4008 * 4009 * Returns 0 on success, non-zero value on failure 4010 */ 4011 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel, 4012 u8 attr_set, u32 mib_val, u8 peer) 4013 { 4014 struct uic_command uic_cmd = {0}; 4015 static const char *const action[] = { 4016 "dme-set", 4017 "dme-peer-set" 4018 }; 4019 const char *set = action[!!peer]; 4020 int ret; 4021 int retries = UFS_UIC_COMMAND_RETRIES; 4022 4023 uic_cmd.command = peer ? 4024 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET; 4025 uic_cmd.argument1 = attr_sel; 4026 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set); 4027 uic_cmd.argument3 = mib_val; 4028 4029 do { 4030 /* for peer attributes we retry upon failure */ 4031 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 4032 if (ret) 4033 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n", 4034 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret); 4035 } while (ret && peer && --retries); 4036 4037 if (ret) 4038 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n", 4039 set, UIC_GET_ATTR_ID(attr_sel), mib_val, 4040 UFS_UIC_COMMAND_RETRIES - retries); 4041 4042 return ret; 4043 } 4044 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr); 4045 4046 /** 4047 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET 4048 * @hba: per adapter instance 4049 * @attr_sel: uic command argument1 4050 * @mib_val: the value of the attribute as returned by the UIC command 4051 * @peer: indicate whether peer or local 4052 * 4053 * Returns 0 on success, non-zero value on failure 4054 */ 4055 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel, 4056 u32 *mib_val, u8 peer) 4057 { 4058 struct uic_command uic_cmd = {0}; 4059 static const char *const action[] = { 4060 "dme-get", 4061 "dme-peer-get" 4062 }; 4063 const char *get = action[!!peer]; 4064 int ret; 4065 int retries = UFS_UIC_COMMAND_RETRIES; 4066 struct ufs_pa_layer_attr orig_pwr_info; 4067 struct ufs_pa_layer_attr temp_pwr_info; 4068 bool pwr_mode_change = false; 4069 4070 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) { 4071 orig_pwr_info = hba->pwr_info; 4072 temp_pwr_info = orig_pwr_info; 4073 4074 if (orig_pwr_info.pwr_tx == FAST_MODE || 4075 orig_pwr_info.pwr_rx == FAST_MODE) { 4076 temp_pwr_info.pwr_tx = FASTAUTO_MODE; 4077 temp_pwr_info.pwr_rx = FASTAUTO_MODE; 4078 pwr_mode_change = true; 4079 } else if (orig_pwr_info.pwr_tx == SLOW_MODE || 4080 orig_pwr_info.pwr_rx == SLOW_MODE) { 4081 temp_pwr_info.pwr_tx = SLOWAUTO_MODE; 4082 temp_pwr_info.pwr_rx = SLOWAUTO_MODE; 4083 pwr_mode_change = true; 4084 } 4085 if (pwr_mode_change) { 4086 ret = ufshcd_change_power_mode(hba, &temp_pwr_info); 4087 if (ret) 4088 goto out; 4089 } 4090 } 4091 4092 uic_cmd.command = peer ? 4093 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET; 4094 uic_cmd.argument1 = attr_sel; 4095 4096 do { 4097 /* for peer attributes we retry upon failure */ 4098 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 4099 if (ret) 4100 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n", 4101 get, UIC_GET_ATTR_ID(attr_sel), ret); 4102 } while (ret && peer && --retries); 4103 4104 if (ret) 4105 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n", 4106 get, UIC_GET_ATTR_ID(attr_sel), 4107 UFS_UIC_COMMAND_RETRIES - retries); 4108 4109 if (mib_val && !ret) 4110 *mib_val = uic_cmd.argument3; 4111 4112 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE) 4113 && pwr_mode_change) 4114 ufshcd_change_power_mode(hba, &orig_pwr_info); 4115 out: 4116 return ret; 4117 } 4118 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr); 4119 4120 /** 4121 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power 4122 * state) and waits for it to take effect. 4123 * 4124 * @hba: per adapter instance 4125 * @cmd: UIC command to execute 4126 * 4127 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER & 4128 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host 4129 * and device UniPro link and hence it's final completion would be indicated by 4130 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in 4131 * addition to normal UIC command completion Status (UCCS). This function only 4132 * returns after the relevant status bits indicate the completion. 4133 * 4134 * Returns 0 on success, non-zero value on failure 4135 */ 4136 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd) 4137 { 4138 DECLARE_COMPLETION_ONSTACK(uic_async_done); 4139 unsigned long flags; 4140 u8 status; 4141 int ret; 4142 bool reenable_intr = false; 4143 4144 mutex_lock(&hba->uic_cmd_mutex); 4145 ufshcd_add_delay_before_dme_cmd(hba); 4146 4147 spin_lock_irqsave(hba->host->host_lock, flags); 4148 if (ufshcd_is_link_broken(hba)) { 4149 ret = -ENOLINK; 4150 goto out_unlock; 4151 } 4152 hba->uic_async_done = &uic_async_done; 4153 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) { 4154 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL); 4155 /* 4156 * Make sure UIC command completion interrupt is disabled before 4157 * issuing UIC command. 4158 */ 4159 wmb(); 4160 reenable_intr = true; 4161 } 4162 ret = __ufshcd_send_uic_cmd(hba, cmd, false); 4163 spin_unlock_irqrestore(hba->host->host_lock, flags); 4164 if (ret) { 4165 dev_err(hba->dev, 4166 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n", 4167 cmd->command, cmd->argument3, ret); 4168 goto out; 4169 } 4170 4171 if (!wait_for_completion_timeout(hba->uic_async_done, 4172 msecs_to_jiffies(UIC_CMD_TIMEOUT))) { 4173 dev_err(hba->dev, 4174 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n", 4175 cmd->command, cmd->argument3); 4176 4177 if (!cmd->cmd_active) { 4178 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n", 4179 __func__); 4180 goto check_upmcrs; 4181 } 4182 4183 ret = -ETIMEDOUT; 4184 goto out; 4185 } 4186 4187 check_upmcrs: 4188 status = ufshcd_get_upmcrs(hba); 4189 if (status != PWR_LOCAL) { 4190 dev_err(hba->dev, 4191 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n", 4192 cmd->command, status); 4193 ret = (status != PWR_OK) ? status : -1; 4194 } 4195 out: 4196 if (ret) { 4197 ufshcd_print_host_state(hba); 4198 ufshcd_print_pwr_info(hba); 4199 ufshcd_print_evt_hist(hba); 4200 } 4201 4202 spin_lock_irqsave(hba->host->host_lock, flags); 4203 hba->active_uic_cmd = NULL; 4204 hba->uic_async_done = NULL; 4205 if (reenable_intr) 4206 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL); 4207 if (ret) { 4208 ufshcd_set_link_broken(hba); 4209 ufshcd_schedule_eh_work(hba); 4210 } 4211 out_unlock: 4212 spin_unlock_irqrestore(hba->host->host_lock, flags); 4213 mutex_unlock(&hba->uic_cmd_mutex); 4214 4215 return ret; 4216 } 4217 4218 /** 4219 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage 4220 * using DME_SET primitives. 4221 * @hba: per adapter instance 4222 * @mode: powr mode value 4223 * 4224 * Returns 0 on success, non-zero value on failure 4225 */ 4226 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode) 4227 { 4228 struct uic_command uic_cmd = {0}; 4229 int ret; 4230 4231 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) { 4232 ret = ufshcd_dme_set(hba, 4233 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1); 4234 if (ret) { 4235 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n", 4236 __func__, ret); 4237 goto out; 4238 } 4239 } 4240 4241 uic_cmd.command = UIC_CMD_DME_SET; 4242 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE); 4243 uic_cmd.argument3 = mode; 4244 ufshcd_hold(hba, false); 4245 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd); 4246 ufshcd_release(hba); 4247 4248 out: 4249 return ret; 4250 } 4251 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode); 4252 4253 int ufshcd_link_recovery(struct ufs_hba *hba) 4254 { 4255 int ret; 4256 unsigned long flags; 4257 4258 spin_lock_irqsave(hba->host->host_lock, flags); 4259 hba->ufshcd_state = UFSHCD_STATE_RESET; 4260 ufshcd_set_eh_in_progress(hba); 4261 spin_unlock_irqrestore(hba->host->host_lock, flags); 4262 4263 /* Reset the attached device */ 4264 ufshcd_device_reset(hba); 4265 4266 ret = ufshcd_host_reset_and_restore(hba); 4267 4268 spin_lock_irqsave(hba->host->host_lock, flags); 4269 if (ret) 4270 hba->ufshcd_state = UFSHCD_STATE_ERROR; 4271 ufshcd_clear_eh_in_progress(hba); 4272 spin_unlock_irqrestore(hba->host->host_lock, flags); 4273 4274 if (ret) 4275 dev_err(hba->dev, "%s: link recovery failed, err %d", 4276 __func__, ret); 4277 4278 return ret; 4279 } 4280 EXPORT_SYMBOL_GPL(ufshcd_link_recovery); 4281 4282 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba) 4283 { 4284 int ret; 4285 struct uic_command uic_cmd = {0}; 4286 ktime_t start = ktime_get(); 4287 4288 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE); 4289 4290 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER; 4291 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd); 4292 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter", 4293 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 4294 4295 if (ret) 4296 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n", 4297 __func__, ret); 4298 else 4299 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, 4300 POST_CHANGE); 4301 4302 return ret; 4303 } 4304 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter); 4305 4306 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba) 4307 { 4308 struct uic_command uic_cmd = {0}; 4309 int ret; 4310 ktime_t start = ktime_get(); 4311 4312 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE); 4313 4314 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT; 4315 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd); 4316 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit", 4317 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 4318 4319 if (ret) { 4320 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n", 4321 __func__, ret); 4322 } else { 4323 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, 4324 POST_CHANGE); 4325 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock(); 4326 hba->ufs_stats.hibern8_exit_cnt++; 4327 } 4328 4329 return ret; 4330 } 4331 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit); 4332 4333 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit) 4334 { 4335 unsigned long flags; 4336 bool update = false; 4337 4338 if (!ufshcd_is_auto_hibern8_supported(hba)) 4339 return; 4340 4341 spin_lock_irqsave(hba->host->host_lock, flags); 4342 if (hba->ahit != ahit) { 4343 hba->ahit = ahit; 4344 update = true; 4345 } 4346 spin_unlock_irqrestore(hba->host->host_lock, flags); 4347 4348 if (update && 4349 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) { 4350 ufshcd_rpm_get_sync(hba); 4351 ufshcd_hold(hba, false); 4352 ufshcd_auto_hibern8_enable(hba); 4353 ufshcd_release(hba); 4354 ufshcd_rpm_put_sync(hba); 4355 } 4356 } 4357 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update); 4358 4359 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba) 4360 { 4361 if (!ufshcd_is_auto_hibern8_supported(hba)) 4362 return; 4363 4364 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER); 4365 } 4366 4367 /** 4368 * ufshcd_init_pwr_info - setting the POR (power on reset) 4369 * values in hba power info 4370 * @hba: per-adapter instance 4371 */ 4372 static void ufshcd_init_pwr_info(struct ufs_hba *hba) 4373 { 4374 hba->pwr_info.gear_rx = UFS_PWM_G1; 4375 hba->pwr_info.gear_tx = UFS_PWM_G1; 4376 hba->pwr_info.lane_rx = 1; 4377 hba->pwr_info.lane_tx = 1; 4378 hba->pwr_info.pwr_rx = SLOWAUTO_MODE; 4379 hba->pwr_info.pwr_tx = SLOWAUTO_MODE; 4380 hba->pwr_info.hs_rate = 0; 4381 } 4382 4383 /** 4384 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device 4385 * @hba: per-adapter instance 4386 */ 4387 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba) 4388 { 4389 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info; 4390 4391 if (hba->max_pwr_info.is_valid) 4392 return 0; 4393 4394 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) { 4395 pwr_info->pwr_tx = FASTAUTO_MODE; 4396 pwr_info->pwr_rx = FASTAUTO_MODE; 4397 } else { 4398 pwr_info->pwr_tx = FAST_MODE; 4399 pwr_info->pwr_rx = FAST_MODE; 4400 } 4401 pwr_info->hs_rate = PA_HS_MODE_B; 4402 4403 /* Get the connected lane count */ 4404 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES), 4405 &pwr_info->lane_rx); 4406 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES), 4407 &pwr_info->lane_tx); 4408 4409 if (!pwr_info->lane_rx || !pwr_info->lane_tx) { 4410 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n", 4411 __func__, 4412 pwr_info->lane_rx, 4413 pwr_info->lane_tx); 4414 return -EINVAL; 4415 } 4416 4417 /* 4418 * First, get the maximum gears of HS speed. 4419 * If a zero value, it means there is no HSGEAR capability. 4420 * Then, get the maximum gears of PWM speed. 4421 */ 4422 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx); 4423 if (!pwr_info->gear_rx) { 4424 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR), 4425 &pwr_info->gear_rx); 4426 if (!pwr_info->gear_rx) { 4427 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n", 4428 __func__, pwr_info->gear_rx); 4429 return -EINVAL; 4430 } 4431 pwr_info->pwr_rx = SLOW_MODE; 4432 } 4433 4434 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), 4435 &pwr_info->gear_tx); 4436 if (!pwr_info->gear_tx) { 4437 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR), 4438 &pwr_info->gear_tx); 4439 if (!pwr_info->gear_tx) { 4440 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n", 4441 __func__, pwr_info->gear_tx); 4442 return -EINVAL; 4443 } 4444 pwr_info->pwr_tx = SLOW_MODE; 4445 } 4446 4447 hba->max_pwr_info.is_valid = true; 4448 return 0; 4449 } 4450 4451 static int ufshcd_change_power_mode(struct ufs_hba *hba, 4452 struct ufs_pa_layer_attr *pwr_mode) 4453 { 4454 int ret; 4455 4456 /* if already configured to the requested pwr_mode */ 4457 if (!hba->force_pmc && 4458 pwr_mode->gear_rx == hba->pwr_info.gear_rx && 4459 pwr_mode->gear_tx == hba->pwr_info.gear_tx && 4460 pwr_mode->lane_rx == hba->pwr_info.lane_rx && 4461 pwr_mode->lane_tx == hba->pwr_info.lane_tx && 4462 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx && 4463 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx && 4464 pwr_mode->hs_rate == hba->pwr_info.hs_rate) { 4465 dev_dbg(hba->dev, "%s: power already configured\n", __func__); 4466 return 0; 4467 } 4468 4469 /* 4470 * Configure attributes for power mode change with below. 4471 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION, 4472 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION, 4473 * - PA_HSSERIES 4474 */ 4475 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx); 4476 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES), 4477 pwr_mode->lane_rx); 4478 if (pwr_mode->pwr_rx == FASTAUTO_MODE || 4479 pwr_mode->pwr_rx == FAST_MODE) 4480 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true); 4481 else 4482 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false); 4483 4484 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx); 4485 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES), 4486 pwr_mode->lane_tx); 4487 if (pwr_mode->pwr_tx == FASTAUTO_MODE || 4488 pwr_mode->pwr_tx == FAST_MODE) 4489 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true); 4490 else 4491 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false); 4492 4493 if (pwr_mode->pwr_rx == FASTAUTO_MODE || 4494 pwr_mode->pwr_tx == FASTAUTO_MODE || 4495 pwr_mode->pwr_rx == FAST_MODE || 4496 pwr_mode->pwr_tx == FAST_MODE) 4497 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES), 4498 pwr_mode->hs_rate); 4499 4500 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) { 4501 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0), 4502 DL_FC0ProtectionTimeOutVal_Default); 4503 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1), 4504 DL_TC0ReplayTimeOutVal_Default); 4505 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2), 4506 DL_AFC0ReqTimeOutVal_Default); 4507 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3), 4508 DL_FC1ProtectionTimeOutVal_Default); 4509 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4), 4510 DL_TC1ReplayTimeOutVal_Default); 4511 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5), 4512 DL_AFC1ReqTimeOutVal_Default); 4513 4514 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal), 4515 DL_FC0ProtectionTimeOutVal_Default); 4516 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal), 4517 DL_TC0ReplayTimeOutVal_Default); 4518 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal), 4519 DL_AFC0ReqTimeOutVal_Default); 4520 } 4521 4522 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4 4523 | pwr_mode->pwr_tx); 4524 4525 if (ret) { 4526 dev_err(hba->dev, 4527 "%s: power mode change failed %d\n", __func__, ret); 4528 } else { 4529 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL, 4530 pwr_mode); 4531 4532 memcpy(&hba->pwr_info, pwr_mode, 4533 sizeof(struct ufs_pa_layer_attr)); 4534 } 4535 4536 return ret; 4537 } 4538 4539 /** 4540 * ufshcd_config_pwr_mode - configure a new power mode 4541 * @hba: per-adapter instance 4542 * @desired_pwr_mode: desired power configuration 4543 */ 4544 int ufshcd_config_pwr_mode(struct ufs_hba *hba, 4545 struct ufs_pa_layer_attr *desired_pwr_mode) 4546 { 4547 struct ufs_pa_layer_attr final_params = { 0 }; 4548 int ret; 4549 4550 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE, 4551 desired_pwr_mode, &final_params); 4552 4553 if (ret) 4554 memcpy(&final_params, desired_pwr_mode, sizeof(final_params)); 4555 4556 ret = ufshcd_change_power_mode(hba, &final_params); 4557 4558 return ret; 4559 } 4560 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode); 4561 4562 /** 4563 * ufshcd_complete_dev_init() - checks device readiness 4564 * @hba: per-adapter instance 4565 * 4566 * Set fDeviceInit flag and poll until device toggles it. 4567 */ 4568 static int ufshcd_complete_dev_init(struct ufs_hba *hba) 4569 { 4570 int err; 4571 bool flag_res = true; 4572 ktime_t timeout; 4573 4574 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG, 4575 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL); 4576 if (err) { 4577 dev_err(hba->dev, 4578 "%s: setting fDeviceInit flag failed with error %d\n", 4579 __func__, err); 4580 goto out; 4581 } 4582 4583 /* Poll fDeviceInit flag to be cleared */ 4584 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT); 4585 do { 4586 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG, 4587 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res); 4588 if (!flag_res) 4589 break; 4590 usleep_range(500, 1000); 4591 } while (ktime_before(ktime_get(), timeout)); 4592 4593 if (err) { 4594 dev_err(hba->dev, 4595 "%s: reading fDeviceInit flag failed with error %d\n", 4596 __func__, err); 4597 } else if (flag_res) { 4598 dev_err(hba->dev, 4599 "%s: fDeviceInit was not cleared by the device\n", 4600 __func__); 4601 err = -EBUSY; 4602 } 4603 out: 4604 return err; 4605 } 4606 4607 /** 4608 * ufshcd_make_hba_operational - Make UFS controller operational 4609 * @hba: per adapter instance 4610 * 4611 * To bring UFS host controller to operational state, 4612 * 1. Enable required interrupts 4613 * 2. Configure interrupt aggregation 4614 * 3. Program UTRL and UTMRL base address 4615 * 4. Configure run-stop-registers 4616 * 4617 * Returns 0 on success, non-zero value on failure 4618 */ 4619 int ufshcd_make_hba_operational(struct ufs_hba *hba) 4620 { 4621 int err = 0; 4622 u32 reg; 4623 4624 /* Enable required interrupts */ 4625 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS); 4626 4627 /* Configure interrupt aggregation */ 4628 if (ufshcd_is_intr_aggr_allowed(hba)) 4629 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO); 4630 else 4631 ufshcd_disable_intr_aggr(hba); 4632 4633 /* Configure UTRL and UTMRL base address registers */ 4634 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr), 4635 REG_UTP_TRANSFER_REQ_LIST_BASE_L); 4636 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr), 4637 REG_UTP_TRANSFER_REQ_LIST_BASE_H); 4638 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr), 4639 REG_UTP_TASK_REQ_LIST_BASE_L); 4640 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr), 4641 REG_UTP_TASK_REQ_LIST_BASE_H); 4642 4643 /* 4644 * Make sure base address and interrupt setup are updated before 4645 * enabling the run/stop registers below. 4646 */ 4647 wmb(); 4648 4649 /* 4650 * UCRDY, UTMRLDY and UTRLRDY bits must be 1 4651 */ 4652 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS); 4653 if (!(ufshcd_get_lists_status(reg))) { 4654 ufshcd_enable_run_stop_reg(hba); 4655 } else { 4656 dev_err(hba->dev, 4657 "Host controller not ready to process requests"); 4658 err = -EIO; 4659 } 4660 4661 return err; 4662 } 4663 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational); 4664 4665 /** 4666 * ufshcd_hba_stop - Send controller to reset state 4667 * @hba: per adapter instance 4668 */ 4669 void ufshcd_hba_stop(struct ufs_hba *hba) 4670 { 4671 unsigned long flags; 4672 int err; 4673 4674 /* 4675 * Obtain the host lock to prevent that the controller is disabled 4676 * while the UFS interrupt handler is active on another CPU. 4677 */ 4678 spin_lock_irqsave(hba->host->host_lock, flags); 4679 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE); 4680 spin_unlock_irqrestore(hba->host->host_lock, flags); 4681 4682 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE, 4683 CONTROLLER_ENABLE, CONTROLLER_DISABLE, 4684 10, 1); 4685 if (err) 4686 dev_err(hba->dev, "%s: Controller disable failed\n", __func__); 4687 } 4688 EXPORT_SYMBOL_GPL(ufshcd_hba_stop); 4689 4690 /** 4691 * ufshcd_hba_execute_hce - initialize the controller 4692 * @hba: per adapter instance 4693 * 4694 * The controller resets itself and controller firmware initialization 4695 * sequence kicks off. When controller is ready it will set 4696 * the Host Controller Enable bit to 1. 4697 * 4698 * Returns 0 on success, non-zero value on failure 4699 */ 4700 static int ufshcd_hba_execute_hce(struct ufs_hba *hba) 4701 { 4702 int retry_outer = 3; 4703 int retry_inner; 4704 4705 start: 4706 if (ufshcd_is_hba_active(hba)) 4707 /* change controller state to "reset state" */ 4708 ufshcd_hba_stop(hba); 4709 4710 /* UniPro link is disabled at this point */ 4711 ufshcd_set_link_off(hba); 4712 4713 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE); 4714 4715 /* start controller initialization sequence */ 4716 ufshcd_hba_start(hba); 4717 4718 /* 4719 * To initialize a UFS host controller HCE bit must be set to 1. 4720 * During initialization the HCE bit value changes from 1->0->1. 4721 * When the host controller completes initialization sequence 4722 * it sets the value of HCE bit to 1. The same HCE bit is read back 4723 * to check if the controller has completed initialization sequence. 4724 * So without this delay the value HCE = 1, set in the previous 4725 * instruction might be read back. 4726 * This delay can be changed based on the controller. 4727 */ 4728 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100); 4729 4730 /* wait for the host controller to complete initialization */ 4731 retry_inner = 50; 4732 while (!ufshcd_is_hba_active(hba)) { 4733 if (retry_inner) { 4734 retry_inner--; 4735 } else { 4736 dev_err(hba->dev, 4737 "Controller enable failed\n"); 4738 if (retry_outer) { 4739 retry_outer--; 4740 goto start; 4741 } 4742 return -EIO; 4743 } 4744 usleep_range(1000, 1100); 4745 } 4746 4747 /* enable UIC related interrupts */ 4748 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK); 4749 4750 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE); 4751 4752 return 0; 4753 } 4754 4755 int ufshcd_hba_enable(struct ufs_hba *hba) 4756 { 4757 int ret; 4758 4759 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) { 4760 ufshcd_set_link_off(hba); 4761 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE); 4762 4763 /* enable UIC related interrupts */ 4764 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK); 4765 ret = ufshcd_dme_reset(hba); 4766 if (ret) { 4767 dev_err(hba->dev, "DME_RESET failed\n"); 4768 return ret; 4769 } 4770 4771 ret = ufshcd_dme_enable(hba); 4772 if (ret) { 4773 dev_err(hba->dev, "Enabling DME failed\n"); 4774 return ret; 4775 } 4776 4777 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE); 4778 } else { 4779 ret = ufshcd_hba_execute_hce(hba); 4780 } 4781 4782 return ret; 4783 } 4784 EXPORT_SYMBOL_GPL(ufshcd_hba_enable); 4785 4786 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer) 4787 { 4788 int tx_lanes = 0, i, err = 0; 4789 4790 if (!peer) 4791 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES), 4792 &tx_lanes); 4793 else 4794 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES), 4795 &tx_lanes); 4796 for (i = 0; i < tx_lanes; i++) { 4797 if (!peer) 4798 err = ufshcd_dme_set(hba, 4799 UIC_ARG_MIB_SEL(TX_LCC_ENABLE, 4800 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)), 4801 0); 4802 else 4803 err = ufshcd_dme_peer_set(hba, 4804 UIC_ARG_MIB_SEL(TX_LCC_ENABLE, 4805 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)), 4806 0); 4807 if (err) { 4808 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d", 4809 __func__, peer, i, err); 4810 break; 4811 } 4812 } 4813 4814 return err; 4815 } 4816 4817 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba) 4818 { 4819 return ufshcd_disable_tx_lcc(hba, true); 4820 } 4821 4822 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val) 4823 { 4824 struct ufs_event_hist *e; 4825 4826 if (id >= UFS_EVT_CNT) 4827 return; 4828 4829 e = &hba->ufs_stats.event[id]; 4830 e->val[e->pos] = val; 4831 e->tstamp[e->pos] = local_clock(); 4832 e->cnt += 1; 4833 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH; 4834 4835 ufshcd_vops_event_notify(hba, id, &val); 4836 } 4837 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist); 4838 4839 /** 4840 * ufshcd_link_startup - Initialize unipro link startup 4841 * @hba: per adapter instance 4842 * 4843 * Returns 0 for success, non-zero in case of failure 4844 */ 4845 static int ufshcd_link_startup(struct ufs_hba *hba) 4846 { 4847 int ret; 4848 int retries = DME_LINKSTARTUP_RETRIES; 4849 bool link_startup_again = false; 4850 4851 /* 4852 * If UFS device isn't active then we will have to issue link startup 4853 * 2 times to make sure the device state move to active. 4854 */ 4855 if (!ufshcd_is_ufs_dev_active(hba)) 4856 link_startup_again = true; 4857 4858 link_startup: 4859 do { 4860 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE); 4861 4862 ret = ufshcd_dme_link_startup(hba); 4863 4864 /* check if device is detected by inter-connect layer */ 4865 if (!ret && !ufshcd_is_device_present(hba)) { 4866 ufshcd_update_evt_hist(hba, 4867 UFS_EVT_LINK_STARTUP_FAIL, 4868 0); 4869 dev_err(hba->dev, "%s: Device not present\n", __func__); 4870 ret = -ENXIO; 4871 goto out; 4872 } 4873 4874 /* 4875 * DME link lost indication is only received when link is up, 4876 * but we can't be sure if the link is up until link startup 4877 * succeeds. So reset the local Uni-Pro and try again. 4878 */ 4879 if (ret && retries && ufshcd_hba_enable(hba)) { 4880 ufshcd_update_evt_hist(hba, 4881 UFS_EVT_LINK_STARTUP_FAIL, 4882 (u32)ret); 4883 goto out; 4884 } 4885 } while (ret && retries--); 4886 4887 if (ret) { 4888 /* failed to get the link up... retire */ 4889 ufshcd_update_evt_hist(hba, 4890 UFS_EVT_LINK_STARTUP_FAIL, 4891 (u32)ret); 4892 goto out; 4893 } 4894 4895 if (link_startup_again) { 4896 link_startup_again = false; 4897 retries = DME_LINKSTARTUP_RETRIES; 4898 goto link_startup; 4899 } 4900 4901 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */ 4902 ufshcd_init_pwr_info(hba); 4903 ufshcd_print_pwr_info(hba); 4904 4905 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) { 4906 ret = ufshcd_disable_device_tx_lcc(hba); 4907 if (ret) 4908 goto out; 4909 } 4910 4911 /* Include any host controller configuration via UIC commands */ 4912 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE); 4913 if (ret) 4914 goto out; 4915 4916 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */ 4917 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER); 4918 ret = ufshcd_make_hba_operational(hba); 4919 out: 4920 if (ret) { 4921 dev_err(hba->dev, "link startup failed %d\n", ret); 4922 ufshcd_print_host_state(hba); 4923 ufshcd_print_pwr_info(hba); 4924 ufshcd_print_evt_hist(hba); 4925 } 4926 return ret; 4927 } 4928 4929 /** 4930 * ufshcd_verify_dev_init() - Verify device initialization 4931 * @hba: per-adapter instance 4932 * 4933 * Send NOP OUT UPIU and wait for NOP IN response to check whether the 4934 * device Transport Protocol (UTP) layer is ready after a reset. 4935 * If the UTP layer at the device side is not initialized, it may 4936 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT 4937 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations. 4938 */ 4939 static int ufshcd_verify_dev_init(struct ufs_hba *hba) 4940 { 4941 int err = 0; 4942 int retries; 4943 4944 ufshcd_hold(hba, false); 4945 mutex_lock(&hba->dev_cmd.lock); 4946 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) { 4947 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP, 4948 hba->nop_out_timeout); 4949 4950 if (!err || err == -ETIMEDOUT) 4951 break; 4952 4953 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err); 4954 } 4955 mutex_unlock(&hba->dev_cmd.lock); 4956 ufshcd_release(hba); 4957 4958 if (err) 4959 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err); 4960 return err; 4961 } 4962 4963 /** 4964 * ufshcd_setup_links - associate link b/w device wlun and other luns 4965 * @sdev: pointer to SCSI device 4966 * @hba: pointer to ufs hba 4967 */ 4968 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev) 4969 { 4970 struct device_link *link; 4971 4972 /* 4973 * Device wlun is the supplier & rest of the luns are consumers. 4974 * This ensures that device wlun suspends after all other luns. 4975 */ 4976 if (hba->ufs_device_wlun) { 4977 link = device_link_add(&sdev->sdev_gendev, 4978 &hba->ufs_device_wlun->sdev_gendev, 4979 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE); 4980 if (!link) { 4981 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n", 4982 dev_name(&hba->ufs_device_wlun->sdev_gendev)); 4983 return; 4984 } 4985 hba->luns_avail--; 4986 /* Ignore REPORT_LUN wlun probing */ 4987 if (hba->luns_avail == 1) { 4988 ufshcd_rpm_put(hba); 4989 return; 4990 } 4991 } else { 4992 /* 4993 * Device wlun is probed. The assumption is that WLUNs are 4994 * scanned before other LUNs. 4995 */ 4996 hba->luns_avail--; 4997 } 4998 } 4999 5000 /** 5001 * ufshcd_lu_init - Initialize the relevant parameters of the LU 5002 * @hba: per-adapter instance 5003 * @sdev: pointer to SCSI device 5004 */ 5005 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev) 5006 { 5007 int len = QUERY_DESC_MAX_SIZE; 5008 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun); 5009 u8 lun_qdepth = hba->nutrs; 5010 u8 *desc_buf; 5011 int ret; 5012 5013 desc_buf = kzalloc(len, GFP_KERNEL); 5014 if (!desc_buf) 5015 goto set_qdepth; 5016 5017 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len); 5018 if (ret < 0) { 5019 if (ret == -EOPNOTSUPP) 5020 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */ 5021 lun_qdepth = 1; 5022 kfree(desc_buf); 5023 goto set_qdepth; 5024 } 5025 5026 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) { 5027 /* 5028 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will 5029 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth 5030 */ 5031 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs); 5032 } 5033 /* 5034 * According to UFS device specification, the write protection mode is only supported by 5035 * normal LU, not supported by WLUN. 5036 */ 5037 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported && 5038 !hba->dev_info.is_lu_power_on_wp && 5039 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP) 5040 hba->dev_info.is_lu_power_on_wp = true; 5041 5042 /* In case of RPMB LU, check if advanced RPMB mode is enabled */ 5043 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN && 5044 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4)) 5045 hba->dev_info.b_advanced_rpmb_en = true; 5046 5047 5048 kfree(desc_buf); 5049 set_qdepth: 5050 /* 5051 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose 5052 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue. 5053 */ 5054 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth); 5055 scsi_change_queue_depth(sdev, lun_qdepth); 5056 } 5057 5058 /** 5059 * ufshcd_slave_alloc - handle initial SCSI device configurations 5060 * @sdev: pointer to SCSI device 5061 * 5062 * Returns success 5063 */ 5064 static int ufshcd_slave_alloc(struct scsi_device *sdev) 5065 { 5066 struct ufs_hba *hba; 5067 5068 hba = shost_priv(sdev->host); 5069 5070 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */ 5071 sdev->use_10_for_ms = 1; 5072 5073 /* DBD field should be set to 1 in mode sense(10) */ 5074 sdev->set_dbd_for_ms = 1; 5075 5076 /* allow SCSI layer to restart the device in case of errors */ 5077 sdev->allow_restart = 1; 5078 5079 /* REPORT SUPPORTED OPERATION CODES is not supported */ 5080 sdev->no_report_opcodes = 1; 5081 5082 /* WRITE_SAME command is not supported */ 5083 sdev->no_write_same = 1; 5084 5085 ufshcd_lu_init(hba, sdev); 5086 5087 ufshcd_setup_links(hba, sdev); 5088 5089 return 0; 5090 } 5091 5092 /** 5093 * ufshcd_change_queue_depth - change queue depth 5094 * @sdev: pointer to SCSI device 5095 * @depth: required depth to set 5096 * 5097 * Change queue depth and make sure the max. limits are not crossed. 5098 */ 5099 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth) 5100 { 5101 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue)); 5102 } 5103 5104 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev) 5105 { 5106 /* skip well-known LU */ 5107 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) || 5108 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba)) 5109 return; 5110 5111 ufshpb_destroy_lu(hba, sdev); 5112 } 5113 5114 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev) 5115 { 5116 /* skip well-known LU */ 5117 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) || 5118 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba)) 5119 return; 5120 5121 ufshpb_init_hpb_lu(hba, sdev); 5122 } 5123 5124 /** 5125 * ufshcd_slave_configure - adjust SCSI device configurations 5126 * @sdev: pointer to SCSI device 5127 */ 5128 static int ufshcd_slave_configure(struct scsi_device *sdev) 5129 { 5130 struct ufs_hba *hba = shost_priv(sdev->host); 5131 struct request_queue *q = sdev->request_queue; 5132 5133 ufshcd_hpb_configure(hba, sdev); 5134 5135 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1); 5136 if (hba->quirks & UFSHCD_QUIRK_4KB_DMA_ALIGNMENT) 5137 blk_queue_update_dma_alignment(q, 4096 - 1); 5138 /* 5139 * Block runtime-pm until all consumers are added. 5140 * Refer ufshcd_setup_links(). 5141 */ 5142 if (is_device_wlun(sdev)) 5143 pm_runtime_get_noresume(&sdev->sdev_gendev); 5144 else if (ufshcd_is_rpm_autosuspend_allowed(hba)) 5145 sdev->rpm_autosuspend = 1; 5146 /* 5147 * Do not print messages during runtime PM to avoid never-ending cycles 5148 * of messages written back to storage by user space causing runtime 5149 * resume, causing more messages and so on. 5150 */ 5151 sdev->silence_suspend = 1; 5152 5153 ufshcd_crypto_register(hba, q); 5154 5155 return 0; 5156 } 5157 5158 /** 5159 * ufshcd_slave_destroy - remove SCSI device configurations 5160 * @sdev: pointer to SCSI device 5161 */ 5162 static void ufshcd_slave_destroy(struct scsi_device *sdev) 5163 { 5164 struct ufs_hba *hba; 5165 unsigned long flags; 5166 5167 hba = shost_priv(sdev->host); 5168 5169 ufshcd_hpb_destroy(hba, sdev); 5170 5171 /* Drop the reference as it won't be needed anymore */ 5172 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) { 5173 spin_lock_irqsave(hba->host->host_lock, flags); 5174 hba->ufs_device_wlun = NULL; 5175 spin_unlock_irqrestore(hba->host->host_lock, flags); 5176 } else if (hba->ufs_device_wlun) { 5177 struct device *supplier = NULL; 5178 5179 /* Ensure UFS Device WLUN exists and does not disappear */ 5180 spin_lock_irqsave(hba->host->host_lock, flags); 5181 if (hba->ufs_device_wlun) { 5182 supplier = &hba->ufs_device_wlun->sdev_gendev; 5183 get_device(supplier); 5184 } 5185 spin_unlock_irqrestore(hba->host->host_lock, flags); 5186 5187 if (supplier) { 5188 /* 5189 * If a LUN fails to probe (e.g. absent BOOT WLUN), the 5190 * device will not have been registered but can still 5191 * have a device link holding a reference to the device. 5192 */ 5193 device_link_remove(&sdev->sdev_gendev, supplier); 5194 put_device(supplier); 5195 } 5196 } 5197 } 5198 5199 /** 5200 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status 5201 * @lrbp: pointer to local reference block of completed command 5202 * @scsi_status: SCSI command status 5203 * 5204 * Returns value base on SCSI command status 5205 */ 5206 static inline int 5207 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status) 5208 { 5209 int result = 0; 5210 5211 switch (scsi_status) { 5212 case SAM_STAT_CHECK_CONDITION: 5213 ufshcd_copy_sense_data(lrbp); 5214 fallthrough; 5215 case SAM_STAT_GOOD: 5216 result |= DID_OK << 16 | scsi_status; 5217 break; 5218 case SAM_STAT_TASK_SET_FULL: 5219 case SAM_STAT_BUSY: 5220 case SAM_STAT_TASK_ABORTED: 5221 ufshcd_copy_sense_data(lrbp); 5222 result |= scsi_status; 5223 break; 5224 default: 5225 result |= DID_ERROR << 16; 5226 break; 5227 } /* end of switch */ 5228 5229 return result; 5230 } 5231 5232 /** 5233 * ufshcd_transfer_rsp_status - Get overall status of the response 5234 * @hba: per adapter instance 5235 * @lrbp: pointer to local reference block of completed command 5236 * @cqe: pointer to the completion queue entry 5237 * 5238 * Returns result of the command to notify SCSI midlayer 5239 */ 5240 static inline int 5241 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, 5242 struct cq_entry *cqe) 5243 { 5244 int result = 0; 5245 int scsi_status; 5246 enum utp_ocs ocs; 5247 5248 scsi_set_resid(lrbp->cmd, 5249 be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count)); 5250 5251 /* overall command status of utrd */ 5252 ocs = ufshcd_get_tr_ocs(lrbp, cqe); 5253 5254 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) { 5255 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) & 5256 MASK_RSP_UPIU_RESULT) 5257 ocs = OCS_SUCCESS; 5258 } 5259 5260 switch (ocs) { 5261 case OCS_SUCCESS: 5262 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr); 5263 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0); 5264 switch (result) { 5265 case UPIU_TRANSACTION_RESPONSE: 5266 /* 5267 * get the response UPIU result to extract 5268 * the SCSI command status 5269 */ 5270 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr); 5271 5272 /* 5273 * get the result based on SCSI status response 5274 * to notify the SCSI midlayer of the command status 5275 */ 5276 scsi_status = result & MASK_SCSI_STATUS; 5277 result = ufshcd_scsi_cmd_status(lrbp, scsi_status); 5278 5279 /* 5280 * Currently we are only supporting BKOPs exception 5281 * events hence we can ignore BKOPs exception event 5282 * during power management callbacks. BKOPs exception 5283 * event is not expected to be raised in runtime suspend 5284 * callback as it allows the urgent bkops. 5285 * During system suspend, we are anyway forcefully 5286 * disabling the bkops and if urgent bkops is needed 5287 * it will be enabled on system resume. Long term 5288 * solution could be to abort the system suspend if 5289 * UFS device needs urgent BKOPs. 5290 */ 5291 if (!hba->pm_op_in_progress && 5292 !ufshcd_eh_in_progress(hba) && 5293 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr)) 5294 /* Flushed in suspend */ 5295 schedule_work(&hba->eeh_work); 5296 5297 if (scsi_status == SAM_STAT_GOOD) 5298 ufshpb_rsp_upiu(hba, lrbp); 5299 break; 5300 case UPIU_TRANSACTION_REJECT_UPIU: 5301 /* TODO: handle Reject UPIU Response */ 5302 result = DID_ERROR << 16; 5303 dev_err(hba->dev, 5304 "Reject UPIU not fully implemented\n"); 5305 break; 5306 default: 5307 dev_err(hba->dev, 5308 "Unexpected request response code = %x\n", 5309 result); 5310 result = DID_ERROR << 16; 5311 break; 5312 } 5313 break; 5314 case OCS_ABORTED: 5315 result |= DID_ABORT << 16; 5316 break; 5317 case OCS_INVALID_COMMAND_STATUS: 5318 result |= DID_REQUEUE << 16; 5319 break; 5320 case OCS_INVALID_CMD_TABLE_ATTR: 5321 case OCS_INVALID_PRDT_ATTR: 5322 case OCS_MISMATCH_DATA_BUF_SIZE: 5323 case OCS_MISMATCH_RESP_UPIU_SIZE: 5324 case OCS_PEER_COMM_FAILURE: 5325 case OCS_FATAL_ERROR: 5326 case OCS_DEVICE_FATAL_ERROR: 5327 case OCS_INVALID_CRYPTO_CONFIG: 5328 case OCS_GENERAL_CRYPTO_ERROR: 5329 default: 5330 result |= DID_ERROR << 16; 5331 dev_err(hba->dev, 5332 "OCS error from controller = %x for tag %d\n", 5333 ocs, lrbp->task_tag); 5334 ufshcd_print_evt_hist(hba); 5335 ufshcd_print_host_state(hba); 5336 break; 5337 } /* end of switch */ 5338 5339 if ((host_byte(result) != DID_OK) && 5340 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs) 5341 ufshcd_print_tr(hba, lrbp->task_tag, true); 5342 return result; 5343 } 5344 5345 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba, 5346 u32 intr_mask) 5347 { 5348 if (!ufshcd_is_auto_hibern8_supported(hba) || 5349 !ufshcd_is_auto_hibern8_enabled(hba)) 5350 return false; 5351 5352 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK)) 5353 return false; 5354 5355 if (hba->active_uic_cmd && 5356 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER || 5357 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT)) 5358 return false; 5359 5360 return true; 5361 } 5362 5363 /** 5364 * ufshcd_uic_cmd_compl - handle completion of uic command 5365 * @hba: per adapter instance 5366 * @intr_status: interrupt status generated by the controller 5367 * 5368 * Returns 5369 * IRQ_HANDLED - If interrupt is valid 5370 * IRQ_NONE - If invalid interrupt 5371 */ 5372 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status) 5373 { 5374 irqreturn_t retval = IRQ_NONE; 5375 5376 spin_lock(hba->host->host_lock); 5377 if (ufshcd_is_auto_hibern8_error(hba, intr_status)) 5378 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status); 5379 5380 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) { 5381 hba->active_uic_cmd->argument2 |= 5382 ufshcd_get_uic_cmd_result(hba); 5383 hba->active_uic_cmd->argument3 = 5384 ufshcd_get_dme_attr_val(hba); 5385 if (!hba->uic_async_done) 5386 hba->active_uic_cmd->cmd_active = 0; 5387 complete(&hba->active_uic_cmd->done); 5388 retval = IRQ_HANDLED; 5389 } 5390 5391 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) { 5392 hba->active_uic_cmd->cmd_active = 0; 5393 complete(hba->uic_async_done); 5394 retval = IRQ_HANDLED; 5395 } 5396 5397 if (retval == IRQ_HANDLED) 5398 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd, 5399 UFS_CMD_COMP); 5400 spin_unlock(hba->host->host_lock); 5401 return retval; 5402 } 5403 5404 /* Release the resources allocated for processing a SCSI command. */ 5405 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba, 5406 struct ufshcd_lrb *lrbp) 5407 { 5408 struct scsi_cmnd *cmd = lrbp->cmd; 5409 5410 scsi_dma_unmap(cmd); 5411 lrbp->cmd = NULL; /* Mark the command as completed. */ 5412 ufshcd_release(hba); 5413 ufshcd_clk_scaling_update_busy(hba); 5414 } 5415 5416 /** 5417 * ufshcd_compl_one_cqe - handle a completion queue entry 5418 * @hba: per adapter instance 5419 * @task_tag: the task tag of the request to be completed 5420 * @cqe: pointer to the completion queue entry 5421 */ 5422 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag, 5423 struct cq_entry *cqe) 5424 { 5425 struct ufshcd_lrb *lrbp; 5426 struct scsi_cmnd *cmd; 5427 5428 lrbp = &hba->lrb[task_tag]; 5429 lrbp->compl_time_stamp = ktime_get(); 5430 cmd = lrbp->cmd; 5431 if (cmd) { 5432 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp))) 5433 ufshcd_update_monitor(hba, lrbp); 5434 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP); 5435 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe); 5436 ufshcd_release_scsi_cmd(hba, lrbp); 5437 /* Do not touch lrbp after scsi done */ 5438 scsi_done(cmd); 5439 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE || 5440 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) { 5441 if (hba->dev_cmd.complete) { 5442 hba->dev_cmd.cqe = cqe; 5443 ufshcd_add_command_trace(hba, task_tag, UFS_DEV_COMP); 5444 complete(hba->dev_cmd.complete); 5445 ufshcd_clk_scaling_update_busy(hba); 5446 } 5447 } 5448 } 5449 5450 /** 5451 * __ufshcd_transfer_req_compl - handle SCSI and query command completion 5452 * @hba: per adapter instance 5453 * @completed_reqs: bitmask that indicates which requests to complete 5454 */ 5455 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba, 5456 unsigned long completed_reqs) 5457 { 5458 int tag; 5459 5460 for_each_set_bit(tag, &completed_reqs, hba->nutrs) 5461 ufshcd_compl_one_cqe(hba, tag, NULL); 5462 } 5463 5464 /* Any value that is not an existing queue number is fine for this constant. */ 5465 enum { 5466 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1 5467 }; 5468 5469 static void ufshcd_clear_polled(struct ufs_hba *hba, 5470 unsigned long *completed_reqs) 5471 { 5472 int tag; 5473 5474 for_each_set_bit(tag, completed_reqs, hba->nutrs) { 5475 struct scsi_cmnd *cmd = hba->lrb[tag].cmd; 5476 5477 if (!cmd) 5478 continue; 5479 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED) 5480 __clear_bit(tag, completed_reqs); 5481 } 5482 } 5483 5484 /* 5485 * Returns > 0 if one or more commands have been completed or 0 if no 5486 * requests have been completed. 5487 */ 5488 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num) 5489 { 5490 struct ufs_hba *hba = shost_priv(shost); 5491 unsigned long completed_reqs, flags; 5492 u32 tr_doorbell; 5493 struct ufs_hw_queue *hwq; 5494 5495 if (is_mcq_enabled(hba)) { 5496 hwq = &hba->uhq[queue_num + UFSHCD_MCQ_IO_QUEUE_OFFSET]; 5497 5498 return ufshcd_mcq_poll_cqe_lock(hba, hwq); 5499 } 5500 5501 spin_lock_irqsave(&hba->outstanding_lock, flags); 5502 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 5503 completed_reqs = ~tr_doorbell & hba->outstanding_reqs; 5504 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs, 5505 "completed: %#lx; outstanding: %#lx\n", completed_reqs, 5506 hba->outstanding_reqs); 5507 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) { 5508 /* Do not complete polled requests from interrupt context. */ 5509 ufshcd_clear_polled(hba, &completed_reqs); 5510 } 5511 hba->outstanding_reqs &= ~completed_reqs; 5512 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 5513 5514 if (completed_reqs) 5515 __ufshcd_transfer_req_compl(hba, completed_reqs); 5516 5517 return completed_reqs != 0; 5518 } 5519 5520 /** 5521 * ufshcd_transfer_req_compl - handle SCSI and query command completion 5522 * @hba: per adapter instance 5523 * 5524 * Returns 5525 * IRQ_HANDLED - If interrupt is valid 5526 * IRQ_NONE - If invalid interrupt 5527 */ 5528 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba) 5529 { 5530 /* Resetting interrupt aggregation counters first and reading the 5531 * DOOR_BELL afterward allows us to handle all the completed requests. 5532 * In order to prevent other interrupts starvation the DB is read once 5533 * after reset. The down side of this solution is the possibility of 5534 * false interrupt if device completes another request after resetting 5535 * aggregation and before reading the DB. 5536 */ 5537 if (ufshcd_is_intr_aggr_allowed(hba) && 5538 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR)) 5539 ufshcd_reset_intr_aggr(hba); 5540 5541 if (ufs_fail_completion()) 5542 return IRQ_HANDLED; 5543 5544 /* 5545 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we 5546 * do not want polling to trigger spurious interrupt complaints. 5547 */ 5548 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT); 5549 5550 return IRQ_HANDLED; 5551 } 5552 5553 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask) 5554 { 5555 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, 5556 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, 5557 &ee_ctrl_mask); 5558 } 5559 5560 int ufshcd_write_ee_control(struct ufs_hba *hba) 5561 { 5562 int err; 5563 5564 mutex_lock(&hba->ee_ctrl_mutex); 5565 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask); 5566 mutex_unlock(&hba->ee_ctrl_mutex); 5567 if (err) 5568 dev_err(hba->dev, "%s: failed to write ee control %d\n", 5569 __func__, err); 5570 return err; 5571 } 5572 5573 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, 5574 const u16 *other_mask, u16 set, u16 clr) 5575 { 5576 u16 new_mask, ee_ctrl_mask; 5577 int err = 0; 5578 5579 mutex_lock(&hba->ee_ctrl_mutex); 5580 new_mask = (*mask & ~clr) | set; 5581 ee_ctrl_mask = new_mask | *other_mask; 5582 if (ee_ctrl_mask != hba->ee_ctrl_mask) 5583 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask); 5584 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */ 5585 if (!err) { 5586 hba->ee_ctrl_mask = ee_ctrl_mask; 5587 *mask = new_mask; 5588 } 5589 mutex_unlock(&hba->ee_ctrl_mutex); 5590 return err; 5591 } 5592 5593 /** 5594 * ufshcd_disable_ee - disable exception event 5595 * @hba: per-adapter instance 5596 * @mask: exception event to disable 5597 * 5598 * Disables exception event in the device so that the EVENT_ALERT 5599 * bit is not set. 5600 * 5601 * Returns zero on success, non-zero error value on failure. 5602 */ 5603 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask) 5604 { 5605 return ufshcd_update_ee_drv_mask(hba, 0, mask); 5606 } 5607 5608 /** 5609 * ufshcd_enable_ee - enable exception event 5610 * @hba: per-adapter instance 5611 * @mask: exception event to enable 5612 * 5613 * Enable corresponding exception event in the device to allow 5614 * device to alert host in critical scenarios. 5615 * 5616 * Returns zero on success, non-zero error value on failure. 5617 */ 5618 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask) 5619 { 5620 return ufshcd_update_ee_drv_mask(hba, mask, 0); 5621 } 5622 5623 /** 5624 * ufshcd_enable_auto_bkops - Allow device managed BKOPS 5625 * @hba: per-adapter instance 5626 * 5627 * Allow device to manage background operations on its own. Enabling 5628 * this might lead to inconsistent latencies during normal data transfers 5629 * as the device is allowed to manage its own way of handling background 5630 * operations. 5631 * 5632 * Returns zero on success, non-zero on failure. 5633 */ 5634 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba) 5635 { 5636 int err = 0; 5637 5638 if (hba->auto_bkops_enabled) 5639 goto out; 5640 5641 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG, 5642 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL); 5643 if (err) { 5644 dev_err(hba->dev, "%s: failed to enable bkops %d\n", 5645 __func__, err); 5646 goto out; 5647 } 5648 5649 hba->auto_bkops_enabled = true; 5650 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled"); 5651 5652 /* No need of URGENT_BKOPS exception from the device */ 5653 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS); 5654 if (err) 5655 dev_err(hba->dev, "%s: failed to disable exception event %d\n", 5656 __func__, err); 5657 out: 5658 return err; 5659 } 5660 5661 /** 5662 * ufshcd_disable_auto_bkops - block device in doing background operations 5663 * @hba: per-adapter instance 5664 * 5665 * Disabling background operations improves command response latency but 5666 * has drawback of device moving into critical state where the device is 5667 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the 5668 * host is idle so that BKOPS are managed effectively without any negative 5669 * impacts. 5670 * 5671 * Returns zero on success, non-zero on failure. 5672 */ 5673 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba) 5674 { 5675 int err = 0; 5676 5677 if (!hba->auto_bkops_enabled) 5678 goto out; 5679 5680 /* 5681 * If host assisted BKOPs is to be enabled, make sure 5682 * urgent bkops exception is allowed. 5683 */ 5684 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS); 5685 if (err) { 5686 dev_err(hba->dev, "%s: failed to enable exception event %d\n", 5687 __func__, err); 5688 goto out; 5689 } 5690 5691 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG, 5692 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL); 5693 if (err) { 5694 dev_err(hba->dev, "%s: failed to disable bkops %d\n", 5695 __func__, err); 5696 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS); 5697 goto out; 5698 } 5699 5700 hba->auto_bkops_enabled = false; 5701 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled"); 5702 hba->is_urgent_bkops_lvl_checked = false; 5703 out: 5704 return err; 5705 } 5706 5707 /** 5708 * ufshcd_force_reset_auto_bkops - force reset auto bkops state 5709 * @hba: per adapter instance 5710 * 5711 * After a device reset the device may toggle the BKOPS_EN flag 5712 * to default value. The s/w tracking variables should be updated 5713 * as well. This function would change the auto-bkops state based on 5714 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND. 5715 */ 5716 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba) 5717 { 5718 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) { 5719 hba->auto_bkops_enabled = false; 5720 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS; 5721 ufshcd_enable_auto_bkops(hba); 5722 } else { 5723 hba->auto_bkops_enabled = true; 5724 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS; 5725 ufshcd_disable_auto_bkops(hba); 5726 } 5727 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT; 5728 hba->is_urgent_bkops_lvl_checked = false; 5729 } 5730 5731 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status) 5732 { 5733 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5734 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status); 5735 } 5736 5737 /** 5738 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status 5739 * @hba: per-adapter instance 5740 * @status: bkops_status value 5741 * 5742 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn 5743 * flag in the device to permit background operations if the device 5744 * bkops_status is greater than or equal to "status" argument passed to 5745 * this function, disable otherwise. 5746 * 5747 * Returns 0 for success, non-zero in case of failure. 5748 * 5749 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag 5750 * to know whether auto bkops is enabled or disabled after this function 5751 * returns control to it. 5752 */ 5753 static int ufshcd_bkops_ctrl(struct ufs_hba *hba, 5754 enum bkops_status status) 5755 { 5756 int err; 5757 u32 curr_status = 0; 5758 5759 err = ufshcd_get_bkops_status(hba, &curr_status); 5760 if (err) { 5761 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n", 5762 __func__, err); 5763 goto out; 5764 } else if (curr_status > BKOPS_STATUS_MAX) { 5765 dev_err(hba->dev, "%s: invalid BKOPS status %d\n", 5766 __func__, curr_status); 5767 err = -EINVAL; 5768 goto out; 5769 } 5770 5771 if (curr_status >= status) 5772 err = ufshcd_enable_auto_bkops(hba); 5773 else 5774 err = ufshcd_disable_auto_bkops(hba); 5775 out: 5776 return err; 5777 } 5778 5779 /** 5780 * ufshcd_urgent_bkops - handle urgent bkops exception event 5781 * @hba: per-adapter instance 5782 * 5783 * Enable fBackgroundOpsEn flag in the device to permit background 5784 * operations. 5785 * 5786 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled 5787 * and negative error value for any other failure. 5788 */ 5789 static int ufshcd_urgent_bkops(struct ufs_hba *hba) 5790 { 5791 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl); 5792 } 5793 5794 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status) 5795 { 5796 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5797 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status); 5798 } 5799 5800 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba) 5801 { 5802 int err; 5803 u32 curr_status = 0; 5804 5805 if (hba->is_urgent_bkops_lvl_checked) 5806 goto enable_auto_bkops; 5807 5808 err = ufshcd_get_bkops_status(hba, &curr_status); 5809 if (err) { 5810 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n", 5811 __func__, err); 5812 goto out; 5813 } 5814 5815 /* 5816 * We are seeing that some devices are raising the urgent bkops 5817 * exception events even when BKOPS status doesn't indicate performace 5818 * impacted or critical. Handle these device by determining their urgent 5819 * bkops status at runtime. 5820 */ 5821 if (curr_status < BKOPS_STATUS_PERF_IMPACT) { 5822 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n", 5823 __func__, curr_status); 5824 /* update the current status as the urgent bkops level */ 5825 hba->urgent_bkops_lvl = curr_status; 5826 hba->is_urgent_bkops_lvl_checked = true; 5827 } 5828 5829 enable_auto_bkops: 5830 err = ufshcd_enable_auto_bkops(hba); 5831 out: 5832 if (err < 0) 5833 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n", 5834 __func__, err); 5835 } 5836 5837 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status) 5838 { 5839 u32 value; 5840 5841 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5842 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value)) 5843 return; 5844 5845 dev_info(hba->dev, "exception Tcase %d\n", value - 80); 5846 5847 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP); 5848 5849 /* 5850 * A placeholder for the platform vendors to add whatever additional 5851 * steps required 5852 */ 5853 } 5854 5855 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn) 5856 { 5857 u8 index; 5858 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG : 5859 UPIU_QUERY_OPCODE_CLEAR_FLAG; 5860 5861 index = ufshcd_wb_get_query_index(hba); 5862 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL); 5863 } 5864 5865 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable) 5866 { 5867 int ret; 5868 5869 if (!ufshcd_is_wb_allowed(hba) || 5870 hba->dev_info.wb_enabled == enable) 5871 return 0; 5872 5873 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN); 5874 if (ret) { 5875 dev_err(hba->dev, "%s: Write Booster %s failed %d\n", 5876 __func__, enable ? "enabling" : "disabling", ret); 5877 return ret; 5878 } 5879 5880 hba->dev_info.wb_enabled = enable; 5881 dev_dbg(hba->dev, "%s: Write Booster %s\n", 5882 __func__, enable ? "enabled" : "disabled"); 5883 5884 return ret; 5885 } 5886 5887 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba, 5888 bool enable) 5889 { 5890 int ret; 5891 5892 ret = __ufshcd_wb_toggle(hba, enable, 5893 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8); 5894 if (ret) { 5895 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n", 5896 __func__, enable ? "enabling" : "disabling", ret); 5897 return; 5898 } 5899 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n", 5900 __func__, enable ? "enabled" : "disabled"); 5901 } 5902 5903 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable) 5904 { 5905 int ret; 5906 5907 if (!ufshcd_is_wb_allowed(hba) || 5908 hba->dev_info.wb_buf_flush_enabled == enable) 5909 return 0; 5910 5911 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN); 5912 if (ret) { 5913 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n", 5914 __func__, enable ? "enabling" : "disabling", ret); 5915 return ret; 5916 } 5917 5918 hba->dev_info.wb_buf_flush_enabled = enable; 5919 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n", 5920 __func__, enable ? "enabled" : "disabled"); 5921 5922 return ret; 5923 } 5924 5925 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba, 5926 u32 avail_buf) 5927 { 5928 u32 cur_buf; 5929 int ret; 5930 u8 index; 5931 5932 index = ufshcd_wb_get_query_index(hba); 5933 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5934 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE, 5935 index, 0, &cur_buf); 5936 if (ret) { 5937 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n", 5938 __func__, ret); 5939 return false; 5940 } 5941 5942 if (!cur_buf) { 5943 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n", 5944 cur_buf); 5945 return false; 5946 } 5947 /* Let it continue to flush when available buffer exceeds threshold */ 5948 return avail_buf < hba->vps->wb_flush_threshold; 5949 } 5950 5951 static void ufshcd_wb_force_disable(struct ufs_hba *hba) 5952 { 5953 if (ufshcd_is_wb_buf_flush_allowed(hba)) 5954 ufshcd_wb_toggle_buf_flush(hba, false); 5955 5956 ufshcd_wb_toggle_buf_flush_during_h8(hba, false); 5957 ufshcd_wb_toggle(hba, false); 5958 hba->caps &= ~UFSHCD_CAP_WB_EN; 5959 5960 dev_info(hba->dev, "%s: WB force disabled\n", __func__); 5961 } 5962 5963 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba) 5964 { 5965 u32 lifetime; 5966 int ret; 5967 u8 index; 5968 5969 index = ufshcd_wb_get_query_index(hba); 5970 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5971 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST, 5972 index, 0, &lifetime); 5973 if (ret) { 5974 dev_err(hba->dev, 5975 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n", 5976 __func__, ret); 5977 return false; 5978 } 5979 5980 if (lifetime == UFS_WB_EXCEED_LIFETIME) { 5981 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n", 5982 __func__, lifetime); 5983 return false; 5984 } 5985 5986 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n", 5987 __func__, lifetime); 5988 5989 return true; 5990 } 5991 5992 static bool ufshcd_wb_need_flush(struct ufs_hba *hba) 5993 { 5994 int ret; 5995 u32 avail_buf; 5996 u8 index; 5997 5998 if (!ufshcd_is_wb_allowed(hba)) 5999 return false; 6000 6001 if (!ufshcd_is_wb_buf_lifetime_available(hba)) { 6002 ufshcd_wb_force_disable(hba); 6003 return false; 6004 } 6005 6006 /* 6007 * The ufs device needs the vcc to be ON to flush. 6008 * With user-space reduction enabled, it's enough to enable flush 6009 * by checking only the available buffer. The threshold 6010 * defined here is > 90% full. 6011 * With user-space preserved enabled, the current-buffer 6012 * should be checked too because the wb buffer size can reduce 6013 * when disk tends to be full. This info is provided by current 6014 * buffer (dCurrentWriteBoosterBufferSize). There's no point in 6015 * keeping vcc on when current buffer is empty. 6016 */ 6017 index = ufshcd_wb_get_query_index(hba); 6018 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 6019 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE, 6020 index, 0, &avail_buf); 6021 if (ret) { 6022 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n", 6023 __func__, ret); 6024 return false; 6025 } 6026 6027 if (!hba->dev_info.b_presrv_uspc_en) 6028 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10); 6029 6030 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf); 6031 } 6032 6033 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work) 6034 { 6035 struct ufs_hba *hba = container_of(to_delayed_work(work), 6036 struct ufs_hba, 6037 rpm_dev_flush_recheck_work); 6038 /* 6039 * To prevent unnecessary VCC power drain after device finishes 6040 * WriteBooster buffer flush or Auto BKOPs, force runtime resume 6041 * after a certain delay to recheck the threshold by next runtime 6042 * suspend. 6043 */ 6044 ufshcd_rpm_get_sync(hba); 6045 ufshcd_rpm_put_sync(hba); 6046 } 6047 6048 /** 6049 * ufshcd_exception_event_handler - handle exceptions raised by device 6050 * @work: pointer to work data 6051 * 6052 * Read bExceptionEventStatus attribute from the device and handle the 6053 * exception event accordingly. 6054 */ 6055 static void ufshcd_exception_event_handler(struct work_struct *work) 6056 { 6057 struct ufs_hba *hba; 6058 int err; 6059 u32 status = 0; 6060 hba = container_of(work, struct ufs_hba, eeh_work); 6061 6062 ufshcd_scsi_block_requests(hba); 6063 err = ufshcd_get_ee_status(hba, &status); 6064 if (err) { 6065 dev_err(hba->dev, "%s: failed to get exception status %d\n", 6066 __func__, err); 6067 goto out; 6068 } 6069 6070 trace_ufshcd_exception_event(dev_name(hba->dev), status); 6071 6072 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS) 6073 ufshcd_bkops_exception_event_handler(hba); 6074 6075 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP) 6076 ufshcd_temp_exception_event_handler(hba, status); 6077 6078 ufs_debugfs_exception_event(hba, status); 6079 out: 6080 ufshcd_scsi_unblock_requests(hba); 6081 } 6082 6083 /* Complete requests that have door-bell cleared */ 6084 static void ufshcd_complete_requests(struct ufs_hba *hba) 6085 { 6086 ufshcd_transfer_req_compl(hba); 6087 ufshcd_tmc_handler(hba); 6088 } 6089 6090 /** 6091 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is 6092 * to recover from the DL NAC errors or not. 6093 * @hba: per-adapter instance 6094 * 6095 * Returns true if error handling is required, false otherwise 6096 */ 6097 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba) 6098 { 6099 unsigned long flags; 6100 bool err_handling = true; 6101 6102 spin_lock_irqsave(hba->host->host_lock, flags); 6103 /* 6104 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the 6105 * device fatal error and/or DL NAC & REPLAY timeout errors. 6106 */ 6107 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR)) 6108 goto out; 6109 6110 if ((hba->saved_err & DEVICE_FATAL_ERROR) || 6111 ((hba->saved_err & UIC_ERROR) && 6112 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR))) 6113 goto out; 6114 6115 if ((hba->saved_err & UIC_ERROR) && 6116 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) { 6117 int err; 6118 /* 6119 * wait for 50ms to see if we can get any other errors or not. 6120 */ 6121 spin_unlock_irqrestore(hba->host->host_lock, flags); 6122 msleep(50); 6123 spin_lock_irqsave(hba->host->host_lock, flags); 6124 6125 /* 6126 * now check if we have got any other severe errors other than 6127 * DL NAC error? 6128 */ 6129 if ((hba->saved_err & INT_FATAL_ERRORS) || 6130 ((hba->saved_err & UIC_ERROR) && 6131 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR))) 6132 goto out; 6133 6134 /* 6135 * As DL NAC is the only error received so far, send out NOP 6136 * command to confirm if link is still active or not. 6137 * - If we don't get any response then do error recovery. 6138 * - If we get response then clear the DL NAC error bit. 6139 */ 6140 6141 spin_unlock_irqrestore(hba->host->host_lock, flags); 6142 err = ufshcd_verify_dev_init(hba); 6143 spin_lock_irqsave(hba->host->host_lock, flags); 6144 6145 if (err) 6146 goto out; 6147 6148 /* Link seems to be alive hence ignore the DL NAC errors */ 6149 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR) 6150 hba->saved_err &= ~UIC_ERROR; 6151 /* clear NAC error */ 6152 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR; 6153 if (!hba->saved_uic_err) 6154 err_handling = false; 6155 } 6156 out: 6157 spin_unlock_irqrestore(hba->host->host_lock, flags); 6158 return err_handling; 6159 } 6160 6161 /* host lock must be held before calling this func */ 6162 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba) 6163 { 6164 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) || 6165 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)); 6166 } 6167 6168 void ufshcd_schedule_eh_work(struct ufs_hba *hba) 6169 { 6170 lockdep_assert_held(hba->host->host_lock); 6171 6172 /* handle fatal errors only when link is not in error state */ 6173 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) { 6174 if (hba->force_reset || ufshcd_is_link_broken(hba) || 6175 ufshcd_is_saved_err_fatal(hba)) 6176 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL; 6177 else 6178 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL; 6179 queue_work(hba->eh_wq, &hba->eh_work); 6180 } 6181 } 6182 6183 static void ufshcd_force_error_recovery(struct ufs_hba *hba) 6184 { 6185 spin_lock_irq(hba->host->host_lock); 6186 hba->force_reset = true; 6187 ufshcd_schedule_eh_work(hba); 6188 spin_unlock_irq(hba->host->host_lock); 6189 } 6190 6191 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow) 6192 { 6193 mutex_lock(&hba->wb_mutex); 6194 down_write(&hba->clk_scaling_lock); 6195 hba->clk_scaling.is_allowed = allow; 6196 up_write(&hba->clk_scaling_lock); 6197 mutex_unlock(&hba->wb_mutex); 6198 } 6199 6200 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend) 6201 { 6202 if (suspend) { 6203 if (hba->clk_scaling.is_enabled) 6204 ufshcd_suspend_clkscaling(hba); 6205 ufshcd_clk_scaling_allow(hba, false); 6206 } else { 6207 ufshcd_clk_scaling_allow(hba, true); 6208 if (hba->clk_scaling.is_enabled) 6209 ufshcd_resume_clkscaling(hba); 6210 } 6211 } 6212 6213 static void ufshcd_err_handling_prepare(struct ufs_hba *hba) 6214 { 6215 ufshcd_rpm_get_sync(hba); 6216 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) || 6217 hba->is_sys_suspended) { 6218 enum ufs_pm_op pm_op; 6219 6220 /* 6221 * Don't assume anything of resume, if 6222 * resume fails, irq and clocks can be OFF, and powers 6223 * can be OFF or in LPM. 6224 */ 6225 ufshcd_setup_hba_vreg(hba, true); 6226 ufshcd_enable_irq(hba); 6227 ufshcd_setup_vreg(hba, true); 6228 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq); 6229 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2); 6230 ufshcd_hold(hba, false); 6231 if (!ufshcd_is_clkgating_allowed(hba)) 6232 ufshcd_setup_clocks(hba, true); 6233 ufshcd_release(hba); 6234 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM; 6235 ufshcd_vops_resume(hba, pm_op); 6236 } else { 6237 ufshcd_hold(hba, false); 6238 if (ufshcd_is_clkscaling_supported(hba) && 6239 hba->clk_scaling.is_enabled) 6240 ufshcd_suspend_clkscaling(hba); 6241 ufshcd_clk_scaling_allow(hba, false); 6242 } 6243 ufshcd_scsi_block_requests(hba); 6244 /* Drain ufshcd_queuecommand() */ 6245 synchronize_rcu(); 6246 cancel_work_sync(&hba->eeh_work); 6247 } 6248 6249 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba) 6250 { 6251 ufshcd_scsi_unblock_requests(hba); 6252 ufshcd_release(hba); 6253 if (ufshcd_is_clkscaling_supported(hba)) 6254 ufshcd_clk_scaling_suspend(hba, false); 6255 ufshcd_rpm_put(hba); 6256 } 6257 6258 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba) 6259 { 6260 return (!hba->is_powered || hba->shutting_down || 6261 !hba->ufs_device_wlun || 6262 hba->ufshcd_state == UFSHCD_STATE_ERROR || 6263 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset || 6264 ufshcd_is_link_broken(hba)))); 6265 } 6266 6267 #ifdef CONFIG_PM 6268 static void ufshcd_recover_pm_error(struct ufs_hba *hba) 6269 { 6270 struct Scsi_Host *shost = hba->host; 6271 struct scsi_device *sdev; 6272 struct request_queue *q; 6273 int ret; 6274 6275 hba->is_sys_suspended = false; 6276 /* 6277 * Set RPM status of wlun device to RPM_ACTIVE, 6278 * this also clears its runtime error. 6279 */ 6280 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev); 6281 6282 /* hba device might have a runtime error otherwise */ 6283 if (ret) 6284 ret = pm_runtime_set_active(hba->dev); 6285 /* 6286 * If wlun device had runtime error, we also need to resume those 6287 * consumer scsi devices in case any of them has failed to be 6288 * resumed due to supplier runtime resume failure. This is to unblock 6289 * blk_queue_enter in case there are bios waiting inside it. 6290 */ 6291 if (!ret) { 6292 shost_for_each_device(sdev, shost) { 6293 q = sdev->request_queue; 6294 if (q->dev && (q->rpm_status == RPM_SUSPENDED || 6295 q->rpm_status == RPM_SUSPENDING)) 6296 pm_request_resume(q->dev); 6297 } 6298 } 6299 } 6300 #else 6301 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba) 6302 { 6303 } 6304 #endif 6305 6306 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba) 6307 { 6308 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info; 6309 u32 mode; 6310 6311 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode); 6312 6313 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK)) 6314 return true; 6315 6316 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK)) 6317 return true; 6318 6319 return false; 6320 } 6321 6322 static bool ufshcd_abort_all(struct ufs_hba *hba) 6323 { 6324 bool needs_reset = false; 6325 int tag, ret; 6326 6327 /* Clear pending transfer requests */ 6328 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) { 6329 ret = ufshcd_try_to_abort_task(hba, tag); 6330 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag, 6331 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1, 6332 ret ? "failed" : "succeeded"); 6333 if (ret) { 6334 needs_reset = true; 6335 goto out; 6336 } 6337 } 6338 6339 /* Clear pending task management requests */ 6340 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) { 6341 if (ufshcd_clear_tm_cmd(hba, tag)) { 6342 needs_reset = true; 6343 goto out; 6344 } 6345 } 6346 6347 out: 6348 /* Complete the requests that are cleared by s/w */ 6349 ufshcd_complete_requests(hba); 6350 6351 return needs_reset; 6352 } 6353 6354 /** 6355 * ufshcd_err_handler - handle UFS errors that require s/w attention 6356 * @work: pointer to work structure 6357 */ 6358 static void ufshcd_err_handler(struct work_struct *work) 6359 { 6360 int retries = MAX_ERR_HANDLER_RETRIES; 6361 struct ufs_hba *hba; 6362 unsigned long flags; 6363 bool needs_restore; 6364 bool needs_reset; 6365 int pmc_err; 6366 6367 hba = container_of(work, struct ufs_hba, eh_work); 6368 6369 dev_info(hba->dev, 6370 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n", 6371 __func__, ufshcd_state_name[hba->ufshcd_state], 6372 hba->is_powered, hba->shutting_down, hba->saved_err, 6373 hba->saved_uic_err, hba->force_reset, 6374 ufshcd_is_link_broken(hba) ? "; link is broken" : ""); 6375 6376 down(&hba->host_sem); 6377 spin_lock_irqsave(hba->host->host_lock, flags); 6378 if (ufshcd_err_handling_should_stop(hba)) { 6379 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) 6380 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL; 6381 spin_unlock_irqrestore(hba->host->host_lock, flags); 6382 up(&hba->host_sem); 6383 return; 6384 } 6385 ufshcd_set_eh_in_progress(hba); 6386 spin_unlock_irqrestore(hba->host->host_lock, flags); 6387 ufshcd_err_handling_prepare(hba); 6388 /* Complete requests that have door-bell cleared by h/w */ 6389 ufshcd_complete_requests(hba); 6390 spin_lock_irqsave(hba->host->host_lock, flags); 6391 again: 6392 needs_restore = false; 6393 needs_reset = false; 6394 6395 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) 6396 hba->ufshcd_state = UFSHCD_STATE_RESET; 6397 /* 6398 * A full reset and restore might have happened after preparation 6399 * is finished, double check whether we should stop. 6400 */ 6401 if (ufshcd_err_handling_should_stop(hba)) 6402 goto skip_err_handling; 6403 6404 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) { 6405 bool ret; 6406 6407 spin_unlock_irqrestore(hba->host->host_lock, flags); 6408 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */ 6409 ret = ufshcd_quirk_dl_nac_errors(hba); 6410 spin_lock_irqsave(hba->host->host_lock, flags); 6411 if (!ret && ufshcd_err_handling_should_stop(hba)) 6412 goto skip_err_handling; 6413 } 6414 6415 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) || 6416 (hba->saved_uic_err && 6417 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) { 6418 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR); 6419 6420 spin_unlock_irqrestore(hba->host->host_lock, flags); 6421 ufshcd_print_host_state(hba); 6422 ufshcd_print_pwr_info(hba); 6423 ufshcd_print_evt_hist(hba); 6424 ufshcd_print_tmrs(hba, hba->outstanding_tasks); 6425 ufshcd_print_trs_all(hba, pr_prdt); 6426 spin_lock_irqsave(hba->host->host_lock, flags); 6427 } 6428 6429 /* 6430 * if host reset is required then skip clearing the pending 6431 * transfers forcefully because they will get cleared during 6432 * host reset and restore 6433 */ 6434 if (hba->force_reset || ufshcd_is_link_broken(hba) || 6435 ufshcd_is_saved_err_fatal(hba) || 6436 ((hba->saved_err & UIC_ERROR) && 6437 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR | 6438 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) { 6439 needs_reset = true; 6440 goto do_reset; 6441 } 6442 6443 /* 6444 * If LINERESET was caught, UFS might have been put to PWM mode, 6445 * check if power mode restore is needed. 6446 */ 6447 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) { 6448 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR; 6449 if (!hba->saved_uic_err) 6450 hba->saved_err &= ~UIC_ERROR; 6451 spin_unlock_irqrestore(hba->host->host_lock, flags); 6452 if (ufshcd_is_pwr_mode_restore_needed(hba)) 6453 needs_restore = true; 6454 spin_lock_irqsave(hba->host->host_lock, flags); 6455 if (!hba->saved_err && !needs_restore) 6456 goto skip_err_handling; 6457 } 6458 6459 hba->silence_err_logs = true; 6460 /* release lock as clear command might sleep */ 6461 spin_unlock_irqrestore(hba->host->host_lock, flags); 6462 6463 needs_reset = ufshcd_abort_all(hba); 6464 6465 spin_lock_irqsave(hba->host->host_lock, flags); 6466 hba->silence_err_logs = false; 6467 if (needs_reset) 6468 goto do_reset; 6469 6470 /* 6471 * After all reqs and tasks are cleared from doorbell, 6472 * now it is safe to retore power mode. 6473 */ 6474 if (needs_restore) { 6475 spin_unlock_irqrestore(hba->host->host_lock, flags); 6476 /* 6477 * Hold the scaling lock just in case dev cmds 6478 * are sent via bsg and/or sysfs. 6479 */ 6480 down_write(&hba->clk_scaling_lock); 6481 hba->force_pmc = true; 6482 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info)); 6483 if (pmc_err) { 6484 needs_reset = true; 6485 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n", 6486 __func__, pmc_err); 6487 } 6488 hba->force_pmc = false; 6489 ufshcd_print_pwr_info(hba); 6490 up_write(&hba->clk_scaling_lock); 6491 spin_lock_irqsave(hba->host->host_lock, flags); 6492 } 6493 6494 do_reset: 6495 /* Fatal errors need reset */ 6496 if (needs_reset) { 6497 int err; 6498 6499 hba->force_reset = false; 6500 spin_unlock_irqrestore(hba->host->host_lock, flags); 6501 err = ufshcd_reset_and_restore(hba); 6502 if (err) 6503 dev_err(hba->dev, "%s: reset and restore failed with err %d\n", 6504 __func__, err); 6505 else 6506 ufshcd_recover_pm_error(hba); 6507 spin_lock_irqsave(hba->host->host_lock, flags); 6508 } 6509 6510 skip_err_handling: 6511 if (!needs_reset) { 6512 if (hba->ufshcd_state == UFSHCD_STATE_RESET) 6513 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL; 6514 if (hba->saved_err || hba->saved_uic_err) 6515 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x", 6516 __func__, hba->saved_err, hba->saved_uic_err); 6517 } 6518 /* Exit in an operational state or dead */ 6519 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL && 6520 hba->ufshcd_state != UFSHCD_STATE_ERROR) { 6521 if (--retries) 6522 goto again; 6523 hba->ufshcd_state = UFSHCD_STATE_ERROR; 6524 } 6525 ufshcd_clear_eh_in_progress(hba); 6526 spin_unlock_irqrestore(hba->host->host_lock, flags); 6527 ufshcd_err_handling_unprepare(hba); 6528 up(&hba->host_sem); 6529 6530 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__, 6531 ufshcd_state_name[hba->ufshcd_state]); 6532 } 6533 6534 /** 6535 * ufshcd_update_uic_error - check and set fatal UIC error flags. 6536 * @hba: per-adapter instance 6537 * 6538 * Returns 6539 * IRQ_HANDLED - If interrupt is valid 6540 * IRQ_NONE - If invalid interrupt 6541 */ 6542 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba) 6543 { 6544 u32 reg; 6545 irqreturn_t retval = IRQ_NONE; 6546 6547 /* PHY layer error */ 6548 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER); 6549 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) && 6550 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) { 6551 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg); 6552 /* 6553 * To know whether this error is fatal or not, DB timeout 6554 * must be checked but this error is handled separately. 6555 */ 6556 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK) 6557 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", 6558 __func__); 6559 6560 /* Got a LINERESET indication. */ 6561 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) { 6562 struct uic_command *cmd = NULL; 6563 6564 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR; 6565 if (hba->uic_async_done && hba->active_uic_cmd) 6566 cmd = hba->active_uic_cmd; 6567 /* 6568 * Ignore the LINERESET during power mode change 6569 * operation via DME_SET command. 6570 */ 6571 if (cmd && (cmd->command == UIC_CMD_DME_SET)) 6572 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR; 6573 } 6574 retval |= IRQ_HANDLED; 6575 } 6576 6577 /* PA_INIT_ERROR is fatal and needs UIC reset */ 6578 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER); 6579 if ((reg & UIC_DATA_LINK_LAYER_ERROR) && 6580 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) { 6581 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg); 6582 6583 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT) 6584 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR; 6585 else if (hba->dev_quirks & 6586 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) { 6587 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED) 6588 hba->uic_error |= 6589 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR; 6590 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT) 6591 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR; 6592 } 6593 retval |= IRQ_HANDLED; 6594 } 6595 6596 /* UIC NL/TL/DME errors needs software retry */ 6597 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER); 6598 if ((reg & UIC_NETWORK_LAYER_ERROR) && 6599 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) { 6600 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg); 6601 hba->uic_error |= UFSHCD_UIC_NL_ERROR; 6602 retval |= IRQ_HANDLED; 6603 } 6604 6605 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER); 6606 if ((reg & UIC_TRANSPORT_LAYER_ERROR) && 6607 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) { 6608 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg); 6609 hba->uic_error |= UFSHCD_UIC_TL_ERROR; 6610 retval |= IRQ_HANDLED; 6611 } 6612 6613 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME); 6614 if ((reg & UIC_DME_ERROR) && 6615 (reg & UIC_DME_ERROR_CODE_MASK)) { 6616 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg); 6617 hba->uic_error |= UFSHCD_UIC_DME_ERROR; 6618 retval |= IRQ_HANDLED; 6619 } 6620 6621 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n", 6622 __func__, hba->uic_error); 6623 return retval; 6624 } 6625 6626 /** 6627 * ufshcd_check_errors - Check for errors that need s/w attention 6628 * @hba: per-adapter instance 6629 * @intr_status: interrupt status generated by the controller 6630 * 6631 * Returns 6632 * IRQ_HANDLED - If interrupt is valid 6633 * IRQ_NONE - If invalid interrupt 6634 */ 6635 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status) 6636 { 6637 bool queue_eh_work = false; 6638 irqreturn_t retval = IRQ_NONE; 6639 6640 spin_lock(hba->host->host_lock); 6641 hba->errors |= UFSHCD_ERROR_MASK & intr_status; 6642 6643 if (hba->errors & INT_FATAL_ERRORS) { 6644 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR, 6645 hba->errors); 6646 queue_eh_work = true; 6647 } 6648 6649 if (hba->errors & UIC_ERROR) { 6650 hba->uic_error = 0; 6651 retval = ufshcd_update_uic_error(hba); 6652 if (hba->uic_error) 6653 queue_eh_work = true; 6654 } 6655 6656 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) { 6657 dev_err(hba->dev, 6658 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n", 6659 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ? 6660 "Enter" : "Exit", 6661 hba->errors, ufshcd_get_upmcrs(hba)); 6662 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR, 6663 hba->errors); 6664 ufshcd_set_link_broken(hba); 6665 queue_eh_work = true; 6666 } 6667 6668 if (queue_eh_work) { 6669 /* 6670 * update the transfer error masks to sticky bits, let's do this 6671 * irrespective of current ufshcd_state. 6672 */ 6673 hba->saved_err |= hba->errors; 6674 hba->saved_uic_err |= hba->uic_error; 6675 6676 /* dump controller state before resetting */ 6677 if ((hba->saved_err & 6678 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) || 6679 (hba->saved_uic_err && 6680 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) { 6681 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n", 6682 __func__, hba->saved_err, 6683 hba->saved_uic_err); 6684 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, 6685 "host_regs: "); 6686 ufshcd_print_pwr_info(hba); 6687 } 6688 ufshcd_schedule_eh_work(hba); 6689 retval |= IRQ_HANDLED; 6690 } 6691 /* 6692 * if (!queue_eh_work) - 6693 * Other errors are either non-fatal where host recovers 6694 * itself without s/w intervention or errors that will be 6695 * handled by the SCSI core layer. 6696 */ 6697 hba->errors = 0; 6698 hba->uic_error = 0; 6699 spin_unlock(hba->host->host_lock); 6700 return retval; 6701 } 6702 6703 /** 6704 * ufshcd_tmc_handler - handle task management function completion 6705 * @hba: per adapter instance 6706 * 6707 * Returns 6708 * IRQ_HANDLED - If interrupt is valid 6709 * IRQ_NONE - If invalid interrupt 6710 */ 6711 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba) 6712 { 6713 unsigned long flags, pending, issued; 6714 irqreturn_t ret = IRQ_NONE; 6715 int tag; 6716 6717 spin_lock_irqsave(hba->host->host_lock, flags); 6718 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL); 6719 issued = hba->outstanding_tasks & ~pending; 6720 for_each_set_bit(tag, &issued, hba->nutmrs) { 6721 struct request *req = hba->tmf_rqs[tag]; 6722 struct completion *c = req->end_io_data; 6723 6724 complete(c); 6725 ret = IRQ_HANDLED; 6726 } 6727 spin_unlock_irqrestore(hba->host->host_lock, flags); 6728 6729 return ret; 6730 } 6731 6732 /** 6733 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events 6734 * @hba: per adapter instance 6735 * 6736 * Returns IRQ_HANDLED if interrupt is handled 6737 */ 6738 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba) 6739 { 6740 struct ufs_hw_queue *hwq; 6741 unsigned long outstanding_cqs; 6742 unsigned int nr_queues; 6743 int i, ret; 6744 u32 events; 6745 6746 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs); 6747 if (ret) 6748 outstanding_cqs = (1U << hba->nr_hw_queues) - 1; 6749 6750 /* Exclude the poll queues */ 6751 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL]; 6752 for_each_set_bit(i, &outstanding_cqs, nr_queues) { 6753 hwq = &hba->uhq[i]; 6754 6755 events = ufshcd_mcq_read_cqis(hba, i); 6756 if (events) 6757 ufshcd_mcq_write_cqis(hba, events, i); 6758 6759 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS) 6760 ufshcd_mcq_poll_cqe_nolock(hba, hwq); 6761 } 6762 6763 return IRQ_HANDLED; 6764 } 6765 6766 /** 6767 * ufshcd_sl_intr - Interrupt service routine 6768 * @hba: per adapter instance 6769 * @intr_status: contains interrupts generated by the controller 6770 * 6771 * Returns 6772 * IRQ_HANDLED - If interrupt is valid 6773 * IRQ_NONE - If invalid interrupt 6774 */ 6775 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status) 6776 { 6777 irqreturn_t retval = IRQ_NONE; 6778 6779 if (intr_status & UFSHCD_UIC_MASK) 6780 retval |= ufshcd_uic_cmd_compl(hba, intr_status); 6781 6782 if (intr_status & UFSHCD_ERROR_MASK || hba->errors) 6783 retval |= ufshcd_check_errors(hba, intr_status); 6784 6785 if (intr_status & UTP_TASK_REQ_COMPL) 6786 retval |= ufshcd_tmc_handler(hba); 6787 6788 if (intr_status & UTP_TRANSFER_REQ_COMPL) 6789 retval |= ufshcd_transfer_req_compl(hba); 6790 6791 if (intr_status & MCQ_CQ_EVENT_STATUS) 6792 retval |= ufshcd_handle_mcq_cq_events(hba); 6793 6794 return retval; 6795 } 6796 6797 /** 6798 * ufshcd_intr - Main interrupt service routine 6799 * @irq: irq number 6800 * @__hba: pointer to adapter instance 6801 * 6802 * Returns 6803 * IRQ_HANDLED - If interrupt is valid 6804 * IRQ_NONE - If invalid interrupt 6805 */ 6806 static irqreturn_t ufshcd_intr(int irq, void *__hba) 6807 { 6808 u32 intr_status, enabled_intr_status = 0; 6809 irqreturn_t retval = IRQ_NONE; 6810 struct ufs_hba *hba = __hba; 6811 int retries = hba->nutrs; 6812 6813 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS); 6814 hba->ufs_stats.last_intr_status = intr_status; 6815 hba->ufs_stats.last_intr_ts = local_clock(); 6816 6817 /* 6818 * There could be max of hba->nutrs reqs in flight and in worst case 6819 * if the reqs get finished 1 by 1 after the interrupt status is 6820 * read, make sure we handle them by checking the interrupt status 6821 * again in a loop until we process all of the reqs before returning. 6822 */ 6823 while (intr_status && retries--) { 6824 enabled_intr_status = 6825 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE); 6826 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS); 6827 if (enabled_intr_status) 6828 retval |= ufshcd_sl_intr(hba, enabled_intr_status); 6829 6830 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS); 6831 } 6832 6833 if (enabled_intr_status && retval == IRQ_NONE && 6834 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) || 6835 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) { 6836 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n", 6837 __func__, 6838 intr_status, 6839 hba->ufs_stats.last_intr_status, 6840 enabled_intr_status); 6841 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: "); 6842 } 6843 6844 return retval; 6845 } 6846 6847 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag) 6848 { 6849 int err = 0; 6850 u32 mask = 1 << tag; 6851 unsigned long flags; 6852 6853 if (!test_bit(tag, &hba->outstanding_tasks)) 6854 goto out; 6855 6856 spin_lock_irqsave(hba->host->host_lock, flags); 6857 ufshcd_utmrl_clear(hba, tag); 6858 spin_unlock_irqrestore(hba->host->host_lock, flags); 6859 6860 /* poll for max. 1 sec to clear door bell register by h/w */ 6861 err = ufshcd_wait_for_register(hba, 6862 REG_UTP_TASK_REQ_DOOR_BELL, 6863 mask, 0, 1000, 1000); 6864 6865 dev_err(hba->dev, "Clearing task management function with tag %d %s\n", 6866 tag, err ? "succeeded" : "failed"); 6867 6868 out: 6869 return err; 6870 } 6871 6872 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba, 6873 struct utp_task_req_desc *treq, u8 tm_function) 6874 { 6875 struct request_queue *q = hba->tmf_queue; 6876 struct Scsi_Host *host = hba->host; 6877 DECLARE_COMPLETION_ONSTACK(wait); 6878 struct request *req; 6879 unsigned long flags; 6880 int task_tag, err; 6881 6882 /* 6883 * blk_mq_alloc_request() is used here only to get a free tag. 6884 */ 6885 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0); 6886 if (IS_ERR(req)) 6887 return PTR_ERR(req); 6888 6889 req->end_io_data = &wait; 6890 ufshcd_hold(hba, false); 6891 6892 spin_lock_irqsave(host->host_lock, flags); 6893 6894 task_tag = req->tag; 6895 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n", 6896 task_tag); 6897 hba->tmf_rqs[req->tag] = req; 6898 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag); 6899 6900 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq)); 6901 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function); 6902 6903 /* send command to the controller */ 6904 __set_bit(task_tag, &hba->outstanding_tasks); 6905 6906 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL); 6907 /* Make sure that doorbell is committed immediately */ 6908 wmb(); 6909 6910 spin_unlock_irqrestore(host->host_lock, flags); 6911 6912 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND); 6913 6914 /* wait until the task management command is completed */ 6915 err = wait_for_completion_io_timeout(&wait, 6916 msecs_to_jiffies(TM_CMD_TIMEOUT)); 6917 if (!err) { 6918 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR); 6919 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n", 6920 __func__, tm_function); 6921 if (ufshcd_clear_tm_cmd(hba, task_tag)) 6922 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n", 6923 __func__, task_tag); 6924 err = -ETIMEDOUT; 6925 } else { 6926 err = 0; 6927 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq)); 6928 6929 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP); 6930 } 6931 6932 spin_lock_irqsave(hba->host->host_lock, flags); 6933 hba->tmf_rqs[req->tag] = NULL; 6934 __clear_bit(task_tag, &hba->outstanding_tasks); 6935 spin_unlock_irqrestore(hba->host->host_lock, flags); 6936 6937 ufshcd_release(hba); 6938 blk_mq_free_request(req); 6939 6940 return err; 6941 } 6942 6943 /** 6944 * ufshcd_issue_tm_cmd - issues task management commands to controller 6945 * @hba: per adapter instance 6946 * @lun_id: LUN ID to which TM command is sent 6947 * @task_id: task ID to which the TM command is applicable 6948 * @tm_function: task management function opcode 6949 * @tm_response: task management service response return value 6950 * 6951 * Returns non-zero value on error, zero on success. 6952 */ 6953 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id, 6954 u8 tm_function, u8 *tm_response) 6955 { 6956 struct utp_task_req_desc treq = { { 0 }, }; 6957 enum utp_ocs ocs_value; 6958 int err; 6959 6960 /* Configure task request descriptor */ 6961 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD); 6962 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS); 6963 6964 /* Configure task request UPIU */ 6965 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) | 6966 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24); 6967 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16); 6968 6969 /* 6970 * The host shall provide the same value for LUN field in the basic 6971 * header and for Input Parameter. 6972 */ 6973 treq.upiu_req.input_param1 = cpu_to_be32(lun_id); 6974 treq.upiu_req.input_param2 = cpu_to_be32(task_id); 6975 6976 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function); 6977 if (err == -ETIMEDOUT) 6978 return err; 6979 6980 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS; 6981 if (ocs_value != OCS_SUCCESS) 6982 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", 6983 __func__, ocs_value); 6984 else if (tm_response) 6985 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) & 6986 MASK_TM_SERVICE_RESP; 6987 return err; 6988 } 6989 6990 /** 6991 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests 6992 * @hba: per-adapter instance 6993 * @req_upiu: upiu request 6994 * @rsp_upiu: upiu reply 6995 * @desc_buff: pointer to descriptor buffer, NULL if NA 6996 * @buff_len: descriptor size, 0 if NA 6997 * @cmd_type: specifies the type (NOP, Query...) 6998 * @desc_op: descriptor operation 6999 * 7000 * Those type of requests uses UTP Transfer Request Descriptor - utrd. 7001 * Therefore, it "rides" the device management infrastructure: uses its tag and 7002 * tasks work queues. 7003 * 7004 * Since there is only one available tag for device management commands, 7005 * the caller is expected to hold the hba->dev_cmd.lock mutex. 7006 */ 7007 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba, 7008 struct utp_upiu_req *req_upiu, 7009 struct utp_upiu_req *rsp_upiu, 7010 u8 *desc_buff, int *buff_len, 7011 enum dev_cmd_type cmd_type, 7012 enum query_opcode desc_op) 7013 { 7014 DECLARE_COMPLETION_ONSTACK(wait); 7015 const u32 tag = hba->reserved_slot; 7016 struct ufshcd_lrb *lrbp; 7017 int err = 0; 7018 u8 upiu_flags; 7019 7020 /* Protects use of hba->reserved_slot. */ 7021 lockdep_assert_held(&hba->dev_cmd.lock); 7022 7023 down_read(&hba->clk_scaling_lock); 7024 7025 lrbp = &hba->lrb[tag]; 7026 WARN_ON(lrbp->cmd); 7027 lrbp->cmd = NULL; 7028 lrbp->task_tag = tag; 7029 lrbp->lun = 0; 7030 lrbp->intr_cmd = true; 7031 ufshcd_prepare_lrbp_crypto(NULL, lrbp); 7032 hba->dev_cmd.type = cmd_type; 7033 7034 if (hba->ufs_version <= ufshci_version(1, 1)) 7035 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE; 7036 else 7037 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE; 7038 7039 /* update the task tag in the request upiu */ 7040 req_upiu->header.dword_0 |= cpu_to_be32(tag); 7041 7042 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0); 7043 7044 /* just copy the upiu request as it is */ 7045 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr)); 7046 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) { 7047 /* The Data Segment Area is optional depending upon the query 7048 * function value. for WRITE DESCRIPTOR, the data segment 7049 * follows right after the tsf. 7050 */ 7051 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len); 7052 *buff_len = 0; 7053 } 7054 7055 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp)); 7056 7057 hba->dev_cmd.complete = &wait; 7058 7059 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr); 7060 7061 ufshcd_send_command(hba, tag, hba->dev_cmd_queue); 7062 /* 7063 * ignore the returning value here - ufshcd_check_query_response is 7064 * bound to fail since dev_cmd.query and dev_cmd.type were left empty. 7065 * read the response directly ignoring all errors. 7066 */ 7067 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT); 7068 7069 /* just copy the upiu response as it is */ 7070 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu)); 7071 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) { 7072 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu); 7073 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) & 7074 MASK_QUERY_DATA_SEG_LEN; 7075 7076 if (*buff_len >= resp_len) { 7077 memcpy(desc_buff, descp, resp_len); 7078 *buff_len = resp_len; 7079 } else { 7080 dev_warn(hba->dev, 7081 "%s: rsp size %d is bigger than buffer size %d", 7082 __func__, resp_len, *buff_len); 7083 *buff_len = 0; 7084 err = -EINVAL; 7085 } 7086 } 7087 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP, 7088 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr); 7089 7090 up_read(&hba->clk_scaling_lock); 7091 return err; 7092 } 7093 7094 /** 7095 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands 7096 * @hba: per-adapter instance 7097 * @req_upiu: upiu request 7098 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands 7099 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target 7100 * @desc_buff: pointer to descriptor buffer, NULL if NA 7101 * @buff_len: descriptor size, 0 if NA 7102 * @desc_op: descriptor operation 7103 * 7104 * Supports UTP Transfer requests (nop and query), and UTP Task 7105 * Management requests. 7106 * It is up to the caller to fill the upiu conent properly, as it will 7107 * be copied without any further input validations. 7108 */ 7109 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba, 7110 struct utp_upiu_req *req_upiu, 7111 struct utp_upiu_req *rsp_upiu, 7112 int msgcode, 7113 u8 *desc_buff, int *buff_len, 7114 enum query_opcode desc_op) 7115 { 7116 int err; 7117 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY; 7118 struct utp_task_req_desc treq = { { 0 }, }; 7119 enum utp_ocs ocs_value; 7120 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC; 7121 7122 switch (msgcode) { 7123 case UPIU_TRANSACTION_NOP_OUT: 7124 cmd_type = DEV_CMD_TYPE_NOP; 7125 fallthrough; 7126 case UPIU_TRANSACTION_QUERY_REQ: 7127 ufshcd_hold(hba, false); 7128 mutex_lock(&hba->dev_cmd.lock); 7129 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu, 7130 desc_buff, buff_len, 7131 cmd_type, desc_op); 7132 mutex_unlock(&hba->dev_cmd.lock); 7133 ufshcd_release(hba); 7134 7135 break; 7136 case UPIU_TRANSACTION_TASK_REQ: 7137 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD); 7138 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS); 7139 7140 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu)); 7141 7142 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f); 7143 if (err == -ETIMEDOUT) 7144 break; 7145 7146 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS; 7147 if (ocs_value != OCS_SUCCESS) { 7148 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__, 7149 ocs_value); 7150 break; 7151 } 7152 7153 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu)); 7154 7155 break; 7156 default: 7157 err = -EINVAL; 7158 7159 break; 7160 } 7161 7162 return err; 7163 } 7164 7165 /** 7166 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request 7167 * @hba: per adapter instance 7168 * @req_upiu: upiu request 7169 * @rsp_upiu: upiu reply 7170 * @req_ehs: EHS field which contains Advanced RPMB Request Message 7171 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message 7172 * @sg_cnt: The number of sg lists actually used 7173 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation 7174 * @dir: DMA direction 7175 * 7176 * Returns zero on success, non-zero on failure 7177 */ 7178 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu, 7179 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs, 7180 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list, 7181 enum dma_data_direction dir) 7182 { 7183 DECLARE_COMPLETION_ONSTACK(wait); 7184 const u32 tag = hba->reserved_slot; 7185 struct ufshcd_lrb *lrbp; 7186 int err = 0; 7187 int result; 7188 u8 upiu_flags; 7189 u8 *ehs_data; 7190 u16 ehs_len; 7191 7192 /* Protects use of hba->reserved_slot. */ 7193 ufshcd_hold(hba, false); 7194 mutex_lock(&hba->dev_cmd.lock); 7195 down_read(&hba->clk_scaling_lock); 7196 7197 lrbp = &hba->lrb[tag]; 7198 WARN_ON(lrbp->cmd); 7199 lrbp->cmd = NULL; 7200 lrbp->task_tag = tag; 7201 lrbp->lun = UFS_UPIU_RPMB_WLUN; 7202 7203 lrbp->intr_cmd = true; 7204 ufshcd_prepare_lrbp_crypto(NULL, lrbp); 7205 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB; 7206 7207 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */ 7208 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE; 7209 7210 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2); 7211 7212 /* update the task tag and LUN in the request upiu */ 7213 req_upiu->header.dword_0 |= cpu_to_be32(upiu_flags << 16 | UFS_UPIU_RPMB_WLUN << 8 | tag); 7214 7215 /* copy the UPIU(contains CDB) request as it is */ 7216 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr)); 7217 /* Copy EHS, starting with byte32, immediately after the CDB package */ 7218 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs)); 7219 7220 if (dir != DMA_NONE && sg_list) 7221 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list); 7222 7223 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp)); 7224 7225 hba->dev_cmd.complete = &wait; 7226 7227 ufshcd_send_command(hba, tag, hba->dev_cmd_queue); 7228 7229 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT); 7230 7231 if (!err) { 7232 /* Just copy the upiu response as it is */ 7233 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu)); 7234 /* Get the response UPIU result */ 7235 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr); 7236 7237 ehs_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) >> 24; 7238 /* 7239 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data 7240 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB 7241 * Message is 02h 7242 */ 7243 if (ehs_len == 2 && rsp_ehs) { 7244 /* 7245 * ucd_rsp_ptr points to a buffer with a length of 512 bytes 7246 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32 7247 */ 7248 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE; 7249 memcpy(rsp_ehs, ehs_data, ehs_len * 32); 7250 } 7251 } 7252 7253 up_read(&hba->clk_scaling_lock); 7254 mutex_unlock(&hba->dev_cmd.lock); 7255 ufshcd_release(hba); 7256 return err ? : result; 7257 } 7258 7259 /** 7260 * ufshcd_eh_device_reset_handler() - Reset a single logical unit. 7261 * @cmd: SCSI command pointer 7262 * 7263 * Returns SUCCESS/FAILED 7264 */ 7265 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd) 7266 { 7267 unsigned long flags, pending_reqs = 0, not_cleared = 0; 7268 struct Scsi_Host *host; 7269 struct ufs_hba *hba; 7270 u32 pos; 7271 int err; 7272 u8 resp = 0xF, lun; 7273 7274 host = cmd->device->host; 7275 hba = shost_priv(host); 7276 7277 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun); 7278 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp); 7279 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) { 7280 if (!err) 7281 err = resp; 7282 goto out; 7283 } 7284 7285 /* clear the commands that were pending for corresponding LUN */ 7286 spin_lock_irqsave(&hba->outstanding_lock, flags); 7287 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) 7288 if (hba->lrb[pos].lun == lun) 7289 __set_bit(pos, &pending_reqs); 7290 hba->outstanding_reqs &= ~pending_reqs; 7291 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 7292 7293 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) { 7294 spin_lock_irqsave(&hba->outstanding_lock, flags); 7295 not_cleared = pending_reqs & 7296 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 7297 hba->outstanding_reqs |= not_cleared; 7298 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 7299 7300 dev_err(hba->dev, "%s: failed to clear requests %#lx\n", 7301 __func__, not_cleared); 7302 } 7303 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared); 7304 7305 out: 7306 hba->req_abort_count = 0; 7307 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err); 7308 if (!err) { 7309 err = SUCCESS; 7310 } else { 7311 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err); 7312 err = FAILED; 7313 } 7314 return err; 7315 } 7316 7317 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap) 7318 { 7319 struct ufshcd_lrb *lrbp; 7320 int tag; 7321 7322 for_each_set_bit(tag, &bitmap, hba->nutrs) { 7323 lrbp = &hba->lrb[tag]; 7324 lrbp->req_abort_skip = true; 7325 } 7326 } 7327 7328 /** 7329 * ufshcd_try_to_abort_task - abort a specific task 7330 * @hba: Pointer to adapter instance 7331 * @tag: Task tag/index to be aborted 7332 * 7333 * Abort the pending command in device by sending UFS_ABORT_TASK task management 7334 * command, and in host controller by clearing the door-bell register. There can 7335 * be race between controller sending the command to the device while abort is 7336 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is 7337 * really issued and then try to abort it. 7338 * 7339 * Returns zero on success, non-zero on failure 7340 */ 7341 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag) 7342 { 7343 struct ufshcd_lrb *lrbp = &hba->lrb[tag]; 7344 int err = 0; 7345 int poll_cnt; 7346 u8 resp = 0xF; 7347 u32 reg; 7348 7349 for (poll_cnt = 100; poll_cnt; poll_cnt--) { 7350 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag, 7351 UFS_QUERY_TASK, &resp); 7352 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) { 7353 /* cmd pending in the device */ 7354 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n", 7355 __func__, tag); 7356 break; 7357 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) { 7358 /* 7359 * cmd not pending in the device, check if it is 7360 * in transition. 7361 */ 7362 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n", 7363 __func__, tag); 7364 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 7365 if (reg & (1 << tag)) { 7366 /* sleep for max. 200us to stabilize */ 7367 usleep_range(100, 200); 7368 continue; 7369 } 7370 /* command completed already */ 7371 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n", 7372 __func__, tag); 7373 goto out; 7374 } else { 7375 dev_err(hba->dev, 7376 "%s: no response from device. tag = %d, err %d\n", 7377 __func__, tag, err); 7378 if (!err) 7379 err = resp; /* service response error */ 7380 goto out; 7381 } 7382 } 7383 7384 if (!poll_cnt) { 7385 err = -EBUSY; 7386 goto out; 7387 } 7388 7389 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag, 7390 UFS_ABORT_TASK, &resp); 7391 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) { 7392 if (!err) { 7393 err = resp; /* service response error */ 7394 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n", 7395 __func__, tag, err); 7396 } 7397 goto out; 7398 } 7399 7400 err = ufshcd_clear_cmds(hba, 1U << tag); 7401 if (err) 7402 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n", 7403 __func__, tag, err); 7404 7405 out: 7406 return err; 7407 } 7408 7409 /** 7410 * ufshcd_abort - scsi host template eh_abort_handler callback 7411 * @cmd: SCSI command pointer 7412 * 7413 * Returns SUCCESS/FAILED 7414 */ 7415 static int ufshcd_abort(struct scsi_cmnd *cmd) 7416 { 7417 struct Scsi_Host *host = cmd->device->host; 7418 struct ufs_hba *hba = shost_priv(host); 7419 int tag = scsi_cmd_to_rq(cmd)->tag; 7420 struct ufshcd_lrb *lrbp = &hba->lrb[tag]; 7421 unsigned long flags; 7422 int err = FAILED; 7423 bool outstanding; 7424 u32 reg; 7425 7426 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag); 7427 7428 ufshcd_hold(hba, false); 7429 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 7430 /* If command is already aborted/completed, return FAILED. */ 7431 if (!(test_bit(tag, &hba->outstanding_reqs))) { 7432 dev_err(hba->dev, 7433 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n", 7434 __func__, tag, hba->outstanding_reqs, reg); 7435 goto release; 7436 } 7437 7438 /* Print Transfer Request of aborted task */ 7439 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag); 7440 7441 /* 7442 * Print detailed info about aborted request. 7443 * As more than one request might get aborted at the same time, 7444 * print full information only for the first aborted request in order 7445 * to reduce repeated printouts. For other aborted requests only print 7446 * basic details. 7447 */ 7448 scsi_print_command(cmd); 7449 if (!hba->req_abort_count) { 7450 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag); 7451 ufshcd_print_evt_hist(hba); 7452 ufshcd_print_host_state(hba); 7453 ufshcd_print_pwr_info(hba); 7454 ufshcd_print_tr(hba, tag, true); 7455 } else { 7456 ufshcd_print_tr(hba, tag, false); 7457 } 7458 hba->req_abort_count++; 7459 7460 if (!(reg & (1 << tag))) { 7461 dev_err(hba->dev, 7462 "%s: cmd was completed, but without a notifying intr, tag = %d", 7463 __func__, tag); 7464 __ufshcd_transfer_req_compl(hba, 1UL << tag); 7465 goto release; 7466 } 7467 7468 /* 7469 * Task abort to the device W-LUN is illegal. When this command 7470 * will fail, due to spec violation, scsi err handling next step 7471 * will be to send LU reset which, again, is a spec violation. 7472 * To avoid these unnecessary/illegal steps, first we clean up 7473 * the lrb taken by this cmd and re-set it in outstanding_reqs, 7474 * then queue the eh_work and bail. 7475 */ 7476 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) { 7477 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun); 7478 7479 spin_lock_irqsave(host->host_lock, flags); 7480 hba->force_reset = true; 7481 ufshcd_schedule_eh_work(hba); 7482 spin_unlock_irqrestore(host->host_lock, flags); 7483 goto release; 7484 } 7485 7486 /* Skip task abort in case previous aborts failed and report failure */ 7487 if (lrbp->req_abort_skip) { 7488 dev_err(hba->dev, "%s: skipping abort\n", __func__); 7489 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs); 7490 goto release; 7491 } 7492 7493 err = ufshcd_try_to_abort_task(hba, tag); 7494 if (err) { 7495 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err); 7496 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs); 7497 err = FAILED; 7498 goto release; 7499 } 7500 7501 /* 7502 * Clear the corresponding bit from outstanding_reqs since the command 7503 * has been aborted successfully. 7504 */ 7505 spin_lock_irqsave(&hba->outstanding_lock, flags); 7506 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs); 7507 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 7508 7509 if (outstanding) 7510 ufshcd_release_scsi_cmd(hba, lrbp); 7511 7512 err = SUCCESS; 7513 7514 release: 7515 /* Matches the ufshcd_hold() call at the start of this function. */ 7516 ufshcd_release(hba); 7517 return err; 7518 } 7519 7520 /** 7521 * ufshcd_host_reset_and_restore - reset and restore host controller 7522 * @hba: per-adapter instance 7523 * 7524 * Note that host controller reset may issue DME_RESET to 7525 * local and remote (device) Uni-Pro stack and the attributes 7526 * are reset to default state. 7527 * 7528 * Returns zero on success, non-zero on failure 7529 */ 7530 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba) 7531 { 7532 int err; 7533 7534 /* 7535 * Stop the host controller and complete the requests 7536 * cleared by h/w 7537 */ 7538 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET); 7539 ufshcd_hba_stop(hba); 7540 hba->silence_err_logs = true; 7541 ufshcd_complete_requests(hba); 7542 hba->silence_err_logs = false; 7543 7544 /* scale up clocks to max frequency before full reinitialization */ 7545 ufshcd_scale_clks(hba, true); 7546 7547 err = ufshcd_hba_enable(hba); 7548 7549 /* Establish the link again and restore the device */ 7550 if (!err) 7551 err = ufshcd_probe_hba(hba, false); 7552 7553 if (err) 7554 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err); 7555 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err); 7556 return err; 7557 } 7558 7559 /** 7560 * ufshcd_reset_and_restore - reset and re-initialize host/device 7561 * @hba: per-adapter instance 7562 * 7563 * Reset and recover device, host and re-establish link. This 7564 * is helpful to recover the communication in fatal error conditions. 7565 * 7566 * Returns zero on success, non-zero on failure 7567 */ 7568 static int ufshcd_reset_and_restore(struct ufs_hba *hba) 7569 { 7570 u32 saved_err = 0; 7571 u32 saved_uic_err = 0; 7572 int err = 0; 7573 unsigned long flags; 7574 int retries = MAX_HOST_RESET_RETRIES; 7575 7576 spin_lock_irqsave(hba->host->host_lock, flags); 7577 do { 7578 /* 7579 * This is a fresh start, cache and clear saved error first, 7580 * in case new error generated during reset and restore. 7581 */ 7582 saved_err |= hba->saved_err; 7583 saved_uic_err |= hba->saved_uic_err; 7584 hba->saved_err = 0; 7585 hba->saved_uic_err = 0; 7586 hba->force_reset = false; 7587 hba->ufshcd_state = UFSHCD_STATE_RESET; 7588 spin_unlock_irqrestore(hba->host->host_lock, flags); 7589 7590 /* Reset the attached device */ 7591 ufshcd_device_reset(hba); 7592 7593 err = ufshcd_host_reset_and_restore(hba); 7594 7595 spin_lock_irqsave(hba->host->host_lock, flags); 7596 if (err) 7597 continue; 7598 /* Do not exit unless operational or dead */ 7599 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL && 7600 hba->ufshcd_state != UFSHCD_STATE_ERROR && 7601 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL) 7602 err = -EAGAIN; 7603 } while (err && --retries); 7604 7605 /* 7606 * Inform scsi mid-layer that we did reset and allow to handle 7607 * Unit Attention properly. 7608 */ 7609 scsi_report_bus_reset(hba->host, 0); 7610 if (err) { 7611 hba->ufshcd_state = UFSHCD_STATE_ERROR; 7612 hba->saved_err |= saved_err; 7613 hba->saved_uic_err |= saved_uic_err; 7614 } 7615 spin_unlock_irqrestore(hba->host->host_lock, flags); 7616 7617 return err; 7618 } 7619 7620 /** 7621 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer 7622 * @cmd: SCSI command pointer 7623 * 7624 * Returns SUCCESS/FAILED 7625 */ 7626 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd) 7627 { 7628 int err = SUCCESS; 7629 unsigned long flags; 7630 struct ufs_hba *hba; 7631 7632 hba = shost_priv(cmd->device->host); 7633 7634 spin_lock_irqsave(hba->host->host_lock, flags); 7635 hba->force_reset = true; 7636 ufshcd_schedule_eh_work(hba); 7637 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__); 7638 spin_unlock_irqrestore(hba->host->host_lock, flags); 7639 7640 flush_work(&hba->eh_work); 7641 7642 spin_lock_irqsave(hba->host->host_lock, flags); 7643 if (hba->ufshcd_state == UFSHCD_STATE_ERROR) 7644 err = FAILED; 7645 spin_unlock_irqrestore(hba->host->host_lock, flags); 7646 7647 return err; 7648 } 7649 7650 /** 7651 * ufshcd_get_max_icc_level - calculate the ICC level 7652 * @sup_curr_uA: max. current supported by the regulator 7653 * @start_scan: row at the desc table to start scan from 7654 * @buff: power descriptor buffer 7655 * 7656 * Returns calculated max ICC level for specific regulator 7657 */ 7658 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, 7659 const char *buff) 7660 { 7661 int i; 7662 int curr_uA; 7663 u16 data; 7664 u16 unit; 7665 7666 for (i = start_scan; i >= 0; i--) { 7667 data = get_unaligned_be16(&buff[2 * i]); 7668 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >> 7669 ATTR_ICC_LVL_UNIT_OFFSET; 7670 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK; 7671 switch (unit) { 7672 case UFSHCD_NANO_AMP: 7673 curr_uA = curr_uA / 1000; 7674 break; 7675 case UFSHCD_MILI_AMP: 7676 curr_uA = curr_uA * 1000; 7677 break; 7678 case UFSHCD_AMP: 7679 curr_uA = curr_uA * 1000 * 1000; 7680 break; 7681 case UFSHCD_MICRO_AMP: 7682 default: 7683 break; 7684 } 7685 if (sup_curr_uA >= curr_uA) 7686 break; 7687 } 7688 if (i < 0) { 7689 i = 0; 7690 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i); 7691 } 7692 7693 return (u32)i; 7694 } 7695 7696 /** 7697 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level 7698 * In case regulators are not initialized we'll return 0 7699 * @hba: per-adapter instance 7700 * @desc_buf: power descriptor buffer to extract ICC levels from. 7701 * 7702 * Returns calculated ICC level 7703 */ 7704 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba, 7705 const u8 *desc_buf) 7706 { 7707 u32 icc_level = 0; 7708 7709 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq || 7710 !hba->vreg_info.vccq2) { 7711 /* 7712 * Using dev_dbg to avoid messages during runtime PM to avoid 7713 * never-ending cycles of messages written back to storage by 7714 * user space causing runtime resume, causing more messages and 7715 * so on. 7716 */ 7717 dev_dbg(hba->dev, 7718 "%s: Regulator capability was not set, actvIccLevel=%d", 7719 __func__, icc_level); 7720 goto out; 7721 } 7722 7723 if (hba->vreg_info.vcc->max_uA) 7724 icc_level = ufshcd_get_max_icc_level( 7725 hba->vreg_info.vcc->max_uA, 7726 POWER_DESC_MAX_ACTV_ICC_LVLS - 1, 7727 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]); 7728 7729 if (hba->vreg_info.vccq->max_uA) 7730 icc_level = ufshcd_get_max_icc_level( 7731 hba->vreg_info.vccq->max_uA, 7732 icc_level, 7733 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]); 7734 7735 if (hba->vreg_info.vccq2->max_uA) 7736 icc_level = ufshcd_get_max_icc_level( 7737 hba->vreg_info.vccq2->max_uA, 7738 icc_level, 7739 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]); 7740 out: 7741 return icc_level; 7742 } 7743 7744 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba) 7745 { 7746 int ret; 7747 u8 *desc_buf; 7748 u32 icc_level; 7749 7750 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL); 7751 if (!desc_buf) 7752 return; 7753 7754 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0, 7755 desc_buf, QUERY_DESC_MAX_SIZE); 7756 if (ret) { 7757 dev_err(hba->dev, 7758 "%s: Failed reading power descriptor ret = %d", 7759 __func__, ret); 7760 goto out; 7761 } 7762 7763 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf); 7764 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level); 7765 7766 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, 7767 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level); 7768 7769 if (ret) 7770 dev_err(hba->dev, 7771 "%s: Failed configuring bActiveICCLevel = %d ret = %d", 7772 __func__, icc_level, ret); 7773 7774 out: 7775 kfree(desc_buf); 7776 } 7777 7778 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev) 7779 { 7780 scsi_autopm_get_device(sdev); 7781 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev); 7782 if (sdev->rpm_autosuspend) 7783 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev, 7784 RPM_AUTOSUSPEND_DELAY_MS); 7785 scsi_autopm_put_device(sdev); 7786 } 7787 7788 /** 7789 * ufshcd_scsi_add_wlus - Adds required W-LUs 7790 * @hba: per-adapter instance 7791 * 7792 * UFS device specification requires the UFS devices to support 4 well known 7793 * logical units: 7794 * "REPORT_LUNS" (address: 01h) 7795 * "UFS Device" (address: 50h) 7796 * "RPMB" (address: 44h) 7797 * "BOOT" (address: 30h) 7798 * UFS device's power management needs to be controlled by "POWER CONDITION" 7799 * field of SSU (START STOP UNIT) command. But this "power condition" field 7800 * will take effect only when its sent to "UFS device" well known logical unit 7801 * hence we require the scsi_device instance to represent this logical unit in 7802 * order for the UFS host driver to send the SSU command for power management. 7803 * 7804 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory 7805 * Block) LU so user space process can control this LU. User space may also 7806 * want to have access to BOOT LU. 7807 * 7808 * This function adds scsi device instances for each of all well known LUs 7809 * (except "REPORT LUNS" LU). 7810 * 7811 * Returns zero on success (all required W-LUs are added successfully), 7812 * non-zero error value on failure (if failed to add any of the required W-LU). 7813 */ 7814 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba) 7815 { 7816 int ret = 0; 7817 struct scsi_device *sdev_boot, *sdev_rpmb; 7818 7819 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0, 7820 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL); 7821 if (IS_ERR(hba->ufs_device_wlun)) { 7822 ret = PTR_ERR(hba->ufs_device_wlun); 7823 hba->ufs_device_wlun = NULL; 7824 goto out; 7825 } 7826 scsi_device_put(hba->ufs_device_wlun); 7827 7828 sdev_rpmb = __scsi_add_device(hba->host, 0, 0, 7829 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL); 7830 if (IS_ERR(sdev_rpmb)) { 7831 ret = PTR_ERR(sdev_rpmb); 7832 goto remove_ufs_device_wlun; 7833 } 7834 ufshcd_blk_pm_runtime_init(sdev_rpmb); 7835 scsi_device_put(sdev_rpmb); 7836 7837 sdev_boot = __scsi_add_device(hba->host, 0, 0, 7838 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL); 7839 if (IS_ERR(sdev_boot)) { 7840 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__); 7841 } else { 7842 ufshcd_blk_pm_runtime_init(sdev_boot); 7843 scsi_device_put(sdev_boot); 7844 } 7845 goto out; 7846 7847 remove_ufs_device_wlun: 7848 scsi_remove_device(hba->ufs_device_wlun); 7849 out: 7850 return ret; 7851 } 7852 7853 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf) 7854 { 7855 struct ufs_dev_info *dev_info = &hba->dev_info; 7856 u8 lun; 7857 u32 d_lu_wb_buf_alloc; 7858 u32 ext_ufs_feature; 7859 7860 if (!ufshcd_is_wb_allowed(hba)) 7861 return; 7862 7863 /* 7864 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or 7865 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES 7866 * enabled 7867 */ 7868 if (!(dev_info->wspecversion >= 0x310 || 7869 dev_info->wspecversion == 0x220 || 7870 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES))) 7871 goto wb_disabled; 7872 7873 ext_ufs_feature = get_unaligned_be32(desc_buf + 7874 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP); 7875 7876 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP)) 7877 goto wb_disabled; 7878 7879 /* 7880 * WB may be supported but not configured while provisioning. The spec 7881 * says, in dedicated wb buffer mode, a max of 1 lun would have wb 7882 * buffer configured. 7883 */ 7884 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE]; 7885 7886 dev_info->b_presrv_uspc_en = 7887 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN]; 7888 7889 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) { 7890 if (!get_unaligned_be32(desc_buf + 7891 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS)) 7892 goto wb_disabled; 7893 } else { 7894 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) { 7895 d_lu_wb_buf_alloc = 0; 7896 ufshcd_read_unit_desc_param(hba, 7897 lun, 7898 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS, 7899 (u8 *)&d_lu_wb_buf_alloc, 7900 sizeof(d_lu_wb_buf_alloc)); 7901 if (d_lu_wb_buf_alloc) { 7902 dev_info->wb_dedicated_lu = lun; 7903 break; 7904 } 7905 } 7906 7907 if (!d_lu_wb_buf_alloc) 7908 goto wb_disabled; 7909 } 7910 7911 if (!ufshcd_is_wb_buf_lifetime_available(hba)) 7912 goto wb_disabled; 7913 7914 return; 7915 7916 wb_disabled: 7917 hba->caps &= ~UFSHCD_CAP_WB_EN; 7918 } 7919 7920 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf) 7921 { 7922 struct ufs_dev_info *dev_info = &hba->dev_info; 7923 u32 ext_ufs_feature; 7924 u8 mask = 0; 7925 7926 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300) 7927 return; 7928 7929 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP); 7930 7931 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF) 7932 mask |= MASK_EE_TOO_LOW_TEMP; 7933 7934 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF) 7935 mask |= MASK_EE_TOO_HIGH_TEMP; 7936 7937 if (mask) { 7938 ufshcd_enable_ee(hba, mask); 7939 ufs_hwmon_probe(hba, mask); 7940 } 7941 } 7942 7943 static void ufshcd_ext_iid_probe(struct ufs_hba *hba, u8 *desc_buf) 7944 { 7945 struct ufs_dev_info *dev_info = &hba->dev_info; 7946 u32 ext_ufs_feature; 7947 u32 ext_iid_en = 0; 7948 int err; 7949 7950 /* Only UFS-4.0 and above may support EXT_IID */ 7951 if (dev_info->wspecversion < 0x400) 7952 goto out; 7953 7954 ext_ufs_feature = get_unaligned_be32(desc_buf + 7955 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP); 7956 if (!(ext_ufs_feature & UFS_DEV_EXT_IID_SUP)) 7957 goto out; 7958 7959 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 7960 QUERY_ATTR_IDN_EXT_IID_EN, 0, 0, &ext_iid_en); 7961 if (err) 7962 dev_err(hba->dev, "failed reading bEXTIIDEn. err = %d\n", err); 7963 7964 out: 7965 dev_info->b_ext_iid_en = ext_iid_en; 7966 } 7967 7968 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, 7969 const struct ufs_dev_quirk *fixups) 7970 { 7971 const struct ufs_dev_quirk *f; 7972 struct ufs_dev_info *dev_info = &hba->dev_info; 7973 7974 if (!fixups) 7975 return; 7976 7977 for (f = fixups; f->quirk; f++) { 7978 if ((f->wmanufacturerid == dev_info->wmanufacturerid || 7979 f->wmanufacturerid == UFS_ANY_VENDOR) && 7980 ((dev_info->model && 7981 STR_PRFX_EQUAL(f->model, dev_info->model)) || 7982 !strcmp(f->model, UFS_ANY_MODEL))) 7983 hba->dev_quirks |= f->quirk; 7984 } 7985 } 7986 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks); 7987 7988 static void ufs_fixup_device_setup(struct ufs_hba *hba) 7989 { 7990 /* fix by general quirk table */ 7991 ufshcd_fixup_dev_quirks(hba, ufs_fixups); 7992 7993 /* allow vendors to fix quirks */ 7994 ufshcd_vops_fixup_dev_quirks(hba); 7995 } 7996 7997 static int ufs_get_device_desc(struct ufs_hba *hba) 7998 { 7999 int err; 8000 u8 model_index; 8001 u8 b_ufs_feature_sup; 8002 u8 *desc_buf; 8003 struct ufs_dev_info *dev_info = &hba->dev_info; 8004 8005 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL); 8006 if (!desc_buf) { 8007 err = -ENOMEM; 8008 goto out; 8009 } 8010 8011 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf, 8012 QUERY_DESC_MAX_SIZE); 8013 if (err) { 8014 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n", 8015 __func__, err); 8016 goto out; 8017 } 8018 8019 /* 8020 * getting vendor (manufacturerID) and Bank Index in big endian 8021 * format 8022 */ 8023 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 | 8024 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1]; 8025 8026 /* getting Specification Version in big endian format */ 8027 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 | 8028 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1]; 8029 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH]; 8030 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT]; 8031 8032 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME]; 8033 8034 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION && 8035 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) { 8036 bool hpb_en = false; 8037 8038 ufshpb_get_dev_info(hba, desc_buf); 8039 8040 if (!ufshpb_is_legacy(hba)) 8041 err = ufshcd_query_flag_retry(hba, 8042 UPIU_QUERY_OPCODE_READ_FLAG, 8043 QUERY_FLAG_IDN_HPB_EN, 0, 8044 &hpb_en); 8045 8046 if (ufshpb_is_legacy(hba) || (!err && hpb_en)) 8047 dev_info->hpb_enabled = true; 8048 } 8049 8050 err = ufshcd_read_string_desc(hba, model_index, 8051 &dev_info->model, SD_ASCII_STD); 8052 if (err < 0) { 8053 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n", 8054 __func__, err); 8055 goto out; 8056 } 8057 8058 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] + 8059 desc_buf[DEVICE_DESC_PARAM_NUM_WLU]; 8060 8061 ufs_fixup_device_setup(hba); 8062 8063 ufshcd_wb_probe(hba, desc_buf); 8064 8065 ufshcd_temp_notif_probe(hba, desc_buf); 8066 8067 if (hba->ext_iid_sup) 8068 ufshcd_ext_iid_probe(hba, desc_buf); 8069 8070 /* 8071 * ufshcd_read_string_desc returns size of the string 8072 * reset the error value 8073 */ 8074 err = 0; 8075 8076 out: 8077 kfree(desc_buf); 8078 return err; 8079 } 8080 8081 static void ufs_put_device_desc(struct ufs_hba *hba) 8082 { 8083 struct ufs_dev_info *dev_info = &hba->dev_info; 8084 8085 kfree(dev_info->model); 8086 dev_info->model = NULL; 8087 } 8088 8089 /** 8090 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro 8091 * @hba: per-adapter instance 8092 * 8093 * PA_TActivate parameter can be tuned manually if UniPro version is less than 8094 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's 8095 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce 8096 * the hibern8 exit latency. 8097 * 8098 * Returns zero on success, non-zero error value on failure. 8099 */ 8100 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba) 8101 { 8102 int ret = 0; 8103 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate; 8104 8105 ret = ufshcd_dme_peer_get(hba, 8106 UIC_ARG_MIB_SEL( 8107 RX_MIN_ACTIVATETIME_CAPABILITY, 8108 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)), 8109 &peer_rx_min_activatetime); 8110 if (ret) 8111 goto out; 8112 8113 /* make sure proper unit conversion is applied */ 8114 tuned_pa_tactivate = 8115 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US) 8116 / PA_TACTIVATE_TIME_UNIT_US); 8117 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 8118 tuned_pa_tactivate); 8119 8120 out: 8121 return ret; 8122 } 8123 8124 /** 8125 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro 8126 * @hba: per-adapter instance 8127 * 8128 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than 8129 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's 8130 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY. 8131 * This optimal value can help reduce the hibern8 exit latency. 8132 * 8133 * Returns zero on success, non-zero error value on failure. 8134 */ 8135 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba) 8136 { 8137 int ret = 0; 8138 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0; 8139 u32 max_hibern8_time, tuned_pa_hibern8time; 8140 8141 ret = ufshcd_dme_get(hba, 8142 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY, 8143 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)), 8144 &local_tx_hibern8_time_cap); 8145 if (ret) 8146 goto out; 8147 8148 ret = ufshcd_dme_peer_get(hba, 8149 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY, 8150 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)), 8151 &peer_rx_hibern8_time_cap); 8152 if (ret) 8153 goto out; 8154 8155 max_hibern8_time = max(local_tx_hibern8_time_cap, 8156 peer_rx_hibern8_time_cap); 8157 /* make sure proper unit conversion is applied */ 8158 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US) 8159 / PA_HIBERN8_TIME_UNIT_US); 8160 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME), 8161 tuned_pa_hibern8time); 8162 out: 8163 return ret; 8164 } 8165 8166 /** 8167 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is 8168 * less than device PA_TACTIVATE time. 8169 * @hba: per-adapter instance 8170 * 8171 * Some UFS devices require host PA_TACTIVATE to be lower than device 8172 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk 8173 * for such devices. 8174 * 8175 * Returns zero on success, non-zero error value on failure. 8176 */ 8177 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba) 8178 { 8179 int ret = 0; 8180 u32 granularity, peer_granularity; 8181 u32 pa_tactivate, peer_pa_tactivate; 8182 u32 pa_tactivate_us, peer_pa_tactivate_us; 8183 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100}; 8184 8185 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY), 8186 &granularity); 8187 if (ret) 8188 goto out; 8189 8190 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY), 8191 &peer_granularity); 8192 if (ret) 8193 goto out; 8194 8195 if ((granularity < PA_GRANULARITY_MIN_VAL) || 8196 (granularity > PA_GRANULARITY_MAX_VAL)) { 8197 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d", 8198 __func__, granularity); 8199 return -EINVAL; 8200 } 8201 8202 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) || 8203 (peer_granularity > PA_GRANULARITY_MAX_VAL)) { 8204 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d", 8205 __func__, peer_granularity); 8206 return -EINVAL; 8207 } 8208 8209 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate); 8210 if (ret) 8211 goto out; 8212 8213 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE), 8214 &peer_pa_tactivate); 8215 if (ret) 8216 goto out; 8217 8218 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1]; 8219 peer_pa_tactivate_us = peer_pa_tactivate * 8220 gran_to_us_table[peer_granularity - 1]; 8221 8222 if (pa_tactivate_us >= peer_pa_tactivate_us) { 8223 u32 new_peer_pa_tactivate; 8224 8225 new_peer_pa_tactivate = pa_tactivate_us / 8226 gran_to_us_table[peer_granularity - 1]; 8227 new_peer_pa_tactivate++; 8228 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 8229 new_peer_pa_tactivate); 8230 } 8231 8232 out: 8233 return ret; 8234 } 8235 8236 static void ufshcd_tune_unipro_params(struct ufs_hba *hba) 8237 { 8238 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) { 8239 ufshcd_tune_pa_tactivate(hba); 8240 ufshcd_tune_pa_hibern8time(hba); 8241 } 8242 8243 ufshcd_vops_apply_dev_quirks(hba); 8244 8245 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE) 8246 /* set 1ms timeout for PA_TACTIVATE */ 8247 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10); 8248 8249 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE) 8250 ufshcd_quirk_tune_host_pa_tactivate(hba); 8251 } 8252 8253 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba) 8254 { 8255 hba->ufs_stats.hibern8_exit_cnt = 0; 8256 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0); 8257 hba->req_abort_count = 0; 8258 } 8259 8260 static int ufshcd_device_geo_params_init(struct ufs_hba *hba) 8261 { 8262 int err; 8263 u8 *desc_buf; 8264 8265 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL); 8266 if (!desc_buf) { 8267 err = -ENOMEM; 8268 goto out; 8269 } 8270 8271 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0, 8272 desc_buf, QUERY_DESC_MAX_SIZE); 8273 if (err) { 8274 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n", 8275 __func__, err); 8276 goto out; 8277 } 8278 8279 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1) 8280 hba->dev_info.max_lu_supported = 32; 8281 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0) 8282 hba->dev_info.max_lu_supported = 8; 8283 8284 if (desc_buf[QUERY_DESC_LENGTH_OFFSET] >= 8285 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS) 8286 ufshpb_get_geo_info(hba, desc_buf); 8287 8288 out: 8289 kfree(desc_buf); 8290 return err; 8291 } 8292 8293 struct ufs_ref_clk { 8294 unsigned long freq_hz; 8295 enum ufs_ref_clk_freq val; 8296 }; 8297 8298 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = { 8299 {19200000, REF_CLK_FREQ_19_2_MHZ}, 8300 {26000000, REF_CLK_FREQ_26_MHZ}, 8301 {38400000, REF_CLK_FREQ_38_4_MHZ}, 8302 {52000000, REF_CLK_FREQ_52_MHZ}, 8303 {0, REF_CLK_FREQ_INVAL}, 8304 }; 8305 8306 static enum ufs_ref_clk_freq 8307 ufs_get_bref_clk_from_hz(unsigned long freq) 8308 { 8309 int i; 8310 8311 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++) 8312 if (ufs_ref_clk_freqs[i].freq_hz == freq) 8313 return ufs_ref_clk_freqs[i].val; 8314 8315 return REF_CLK_FREQ_INVAL; 8316 } 8317 8318 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk) 8319 { 8320 unsigned long freq; 8321 8322 freq = clk_get_rate(refclk); 8323 8324 hba->dev_ref_clk_freq = 8325 ufs_get_bref_clk_from_hz(freq); 8326 8327 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL) 8328 dev_err(hba->dev, 8329 "invalid ref_clk setting = %ld\n", freq); 8330 } 8331 8332 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba) 8333 { 8334 int err; 8335 u32 ref_clk; 8336 u32 freq = hba->dev_ref_clk_freq; 8337 8338 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 8339 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk); 8340 8341 if (err) { 8342 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n", 8343 err); 8344 goto out; 8345 } 8346 8347 if (ref_clk == freq) 8348 goto out; /* nothing to update */ 8349 8350 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, 8351 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq); 8352 8353 if (err) { 8354 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n", 8355 ufs_ref_clk_freqs[freq].freq_hz); 8356 goto out; 8357 } 8358 8359 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n", 8360 ufs_ref_clk_freqs[freq].freq_hz); 8361 8362 out: 8363 return err; 8364 } 8365 8366 static int ufshcd_device_params_init(struct ufs_hba *hba) 8367 { 8368 bool flag; 8369 int ret; 8370 8371 /* Init UFS geometry descriptor related parameters */ 8372 ret = ufshcd_device_geo_params_init(hba); 8373 if (ret) 8374 goto out; 8375 8376 /* Check and apply UFS device quirks */ 8377 ret = ufs_get_device_desc(hba); 8378 if (ret) { 8379 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n", 8380 __func__, ret); 8381 goto out; 8382 } 8383 8384 ufshcd_get_ref_clk_gating_wait(hba); 8385 8386 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG, 8387 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag)) 8388 hba->dev_info.f_power_on_wp_en = flag; 8389 8390 /* Probe maximum power mode co-supported by both UFS host and device */ 8391 if (ufshcd_get_max_pwr_mode(hba)) 8392 dev_err(hba->dev, 8393 "%s: Failed getting max supported power mode\n", 8394 __func__); 8395 out: 8396 return ret; 8397 } 8398 8399 /** 8400 * ufshcd_add_lus - probe and add UFS logical units 8401 * @hba: per-adapter instance 8402 */ 8403 static int ufshcd_add_lus(struct ufs_hba *hba) 8404 { 8405 int ret; 8406 8407 /* Add required well known logical units to scsi mid layer */ 8408 ret = ufshcd_scsi_add_wlus(hba); 8409 if (ret) 8410 goto out; 8411 8412 /* Initialize devfreq after UFS device is detected */ 8413 if (ufshcd_is_clkscaling_supported(hba)) { 8414 memcpy(&hba->clk_scaling.saved_pwr_info, 8415 &hba->pwr_info, 8416 sizeof(struct ufs_pa_layer_attr)); 8417 hba->clk_scaling.is_allowed = true; 8418 8419 ret = ufshcd_devfreq_init(hba); 8420 if (ret) 8421 goto out; 8422 8423 hba->clk_scaling.is_enabled = true; 8424 ufshcd_init_clk_scaling_sysfs(hba); 8425 } 8426 8427 ufs_bsg_probe(hba); 8428 ufshpb_init(hba); 8429 scsi_scan_host(hba->host); 8430 pm_runtime_put_sync(hba->dev); 8431 8432 out: 8433 return ret; 8434 } 8435 8436 /* SDB - Single Doorbell */ 8437 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs) 8438 { 8439 size_t ucdl_size, utrdl_size; 8440 8441 ucdl_size = sizeof(struct utp_transfer_cmd_desc) * nutrs; 8442 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr, 8443 hba->ucdl_dma_addr); 8444 8445 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs; 8446 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr, 8447 hba->utrdl_dma_addr); 8448 8449 devm_kfree(hba->dev, hba->lrb); 8450 } 8451 8452 static int ufshcd_alloc_mcq(struct ufs_hba *hba) 8453 { 8454 int ret; 8455 int old_nutrs = hba->nutrs; 8456 8457 ret = ufshcd_mcq_decide_queue_depth(hba); 8458 if (ret < 0) 8459 return ret; 8460 8461 hba->nutrs = ret; 8462 ret = ufshcd_mcq_init(hba); 8463 if (ret) 8464 goto err; 8465 8466 /* 8467 * Previously allocated memory for nutrs may not be enough in MCQ mode. 8468 * Number of supported tags in MCQ mode may be larger than SDB mode. 8469 */ 8470 if (hba->nutrs != old_nutrs) { 8471 ufshcd_release_sdb_queue(hba, old_nutrs); 8472 ret = ufshcd_memory_alloc(hba); 8473 if (ret) 8474 goto err; 8475 ufshcd_host_memory_configure(hba); 8476 } 8477 8478 ret = ufshcd_mcq_memory_alloc(hba); 8479 if (ret) 8480 goto err; 8481 8482 return 0; 8483 err: 8484 hba->nutrs = old_nutrs; 8485 return ret; 8486 } 8487 8488 static void ufshcd_config_mcq(struct ufs_hba *hba) 8489 { 8490 int ret; 8491 8492 ret = ufshcd_mcq_vops_config_esi(hba); 8493 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : ""); 8494 8495 ufshcd_enable_intr(hba, UFSHCD_ENABLE_MCQ_INTRS); 8496 ufshcd_mcq_make_queues_operational(hba); 8497 ufshcd_mcq_config_mac(hba, hba->nutrs); 8498 8499 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED; 8500 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED; 8501 8502 /* Select MCQ mode */ 8503 ufshcd_writel(hba, ufshcd_readl(hba, REG_UFS_MEM_CFG) | 0x1, 8504 REG_UFS_MEM_CFG); 8505 hba->mcq_enabled = true; 8506 8507 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n", 8508 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT], 8509 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL], 8510 hba->nutrs); 8511 } 8512 8513 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params) 8514 { 8515 int ret; 8516 struct Scsi_Host *host = hba->host; 8517 8518 hba->ufshcd_state = UFSHCD_STATE_RESET; 8519 8520 ret = ufshcd_link_startup(hba); 8521 if (ret) 8522 return ret; 8523 8524 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION) 8525 return ret; 8526 8527 /* Debug counters initialization */ 8528 ufshcd_clear_dbg_ufs_stats(hba); 8529 8530 /* UniPro link is active now */ 8531 ufshcd_set_link_active(hba); 8532 8533 /* Reconfigure MCQ upon reset */ 8534 if (is_mcq_enabled(hba) && !init_dev_params) 8535 ufshcd_config_mcq(hba); 8536 8537 /* Verify device initialization by sending NOP OUT UPIU */ 8538 ret = ufshcd_verify_dev_init(hba); 8539 if (ret) 8540 return ret; 8541 8542 /* Initiate UFS initialization, and waiting until completion */ 8543 ret = ufshcd_complete_dev_init(hba); 8544 if (ret) 8545 return ret; 8546 8547 /* 8548 * Initialize UFS device parameters used by driver, these 8549 * parameters are associated with UFS descriptors. 8550 */ 8551 if (init_dev_params) { 8552 ret = ufshcd_device_params_init(hba); 8553 if (ret) 8554 return ret; 8555 if (is_mcq_supported(hba) && !hba->scsi_host_added) { 8556 ret = ufshcd_alloc_mcq(hba); 8557 if (!ret) { 8558 ufshcd_config_mcq(hba); 8559 } else { 8560 /* Continue with SDB mode */ 8561 use_mcq_mode = false; 8562 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n", 8563 ret); 8564 } 8565 ret = scsi_add_host(host, hba->dev); 8566 if (ret) { 8567 dev_err(hba->dev, "scsi_add_host failed\n"); 8568 return ret; 8569 } 8570 hba->scsi_host_added = true; 8571 } else if (is_mcq_supported(hba)) { 8572 /* UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is set */ 8573 ufshcd_config_mcq(hba); 8574 } 8575 } 8576 8577 ufshcd_tune_unipro_params(hba); 8578 8579 /* UFS device is also active now */ 8580 ufshcd_set_ufs_dev_active(hba); 8581 ufshcd_force_reset_auto_bkops(hba); 8582 8583 /* Gear up to HS gear if supported */ 8584 if (hba->max_pwr_info.is_valid) { 8585 /* 8586 * Set the right value to bRefClkFreq before attempting to 8587 * switch to HS gears. 8588 */ 8589 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL) 8590 ufshcd_set_dev_ref_clk(hba); 8591 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info); 8592 if (ret) { 8593 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n", 8594 __func__, ret); 8595 return ret; 8596 } 8597 } 8598 8599 return 0; 8600 } 8601 8602 /** 8603 * ufshcd_probe_hba - probe hba to detect device and initialize it 8604 * @hba: per-adapter instance 8605 * @init_dev_params: whether or not to call ufshcd_device_params_init(). 8606 * 8607 * Execute link-startup and verify device initialization 8608 */ 8609 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params) 8610 { 8611 ktime_t start = ktime_get(); 8612 unsigned long flags; 8613 int ret; 8614 8615 ret = ufshcd_device_init(hba, init_dev_params); 8616 if (ret) 8617 goto out; 8618 8619 if (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH) { 8620 /* Reset the device and controller before doing reinit */ 8621 ufshcd_device_reset(hba); 8622 ufshcd_hba_stop(hba); 8623 ufshcd_vops_reinit_notify(hba); 8624 ret = ufshcd_hba_enable(hba); 8625 if (ret) { 8626 dev_err(hba->dev, "Host controller enable failed\n"); 8627 ufshcd_print_evt_hist(hba); 8628 ufshcd_print_host_state(hba); 8629 goto out; 8630 } 8631 8632 /* Reinit the device */ 8633 ret = ufshcd_device_init(hba, init_dev_params); 8634 if (ret) 8635 goto out; 8636 } 8637 8638 ufshcd_print_pwr_info(hba); 8639 8640 /* 8641 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec) 8642 * and for removable UFS card as well, hence always set the parameter. 8643 * Note: Error handler may issue the device reset hence resetting 8644 * bActiveICCLevel as well so it is always safe to set this here. 8645 */ 8646 ufshcd_set_active_icc_lvl(hba); 8647 8648 /* Enable UFS Write Booster if supported */ 8649 ufshcd_configure_wb(hba); 8650 8651 if (hba->ee_usr_mask) 8652 ufshcd_write_ee_control(hba); 8653 /* Enable Auto-Hibernate if configured */ 8654 ufshcd_auto_hibern8_enable(hba); 8655 8656 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT); 8657 out: 8658 spin_lock_irqsave(hba->host->host_lock, flags); 8659 if (ret) 8660 hba->ufshcd_state = UFSHCD_STATE_ERROR; 8661 else if (hba->ufshcd_state == UFSHCD_STATE_RESET) 8662 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL; 8663 spin_unlock_irqrestore(hba->host->host_lock, flags); 8664 8665 trace_ufshcd_init(dev_name(hba->dev), ret, 8666 ktime_to_us(ktime_sub(ktime_get(), start)), 8667 hba->curr_dev_pwr_mode, hba->uic_link_state); 8668 return ret; 8669 } 8670 8671 /** 8672 * ufshcd_async_scan - asynchronous execution for probing hba 8673 * @data: data pointer to pass to this function 8674 * @cookie: cookie data 8675 */ 8676 static void ufshcd_async_scan(void *data, async_cookie_t cookie) 8677 { 8678 struct ufs_hba *hba = (struct ufs_hba *)data; 8679 int ret; 8680 8681 down(&hba->host_sem); 8682 /* Initialize hba, detect and initialize UFS device */ 8683 ret = ufshcd_probe_hba(hba, true); 8684 up(&hba->host_sem); 8685 if (ret) 8686 goto out; 8687 8688 /* Probe and add UFS logical units */ 8689 ret = ufshcd_add_lus(hba); 8690 out: 8691 /* 8692 * If we failed to initialize the device or the device is not 8693 * present, turn off the power/clocks etc. 8694 */ 8695 if (ret) { 8696 pm_runtime_put_sync(hba->dev); 8697 ufshcd_hba_exit(hba); 8698 } 8699 } 8700 8701 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd) 8702 { 8703 struct ufs_hba *hba = shost_priv(scmd->device->host); 8704 8705 if (!hba->system_suspending) { 8706 /* Activate the error handler in the SCSI core. */ 8707 return SCSI_EH_NOT_HANDLED; 8708 } 8709 8710 /* 8711 * If we get here we know that no TMFs are outstanding and also that 8712 * the only pending command is a START STOP UNIT command. Handle the 8713 * timeout of that command directly to prevent a deadlock between 8714 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler(). 8715 */ 8716 ufshcd_link_recovery(hba); 8717 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n", 8718 __func__, hba->outstanding_tasks); 8719 8720 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE; 8721 } 8722 8723 static const struct attribute_group *ufshcd_driver_groups[] = { 8724 &ufs_sysfs_unit_descriptor_group, 8725 &ufs_sysfs_lun_attributes_group, 8726 #ifdef CONFIG_SCSI_UFS_HPB 8727 &ufs_sysfs_hpb_stat_group, 8728 &ufs_sysfs_hpb_param_group, 8729 #endif 8730 NULL, 8731 }; 8732 8733 static struct ufs_hba_variant_params ufs_hba_vps = { 8734 .hba_enable_delay_us = 1000, 8735 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40), 8736 .devfreq_profile.polling_ms = 100, 8737 .devfreq_profile.target = ufshcd_devfreq_target, 8738 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status, 8739 .ondemand_data.upthreshold = 70, 8740 .ondemand_data.downdifferential = 5, 8741 }; 8742 8743 static const struct scsi_host_template ufshcd_driver_template = { 8744 .module = THIS_MODULE, 8745 .name = UFSHCD, 8746 .proc_name = UFSHCD, 8747 .map_queues = ufshcd_map_queues, 8748 .queuecommand = ufshcd_queuecommand, 8749 .mq_poll = ufshcd_poll, 8750 .slave_alloc = ufshcd_slave_alloc, 8751 .slave_configure = ufshcd_slave_configure, 8752 .slave_destroy = ufshcd_slave_destroy, 8753 .change_queue_depth = ufshcd_change_queue_depth, 8754 .eh_abort_handler = ufshcd_abort, 8755 .eh_device_reset_handler = ufshcd_eh_device_reset_handler, 8756 .eh_host_reset_handler = ufshcd_eh_host_reset_handler, 8757 .eh_timed_out = ufshcd_eh_timed_out, 8758 .this_id = -1, 8759 .sg_tablesize = SG_ALL, 8760 .cmd_per_lun = UFSHCD_CMD_PER_LUN, 8761 .can_queue = UFSHCD_CAN_QUEUE, 8762 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX, 8763 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */ 8764 .max_host_blocked = 1, 8765 .track_queue_depth = 1, 8766 .skip_settle_delay = 1, 8767 .sdev_groups = ufshcd_driver_groups, 8768 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS, 8769 }; 8770 8771 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg, 8772 int ua) 8773 { 8774 int ret; 8775 8776 if (!vreg) 8777 return 0; 8778 8779 /* 8780 * "set_load" operation shall be required on those regulators 8781 * which specifically configured current limitation. Otherwise 8782 * zero max_uA may cause unexpected behavior when regulator is 8783 * enabled or set as high power mode. 8784 */ 8785 if (!vreg->max_uA) 8786 return 0; 8787 8788 ret = regulator_set_load(vreg->reg, ua); 8789 if (ret < 0) { 8790 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n", 8791 __func__, vreg->name, ua, ret); 8792 } 8793 8794 return ret; 8795 } 8796 8797 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba, 8798 struct ufs_vreg *vreg) 8799 { 8800 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA); 8801 } 8802 8803 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba, 8804 struct ufs_vreg *vreg) 8805 { 8806 if (!vreg) 8807 return 0; 8808 8809 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA); 8810 } 8811 8812 static int ufshcd_config_vreg(struct device *dev, 8813 struct ufs_vreg *vreg, bool on) 8814 { 8815 if (regulator_count_voltages(vreg->reg) <= 0) 8816 return 0; 8817 8818 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0); 8819 } 8820 8821 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg) 8822 { 8823 int ret = 0; 8824 8825 if (!vreg || vreg->enabled) 8826 goto out; 8827 8828 ret = ufshcd_config_vreg(dev, vreg, true); 8829 if (!ret) 8830 ret = regulator_enable(vreg->reg); 8831 8832 if (!ret) 8833 vreg->enabled = true; 8834 else 8835 dev_err(dev, "%s: %s enable failed, err=%d\n", 8836 __func__, vreg->name, ret); 8837 out: 8838 return ret; 8839 } 8840 8841 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg) 8842 { 8843 int ret = 0; 8844 8845 if (!vreg || !vreg->enabled || vreg->always_on) 8846 goto out; 8847 8848 ret = regulator_disable(vreg->reg); 8849 8850 if (!ret) { 8851 /* ignore errors on applying disable config */ 8852 ufshcd_config_vreg(dev, vreg, false); 8853 vreg->enabled = false; 8854 } else { 8855 dev_err(dev, "%s: %s disable failed, err=%d\n", 8856 __func__, vreg->name, ret); 8857 } 8858 out: 8859 return ret; 8860 } 8861 8862 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on) 8863 { 8864 int ret = 0; 8865 struct device *dev = hba->dev; 8866 struct ufs_vreg_info *info = &hba->vreg_info; 8867 8868 ret = ufshcd_toggle_vreg(dev, info->vcc, on); 8869 if (ret) 8870 goto out; 8871 8872 ret = ufshcd_toggle_vreg(dev, info->vccq, on); 8873 if (ret) 8874 goto out; 8875 8876 ret = ufshcd_toggle_vreg(dev, info->vccq2, on); 8877 8878 out: 8879 if (ret) { 8880 ufshcd_toggle_vreg(dev, info->vccq2, false); 8881 ufshcd_toggle_vreg(dev, info->vccq, false); 8882 ufshcd_toggle_vreg(dev, info->vcc, false); 8883 } 8884 return ret; 8885 } 8886 8887 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on) 8888 { 8889 struct ufs_vreg_info *info = &hba->vreg_info; 8890 8891 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on); 8892 } 8893 8894 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg) 8895 { 8896 int ret = 0; 8897 8898 if (!vreg) 8899 goto out; 8900 8901 vreg->reg = devm_regulator_get(dev, vreg->name); 8902 if (IS_ERR(vreg->reg)) { 8903 ret = PTR_ERR(vreg->reg); 8904 dev_err(dev, "%s: %s get failed, err=%d\n", 8905 __func__, vreg->name, ret); 8906 } 8907 out: 8908 return ret; 8909 } 8910 EXPORT_SYMBOL_GPL(ufshcd_get_vreg); 8911 8912 static int ufshcd_init_vreg(struct ufs_hba *hba) 8913 { 8914 int ret = 0; 8915 struct device *dev = hba->dev; 8916 struct ufs_vreg_info *info = &hba->vreg_info; 8917 8918 ret = ufshcd_get_vreg(dev, info->vcc); 8919 if (ret) 8920 goto out; 8921 8922 ret = ufshcd_get_vreg(dev, info->vccq); 8923 if (!ret) 8924 ret = ufshcd_get_vreg(dev, info->vccq2); 8925 out: 8926 return ret; 8927 } 8928 8929 static int ufshcd_init_hba_vreg(struct ufs_hba *hba) 8930 { 8931 struct ufs_vreg_info *info = &hba->vreg_info; 8932 8933 return ufshcd_get_vreg(hba->dev, info->vdd_hba); 8934 } 8935 8936 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on) 8937 { 8938 int ret = 0; 8939 struct ufs_clk_info *clki; 8940 struct list_head *head = &hba->clk_list_head; 8941 unsigned long flags; 8942 ktime_t start = ktime_get(); 8943 bool clk_state_changed = false; 8944 8945 if (list_empty(head)) 8946 goto out; 8947 8948 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE); 8949 if (ret) 8950 return ret; 8951 8952 list_for_each_entry(clki, head, list) { 8953 if (!IS_ERR_OR_NULL(clki->clk)) { 8954 /* 8955 * Don't disable clocks which are needed 8956 * to keep the link active. 8957 */ 8958 if (ufshcd_is_link_active(hba) && 8959 clki->keep_link_active) 8960 continue; 8961 8962 clk_state_changed = on ^ clki->enabled; 8963 if (on && !clki->enabled) { 8964 ret = clk_prepare_enable(clki->clk); 8965 if (ret) { 8966 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n", 8967 __func__, clki->name, ret); 8968 goto out; 8969 } 8970 } else if (!on && clki->enabled) { 8971 clk_disable_unprepare(clki->clk); 8972 } 8973 clki->enabled = on; 8974 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__, 8975 clki->name, on ? "en" : "dis"); 8976 } 8977 } 8978 8979 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE); 8980 if (ret) 8981 return ret; 8982 8983 out: 8984 if (ret) { 8985 list_for_each_entry(clki, head, list) { 8986 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled) 8987 clk_disable_unprepare(clki->clk); 8988 } 8989 } else if (!ret && on) { 8990 spin_lock_irqsave(hba->host->host_lock, flags); 8991 hba->clk_gating.state = CLKS_ON; 8992 trace_ufshcd_clk_gating(dev_name(hba->dev), 8993 hba->clk_gating.state); 8994 spin_unlock_irqrestore(hba->host->host_lock, flags); 8995 } 8996 8997 if (clk_state_changed) 8998 trace_ufshcd_profile_clk_gating(dev_name(hba->dev), 8999 (on ? "on" : "off"), 9000 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 9001 return ret; 9002 } 9003 9004 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba) 9005 { 9006 u32 freq; 9007 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq); 9008 9009 if (ret) { 9010 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret); 9011 return REF_CLK_FREQ_INVAL; 9012 } 9013 9014 return ufs_get_bref_clk_from_hz(freq); 9015 } 9016 9017 static int ufshcd_init_clocks(struct ufs_hba *hba) 9018 { 9019 int ret = 0; 9020 struct ufs_clk_info *clki; 9021 struct device *dev = hba->dev; 9022 struct list_head *head = &hba->clk_list_head; 9023 9024 if (list_empty(head)) 9025 goto out; 9026 9027 list_for_each_entry(clki, head, list) { 9028 if (!clki->name) 9029 continue; 9030 9031 clki->clk = devm_clk_get(dev, clki->name); 9032 if (IS_ERR(clki->clk)) { 9033 ret = PTR_ERR(clki->clk); 9034 dev_err(dev, "%s: %s clk get failed, %d\n", 9035 __func__, clki->name, ret); 9036 goto out; 9037 } 9038 9039 /* 9040 * Parse device ref clk freq as per device tree "ref_clk". 9041 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL 9042 * in ufshcd_alloc_host(). 9043 */ 9044 if (!strcmp(clki->name, "ref_clk")) 9045 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk); 9046 9047 if (clki->max_freq) { 9048 ret = clk_set_rate(clki->clk, clki->max_freq); 9049 if (ret) { 9050 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n", 9051 __func__, clki->name, 9052 clki->max_freq, ret); 9053 goto out; 9054 } 9055 clki->curr_freq = clki->max_freq; 9056 } 9057 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__, 9058 clki->name, clk_get_rate(clki->clk)); 9059 } 9060 out: 9061 return ret; 9062 } 9063 9064 static int ufshcd_variant_hba_init(struct ufs_hba *hba) 9065 { 9066 int err = 0; 9067 9068 if (!hba->vops) 9069 goto out; 9070 9071 err = ufshcd_vops_init(hba); 9072 if (err) 9073 dev_err(hba->dev, "%s: variant %s init failed err %d\n", 9074 __func__, ufshcd_get_var_name(hba), err); 9075 out: 9076 return err; 9077 } 9078 9079 static void ufshcd_variant_hba_exit(struct ufs_hba *hba) 9080 { 9081 if (!hba->vops) 9082 return; 9083 9084 ufshcd_vops_exit(hba); 9085 } 9086 9087 static int ufshcd_hba_init(struct ufs_hba *hba) 9088 { 9089 int err; 9090 9091 /* 9092 * Handle host controller power separately from the UFS device power 9093 * rails as it will help controlling the UFS host controller power 9094 * collapse easily which is different than UFS device power collapse. 9095 * Also, enable the host controller power before we go ahead with rest 9096 * of the initialization here. 9097 */ 9098 err = ufshcd_init_hba_vreg(hba); 9099 if (err) 9100 goto out; 9101 9102 err = ufshcd_setup_hba_vreg(hba, true); 9103 if (err) 9104 goto out; 9105 9106 err = ufshcd_init_clocks(hba); 9107 if (err) 9108 goto out_disable_hba_vreg; 9109 9110 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL) 9111 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba); 9112 9113 err = ufshcd_setup_clocks(hba, true); 9114 if (err) 9115 goto out_disable_hba_vreg; 9116 9117 err = ufshcd_init_vreg(hba); 9118 if (err) 9119 goto out_disable_clks; 9120 9121 err = ufshcd_setup_vreg(hba, true); 9122 if (err) 9123 goto out_disable_clks; 9124 9125 err = ufshcd_variant_hba_init(hba); 9126 if (err) 9127 goto out_disable_vreg; 9128 9129 ufs_debugfs_hba_init(hba); 9130 9131 hba->is_powered = true; 9132 goto out; 9133 9134 out_disable_vreg: 9135 ufshcd_setup_vreg(hba, false); 9136 out_disable_clks: 9137 ufshcd_setup_clocks(hba, false); 9138 out_disable_hba_vreg: 9139 ufshcd_setup_hba_vreg(hba, false); 9140 out: 9141 return err; 9142 } 9143 9144 static void ufshcd_hba_exit(struct ufs_hba *hba) 9145 { 9146 if (hba->is_powered) { 9147 ufshcd_exit_clk_scaling(hba); 9148 ufshcd_exit_clk_gating(hba); 9149 if (hba->eh_wq) 9150 destroy_workqueue(hba->eh_wq); 9151 ufs_debugfs_hba_exit(hba); 9152 ufshcd_variant_hba_exit(hba); 9153 ufshcd_setup_vreg(hba, false); 9154 ufshcd_setup_clocks(hba, false); 9155 ufshcd_setup_hba_vreg(hba, false); 9156 hba->is_powered = false; 9157 ufs_put_device_desc(hba); 9158 } 9159 } 9160 9161 static int ufshcd_execute_start_stop(struct scsi_device *sdev, 9162 enum ufs_dev_pwr_mode pwr_mode, 9163 struct scsi_sense_hdr *sshdr) 9164 { 9165 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 }; 9166 const struct scsi_exec_args args = { 9167 .sshdr = sshdr, 9168 .req_flags = BLK_MQ_REQ_PM, 9169 .scmd_flags = SCMD_FAIL_IF_RECOVERING, 9170 }; 9171 9172 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL, 9173 /*bufflen=*/0, /*timeout=*/HZ, /*retries=*/0, &args); 9174 } 9175 9176 /** 9177 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device 9178 * power mode 9179 * @hba: per adapter instance 9180 * @pwr_mode: device power mode to set 9181 * 9182 * Returns 0 if requested power mode is set successfully 9183 * Returns < 0 if failed to set the requested power mode 9184 */ 9185 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba, 9186 enum ufs_dev_pwr_mode pwr_mode) 9187 { 9188 struct scsi_sense_hdr sshdr; 9189 struct scsi_device *sdp; 9190 unsigned long flags; 9191 int ret, retries; 9192 9193 spin_lock_irqsave(hba->host->host_lock, flags); 9194 sdp = hba->ufs_device_wlun; 9195 if (sdp && scsi_device_online(sdp)) 9196 ret = scsi_device_get(sdp); 9197 else 9198 ret = -ENODEV; 9199 spin_unlock_irqrestore(hba->host->host_lock, flags); 9200 9201 if (ret) 9202 return ret; 9203 9204 /* 9205 * If scsi commands fail, the scsi mid-layer schedules scsi error- 9206 * handling, which would wait for host to be resumed. Since we know 9207 * we are functional while we are here, skip host resume in error 9208 * handling context. 9209 */ 9210 hba->host->eh_noresume = 1; 9211 9212 /* 9213 * Current function would be generally called from the power management 9214 * callbacks hence set the RQF_PM flag so that it doesn't resume the 9215 * already suspended childs. 9216 */ 9217 for (retries = 3; retries > 0; --retries) { 9218 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr); 9219 /* 9220 * scsi_execute() only returns a negative value if the request 9221 * queue is dying. 9222 */ 9223 if (ret <= 0) 9224 break; 9225 } 9226 if (ret) { 9227 sdev_printk(KERN_WARNING, sdp, 9228 "START_STOP failed for power mode: %d, result %x\n", 9229 pwr_mode, ret); 9230 if (ret > 0) { 9231 if (scsi_sense_valid(&sshdr)) 9232 scsi_print_sense_hdr(sdp, NULL, &sshdr); 9233 ret = -EIO; 9234 } 9235 } else { 9236 hba->curr_dev_pwr_mode = pwr_mode; 9237 } 9238 9239 scsi_device_put(sdp); 9240 hba->host->eh_noresume = 0; 9241 return ret; 9242 } 9243 9244 static int ufshcd_link_state_transition(struct ufs_hba *hba, 9245 enum uic_link_state req_link_state, 9246 bool check_for_bkops) 9247 { 9248 int ret = 0; 9249 9250 if (req_link_state == hba->uic_link_state) 9251 return 0; 9252 9253 if (req_link_state == UIC_LINK_HIBERN8_STATE) { 9254 ret = ufshcd_uic_hibern8_enter(hba); 9255 if (!ret) { 9256 ufshcd_set_link_hibern8(hba); 9257 } else { 9258 dev_err(hba->dev, "%s: hibern8 enter failed %d\n", 9259 __func__, ret); 9260 goto out; 9261 } 9262 } 9263 /* 9264 * If autobkops is enabled, link can't be turned off because 9265 * turning off the link would also turn off the device, except in the 9266 * case of DeepSleep where the device is expected to remain powered. 9267 */ 9268 else if ((req_link_state == UIC_LINK_OFF_STATE) && 9269 (!check_for_bkops || !hba->auto_bkops_enabled)) { 9270 /* 9271 * Let's make sure that link is in low power mode, we are doing 9272 * this currently by putting the link in Hibern8. Otherway to 9273 * put the link in low power mode is to send the DME end point 9274 * to device and then send the DME reset command to local 9275 * unipro. But putting the link in hibern8 is much faster. 9276 * 9277 * Note also that putting the link in Hibern8 is a requirement 9278 * for entering DeepSleep. 9279 */ 9280 ret = ufshcd_uic_hibern8_enter(hba); 9281 if (ret) { 9282 dev_err(hba->dev, "%s: hibern8 enter failed %d\n", 9283 __func__, ret); 9284 goto out; 9285 } 9286 /* 9287 * Change controller state to "reset state" which 9288 * should also put the link in off/reset state 9289 */ 9290 ufshcd_hba_stop(hba); 9291 /* 9292 * TODO: Check if we need any delay to make sure that 9293 * controller is reset 9294 */ 9295 ufshcd_set_link_off(hba); 9296 } 9297 9298 out: 9299 return ret; 9300 } 9301 9302 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba) 9303 { 9304 bool vcc_off = false; 9305 9306 /* 9307 * It seems some UFS devices may keep drawing more than sleep current 9308 * (atleast for 500us) from UFS rails (especially from VCCQ rail). 9309 * To avoid this situation, add 2ms delay before putting these UFS 9310 * rails in LPM mode. 9311 */ 9312 if (!ufshcd_is_link_active(hba) && 9313 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM) 9314 usleep_range(2000, 2100); 9315 9316 /* 9317 * If UFS device is either in UFS_Sleep turn off VCC rail to save some 9318 * power. 9319 * 9320 * If UFS device and link is in OFF state, all power supplies (VCC, 9321 * VCCQ, VCCQ2) can be turned off if power on write protect is not 9322 * required. If UFS link is inactive (Hibern8 or OFF state) and device 9323 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode. 9324 * 9325 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway 9326 * in low power state which would save some power. 9327 * 9328 * If Write Booster is enabled and the device needs to flush the WB 9329 * buffer OR if bkops status is urgent for WB, keep Vcc on. 9330 */ 9331 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) && 9332 !hba->dev_info.is_lu_power_on_wp) { 9333 ufshcd_setup_vreg(hba, false); 9334 vcc_off = true; 9335 } else if (!ufshcd_is_ufs_dev_active(hba)) { 9336 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false); 9337 vcc_off = true; 9338 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) { 9339 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq); 9340 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2); 9341 } 9342 } 9343 9344 /* 9345 * Some UFS devices require delay after VCC power rail is turned-off. 9346 */ 9347 if (vcc_off && hba->vreg_info.vcc && 9348 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM) 9349 usleep_range(5000, 5100); 9350 } 9351 9352 #ifdef CONFIG_PM 9353 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba) 9354 { 9355 int ret = 0; 9356 9357 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) && 9358 !hba->dev_info.is_lu_power_on_wp) { 9359 ret = ufshcd_setup_vreg(hba, true); 9360 } else if (!ufshcd_is_ufs_dev_active(hba)) { 9361 if (!ufshcd_is_link_active(hba)) { 9362 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq); 9363 if (ret) 9364 goto vcc_disable; 9365 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2); 9366 if (ret) 9367 goto vccq_lpm; 9368 } 9369 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true); 9370 } 9371 goto out; 9372 9373 vccq_lpm: 9374 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq); 9375 vcc_disable: 9376 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false); 9377 out: 9378 return ret; 9379 } 9380 #endif /* CONFIG_PM */ 9381 9382 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba) 9383 { 9384 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba)) 9385 ufshcd_setup_hba_vreg(hba, false); 9386 } 9387 9388 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba) 9389 { 9390 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba)) 9391 ufshcd_setup_hba_vreg(hba, true); 9392 } 9393 9394 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op) 9395 { 9396 int ret = 0; 9397 bool check_for_bkops; 9398 enum ufs_pm_level pm_lvl; 9399 enum ufs_dev_pwr_mode req_dev_pwr_mode; 9400 enum uic_link_state req_link_state; 9401 9402 hba->pm_op_in_progress = true; 9403 if (pm_op != UFS_SHUTDOWN_PM) { 9404 pm_lvl = pm_op == UFS_RUNTIME_PM ? 9405 hba->rpm_lvl : hba->spm_lvl; 9406 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl); 9407 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl); 9408 } else { 9409 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE; 9410 req_link_state = UIC_LINK_OFF_STATE; 9411 } 9412 9413 ufshpb_suspend(hba); 9414 9415 /* 9416 * If we can't transition into any of the low power modes 9417 * just gate the clocks. 9418 */ 9419 ufshcd_hold(hba, false); 9420 hba->clk_gating.is_suspended = true; 9421 9422 if (ufshcd_is_clkscaling_supported(hba)) 9423 ufshcd_clk_scaling_suspend(hba, true); 9424 9425 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE && 9426 req_link_state == UIC_LINK_ACTIVE_STATE) { 9427 goto vops_suspend; 9428 } 9429 9430 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) && 9431 (req_link_state == hba->uic_link_state)) 9432 goto enable_scaling; 9433 9434 /* UFS device & link must be active before we enter in this function */ 9435 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) { 9436 ret = -EINVAL; 9437 goto enable_scaling; 9438 } 9439 9440 if (pm_op == UFS_RUNTIME_PM) { 9441 if (ufshcd_can_autobkops_during_suspend(hba)) { 9442 /* 9443 * The device is idle with no requests in the queue, 9444 * allow background operations if bkops status shows 9445 * that performance might be impacted. 9446 */ 9447 ret = ufshcd_urgent_bkops(hba); 9448 if (ret) 9449 goto enable_scaling; 9450 } else { 9451 /* make sure that auto bkops is disabled */ 9452 ufshcd_disable_auto_bkops(hba); 9453 } 9454 /* 9455 * If device needs to do BKOP or WB buffer flush during 9456 * Hibern8, keep device power mode as "active power mode" 9457 * and VCC supply. 9458 */ 9459 hba->dev_info.b_rpm_dev_flush_capable = 9460 hba->auto_bkops_enabled || 9461 (((req_link_state == UIC_LINK_HIBERN8_STATE) || 9462 ((req_link_state == UIC_LINK_ACTIVE_STATE) && 9463 ufshcd_is_auto_hibern8_enabled(hba))) && 9464 ufshcd_wb_need_flush(hba)); 9465 } 9466 9467 flush_work(&hba->eeh_work); 9468 9469 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE); 9470 if (ret) 9471 goto enable_scaling; 9472 9473 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) { 9474 if (pm_op != UFS_RUNTIME_PM) 9475 /* ensure that bkops is disabled */ 9476 ufshcd_disable_auto_bkops(hba); 9477 9478 if (!hba->dev_info.b_rpm_dev_flush_capable) { 9479 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode); 9480 if (ret && pm_op != UFS_SHUTDOWN_PM) { 9481 /* 9482 * If return err in suspend flow, IO will hang. 9483 * Trigger error handler and break suspend for 9484 * error recovery. 9485 */ 9486 ufshcd_force_error_recovery(hba); 9487 ret = -EBUSY; 9488 } 9489 if (ret) 9490 goto enable_scaling; 9491 } 9492 } 9493 9494 /* 9495 * In the case of DeepSleep, the device is expected to remain powered 9496 * with the link off, so do not check for bkops. 9497 */ 9498 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba); 9499 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops); 9500 if (ret && pm_op != UFS_SHUTDOWN_PM) { 9501 /* 9502 * If return err in suspend flow, IO will hang. 9503 * Trigger error handler and break suspend for 9504 * error recovery. 9505 */ 9506 ufshcd_force_error_recovery(hba); 9507 ret = -EBUSY; 9508 } 9509 if (ret) 9510 goto set_dev_active; 9511 9512 vops_suspend: 9513 /* 9514 * Call vendor specific suspend callback. As these callbacks may access 9515 * vendor specific host controller register space call them before the 9516 * host clocks are ON. 9517 */ 9518 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE); 9519 if (ret) 9520 goto set_link_active; 9521 goto out; 9522 9523 set_link_active: 9524 /* 9525 * Device hardware reset is required to exit DeepSleep. Also, for 9526 * DeepSleep, the link is off so host reset and restore will be done 9527 * further below. 9528 */ 9529 if (ufshcd_is_ufs_dev_deepsleep(hba)) { 9530 ufshcd_device_reset(hba); 9531 WARN_ON(!ufshcd_is_link_off(hba)); 9532 } 9533 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba)) 9534 ufshcd_set_link_active(hba); 9535 else if (ufshcd_is_link_off(hba)) 9536 ufshcd_host_reset_and_restore(hba); 9537 set_dev_active: 9538 /* Can also get here needing to exit DeepSleep */ 9539 if (ufshcd_is_ufs_dev_deepsleep(hba)) { 9540 ufshcd_device_reset(hba); 9541 ufshcd_host_reset_and_restore(hba); 9542 } 9543 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE)) 9544 ufshcd_disable_auto_bkops(hba); 9545 enable_scaling: 9546 if (ufshcd_is_clkscaling_supported(hba)) 9547 ufshcd_clk_scaling_suspend(hba, false); 9548 9549 hba->dev_info.b_rpm_dev_flush_capable = false; 9550 out: 9551 if (hba->dev_info.b_rpm_dev_flush_capable) { 9552 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work, 9553 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS)); 9554 } 9555 9556 if (ret) { 9557 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret); 9558 hba->clk_gating.is_suspended = false; 9559 ufshcd_release(hba); 9560 ufshpb_resume(hba); 9561 } 9562 hba->pm_op_in_progress = false; 9563 return ret; 9564 } 9565 9566 #ifdef CONFIG_PM 9567 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op) 9568 { 9569 int ret; 9570 enum uic_link_state old_link_state = hba->uic_link_state; 9571 9572 hba->pm_op_in_progress = true; 9573 9574 /* 9575 * Call vendor specific resume callback. As these callbacks may access 9576 * vendor specific host controller register space call them when the 9577 * host clocks are ON. 9578 */ 9579 ret = ufshcd_vops_resume(hba, pm_op); 9580 if (ret) 9581 goto out; 9582 9583 /* For DeepSleep, the only supported option is to have the link off */ 9584 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba)); 9585 9586 if (ufshcd_is_link_hibern8(hba)) { 9587 ret = ufshcd_uic_hibern8_exit(hba); 9588 if (!ret) { 9589 ufshcd_set_link_active(hba); 9590 } else { 9591 dev_err(hba->dev, "%s: hibern8 exit failed %d\n", 9592 __func__, ret); 9593 goto vendor_suspend; 9594 } 9595 } else if (ufshcd_is_link_off(hba)) { 9596 /* 9597 * A full initialization of the host and the device is 9598 * required since the link was put to off during suspend. 9599 * Note, in the case of DeepSleep, the device will exit 9600 * DeepSleep due to device reset. 9601 */ 9602 ret = ufshcd_reset_and_restore(hba); 9603 /* 9604 * ufshcd_reset_and_restore() should have already 9605 * set the link state as active 9606 */ 9607 if (ret || !ufshcd_is_link_active(hba)) 9608 goto vendor_suspend; 9609 } 9610 9611 if (!ufshcd_is_ufs_dev_active(hba)) { 9612 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE); 9613 if (ret) 9614 goto set_old_link_state; 9615 } 9616 9617 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) 9618 ufshcd_enable_auto_bkops(hba); 9619 else 9620 /* 9621 * If BKOPs operations are urgently needed at this moment then 9622 * keep auto-bkops enabled or else disable it. 9623 */ 9624 ufshcd_urgent_bkops(hba); 9625 9626 if (hba->ee_usr_mask) 9627 ufshcd_write_ee_control(hba); 9628 9629 if (ufshcd_is_clkscaling_supported(hba)) 9630 ufshcd_clk_scaling_suspend(hba, false); 9631 9632 if (hba->dev_info.b_rpm_dev_flush_capable) { 9633 hba->dev_info.b_rpm_dev_flush_capable = false; 9634 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work); 9635 } 9636 9637 /* Enable Auto-Hibernate if configured */ 9638 ufshcd_auto_hibern8_enable(hba); 9639 9640 ufshpb_resume(hba); 9641 goto out; 9642 9643 set_old_link_state: 9644 ufshcd_link_state_transition(hba, old_link_state, 0); 9645 vendor_suspend: 9646 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE); 9647 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE); 9648 out: 9649 if (ret) 9650 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret); 9651 hba->clk_gating.is_suspended = false; 9652 ufshcd_release(hba); 9653 hba->pm_op_in_progress = false; 9654 return ret; 9655 } 9656 9657 static int ufshcd_wl_runtime_suspend(struct device *dev) 9658 { 9659 struct scsi_device *sdev = to_scsi_device(dev); 9660 struct ufs_hba *hba; 9661 int ret; 9662 ktime_t start = ktime_get(); 9663 9664 hba = shost_priv(sdev->host); 9665 9666 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM); 9667 if (ret) 9668 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9669 9670 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret, 9671 ktime_to_us(ktime_sub(ktime_get(), start)), 9672 hba->curr_dev_pwr_mode, hba->uic_link_state); 9673 9674 return ret; 9675 } 9676 9677 static int ufshcd_wl_runtime_resume(struct device *dev) 9678 { 9679 struct scsi_device *sdev = to_scsi_device(dev); 9680 struct ufs_hba *hba; 9681 int ret = 0; 9682 ktime_t start = ktime_get(); 9683 9684 hba = shost_priv(sdev->host); 9685 9686 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM); 9687 if (ret) 9688 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9689 9690 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret, 9691 ktime_to_us(ktime_sub(ktime_get(), start)), 9692 hba->curr_dev_pwr_mode, hba->uic_link_state); 9693 9694 return ret; 9695 } 9696 #endif 9697 9698 #ifdef CONFIG_PM_SLEEP 9699 static int ufshcd_wl_suspend(struct device *dev) 9700 { 9701 struct scsi_device *sdev = to_scsi_device(dev); 9702 struct ufs_hba *hba; 9703 int ret = 0; 9704 ktime_t start = ktime_get(); 9705 9706 hba = shost_priv(sdev->host); 9707 down(&hba->host_sem); 9708 hba->system_suspending = true; 9709 9710 if (pm_runtime_suspended(dev)) 9711 goto out; 9712 9713 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM); 9714 if (ret) { 9715 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9716 up(&hba->host_sem); 9717 } 9718 9719 out: 9720 if (!ret) 9721 hba->is_sys_suspended = true; 9722 trace_ufshcd_wl_suspend(dev_name(dev), ret, 9723 ktime_to_us(ktime_sub(ktime_get(), start)), 9724 hba->curr_dev_pwr_mode, hba->uic_link_state); 9725 9726 return ret; 9727 } 9728 9729 static int ufshcd_wl_resume(struct device *dev) 9730 { 9731 struct scsi_device *sdev = to_scsi_device(dev); 9732 struct ufs_hba *hba; 9733 int ret = 0; 9734 ktime_t start = ktime_get(); 9735 9736 hba = shost_priv(sdev->host); 9737 9738 if (pm_runtime_suspended(dev)) 9739 goto out; 9740 9741 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM); 9742 if (ret) 9743 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9744 out: 9745 trace_ufshcd_wl_resume(dev_name(dev), ret, 9746 ktime_to_us(ktime_sub(ktime_get(), start)), 9747 hba->curr_dev_pwr_mode, hba->uic_link_state); 9748 if (!ret) 9749 hba->is_sys_suspended = false; 9750 hba->system_suspending = false; 9751 up(&hba->host_sem); 9752 return ret; 9753 } 9754 #endif 9755 9756 static void ufshcd_wl_shutdown(struct device *dev) 9757 { 9758 struct scsi_device *sdev = to_scsi_device(dev); 9759 struct ufs_hba *hba; 9760 9761 hba = shost_priv(sdev->host); 9762 9763 down(&hba->host_sem); 9764 hba->shutting_down = true; 9765 up(&hba->host_sem); 9766 9767 /* Turn on everything while shutting down */ 9768 ufshcd_rpm_get_sync(hba); 9769 scsi_device_quiesce(sdev); 9770 shost_for_each_device(sdev, hba->host) { 9771 if (sdev == hba->ufs_device_wlun) 9772 continue; 9773 scsi_device_quiesce(sdev); 9774 } 9775 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM); 9776 } 9777 9778 /** 9779 * ufshcd_suspend - helper function for suspend operations 9780 * @hba: per adapter instance 9781 * 9782 * This function will put disable irqs, turn off clocks 9783 * and set vreg and hba-vreg in lpm mode. 9784 */ 9785 static int ufshcd_suspend(struct ufs_hba *hba) 9786 { 9787 int ret; 9788 9789 if (!hba->is_powered) 9790 return 0; 9791 /* 9792 * Disable the host irq as host controller as there won't be any 9793 * host controller transaction expected till resume. 9794 */ 9795 ufshcd_disable_irq(hba); 9796 ret = ufshcd_setup_clocks(hba, false); 9797 if (ret) { 9798 ufshcd_enable_irq(hba); 9799 return ret; 9800 } 9801 if (ufshcd_is_clkgating_allowed(hba)) { 9802 hba->clk_gating.state = CLKS_OFF; 9803 trace_ufshcd_clk_gating(dev_name(hba->dev), 9804 hba->clk_gating.state); 9805 } 9806 9807 ufshcd_vreg_set_lpm(hba); 9808 /* Put the host controller in low power mode if possible */ 9809 ufshcd_hba_vreg_set_lpm(hba); 9810 return ret; 9811 } 9812 9813 #ifdef CONFIG_PM 9814 /** 9815 * ufshcd_resume - helper function for resume operations 9816 * @hba: per adapter instance 9817 * 9818 * This function basically turns on the regulators, clocks and 9819 * irqs of the hba. 9820 * 9821 * Returns 0 for success and non-zero for failure 9822 */ 9823 static int ufshcd_resume(struct ufs_hba *hba) 9824 { 9825 int ret; 9826 9827 if (!hba->is_powered) 9828 return 0; 9829 9830 ufshcd_hba_vreg_set_hpm(hba); 9831 ret = ufshcd_vreg_set_hpm(hba); 9832 if (ret) 9833 goto out; 9834 9835 /* Make sure clocks are enabled before accessing controller */ 9836 ret = ufshcd_setup_clocks(hba, true); 9837 if (ret) 9838 goto disable_vreg; 9839 9840 /* enable the host irq as host controller would be active soon */ 9841 ufshcd_enable_irq(hba); 9842 9843 goto out; 9844 9845 disable_vreg: 9846 ufshcd_vreg_set_lpm(hba); 9847 out: 9848 if (ret) 9849 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret); 9850 return ret; 9851 } 9852 #endif /* CONFIG_PM */ 9853 9854 #ifdef CONFIG_PM_SLEEP 9855 /** 9856 * ufshcd_system_suspend - system suspend callback 9857 * @dev: Device associated with the UFS controller. 9858 * 9859 * Executed before putting the system into a sleep state in which the contents 9860 * of main memory are preserved. 9861 * 9862 * Returns 0 for success and non-zero for failure 9863 */ 9864 int ufshcd_system_suspend(struct device *dev) 9865 { 9866 struct ufs_hba *hba = dev_get_drvdata(dev); 9867 int ret = 0; 9868 ktime_t start = ktime_get(); 9869 9870 if (pm_runtime_suspended(hba->dev)) 9871 goto out; 9872 9873 ret = ufshcd_suspend(hba); 9874 out: 9875 trace_ufshcd_system_suspend(dev_name(hba->dev), ret, 9876 ktime_to_us(ktime_sub(ktime_get(), start)), 9877 hba->curr_dev_pwr_mode, hba->uic_link_state); 9878 return ret; 9879 } 9880 EXPORT_SYMBOL(ufshcd_system_suspend); 9881 9882 /** 9883 * ufshcd_system_resume - system resume callback 9884 * @dev: Device associated with the UFS controller. 9885 * 9886 * Executed after waking the system up from a sleep state in which the contents 9887 * of main memory were preserved. 9888 * 9889 * Returns 0 for success and non-zero for failure 9890 */ 9891 int ufshcd_system_resume(struct device *dev) 9892 { 9893 struct ufs_hba *hba = dev_get_drvdata(dev); 9894 ktime_t start = ktime_get(); 9895 int ret = 0; 9896 9897 if (pm_runtime_suspended(hba->dev)) 9898 goto out; 9899 9900 ret = ufshcd_resume(hba); 9901 9902 out: 9903 trace_ufshcd_system_resume(dev_name(hba->dev), ret, 9904 ktime_to_us(ktime_sub(ktime_get(), start)), 9905 hba->curr_dev_pwr_mode, hba->uic_link_state); 9906 9907 return ret; 9908 } 9909 EXPORT_SYMBOL(ufshcd_system_resume); 9910 #endif /* CONFIG_PM_SLEEP */ 9911 9912 #ifdef CONFIG_PM 9913 /** 9914 * ufshcd_runtime_suspend - runtime suspend callback 9915 * @dev: Device associated with the UFS controller. 9916 * 9917 * Check the description of ufshcd_suspend() function for more details. 9918 * 9919 * Returns 0 for success and non-zero for failure 9920 */ 9921 int ufshcd_runtime_suspend(struct device *dev) 9922 { 9923 struct ufs_hba *hba = dev_get_drvdata(dev); 9924 int ret; 9925 ktime_t start = ktime_get(); 9926 9927 ret = ufshcd_suspend(hba); 9928 9929 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret, 9930 ktime_to_us(ktime_sub(ktime_get(), start)), 9931 hba->curr_dev_pwr_mode, hba->uic_link_state); 9932 return ret; 9933 } 9934 EXPORT_SYMBOL(ufshcd_runtime_suspend); 9935 9936 /** 9937 * ufshcd_runtime_resume - runtime resume routine 9938 * @dev: Device associated with the UFS controller. 9939 * 9940 * This function basically brings controller 9941 * to active state. Following operations are done in this function: 9942 * 9943 * 1. Turn on all the controller related clocks 9944 * 2. Turn ON VCC rail 9945 */ 9946 int ufshcd_runtime_resume(struct device *dev) 9947 { 9948 struct ufs_hba *hba = dev_get_drvdata(dev); 9949 int ret; 9950 ktime_t start = ktime_get(); 9951 9952 ret = ufshcd_resume(hba); 9953 9954 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret, 9955 ktime_to_us(ktime_sub(ktime_get(), start)), 9956 hba->curr_dev_pwr_mode, hba->uic_link_state); 9957 return ret; 9958 } 9959 EXPORT_SYMBOL(ufshcd_runtime_resume); 9960 #endif /* CONFIG_PM */ 9961 9962 /** 9963 * ufshcd_shutdown - shutdown routine 9964 * @hba: per adapter instance 9965 * 9966 * This function would turn off both UFS device and UFS hba 9967 * regulators. It would also disable clocks. 9968 * 9969 * Returns 0 always to allow force shutdown even in case of errors. 9970 */ 9971 int ufshcd_shutdown(struct ufs_hba *hba) 9972 { 9973 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba)) 9974 ufshcd_suspend(hba); 9975 9976 hba->is_powered = false; 9977 /* allow force shutdown even in case of errors */ 9978 return 0; 9979 } 9980 EXPORT_SYMBOL(ufshcd_shutdown); 9981 9982 /** 9983 * ufshcd_remove - de-allocate SCSI host and host memory space 9984 * data structure memory 9985 * @hba: per adapter instance 9986 */ 9987 void ufshcd_remove(struct ufs_hba *hba) 9988 { 9989 if (hba->ufs_device_wlun) 9990 ufshcd_rpm_get_sync(hba); 9991 ufs_hwmon_remove(hba); 9992 ufs_bsg_remove(hba); 9993 ufshpb_remove(hba); 9994 ufs_sysfs_remove_nodes(hba->dev); 9995 blk_mq_destroy_queue(hba->tmf_queue); 9996 blk_put_queue(hba->tmf_queue); 9997 blk_mq_free_tag_set(&hba->tmf_tag_set); 9998 scsi_remove_host(hba->host); 9999 /* disable interrupts */ 10000 ufshcd_disable_intr(hba, hba->intr_mask); 10001 ufshcd_hba_stop(hba); 10002 ufshcd_hba_exit(hba); 10003 } 10004 EXPORT_SYMBOL_GPL(ufshcd_remove); 10005 10006 #ifdef CONFIG_PM_SLEEP 10007 int ufshcd_system_freeze(struct device *dev) 10008 { 10009 10010 return ufshcd_system_suspend(dev); 10011 10012 } 10013 EXPORT_SYMBOL_GPL(ufshcd_system_freeze); 10014 10015 int ufshcd_system_restore(struct device *dev) 10016 { 10017 10018 struct ufs_hba *hba = dev_get_drvdata(dev); 10019 int ret; 10020 10021 ret = ufshcd_system_resume(dev); 10022 if (ret) 10023 return ret; 10024 10025 /* Configure UTRL and UTMRL base address registers */ 10026 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr), 10027 REG_UTP_TRANSFER_REQ_LIST_BASE_L); 10028 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr), 10029 REG_UTP_TRANSFER_REQ_LIST_BASE_H); 10030 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr), 10031 REG_UTP_TASK_REQ_LIST_BASE_L); 10032 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr), 10033 REG_UTP_TASK_REQ_LIST_BASE_H); 10034 /* 10035 * Make sure that UTRL and UTMRL base address registers 10036 * are updated with the latest queue addresses. Only after 10037 * updating these addresses, we can queue the new commands. 10038 */ 10039 mb(); 10040 10041 /* Resuming from hibernate, assume that link was OFF */ 10042 ufshcd_set_link_off(hba); 10043 10044 return 0; 10045 10046 } 10047 EXPORT_SYMBOL_GPL(ufshcd_system_restore); 10048 10049 int ufshcd_system_thaw(struct device *dev) 10050 { 10051 return ufshcd_system_resume(dev); 10052 } 10053 EXPORT_SYMBOL_GPL(ufshcd_system_thaw); 10054 #endif /* CONFIG_PM_SLEEP */ 10055 10056 /** 10057 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA) 10058 * @hba: pointer to Host Bus Adapter (HBA) 10059 */ 10060 void ufshcd_dealloc_host(struct ufs_hba *hba) 10061 { 10062 scsi_host_put(hba->host); 10063 } 10064 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host); 10065 10066 /** 10067 * ufshcd_set_dma_mask - Set dma mask based on the controller 10068 * addressing capability 10069 * @hba: per adapter instance 10070 * 10071 * Returns 0 for success, non-zero for failure 10072 */ 10073 static int ufshcd_set_dma_mask(struct ufs_hba *hba) 10074 { 10075 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) { 10076 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64))) 10077 return 0; 10078 } 10079 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32)); 10080 } 10081 10082 /** 10083 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA) 10084 * @dev: pointer to device handle 10085 * @hba_handle: driver private handle 10086 * Returns 0 on success, non-zero value on failure 10087 */ 10088 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle) 10089 { 10090 struct Scsi_Host *host; 10091 struct ufs_hba *hba; 10092 int err = 0; 10093 10094 if (!dev) { 10095 dev_err(dev, 10096 "Invalid memory reference for dev is NULL\n"); 10097 err = -ENODEV; 10098 goto out_error; 10099 } 10100 10101 host = scsi_host_alloc(&ufshcd_driver_template, 10102 sizeof(struct ufs_hba)); 10103 if (!host) { 10104 dev_err(dev, "scsi_host_alloc failed\n"); 10105 err = -ENOMEM; 10106 goto out_error; 10107 } 10108 host->nr_maps = HCTX_TYPE_POLL + 1; 10109 hba = shost_priv(host); 10110 hba->host = host; 10111 hba->dev = dev; 10112 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL; 10113 hba->nop_out_timeout = NOP_OUT_TIMEOUT; 10114 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry)); 10115 INIT_LIST_HEAD(&hba->clk_list_head); 10116 spin_lock_init(&hba->outstanding_lock); 10117 10118 *hba_handle = hba; 10119 10120 out_error: 10121 return err; 10122 } 10123 EXPORT_SYMBOL(ufshcd_alloc_host); 10124 10125 /* This function exists because blk_mq_alloc_tag_set() requires this. */ 10126 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx, 10127 const struct blk_mq_queue_data *qd) 10128 { 10129 WARN_ON_ONCE(true); 10130 return BLK_STS_NOTSUPP; 10131 } 10132 10133 static const struct blk_mq_ops ufshcd_tmf_ops = { 10134 .queue_rq = ufshcd_queue_tmf, 10135 }; 10136 10137 /** 10138 * ufshcd_init - Driver initialization routine 10139 * @hba: per-adapter instance 10140 * @mmio_base: base register address 10141 * @irq: Interrupt line of device 10142 * Returns 0 on success, non-zero value on failure 10143 */ 10144 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) 10145 { 10146 int err; 10147 struct Scsi_Host *host = hba->host; 10148 struct device *dev = hba->dev; 10149 char eh_wq_name[sizeof("ufs_eh_wq_00")]; 10150 10151 /* 10152 * dev_set_drvdata() must be called before any callbacks are registered 10153 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon, 10154 * sysfs). 10155 */ 10156 dev_set_drvdata(dev, hba); 10157 10158 if (!mmio_base) { 10159 dev_err(hba->dev, 10160 "Invalid memory reference for mmio_base is NULL\n"); 10161 err = -ENODEV; 10162 goto out_error; 10163 } 10164 10165 hba->mmio_base = mmio_base; 10166 hba->irq = irq; 10167 hba->vps = &ufs_hba_vps; 10168 10169 err = ufshcd_hba_init(hba); 10170 if (err) 10171 goto out_error; 10172 10173 /* Read capabilities registers */ 10174 err = ufshcd_hba_capabilities(hba); 10175 if (err) 10176 goto out_disable; 10177 10178 /* Get UFS version supported by the controller */ 10179 hba->ufs_version = ufshcd_get_ufs_version(hba); 10180 10181 /* Get Interrupt bit mask per version */ 10182 hba->intr_mask = ufshcd_get_intr_mask(hba); 10183 10184 err = ufshcd_set_dma_mask(hba); 10185 if (err) { 10186 dev_err(hba->dev, "set dma mask failed\n"); 10187 goto out_disable; 10188 } 10189 10190 /* Allocate memory for host memory space */ 10191 err = ufshcd_memory_alloc(hba); 10192 if (err) { 10193 dev_err(hba->dev, "Memory allocation failed\n"); 10194 goto out_disable; 10195 } 10196 10197 /* Configure LRB */ 10198 ufshcd_host_memory_configure(hba); 10199 10200 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED; 10201 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED; 10202 host->max_id = UFSHCD_MAX_ID; 10203 host->max_lun = UFS_MAX_LUNS; 10204 host->max_channel = UFSHCD_MAX_CHANNEL; 10205 host->unique_id = host->host_no; 10206 host->max_cmd_len = UFS_CDB_SIZE; 10207 10208 hba->max_pwr_info.is_valid = false; 10209 10210 /* Initialize work queues */ 10211 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d", 10212 hba->host->host_no); 10213 hba->eh_wq = create_singlethread_workqueue(eh_wq_name); 10214 if (!hba->eh_wq) { 10215 dev_err(hba->dev, "%s: failed to create eh workqueue\n", 10216 __func__); 10217 err = -ENOMEM; 10218 goto out_disable; 10219 } 10220 INIT_WORK(&hba->eh_work, ufshcd_err_handler); 10221 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler); 10222 10223 sema_init(&hba->host_sem, 1); 10224 10225 /* Initialize UIC command mutex */ 10226 mutex_init(&hba->uic_cmd_mutex); 10227 10228 /* Initialize mutex for device management commands */ 10229 mutex_init(&hba->dev_cmd.lock); 10230 10231 /* Initialize mutex for exception event control */ 10232 mutex_init(&hba->ee_ctrl_mutex); 10233 10234 mutex_init(&hba->wb_mutex); 10235 init_rwsem(&hba->clk_scaling_lock); 10236 10237 ufshcd_init_clk_gating(hba); 10238 10239 ufshcd_init_clk_scaling(hba); 10240 10241 /* 10242 * In order to avoid any spurious interrupt immediately after 10243 * registering UFS controller interrupt handler, clear any pending UFS 10244 * interrupt status and disable all the UFS interrupts. 10245 */ 10246 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS), 10247 REG_INTERRUPT_STATUS); 10248 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE); 10249 /* 10250 * Make sure that UFS interrupts are disabled and any pending interrupt 10251 * status is cleared before registering UFS interrupt handler. 10252 */ 10253 mb(); 10254 10255 /* IRQ registration */ 10256 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba); 10257 if (err) { 10258 dev_err(hba->dev, "request irq failed\n"); 10259 goto out_disable; 10260 } else { 10261 hba->is_irq_enabled = true; 10262 } 10263 10264 if (!is_mcq_supported(hba)) { 10265 err = scsi_add_host(host, hba->dev); 10266 if (err) { 10267 dev_err(hba->dev, "scsi_add_host failed\n"); 10268 goto out_disable; 10269 } 10270 } 10271 10272 hba->tmf_tag_set = (struct blk_mq_tag_set) { 10273 .nr_hw_queues = 1, 10274 .queue_depth = hba->nutmrs, 10275 .ops = &ufshcd_tmf_ops, 10276 .flags = BLK_MQ_F_NO_SCHED, 10277 }; 10278 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set); 10279 if (err < 0) 10280 goto out_remove_scsi_host; 10281 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set); 10282 if (IS_ERR(hba->tmf_queue)) { 10283 err = PTR_ERR(hba->tmf_queue); 10284 goto free_tmf_tag_set; 10285 } 10286 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs, 10287 sizeof(*hba->tmf_rqs), GFP_KERNEL); 10288 if (!hba->tmf_rqs) { 10289 err = -ENOMEM; 10290 goto free_tmf_queue; 10291 } 10292 10293 /* Reset the attached device */ 10294 ufshcd_device_reset(hba); 10295 10296 ufshcd_init_crypto(hba); 10297 10298 /* Host controller enable */ 10299 err = ufshcd_hba_enable(hba); 10300 if (err) { 10301 dev_err(hba->dev, "Host controller enable failed\n"); 10302 ufshcd_print_evt_hist(hba); 10303 ufshcd_print_host_state(hba); 10304 goto free_tmf_queue; 10305 } 10306 10307 /* 10308 * Set the default power management level for runtime and system PM. 10309 * Default power saving mode is to keep UFS link in Hibern8 state 10310 * and UFS device in sleep state. 10311 */ 10312 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state( 10313 UFS_SLEEP_PWR_MODE, 10314 UIC_LINK_HIBERN8_STATE); 10315 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state( 10316 UFS_SLEEP_PWR_MODE, 10317 UIC_LINK_HIBERN8_STATE); 10318 10319 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, 10320 ufshcd_rpm_dev_flush_recheck_work); 10321 10322 /* Set the default auto-hiberate idle timer value to 150 ms */ 10323 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) { 10324 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) | 10325 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3); 10326 } 10327 10328 /* Hold auto suspend until async scan completes */ 10329 pm_runtime_get_sync(dev); 10330 atomic_set(&hba->scsi_block_reqs_cnt, 0); 10331 /* 10332 * We are assuming that device wasn't put in sleep/power-down 10333 * state exclusively during the boot stage before kernel. 10334 * This assumption helps avoid doing link startup twice during 10335 * ufshcd_probe_hba(). 10336 */ 10337 ufshcd_set_ufs_dev_active(hba); 10338 10339 async_schedule(ufshcd_async_scan, hba); 10340 ufs_sysfs_add_nodes(hba->dev); 10341 10342 device_enable_async_suspend(dev); 10343 return 0; 10344 10345 free_tmf_queue: 10346 blk_mq_destroy_queue(hba->tmf_queue); 10347 blk_put_queue(hba->tmf_queue); 10348 free_tmf_tag_set: 10349 blk_mq_free_tag_set(&hba->tmf_tag_set); 10350 out_remove_scsi_host: 10351 scsi_remove_host(hba->host); 10352 out_disable: 10353 hba->is_irq_enabled = false; 10354 ufshcd_hba_exit(hba); 10355 out_error: 10356 return err; 10357 } 10358 EXPORT_SYMBOL_GPL(ufshcd_init); 10359 10360 void ufshcd_resume_complete(struct device *dev) 10361 { 10362 struct ufs_hba *hba = dev_get_drvdata(dev); 10363 10364 if (hba->complete_put) { 10365 ufshcd_rpm_put(hba); 10366 hba->complete_put = false; 10367 } 10368 } 10369 EXPORT_SYMBOL_GPL(ufshcd_resume_complete); 10370 10371 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba) 10372 { 10373 struct device *dev = &hba->ufs_device_wlun->sdev_gendev; 10374 enum ufs_dev_pwr_mode dev_pwr_mode; 10375 enum uic_link_state link_state; 10376 unsigned long flags; 10377 bool res; 10378 10379 spin_lock_irqsave(&dev->power.lock, flags); 10380 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl); 10381 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl); 10382 res = pm_runtime_suspended(dev) && 10383 hba->curr_dev_pwr_mode == dev_pwr_mode && 10384 hba->uic_link_state == link_state && 10385 !hba->dev_info.b_rpm_dev_flush_capable; 10386 spin_unlock_irqrestore(&dev->power.lock, flags); 10387 10388 return res; 10389 } 10390 10391 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm) 10392 { 10393 struct ufs_hba *hba = dev_get_drvdata(dev); 10394 int ret; 10395 10396 /* 10397 * SCSI assumes that runtime-pm and system-pm for scsi drivers 10398 * are same. And it doesn't wake up the device for system-suspend 10399 * if it's runtime suspended. But ufs doesn't follow that. 10400 * Refer ufshcd_resume_complete() 10401 */ 10402 if (hba->ufs_device_wlun) { 10403 /* Prevent runtime suspend */ 10404 ufshcd_rpm_get_noresume(hba); 10405 /* 10406 * Check if already runtime suspended in same state as system 10407 * suspend would be. 10408 */ 10409 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) { 10410 /* RPM state is not ok for SPM, so runtime resume */ 10411 ret = ufshcd_rpm_resume(hba); 10412 if (ret < 0 && ret != -EACCES) { 10413 ufshcd_rpm_put(hba); 10414 return ret; 10415 } 10416 } 10417 hba->complete_put = true; 10418 } 10419 return 0; 10420 } 10421 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare); 10422 10423 int ufshcd_suspend_prepare(struct device *dev) 10424 { 10425 return __ufshcd_suspend_prepare(dev, true); 10426 } 10427 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare); 10428 10429 #ifdef CONFIG_PM_SLEEP 10430 static int ufshcd_wl_poweroff(struct device *dev) 10431 { 10432 struct scsi_device *sdev = to_scsi_device(dev); 10433 struct ufs_hba *hba = shost_priv(sdev->host); 10434 10435 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM); 10436 return 0; 10437 } 10438 #endif 10439 10440 static int ufshcd_wl_probe(struct device *dev) 10441 { 10442 struct scsi_device *sdev = to_scsi_device(dev); 10443 10444 if (!is_device_wlun(sdev)) 10445 return -ENODEV; 10446 10447 blk_pm_runtime_init(sdev->request_queue, dev); 10448 pm_runtime_set_autosuspend_delay(dev, 0); 10449 pm_runtime_allow(dev); 10450 10451 return 0; 10452 } 10453 10454 static int ufshcd_wl_remove(struct device *dev) 10455 { 10456 pm_runtime_forbid(dev); 10457 return 0; 10458 } 10459 10460 static const struct dev_pm_ops ufshcd_wl_pm_ops = { 10461 #ifdef CONFIG_PM_SLEEP 10462 .suspend = ufshcd_wl_suspend, 10463 .resume = ufshcd_wl_resume, 10464 .freeze = ufshcd_wl_suspend, 10465 .thaw = ufshcd_wl_resume, 10466 .poweroff = ufshcd_wl_poweroff, 10467 .restore = ufshcd_wl_resume, 10468 #endif 10469 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL) 10470 }; 10471 10472 /* 10473 * ufs_dev_wlun_template - describes ufs device wlun 10474 * ufs-device wlun - used to send pm commands 10475 * All luns are consumers of ufs-device wlun. 10476 * 10477 * Currently, no sd driver is present for wluns. 10478 * Hence the no specific pm operations are performed. 10479 * With ufs design, SSU should be sent to ufs-device wlun. 10480 * Hence register a scsi driver for ufs wluns only. 10481 */ 10482 static struct scsi_driver ufs_dev_wlun_template = { 10483 .gendrv = { 10484 .name = "ufs_device_wlun", 10485 .owner = THIS_MODULE, 10486 .probe = ufshcd_wl_probe, 10487 .remove = ufshcd_wl_remove, 10488 .pm = &ufshcd_wl_pm_ops, 10489 .shutdown = ufshcd_wl_shutdown, 10490 }, 10491 }; 10492 10493 static int __init ufshcd_core_init(void) 10494 { 10495 int ret; 10496 10497 ufs_debugfs_init(); 10498 10499 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv); 10500 if (ret) 10501 ufs_debugfs_exit(); 10502 return ret; 10503 } 10504 10505 static void __exit ufshcd_core_exit(void) 10506 { 10507 ufs_debugfs_exit(); 10508 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv); 10509 } 10510 10511 module_init(ufshcd_core_init); 10512 module_exit(ufshcd_core_exit); 10513 10514 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>"); 10515 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>"); 10516 MODULE_DESCRIPTION("Generic UFS host controller driver Core"); 10517 MODULE_SOFTDEP("pre: governor_simpleondemand"); 10518 MODULE_LICENSE("GPL"); 10519