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