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