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 UTMRLCLR 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 void ufshcd_map_queues(struct Scsi_Host *shost) 2711 { 2712 int i; 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 blk_mq_map_queues(map); 2730 } 2731 } 2732 2733 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i) 2734 { 2735 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr; 2736 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr; 2737 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr + 2738 i * sizeof(struct utp_transfer_cmd_desc); 2739 u16 response_offset = offsetof(struct utp_transfer_cmd_desc, 2740 response_upiu); 2741 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table); 2742 2743 lrb->utr_descriptor_ptr = utrdlp + i; 2744 lrb->utrd_dma_addr = hba->utrdl_dma_addr + 2745 i * sizeof(struct utp_transfer_req_desc); 2746 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i); 2747 lrb->ucd_req_dma_addr = cmd_desc_element_addr; 2748 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu; 2749 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset; 2750 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table; 2751 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset; 2752 } 2753 2754 /** 2755 * ufshcd_queuecommand - main entry point for SCSI requests 2756 * @host: SCSI host pointer 2757 * @cmd: command from SCSI Midlayer 2758 * 2759 * Returns 0 for success, non-zero in case of failure 2760 */ 2761 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd) 2762 { 2763 struct ufs_hba *hba = shost_priv(host); 2764 int tag = scsi_cmd_to_rq(cmd)->tag; 2765 struct ufshcd_lrb *lrbp; 2766 int err = 0; 2767 2768 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag); 2769 2770 /* 2771 * Allows the UFS error handler to wait for prior ufshcd_queuecommand() 2772 * calls. 2773 */ 2774 rcu_read_lock(); 2775 2776 switch (hba->ufshcd_state) { 2777 case UFSHCD_STATE_OPERATIONAL: 2778 break; 2779 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL: 2780 /* 2781 * SCSI error handler can call ->queuecommand() while UFS error 2782 * handler is in progress. Error interrupts could change the 2783 * state from UFSHCD_STATE_RESET to 2784 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests 2785 * being issued in that case. 2786 */ 2787 if (ufshcd_eh_in_progress(hba)) { 2788 err = SCSI_MLQUEUE_HOST_BUSY; 2789 goto out; 2790 } 2791 break; 2792 case UFSHCD_STATE_EH_SCHEDULED_FATAL: 2793 /* 2794 * pm_runtime_get_sync() is used at error handling preparation 2795 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's 2796 * PM ops, it can never be finished if we let SCSI layer keep 2797 * retrying it, which gets err handler stuck forever. Neither 2798 * can we let the scsi cmd pass through, because UFS is in bad 2799 * state, the scsi cmd may eventually time out, which will get 2800 * err handler blocked for too long. So, just fail the scsi cmd 2801 * sent from PM ops, err handler can recover PM error anyways. 2802 */ 2803 if (hba->pm_op_in_progress) { 2804 hba->force_reset = true; 2805 set_host_byte(cmd, DID_BAD_TARGET); 2806 scsi_done(cmd); 2807 goto out; 2808 } 2809 fallthrough; 2810 case UFSHCD_STATE_RESET: 2811 err = SCSI_MLQUEUE_HOST_BUSY; 2812 goto out; 2813 case UFSHCD_STATE_ERROR: 2814 set_host_byte(cmd, DID_ERROR); 2815 scsi_done(cmd); 2816 goto out; 2817 } 2818 2819 hba->req_abort_count = 0; 2820 2821 err = ufshcd_hold(hba, true); 2822 if (err) { 2823 err = SCSI_MLQUEUE_HOST_BUSY; 2824 goto out; 2825 } 2826 WARN_ON(ufshcd_is_clkgating_allowed(hba) && 2827 (hba->clk_gating.state != CLKS_ON)); 2828 2829 lrbp = &hba->lrb[tag]; 2830 WARN_ON(lrbp->cmd); 2831 lrbp->cmd = cmd; 2832 lrbp->task_tag = tag; 2833 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun); 2834 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba); 2835 2836 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp); 2837 2838 lrbp->req_abort_skip = false; 2839 2840 ufshpb_prep(hba, lrbp); 2841 2842 ufshcd_comp_scsi_upiu(hba, lrbp); 2843 2844 err = ufshcd_map_sg(hba, lrbp); 2845 if (err) { 2846 lrbp->cmd = NULL; 2847 ufshcd_release(hba); 2848 goto out; 2849 } 2850 2851 ufshcd_send_command(hba, tag); 2852 2853 out: 2854 rcu_read_unlock(); 2855 2856 if (ufs_trigger_eh()) { 2857 unsigned long flags; 2858 2859 spin_lock_irqsave(hba->host->host_lock, flags); 2860 ufshcd_schedule_eh_work(hba); 2861 spin_unlock_irqrestore(hba->host->host_lock, flags); 2862 } 2863 2864 return err; 2865 } 2866 2867 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba, 2868 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag) 2869 { 2870 lrbp->cmd = NULL; 2871 lrbp->task_tag = tag; 2872 lrbp->lun = 0; /* device management cmd is not specific to any LUN */ 2873 lrbp->intr_cmd = true; /* No interrupt aggregation */ 2874 ufshcd_prepare_lrbp_crypto(NULL, lrbp); 2875 hba->dev_cmd.type = cmd_type; 2876 2877 return ufshcd_compose_devman_upiu(hba, lrbp); 2878 } 2879 2880 /* 2881 * Clear all the requests from the controller for which a bit has been set in 2882 * @mask and wait until the controller confirms that these requests have been 2883 * cleared. 2884 */ 2885 static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask) 2886 { 2887 unsigned long flags; 2888 2889 /* clear outstanding transaction before retry */ 2890 spin_lock_irqsave(hba->host->host_lock, flags); 2891 ufshcd_utrl_clear(hba, mask); 2892 spin_unlock_irqrestore(hba->host->host_lock, flags); 2893 2894 /* 2895 * wait for h/w to clear corresponding bit in door-bell. 2896 * max. wait is 1 sec. 2897 */ 2898 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL, 2899 mask, ~mask, 1000, 1000); 2900 } 2901 2902 static int 2903 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 2904 { 2905 struct ufs_query_res *query_res = &hba->dev_cmd.query.response; 2906 2907 /* Get the UPIU response */ 2908 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >> 2909 UPIU_RSP_CODE_OFFSET; 2910 return query_res->response; 2911 } 2912 2913 /** 2914 * ufshcd_dev_cmd_completion() - handles device management command responses 2915 * @hba: per adapter instance 2916 * @lrbp: pointer to local reference block 2917 */ 2918 static int 2919 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 2920 { 2921 int resp; 2922 int err = 0; 2923 2924 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0); 2925 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr); 2926 2927 switch (resp) { 2928 case UPIU_TRANSACTION_NOP_IN: 2929 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) { 2930 err = -EINVAL; 2931 dev_err(hba->dev, "%s: unexpected response %x\n", 2932 __func__, resp); 2933 } 2934 break; 2935 case UPIU_TRANSACTION_QUERY_RSP: 2936 err = ufshcd_check_query_response(hba, lrbp); 2937 if (!err) 2938 err = ufshcd_copy_query_response(hba, lrbp); 2939 break; 2940 case UPIU_TRANSACTION_REJECT_UPIU: 2941 /* TODO: handle Reject UPIU Response */ 2942 err = -EPERM; 2943 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n", 2944 __func__); 2945 break; 2946 default: 2947 err = -EINVAL; 2948 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n", 2949 __func__, resp); 2950 break; 2951 } 2952 2953 return err; 2954 } 2955 2956 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba, 2957 struct ufshcd_lrb *lrbp, int max_timeout) 2958 { 2959 unsigned long time_left = msecs_to_jiffies(max_timeout); 2960 unsigned long flags; 2961 bool pending; 2962 int err; 2963 2964 retry: 2965 time_left = wait_for_completion_timeout(hba->dev_cmd.complete, 2966 time_left); 2967 2968 if (likely(time_left)) { 2969 /* 2970 * The completion handler called complete() and the caller of 2971 * this function still owns the @lrbp tag so the code below does 2972 * not trigger any race conditions. 2973 */ 2974 hba->dev_cmd.complete = NULL; 2975 err = ufshcd_get_tr_ocs(lrbp); 2976 if (!err) 2977 err = ufshcd_dev_cmd_completion(hba, lrbp); 2978 } else { 2979 err = -ETIMEDOUT; 2980 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n", 2981 __func__, lrbp->task_tag); 2982 if (ufshcd_clear_cmds(hba, 1U << lrbp->task_tag) == 0) { 2983 /* successfully cleared the command, retry if needed */ 2984 err = -EAGAIN; 2985 /* 2986 * Since clearing the command succeeded we also need to 2987 * clear the task tag bit from the outstanding_reqs 2988 * variable. 2989 */ 2990 spin_lock_irqsave(&hba->outstanding_lock, flags); 2991 pending = test_bit(lrbp->task_tag, 2992 &hba->outstanding_reqs); 2993 if (pending) { 2994 hba->dev_cmd.complete = NULL; 2995 __clear_bit(lrbp->task_tag, 2996 &hba->outstanding_reqs); 2997 } 2998 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 2999 3000 if (!pending) { 3001 /* 3002 * The completion handler ran while we tried to 3003 * clear the command. 3004 */ 3005 time_left = 1; 3006 goto retry; 3007 } 3008 } else { 3009 dev_err(hba->dev, "%s: failed to clear tag %d\n", 3010 __func__, lrbp->task_tag); 3011 } 3012 } 3013 3014 return err; 3015 } 3016 3017 /** 3018 * ufshcd_exec_dev_cmd - API for sending device management requests 3019 * @hba: UFS hba 3020 * @cmd_type: specifies the type (NOP, Query...) 3021 * @timeout: timeout in milliseconds 3022 * 3023 * NOTE: Since there is only one available tag for device management commands, 3024 * it is expected you hold the hba->dev_cmd.lock mutex. 3025 */ 3026 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba, 3027 enum dev_cmd_type cmd_type, int timeout) 3028 { 3029 DECLARE_COMPLETION_ONSTACK(wait); 3030 const u32 tag = hba->reserved_slot; 3031 struct ufshcd_lrb *lrbp; 3032 int err; 3033 3034 /* Protects use of hba->reserved_slot. */ 3035 lockdep_assert_held(&hba->dev_cmd.lock); 3036 3037 down_read(&hba->clk_scaling_lock); 3038 3039 lrbp = &hba->lrb[tag]; 3040 WARN_ON(lrbp->cmd); 3041 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag); 3042 if (unlikely(err)) 3043 goto out; 3044 3045 hba->dev_cmd.complete = &wait; 3046 3047 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr); 3048 3049 ufshcd_send_command(hba, tag); 3050 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout); 3051 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP, 3052 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr); 3053 3054 out: 3055 up_read(&hba->clk_scaling_lock); 3056 return err; 3057 } 3058 3059 /** 3060 * ufshcd_init_query() - init the query response and request parameters 3061 * @hba: per-adapter instance 3062 * @request: address of the request pointer to be initialized 3063 * @response: address of the response pointer to be initialized 3064 * @opcode: operation to perform 3065 * @idn: flag idn to access 3066 * @index: LU number to access 3067 * @selector: query/flag/descriptor further identification 3068 */ 3069 static inline void ufshcd_init_query(struct ufs_hba *hba, 3070 struct ufs_query_req **request, struct ufs_query_res **response, 3071 enum query_opcode opcode, u8 idn, u8 index, u8 selector) 3072 { 3073 *request = &hba->dev_cmd.query.request; 3074 *response = &hba->dev_cmd.query.response; 3075 memset(*request, 0, sizeof(struct ufs_query_req)); 3076 memset(*response, 0, sizeof(struct ufs_query_res)); 3077 (*request)->upiu_req.opcode = opcode; 3078 (*request)->upiu_req.idn = idn; 3079 (*request)->upiu_req.index = index; 3080 (*request)->upiu_req.selector = selector; 3081 } 3082 3083 static int ufshcd_query_flag_retry(struct ufs_hba *hba, 3084 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res) 3085 { 3086 int ret; 3087 int retries; 3088 3089 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) { 3090 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res); 3091 if (ret) 3092 dev_dbg(hba->dev, 3093 "%s: failed with error %d, retries %d\n", 3094 __func__, ret, retries); 3095 else 3096 break; 3097 } 3098 3099 if (ret) 3100 dev_err(hba->dev, 3101 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n", 3102 __func__, opcode, idn, ret, retries); 3103 return ret; 3104 } 3105 3106 /** 3107 * ufshcd_query_flag() - API function for sending flag query requests 3108 * @hba: per-adapter instance 3109 * @opcode: flag query to perform 3110 * @idn: flag idn to access 3111 * @index: flag index to access 3112 * @flag_res: the flag value after the query request completes 3113 * 3114 * Returns 0 for success, non-zero in case of failure 3115 */ 3116 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode, 3117 enum flag_idn idn, u8 index, bool *flag_res) 3118 { 3119 struct ufs_query_req *request = NULL; 3120 struct ufs_query_res *response = NULL; 3121 int err, selector = 0; 3122 int timeout = QUERY_REQ_TIMEOUT; 3123 3124 BUG_ON(!hba); 3125 3126 ufshcd_hold(hba, false); 3127 mutex_lock(&hba->dev_cmd.lock); 3128 ufshcd_init_query(hba, &request, &response, opcode, idn, index, 3129 selector); 3130 3131 switch (opcode) { 3132 case UPIU_QUERY_OPCODE_SET_FLAG: 3133 case UPIU_QUERY_OPCODE_CLEAR_FLAG: 3134 case UPIU_QUERY_OPCODE_TOGGLE_FLAG: 3135 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST; 3136 break; 3137 case UPIU_QUERY_OPCODE_READ_FLAG: 3138 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST; 3139 if (!flag_res) { 3140 /* No dummy reads */ 3141 dev_err(hba->dev, "%s: Invalid argument for read request\n", 3142 __func__); 3143 err = -EINVAL; 3144 goto out_unlock; 3145 } 3146 break; 3147 default: 3148 dev_err(hba->dev, 3149 "%s: Expected query flag opcode but got = %d\n", 3150 __func__, opcode); 3151 err = -EINVAL; 3152 goto out_unlock; 3153 } 3154 3155 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout); 3156 3157 if (err) { 3158 dev_err(hba->dev, 3159 "%s: Sending flag query for idn %d failed, err = %d\n", 3160 __func__, idn, err); 3161 goto out_unlock; 3162 } 3163 3164 if (flag_res) 3165 *flag_res = (be32_to_cpu(response->upiu_res.value) & 3166 MASK_QUERY_UPIU_FLAG_LOC) & 0x1; 3167 3168 out_unlock: 3169 mutex_unlock(&hba->dev_cmd.lock); 3170 ufshcd_release(hba); 3171 return err; 3172 } 3173 3174 /** 3175 * ufshcd_query_attr - API function for sending attribute requests 3176 * @hba: per-adapter instance 3177 * @opcode: attribute opcode 3178 * @idn: attribute idn to access 3179 * @index: index field 3180 * @selector: selector field 3181 * @attr_val: the attribute value after the query request completes 3182 * 3183 * Returns 0 for success, non-zero in case of failure 3184 */ 3185 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode, 3186 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val) 3187 { 3188 struct ufs_query_req *request = NULL; 3189 struct ufs_query_res *response = NULL; 3190 int err; 3191 3192 BUG_ON(!hba); 3193 3194 if (!attr_val) { 3195 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n", 3196 __func__, opcode); 3197 return -EINVAL; 3198 } 3199 3200 ufshcd_hold(hba, false); 3201 3202 mutex_lock(&hba->dev_cmd.lock); 3203 ufshcd_init_query(hba, &request, &response, opcode, idn, index, 3204 selector); 3205 3206 switch (opcode) { 3207 case UPIU_QUERY_OPCODE_WRITE_ATTR: 3208 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST; 3209 request->upiu_req.value = cpu_to_be32(*attr_val); 3210 break; 3211 case UPIU_QUERY_OPCODE_READ_ATTR: 3212 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST; 3213 break; 3214 default: 3215 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n", 3216 __func__, opcode); 3217 err = -EINVAL; 3218 goto out_unlock; 3219 } 3220 3221 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT); 3222 3223 if (err) { 3224 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n", 3225 __func__, opcode, idn, index, err); 3226 goto out_unlock; 3227 } 3228 3229 *attr_val = be32_to_cpu(response->upiu_res.value); 3230 3231 out_unlock: 3232 mutex_unlock(&hba->dev_cmd.lock); 3233 ufshcd_release(hba); 3234 return err; 3235 } 3236 3237 /** 3238 * ufshcd_query_attr_retry() - API function for sending query 3239 * attribute with retries 3240 * @hba: per-adapter instance 3241 * @opcode: attribute opcode 3242 * @idn: attribute idn to access 3243 * @index: index field 3244 * @selector: selector field 3245 * @attr_val: the attribute value after the query request 3246 * completes 3247 * 3248 * Returns 0 for success, non-zero in case of failure 3249 */ 3250 int ufshcd_query_attr_retry(struct ufs_hba *hba, 3251 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector, 3252 u32 *attr_val) 3253 { 3254 int ret = 0; 3255 u32 retries; 3256 3257 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) { 3258 ret = ufshcd_query_attr(hba, opcode, idn, index, 3259 selector, attr_val); 3260 if (ret) 3261 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n", 3262 __func__, ret, retries); 3263 else 3264 break; 3265 } 3266 3267 if (ret) 3268 dev_err(hba->dev, 3269 "%s: query attribute, idn %d, failed with error %d after %d retries\n", 3270 __func__, idn, ret, QUERY_REQ_RETRIES); 3271 return ret; 3272 } 3273 3274 static int __ufshcd_query_descriptor(struct ufs_hba *hba, 3275 enum query_opcode opcode, enum desc_idn idn, u8 index, 3276 u8 selector, u8 *desc_buf, int *buf_len) 3277 { 3278 struct ufs_query_req *request = NULL; 3279 struct ufs_query_res *response = NULL; 3280 int err; 3281 3282 BUG_ON(!hba); 3283 3284 if (!desc_buf) { 3285 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n", 3286 __func__, opcode); 3287 return -EINVAL; 3288 } 3289 3290 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) { 3291 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n", 3292 __func__, *buf_len); 3293 return -EINVAL; 3294 } 3295 3296 ufshcd_hold(hba, false); 3297 3298 mutex_lock(&hba->dev_cmd.lock); 3299 ufshcd_init_query(hba, &request, &response, opcode, idn, index, 3300 selector); 3301 hba->dev_cmd.query.descriptor = desc_buf; 3302 request->upiu_req.length = cpu_to_be16(*buf_len); 3303 3304 switch (opcode) { 3305 case UPIU_QUERY_OPCODE_WRITE_DESC: 3306 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST; 3307 break; 3308 case UPIU_QUERY_OPCODE_READ_DESC: 3309 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST; 3310 break; 3311 default: 3312 dev_err(hba->dev, 3313 "%s: Expected query descriptor opcode but got = 0x%.2x\n", 3314 __func__, opcode); 3315 err = -EINVAL; 3316 goto out_unlock; 3317 } 3318 3319 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT); 3320 3321 if (err) { 3322 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n", 3323 __func__, opcode, idn, index, err); 3324 goto out_unlock; 3325 } 3326 3327 *buf_len = be16_to_cpu(response->upiu_res.length); 3328 3329 out_unlock: 3330 hba->dev_cmd.query.descriptor = NULL; 3331 mutex_unlock(&hba->dev_cmd.lock); 3332 ufshcd_release(hba); 3333 return err; 3334 } 3335 3336 /** 3337 * ufshcd_query_descriptor_retry - API function for sending descriptor requests 3338 * @hba: per-adapter instance 3339 * @opcode: attribute opcode 3340 * @idn: attribute idn to access 3341 * @index: index field 3342 * @selector: selector field 3343 * @desc_buf: the buffer that contains the descriptor 3344 * @buf_len: length parameter passed to the device 3345 * 3346 * Returns 0 for success, non-zero in case of failure. 3347 * The buf_len parameter will contain, on return, the length parameter 3348 * received on the response. 3349 */ 3350 int ufshcd_query_descriptor_retry(struct ufs_hba *hba, 3351 enum query_opcode opcode, 3352 enum desc_idn idn, u8 index, 3353 u8 selector, 3354 u8 *desc_buf, int *buf_len) 3355 { 3356 int err; 3357 int retries; 3358 3359 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) { 3360 err = __ufshcd_query_descriptor(hba, opcode, idn, index, 3361 selector, desc_buf, buf_len); 3362 if (!err || err == -EINVAL) 3363 break; 3364 } 3365 3366 return err; 3367 } 3368 3369 /** 3370 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length 3371 * @hba: Pointer to adapter instance 3372 * @desc_id: descriptor idn value 3373 * @desc_len: mapped desc length (out) 3374 */ 3375 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id, 3376 int *desc_len) 3377 { 3378 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 || 3379 desc_id == QUERY_DESC_IDN_RFU_1) 3380 *desc_len = 0; 3381 else 3382 *desc_len = hba->desc_size[desc_id]; 3383 } 3384 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length); 3385 3386 static void ufshcd_update_desc_length(struct ufs_hba *hba, 3387 enum desc_idn desc_id, int desc_index, 3388 unsigned char desc_len) 3389 { 3390 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE && 3391 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT) 3392 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger 3393 * than the RPMB unit, however, both descriptors share the same 3394 * desc_idn, to cover both unit descriptors with one length, we 3395 * choose the normal unit descriptor length by desc_index. 3396 */ 3397 hba->desc_size[desc_id] = desc_len; 3398 } 3399 3400 /** 3401 * ufshcd_read_desc_param - read the specified descriptor parameter 3402 * @hba: Pointer to adapter instance 3403 * @desc_id: descriptor idn value 3404 * @desc_index: descriptor index 3405 * @param_offset: offset of the parameter to read 3406 * @param_read_buf: pointer to buffer where parameter would be read 3407 * @param_size: sizeof(param_read_buf) 3408 * 3409 * Return 0 in case of success, non-zero otherwise 3410 */ 3411 int ufshcd_read_desc_param(struct ufs_hba *hba, 3412 enum desc_idn desc_id, 3413 int desc_index, 3414 u8 param_offset, 3415 u8 *param_read_buf, 3416 u8 param_size) 3417 { 3418 int ret; 3419 u8 *desc_buf; 3420 int buff_len; 3421 bool is_kmalloc = true; 3422 3423 /* Safety check */ 3424 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size) 3425 return -EINVAL; 3426 3427 /* Get the length of descriptor */ 3428 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len); 3429 if (!buff_len) { 3430 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__); 3431 return -EINVAL; 3432 } 3433 3434 if (param_offset >= buff_len) { 3435 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n", 3436 __func__, param_offset, desc_id, buff_len); 3437 return -EINVAL; 3438 } 3439 3440 /* Check whether we need temp memory */ 3441 if (param_offset != 0 || param_size < buff_len) { 3442 desc_buf = kzalloc(buff_len, GFP_KERNEL); 3443 if (!desc_buf) 3444 return -ENOMEM; 3445 } else { 3446 desc_buf = param_read_buf; 3447 is_kmalloc = false; 3448 } 3449 3450 /* Request for full descriptor */ 3451 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC, 3452 desc_id, desc_index, 0, 3453 desc_buf, &buff_len); 3454 3455 if (ret) { 3456 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n", 3457 __func__, desc_id, desc_index, param_offset, ret); 3458 goto out; 3459 } 3460 3461 /* Sanity check */ 3462 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) { 3463 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n", 3464 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]); 3465 ret = -EINVAL; 3466 goto out; 3467 } 3468 3469 /* Update descriptor length */ 3470 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET]; 3471 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len); 3472 3473 if (is_kmalloc) { 3474 /* Make sure we don't copy more data than available */ 3475 if (param_offset >= buff_len) 3476 ret = -EINVAL; 3477 else 3478 memcpy(param_read_buf, &desc_buf[param_offset], 3479 min_t(u32, param_size, buff_len - param_offset)); 3480 } 3481 out: 3482 if (is_kmalloc) 3483 kfree(desc_buf); 3484 return ret; 3485 } 3486 3487 /** 3488 * struct uc_string_id - unicode string 3489 * 3490 * @len: size of this descriptor inclusive 3491 * @type: descriptor type 3492 * @uc: unicode string character 3493 */ 3494 struct uc_string_id { 3495 u8 len; 3496 u8 type; 3497 wchar_t uc[]; 3498 } __packed; 3499 3500 /* replace non-printable or non-ASCII characters with spaces */ 3501 static inline char ufshcd_remove_non_printable(u8 ch) 3502 { 3503 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' '; 3504 } 3505 3506 /** 3507 * ufshcd_read_string_desc - read string descriptor 3508 * @hba: pointer to adapter instance 3509 * @desc_index: descriptor index 3510 * @buf: pointer to buffer where descriptor would be read, 3511 * the caller should free the memory. 3512 * @ascii: if true convert from unicode to ascii characters 3513 * null terminated string. 3514 * 3515 * Return: 3516 * * string size on success. 3517 * * -ENOMEM: on allocation failure 3518 * * -EINVAL: on a wrong parameter 3519 */ 3520 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, 3521 u8 **buf, bool ascii) 3522 { 3523 struct uc_string_id *uc_str; 3524 u8 *str; 3525 int ret; 3526 3527 if (!buf) 3528 return -EINVAL; 3529 3530 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL); 3531 if (!uc_str) 3532 return -ENOMEM; 3533 3534 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0, 3535 (u8 *)uc_str, QUERY_DESC_MAX_SIZE); 3536 if (ret < 0) { 3537 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n", 3538 QUERY_REQ_RETRIES, ret); 3539 str = NULL; 3540 goto out; 3541 } 3542 3543 if (uc_str->len <= QUERY_DESC_HDR_SIZE) { 3544 dev_dbg(hba->dev, "String Desc is of zero length\n"); 3545 str = NULL; 3546 ret = 0; 3547 goto out; 3548 } 3549 3550 if (ascii) { 3551 ssize_t ascii_len; 3552 int i; 3553 /* remove header and divide by 2 to move from UTF16 to UTF8 */ 3554 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1; 3555 str = kzalloc(ascii_len, GFP_KERNEL); 3556 if (!str) { 3557 ret = -ENOMEM; 3558 goto out; 3559 } 3560 3561 /* 3562 * the descriptor contains string in UTF16 format 3563 * we need to convert to utf-8 so it can be displayed 3564 */ 3565 ret = utf16s_to_utf8s(uc_str->uc, 3566 uc_str->len - QUERY_DESC_HDR_SIZE, 3567 UTF16_BIG_ENDIAN, str, ascii_len); 3568 3569 /* replace non-printable or non-ASCII characters with spaces */ 3570 for (i = 0; i < ret; i++) 3571 str[i] = ufshcd_remove_non_printable(str[i]); 3572 3573 str[ret++] = '\0'; 3574 3575 } else { 3576 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL); 3577 if (!str) { 3578 ret = -ENOMEM; 3579 goto out; 3580 } 3581 ret = uc_str->len; 3582 } 3583 out: 3584 *buf = str; 3585 kfree(uc_str); 3586 return ret; 3587 } 3588 3589 /** 3590 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter 3591 * @hba: Pointer to adapter instance 3592 * @lun: lun id 3593 * @param_offset: offset of the parameter to read 3594 * @param_read_buf: pointer to buffer where parameter would be read 3595 * @param_size: sizeof(param_read_buf) 3596 * 3597 * Return 0 in case of success, non-zero otherwise 3598 */ 3599 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba, 3600 int lun, 3601 enum unit_desc_param param_offset, 3602 u8 *param_read_buf, 3603 u32 param_size) 3604 { 3605 /* 3606 * Unit descriptors are only available for general purpose LUs (LUN id 3607 * from 0 to 7) and RPMB Well known LU. 3608 */ 3609 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset)) 3610 return -EOPNOTSUPP; 3611 3612 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun, 3613 param_offset, param_read_buf, param_size); 3614 } 3615 3616 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba) 3617 { 3618 int err = 0; 3619 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US; 3620 3621 if (hba->dev_info.wspecversion >= 0x300) { 3622 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 3623 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0, 3624 &gating_wait); 3625 if (err) 3626 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n", 3627 err, gating_wait); 3628 3629 if (gating_wait == 0) { 3630 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US; 3631 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n", 3632 gating_wait); 3633 } 3634 3635 hba->dev_info.clk_gating_wait_us = gating_wait; 3636 } 3637 3638 return err; 3639 } 3640 3641 /** 3642 * ufshcd_memory_alloc - allocate memory for host memory space data structures 3643 * @hba: per adapter instance 3644 * 3645 * 1. Allocate DMA memory for Command Descriptor array 3646 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT 3647 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL). 3648 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List 3649 * (UTMRDL) 3650 * 4. Allocate memory for local reference block(lrb). 3651 * 3652 * Returns 0 for success, non-zero in case of failure 3653 */ 3654 static int ufshcd_memory_alloc(struct ufs_hba *hba) 3655 { 3656 size_t utmrdl_size, utrdl_size, ucdl_size; 3657 3658 /* Allocate memory for UTP command descriptors */ 3659 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs); 3660 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev, 3661 ucdl_size, 3662 &hba->ucdl_dma_addr, 3663 GFP_KERNEL); 3664 3665 /* 3666 * UFSHCI requires UTP command descriptor to be 128 byte aligned. 3667 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE 3668 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will 3669 * be aligned to 128 bytes as well 3670 */ 3671 if (!hba->ucdl_base_addr || 3672 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) { 3673 dev_err(hba->dev, 3674 "Command Descriptor Memory allocation failed\n"); 3675 goto out; 3676 } 3677 3678 /* 3679 * Allocate memory for UTP Transfer descriptors 3680 * UFSHCI requires 1024 byte alignment of UTRD 3681 */ 3682 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs); 3683 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev, 3684 utrdl_size, 3685 &hba->utrdl_dma_addr, 3686 GFP_KERNEL); 3687 if (!hba->utrdl_base_addr || 3688 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) { 3689 dev_err(hba->dev, 3690 "Transfer Descriptor Memory allocation failed\n"); 3691 goto out; 3692 } 3693 3694 /* 3695 * Allocate memory for UTP Task Management descriptors 3696 * UFSHCI requires 1024 byte alignment of UTMRD 3697 */ 3698 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs; 3699 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev, 3700 utmrdl_size, 3701 &hba->utmrdl_dma_addr, 3702 GFP_KERNEL); 3703 if (!hba->utmrdl_base_addr || 3704 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) { 3705 dev_err(hba->dev, 3706 "Task Management Descriptor Memory allocation failed\n"); 3707 goto out; 3708 } 3709 3710 /* Allocate memory for local reference block */ 3711 hba->lrb = devm_kcalloc(hba->dev, 3712 hba->nutrs, sizeof(struct ufshcd_lrb), 3713 GFP_KERNEL); 3714 if (!hba->lrb) { 3715 dev_err(hba->dev, "LRB Memory allocation failed\n"); 3716 goto out; 3717 } 3718 return 0; 3719 out: 3720 return -ENOMEM; 3721 } 3722 3723 /** 3724 * ufshcd_host_memory_configure - configure local reference block with 3725 * memory offsets 3726 * @hba: per adapter instance 3727 * 3728 * Configure Host memory space 3729 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA 3730 * address. 3731 * 2. Update each UTRD with Response UPIU offset, Response UPIU length 3732 * and PRDT offset. 3733 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT 3734 * into local reference block. 3735 */ 3736 static void ufshcd_host_memory_configure(struct ufs_hba *hba) 3737 { 3738 struct utp_transfer_req_desc *utrdlp; 3739 dma_addr_t cmd_desc_dma_addr; 3740 dma_addr_t cmd_desc_element_addr; 3741 u16 response_offset; 3742 u16 prdt_offset; 3743 int cmd_desc_size; 3744 int i; 3745 3746 utrdlp = hba->utrdl_base_addr; 3747 3748 response_offset = 3749 offsetof(struct utp_transfer_cmd_desc, response_upiu); 3750 prdt_offset = 3751 offsetof(struct utp_transfer_cmd_desc, prd_table); 3752 3753 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc); 3754 cmd_desc_dma_addr = hba->ucdl_dma_addr; 3755 3756 for (i = 0; i < hba->nutrs; i++) { 3757 /* Configure UTRD with command descriptor base address */ 3758 cmd_desc_element_addr = 3759 (cmd_desc_dma_addr + (cmd_desc_size * i)); 3760 utrdlp[i].command_desc_base_addr_lo = 3761 cpu_to_le32(lower_32_bits(cmd_desc_element_addr)); 3762 utrdlp[i].command_desc_base_addr_hi = 3763 cpu_to_le32(upper_32_bits(cmd_desc_element_addr)); 3764 3765 /* Response upiu and prdt offset should be in double words */ 3766 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) { 3767 utrdlp[i].response_upiu_offset = 3768 cpu_to_le16(response_offset); 3769 utrdlp[i].prd_table_offset = 3770 cpu_to_le16(prdt_offset); 3771 utrdlp[i].response_upiu_length = 3772 cpu_to_le16(ALIGNED_UPIU_SIZE); 3773 } else { 3774 utrdlp[i].response_upiu_offset = 3775 cpu_to_le16(response_offset >> 2); 3776 utrdlp[i].prd_table_offset = 3777 cpu_to_le16(prdt_offset >> 2); 3778 utrdlp[i].response_upiu_length = 3779 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2); 3780 } 3781 3782 ufshcd_init_lrb(hba, &hba->lrb[i], i); 3783 } 3784 } 3785 3786 /** 3787 * ufshcd_dme_link_startup - Notify Unipro to perform link startup 3788 * @hba: per adapter instance 3789 * 3790 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer, 3791 * in order to initialize the Unipro link startup procedure. 3792 * Once the Unipro links are up, the device connected to the controller 3793 * is detected. 3794 * 3795 * Returns 0 on success, non-zero value on failure 3796 */ 3797 static int ufshcd_dme_link_startup(struct ufs_hba *hba) 3798 { 3799 struct uic_command uic_cmd = {0}; 3800 int ret; 3801 3802 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP; 3803 3804 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 3805 if (ret) 3806 dev_dbg(hba->dev, 3807 "dme-link-startup: error code %d\n", ret); 3808 return ret; 3809 } 3810 /** 3811 * ufshcd_dme_reset - UIC command for DME_RESET 3812 * @hba: per adapter instance 3813 * 3814 * DME_RESET command is issued in order to reset UniPro stack. 3815 * This function now deals with cold reset. 3816 * 3817 * Returns 0 on success, non-zero value on failure 3818 */ 3819 static int ufshcd_dme_reset(struct ufs_hba *hba) 3820 { 3821 struct uic_command uic_cmd = {0}; 3822 int ret; 3823 3824 uic_cmd.command = UIC_CMD_DME_RESET; 3825 3826 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 3827 if (ret) 3828 dev_err(hba->dev, 3829 "dme-reset: error code %d\n", ret); 3830 3831 return ret; 3832 } 3833 3834 int ufshcd_dme_configure_adapt(struct ufs_hba *hba, 3835 int agreed_gear, 3836 int adapt_val) 3837 { 3838 int ret; 3839 3840 if (agreed_gear < UFS_HS_G4) 3841 adapt_val = PA_NO_ADAPT; 3842 3843 ret = ufshcd_dme_set(hba, 3844 UIC_ARG_MIB(PA_TXHSADAPTTYPE), 3845 adapt_val); 3846 return ret; 3847 } 3848 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt); 3849 3850 /** 3851 * ufshcd_dme_enable - UIC command for DME_ENABLE 3852 * @hba: per adapter instance 3853 * 3854 * DME_ENABLE command is issued in order to enable UniPro stack. 3855 * 3856 * Returns 0 on success, non-zero value on failure 3857 */ 3858 static int ufshcd_dme_enable(struct ufs_hba *hba) 3859 { 3860 struct uic_command uic_cmd = {0}; 3861 int ret; 3862 3863 uic_cmd.command = UIC_CMD_DME_ENABLE; 3864 3865 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 3866 if (ret) 3867 dev_err(hba->dev, 3868 "dme-enable: error code %d\n", ret); 3869 3870 return ret; 3871 } 3872 3873 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba) 3874 { 3875 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000 3876 unsigned long min_sleep_time_us; 3877 3878 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS)) 3879 return; 3880 3881 /* 3882 * last_dme_cmd_tstamp will be 0 only for 1st call to 3883 * this function 3884 */ 3885 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) { 3886 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US; 3887 } else { 3888 unsigned long delta = 3889 (unsigned long) ktime_to_us( 3890 ktime_sub(ktime_get(), 3891 hba->last_dme_cmd_tstamp)); 3892 3893 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US) 3894 min_sleep_time_us = 3895 MIN_DELAY_BEFORE_DME_CMDS_US - delta; 3896 else 3897 return; /* no more delay required */ 3898 } 3899 3900 /* allow sleep for extra 50us if needed */ 3901 usleep_range(min_sleep_time_us, min_sleep_time_us + 50); 3902 } 3903 3904 /** 3905 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET 3906 * @hba: per adapter instance 3907 * @attr_sel: uic command argument1 3908 * @attr_set: attribute set type as uic command argument2 3909 * @mib_val: setting value as uic command argument3 3910 * @peer: indicate whether peer or local 3911 * 3912 * Returns 0 on success, non-zero value on failure 3913 */ 3914 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel, 3915 u8 attr_set, u32 mib_val, u8 peer) 3916 { 3917 struct uic_command uic_cmd = {0}; 3918 static const char *const action[] = { 3919 "dme-set", 3920 "dme-peer-set" 3921 }; 3922 const char *set = action[!!peer]; 3923 int ret; 3924 int retries = UFS_UIC_COMMAND_RETRIES; 3925 3926 uic_cmd.command = peer ? 3927 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET; 3928 uic_cmd.argument1 = attr_sel; 3929 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set); 3930 uic_cmd.argument3 = mib_val; 3931 3932 do { 3933 /* for peer attributes we retry upon failure */ 3934 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 3935 if (ret) 3936 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n", 3937 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret); 3938 } while (ret && peer && --retries); 3939 3940 if (ret) 3941 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n", 3942 set, UIC_GET_ATTR_ID(attr_sel), mib_val, 3943 UFS_UIC_COMMAND_RETRIES - retries); 3944 3945 return ret; 3946 } 3947 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr); 3948 3949 /** 3950 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET 3951 * @hba: per adapter instance 3952 * @attr_sel: uic command argument1 3953 * @mib_val: the value of the attribute as returned by the UIC command 3954 * @peer: indicate whether peer or local 3955 * 3956 * Returns 0 on success, non-zero value on failure 3957 */ 3958 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel, 3959 u32 *mib_val, u8 peer) 3960 { 3961 struct uic_command uic_cmd = {0}; 3962 static const char *const action[] = { 3963 "dme-get", 3964 "dme-peer-get" 3965 }; 3966 const char *get = action[!!peer]; 3967 int ret; 3968 int retries = UFS_UIC_COMMAND_RETRIES; 3969 struct ufs_pa_layer_attr orig_pwr_info; 3970 struct ufs_pa_layer_attr temp_pwr_info; 3971 bool pwr_mode_change = false; 3972 3973 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) { 3974 orig_pwr_info = hba->pwr_info; 3975 temp_pwr_info = orig_pwr_info; 3976 3977 if (orig_pwr_info.pwr_tx == FAST_MODE || 3978 orig_pwr_info.pwr_rx == FAST_MODE) { 3979 temp_pwr_info.pwr_tx = FASTAUTO_MODE; 3980 temp_pwr_info.pwr_rx = FASTAUTO_MODE; 3981 pwr_mode_change = true; 3982 } else if (orig_pwr_info.pwr_tx == SLOW_MODE || 3983 orig_pwr_info.pwr_rx == SLOW_MODE) { 3984 temp_pwr_info.pwr_tx = SLOWAUTO_MODE; 3985 temp_pwr_info.pwr_rx = SLOWAUTO_MODE; 3986 pwr_mode_change = true; 3987 } 3988 if (pwr_mode_change) { 3989 ret = ufshcd_change_power_mode(hba, &temp_pwr_info); 3990 if (ret) 3991 goto out; 3992 } 3993 } 3994 3995 uic_cmd.command = peer ? 3996 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET; 3997 uic_cmd.argument1 = attr_sel; 3998 3999 do { 4000 /* for peer attributes we retry upon failure */ 4001 ret = ufshcd_send_uic_cmd(hba, &uic_cmd); 4002 if (ret) 4003 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n", 4004 get, UIC_GET_ATTR_ID(attr_sel), ret); 4005 } while (ret && peer && --retries); 4006 4007 if (ret) 4008 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n", 4009 get, UIC_GET_ATTR_ID(attr_sel), 4010 UFS_UIC_COMMAND_RETRIES - retries); 4011 4012 if (mib_val && !ret) 4013 *mib_val = uic_cmd.argument3; 4014 4015 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE) 4016 && pwr_mode_change) 4017 ufshcd_change_power_mode(hba, &orig_pwr_info); 4018 out: 4019 return ret; 4020 } 4021 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr); 4022 4023 /** 4024 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power 4025 * state) and waits for it to take effect. 4026 * 4027 * @hba: per adapter instance 4028 * @cmd: UIC command to execute 4029 * 4030 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER & 4031 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host 4032 * and device UniPro link and hence it's final completion would be indicated by 4033 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in 4034 * addition to normal UIC command completion Status (UCCS). This function only 4035 * returns after the relevant status bits indicate the completion. 4036 * 4037 * Returns 0 on success, non-zero value on failure 4038 */ 4039 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd) 4040 { 4041 DECLARE_COMPLETION_ONSTACK(uic_async_done); 4042 unsigned long flags; 4043 u8 status; 4044 int ret; 4045 bool reenable_intr = false; 4046 4047 mutex_lock(&hba->uic_cmd_mutex); 4048 ufshcd_add_delay_before_dme_cmd(hba); 4049 4050 spin_lock_irqsave(hba->host->host_lock, flags); 4051 if (ufshcd_is_link_broken(hba)) { 4052 ret = -ENOLINK; 4053 goto out_unlock; 4054 } 4055 hba->uic_async_done = &uic_async_done; 4056 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) { 4057 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL); 4058 /* 4059 * Make sure UIC command completion interrupt is disabled before 4060 * issuing UIC command. 4061 */ 4062 wmb(); 4063 reenable_intr = true; 4064 } 4065 ret = __ufshcd_send_uic_cmd(hba, cmd, false); 4066 spin_unlock_irqrestore(hba->host->host_lock, flags); 4067 if (ret) { 4068 dev_err(hba->dev, 4069 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n", 4070 cmd->command, cmd->argument3, ret); 4071 goto out; 4072 } 4073 4074 if (!wait_for_completion_timeout(hba->uic_async_done, 4075 msecs_to_jiffies(UIC_CMD_TIMEOUT))) { 4076 dev_err(hba->dev, 4077 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n", 4078 cmd->command, cmd->argument3); 4079 4080 if (!cmd->cmd_active) { 4081 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n", 4082 __func__); 4083 goto check_upmcrs; 4084 } 4085 4086 ret = -ETIMEDOUT; 4087 goto out; 4088 } 4089 4090 check_upmcrs: 4091 status = ufshcd_get_upmcrs(hba); 4092 if (status != PWR_LOCAL) { 4093 dev_err(hba->dev, 4094 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n", 4095 cmd->command, status); 4096 ret = (status != PWR_OK) ? status : -1; 4097 } 4098 out: 4099 if (ret) { 4100 ufshcd_print_host_state(hba); 4101 ufshcd_print_pwr_info(hba); 4102 ufshcd_print_evt_hist(hba); 4103 } 4104 4105 spin_lock_irqsave(hba->host->host_lock, flags); 4106 hba->active_uic_cmd = NULL; 4107 hba->uic_async_done = NULL; 4108 if (reenable_intr) 4109 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL); 4110 if (ret) { 4111 ufshcd_set_link_broken(hba); 4112 ufshcd_schedule_eh_work(hba); 4113 } 4114 out_unlock: 4115 spin_unlock_irqrestore(hba->host->host_lock, flags); 4116 mutex_unlock(&hba->uic_cmd_mutex); 4117 4118 return ret; 4119 } 4120 4121 /** 4122 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage 4123 * using DME_SET primitives. 4124 * @hba: per adapter instance 4125 * @mode: powr mode value 4126 * 4127 * Returns 0 on success, non-zero value on failure 4128 */ 4129 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode) 4130 { 4131 struct uic_command uic_cmd = {0}; 4132 int ret; 4133 4134 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) { 4135 ret = ufshcd_dme_set(hba, 4136 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1); 4137 if (ret) { 4138 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n", 4139 __func__, ret); 4140 goto out; 4141 } 4142 } 4143 4144 uic_cmd.command = UIC_CMD_DME_SET; 4145 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE); 4146 uic_cmd.argument3 = mode; 4147 ufshcd_hold(hba, false); 4148 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd); 4149 ufshcd_release(hba); 4150 4151 out: 4152 return ret; 4153 } 4154 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode); 4155 4156 int ufshcd_link_recovery(struct ufs_hba *hba) 4157 { 4158 int ret; 4159 unsigned long flags; 4160 4161 spin_lock_irqsave(hba->host->host_lock, flags); 4162 hba->ufshcd_state = UFSHCD_STATE_RESET; 4163 ufshcd_set_eh_in_progress(hba); 4164 spin_unlock_irqrestore(hba->host->host_lock, flags); 4165 4166 /* Reset the attached device */ 4167 ufshcd_device_reset(hba); 4168 4169 ret = ufshcd_host_reset_and_restore(hba); 4170 4171 spin_lock_irqsave(hba->host->host_lock, flags); 4172 if (ret) 4173 hba->ufshcd_state = UFSHCD_STATE_ERROR; 4174 ufshcd_clear_eh_in_progress(hba); 4175 spin_unlock_irqrestore(hba->host->host_lock, flags); 4176 4177 if (ret) 4178 dev_err(hba->dev, "%s: link recovery failed, err %d", 4179 __func__, ret); 4180 4181 return ret; 4182 } 4183 EXPORT_SYMBOL_GPL(ufshcd_link_recovery); 4184 4185 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba) 4186 { 4187 int ret; 4188 struct uic_command uic_cmd = {0}; 4189 ktime_t start = ktime_get(); 4190 4191 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE); 4192 4193 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER; 4194 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd); 4195 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter", 4196 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 4197 4198 if (ret) 4199 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n", 4200 __func__, ret); 4201 else 4202 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, 4203 POST_CHANGE); 4204 4205 return ret; 4206 } 4207 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter); 4208 4209 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba) 4210 { 4211 struct uic_command uic_cmd = {0}; 4212 int ret; 4213 ktime_t start = ktime_get(); 4214 4215 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE); 4216 4217 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT; 4218 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd); 4219 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit", 4220 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 4221 4222 if (ret) { 4223 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n", 4224 __func__, ret); 4225 } else { 4226 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, 4227 POST_CHANGE); 4228 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock(); 4229 hba->ufs_stats.hibern8_exit_cnt++; 4230 } 4231 4232 return ret; 4233 } 4234 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit); 4235 4236 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit) 4237 { 4238 unsigned long flags; 4239 bool update = false; 4240 4241 if (!ufshcd_is_auto_hibern8_supported(hba)) 4242 return; 4243 4244 spin_lock_irqsave(hba->host->host_lock, flags); 4245 if (hba->ahit != ahit) { 4246 hba->ahit = ahit; 4247 update = true; 4248 } 4249 spin_unlock_irqrestore(hba->host->host_lock, flags); 4250 4251 if (update && 4252 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) { 4253 ufshcd_rpm_get_sync(hba); 4254 ufshcd_hold(hba, false); 4255 ufshcd_auto_hibern8_enable(hba); 4256 ufshcd_release(hba); 4257 ufshcd_rpm_put_sync(hba); 4258 } 4259 } 4260 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update); 4261 4262 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba) 4263 { 4264 if (!ufshcd_is_auto_hibern8_supported(hba)) 4265 return; 4266 4267 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER); 4268 } 4269 4270 /** 4271 * ufshcd_init_pwr_info - setting the POR (power on reset) 4272 * values in hba power info 4273 * @hba: per-adapter instance 4274 */ 4275 static void ufshcd_init_pwr_info(struct ufs_hba *hba) 4276 { 4277 hba->pwr_info.gear_rx = UFS_PWM_G1; 4278 hba->pwr_info.gear_tx = UFS_PWM_G1; 4279 hba->pwr_info.lane_rx = 1; 4280 hba->pwr_info.lane_tx = 1; 4281 hba->pwr_info.pwr_rx = SLOWAUTO_MODE; 4282 hba->pwr_info.pwr_tx = SLOWAUTO_MODE; 4283 hba->pwr_info.hs_rate = 0; 4284 } 4285 4286 /** 4287 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device 4288 * @hba: per-adapter instance 4289 */ 4290 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba) 4291 { 4292 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info; 4293 4294 if (hba->max_pwr_info.is_valid) 4295 return 0; 4296 4297 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) { 4298 pwr_info->pwr_tx = FASTAUTO_MODE; 4299 pwr_info->pwr_rx = FASTAUTO_MODE; 4300 } else { 4301 pwr_info->pwr_tx = FAST_MODE; 4302 pwr_info->pwr_rx = FAST_MODE; 4303 } 4304 pwr_info->hs_rate = PA_HS_MODE_B; 4305 4306 /* Get the connected lane count */ 4307 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES), 4308 &pwr_info->lane_rx); 4309 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES), 4310 &pwr_info->lane_tx); 4311 4312 if (!pwr_info->lane_rx || !pwr_info->lane_tx) { 4313 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n", 4314 __func__, 4315 pwr_info->lane_rx, 4316 pwr_info->lane_tx); 4317 return -EINVAL; 4318 } 4319 4320 /* 4321 * First, get the maximum gears of HS speed. 4322 * If a zero value, it means there is no HSGEAR capability. 4323 * Then, get the maximum gears of PWM speed. 4324 */ 4325 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx); 4326 if (!pwr_info->gear_rx) { 4327 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR), 4328 &pwr_info->gear_rx); 4329 if (!pwr_info->gear_rx) { 4330 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n", 4331 __func__, pwr_info->gear_rx); 4332 return -EINVAL; 4333 } 4334 pwr_info->pwr_rx = SLOW_MODE; 4335 } 4336 4337 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), 4338 &pwr_info->gear_tx); 4339 if (!pwr_info->gear_tx) { 4340 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR), 4341 &pwr_info->gear_tx); 4342 if (!pwr_info->gear_tx) { 4343 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n", 4344 __func__, pwr_info->gear_tx); 4345 return -EINVAL; 4346 } 4347 pwr_info->pwr_tx = SLOW_MODE; 4348 } 4349 4350 hba->max_pwr_info.is_valid = true; 4351 return 0; 4352 } 4353 4354 static int ufshcd_change_power_mode(struct ufs_hba *hba, 4355 struct ufs_pa_layer_attr *pwr_mode) 4356 { 4357 int ret; 4358 4359 /* if already configured to the requested pwr_mode */ 4360 if (!hba->force_pmc && 4361 pwr_mode->gear_rx == hba->pwr_info.gear_rx && 4362 pwr_mode->gear_tx == hba->pwr_info.gear_tx && 4363 pwr_mode->lane_rx == hba->pwr_info.lane_rx && 4364 pwr_mode->lane_tx == hba->pwr_info.lane_tx && 4365 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx && 4366 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx && 4367 pwr_mode->hs_rate == hba->pwr_info.hs_rate) { 4368 dev_dbg(hba->dev, "%s: power already configured\n", __func__); 4369 return 0; 4370 } 4371 4372 /* 4373 * Configure attributes for power mode change with below. 4374 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION, 4375 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION, 4376 * - PA_HSSERIES 4377 */ 4378 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx); 4379 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES), 4380 pwr_mode->lane_rx); 4381 if (pwr_mode->pwr_rx == FASTAUTO_MODE || 4382 pwr_mode->pwr_rx == FAST_MODE) 4383 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true); 4384 else 4385 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false); 4386 4387 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx); 4388 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES), 4389 pwr_mode->lane_tx); 4390 if (pwr_mode->pwr_tx == FASTAUTO_MODE || 4391 pwr_mode->pwr_tx == FAST_MODE) 4392 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true); 4393 else 4394 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false); 4395 4396 if (pwr_mode->pwr_rx == FASTAUTO_MODE || 4397 pwr_mode->pwr_tx == FASTAUTO_MODE || 4398 pwr_mode->pwr_rx == FAST_MODE || 4399 pwr_mode->pwr_tx == FAST_MODE) 4400 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES), 4401 pwr_mode->hs_rate); 4402 4403 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) { 4404 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0), 4405 DL_FC0ProtectionTimeOutVal_Default); 4406 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1), 4407 DL_TC0ReplayTimeOutVal_Default); 4408 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2), 4409 DL_AFC0ReqTimeOutVal_Default); 4410 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3), 4411 DL_FC1ProtectionTimeOutVal_Default); 4412 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4), 4413 DL_TC1ReplayTimeOutVal_Default); 4414 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5), 4415 DL_AFC1ReqTimeOutVal_Default); 4416 4417 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal), 4418 DL_FC0ProtectionTimeOutVal_Default); 4419 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal), 4420 DL_TC0ReplayTimeOutVal_Default); 4421 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal), 4422 DL_AFC0ReqTimeOutVal_Default); 4423 } 4424 4425 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4 4426 | pwr_mode->pwr_tx); 4427 4428 if (ret) { 4429 dev_err(hba->dev, 4430 "%s: power mode change failed %d\n", __func__, ret); 4431 } else { 4432 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL, 4433 pwr_mode); 4434 4435 memcpy(&hba->pwr_info, pwr_mode, 4436 sizeof(struct ufs_pa_layer_attr)); 4437 } 4438 4439 return ret; 4440 } 4441 4442 /** 4443 * ufshcd_config_pwr_mode - configure a new power mode 4444 * @hba: per-adapter instance 4445 * @desired_pwr_mode: desired power configuration 4446 */ 4447 int ufshcd_config_pwr_mode(struct ufs_hba *hba, 4448 struct ufs_pa_layer_attr *desired_pwr_mode) 4449 { 4450 struct ufs_pa_layer_attr final_params = { 0 }; 4451 int ret; 4452 4453 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE, 4454 desired_pwr_mode, &final_params); 4455 4456 if (ret) 4457 memcpy(&final_params, desired_pwr_mode, sizeof(final_params)); 4458 4459 ret = ufshcd_change_power_mode(hba, &final_params); 4460 4461 return ret; 4462 } 4463 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode); 4464 4465 /** 4466 * ufshcd_complete_dev_init() - checks device readiness 4467 * @hba: per-adapter instance 4468 * 4469 * Set fDeviceInit flag and poll until device toggles it. 4470 */ 4471 static int ufshcd_complete_dev_init(struct ufs_hba *hba) 4472 { 4473 int err; 4474 bool flag_res = true; 4475 ktime_t timeout; 4476 4477 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG, 4478 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL); 4479 if (err) { 4480 dev_err(hba->dev, 4481 "%s setting fDeviceInit flag failed with error %d\n", 4482 __func__, err); 4483 goto out; 4484 } 4485 4486 /* Poll fDeviceInit flag to be cleared */ 4487 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT); 4488 do { 4489 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG, 4490 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res); 4491 if (!flag_res) 4492 break; 4493 usleep_range(500, 1000); 4494 } while (ktime_before(ktime_get(), timeout)); 4495 4496 if (err) { 4497 dev_err(hba->dev, 4498 "%s reading fDeviceInit flag failed with error %d\n", 4499 __func__, err); 4500 } else if (flag_res) { 4501 dev_err(hba->dev, 4502 "%s fDeviceInit was not cleared by the device\n", 4503 __func__); 4504 err = -EBUSY; 4505 } 4506 out: 4507 return err; 4508 } 4509 4510 /** 4511 * ufshcd_make_hba_operational - Make UFS controller operational 4512 * @hba: per adapter instance 4513 * 4514 * To bring UFS host controller to operational state, 4515 * 1. Enable required interrupts 4516 * 2. Configure interrupt aggregation 4517 * 3. Program UTRL and UTMRL base address 4518 * 4. Configure run-stop-registers 4519 * 4520 * Returns 0 on success, non-zero value on failure 4521 */ 4522 int ufshcd_make_hba_operational(struct ufs_hba *hba) 4523 { 4524 int err = 0; 4525 u32 reg; 4526 4527 /* Enable required interrupts */ 4528 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS); 4529 4530 /* Configure interrupt aggregation */ 4531 if (ufshcd_is_intr_aggr_allowed(hba)) 4532 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO); 4533 else 4534 ufshcd_disable_intr_aggr(hba); 4535 4536 /* Configure UTRL and UTMRL base address registers */ 4537 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr), 4538 REG_UTP_TRANSFER_REQ_LIST_BASE_L); 4539 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr), 4540 REG_UTP_TRANSFER_REQ_LIST_BASE_H); 4541 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr), 4542 REG_UTP_TASK_REQ_LIST_BASE_L); 4543 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr), 4544 REG_UTP_TASK_REQ_LIST_BASE_H); 4545 4546 /* 4547 * Make sure base address and interrupt setup are updated before 4548 * enabling the run/stop registers below. 4549 */ 4550 wmb(); 4551 4552 /* 4553 * UCRDY, UTMRLDY and UTRLRDY bits must be 1 4554 */ 4555 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS); 4556 if (!(ufshcd_get_lists_status(reg))) { 4557 ufshcd_enable_run_stop_reg(hba); 4558 } else { 4559 dev_err(hba->dev, 4560 "Host controller not ready to process requests"); 4561 err = -EIO; 4562 } 4563 4564 return err; 4565 } 4566 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational); 4567 4568 /** 4569 * ufshcd_hba_stop - Send controller to reset state 4570 * @hba: per adapter instance 4571 */ 4572 void ufshcd_hba_stop(struct ufs_hba *hba) 4573 { 4574 unsigned long flags; 4575 int err; 4576 4577 /* 4578 * Obtain the host lock to prevent that the controller is disabled 4579 * while the UFS interrupt handler is active on another CPU. 4580 */ 4581 spin_lock_irqsave(hba->host->host_lock, flags); 4582 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE); 4583 spin_unlock_irqrestore(hba->host->host_lock, flags); 4584 4585 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE, 4586 CONTROLLER_ENABLE, CONTROLLER_DISABLE, 4587 10, 1); 4588 if (err) 4589 dev_err(hba->dev, "%s: Controller disable failed\n", __func__); 4590 } 4591 EXPORT_SYMBOL_GPL(ufshcd_hba_stop); 4592 4593 /** 4594 * ufshcd_hba_execute_hce - initialize the controller 4595 * @hba: per adapter instance 4596 * 4597 * The controller resets itself and controller firmware initialization 4598 * sequence kicks off. When controller is ready it will set 4599 * the Host Controller Enable bit to 1. 4600 * 4601 * Returns 0 on success, non-zero value on failure 4602 */ 4603 static int ufshcd_hba_execute_hce(struct ufs_hba *hba) 4604 { 4605 int retry_outer = 3; 4606 int retry_inner; 4607 4608 start: 4609 if (ufshcd_is_hba_active(hba)) 4610 /* change controller state to "reset state" */ 4611 ufshcd_hba_stop(hba); 4612 4613 /* UniPro link is disabled at this point */ 4614 ufshcd_set_link_off(hba); 4615 4616 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE); 4617 4618 /* start controller initialization sequence */ 4619 ufshcd_hba_start(hba); 4620 4621 /* 4622 * To initialize a UFS host controller HCE bit must be set to 1. 4623 * During initialization the HCE bit value changes from 1->0->1. 4624 * When the host controller completes initialization sequence 4625 * it sets the value of HCE bit to 1. The same HCE bit is read back 4626 * to check if the controller has completed initialization sequence. 4627 * So without this delay the value HCE = 1, set in the previous 4628 * instruction might be read back. 4629 * This delay can be changed based on the controller. 4630 */ 4631 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100); 4632 4633 /* wait for the host controller to complete initialization */ 4634 retry_inner = 50; 4635 while (!ufshcd_is_hba_active(hba)) { 4636 if (retry_inner) { 4637 retry_inner--; 4638 } else { 4639 dev_err(hba->dev, 4640 "Controller enable failed\n"); 4641 if (retry_outer) { 4642 retry_outer--; 4643 goto start; 4644 } 4645 return -EIO; 4646 } 4647 usleep_range(1000, 1100); 4648 } 4649 4650 /* enable UIC related interrupts */ 4651 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK); 4652 4653 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE); 4654 4655 return 0; 4656 } 4657 4658 int ufshcd_hba_enable(struct ufs_hba *hba) 4659 { 4660 int ret; 4661 4662 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) { 4663 ufshcd_set_link_off(hba); 4664 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE); 4665 4666 /* enable UIC related interrupts */ 4667 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK); 4668 ret = ufshcd_dme_reset(hba); 4669 if (!ret) { 4670 ret = ufshcd_dme_enable(hba); 4671 if (!ret) 4672 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE); 4673 if (ret) 4674 dev_err(hba->dev, 4675 "Host controller enable failed with non-hce\n"); 4676 } 4677 } else { 4678 ret = ufshcd_hba_execute_hce(hba); 4679 } 4680 4681 return ret; 4682 } 4683 EXPORT_SYMBOL_GPL(ufshcd_hba_enable); 4684 4685 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer) 4686 { 4687 int tx_lanes = 0, i, err = 0; 4688 4689 if (!peer) 4690 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES), 4691 &tx_lanes); 4692 else 4693 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES), 4694 &tx_lanes); 4695 for (i = 0; i < tx_lanes; i++) { 4696 if (!peer) 4697 err = ufshcd_dme_set(hba, 4698 UIC_ARG_MIB_SEL(TX_LCC_ENABLE, 4699 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)), 4700 0); 4701 else 4702 err = ufshcd_dme_peer_set(hba, 4703 UIC_ARG_MIB_SEL(TX_LCC_ENABLE, 4704 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)), 4705 0); 4706 if (err) { 4707 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d", 4708 __func__, peer, i, err); 4709 break; 4710 } 4711 } 4712 4713 return err; 4714 } 4715 4716 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba) 4717 { 4718 return ufshcd_disable_tx_lcc(hba, true); 4719 } 4720 4721 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val) 4722 { 4723 struct ufs_event_hist *e; 4724 4725 if (id >= UFS_EVT_CNT) 4726 return; 4727 4728 e = &hba->ufs_stats.event[id]; 4729 e->val[e->pos] = val; 4730 e->tstamp[e->pos] = local_clock(); 4731 e->cnt += 1; 4732 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH; 4733 4734 ufshcd_vops_event_notify(hba, id, &val); 4735 } 4736 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist); 4737 4738 /** 4739 * ufshcd_link_startup - Initialize unipro link startup 4740 * @hba: per adapter instance 4741 * 4742 * Returns 0 for success, non-zero in case of failure 4743 */ 4744 static int ufshcd_link_startup(struct ufs_hba *hba) 4745 { 4746 int ret; 4747 int retries = DME_LINKSTARTUP_RETRIES; 4748 bool link_startup_again = false; 4749 4750 /* 4751 * If UFS device isn't active then we will have to issue link startup 4752 * 2 times to make sure the device state move to active. 4753 */ 4754 if (!ufshcd_is_ufs_dev_active(hba)) 4755 link_startup_again = true; 4756 4757 link_startup: 4758 do { 4759 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE); 4760 4761 ret = ufshcd_dme_link_startup(hba); 4762 4763 /* check if device is detected by inter-connect layer */ 4764 if (!ret && !ufshcd_is_device_present(hba)) { 4765 ufshcd_update_evt_hist(hba, 4766 UFS_EVT_LINK_STARTUP_FAIL, 4767 0); 4768 dev_err(hba->dev, "%s: Device not present\n", __func__); 4769 ret = -ENXIO; 4770 goto out; 4771 } 4772 4773 /* 4774 * DME link lost indication is only received when link is up, 4775 * but we can't be sure if the link is up until link startup 4776 * succeeds. So reset the local Uni-Pro and try again. 4777 */ 4778 if (ret && retries && ufshcd_hba_enable(hba)) { 4779 ufshcd_update_evt_hist(hba, 4780 UFS_EVT_LINK_STARTUP_FAIL, 4781 (u32)ret); 4782 goto out; 4783 } 4784 } while (ret && retries--); 4785 4786 if (ret) { 4787 /* failed to get the link up... retire */ 4788 ufshcd_update_evt_hist(hba, 4789 UFS_EVT_LINK_STARTUP_FAIL, 4790 (u32)ret); 4791 goto out; 4792 } 4793 4794 if (link_startup_again) { 4795 link_startup_again = false; 4796 retries = DME_LINKSTARTUP_RETRIES; 4797 goto link_startup; 4798 } 4799 4800 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */ 4801 ufshcd_init_pwr_info(hba); 4802 ufshcd_print_pwr_info(hba); 4803 4804 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) { 4805 ret = ufshcd_disable_device_tx_lcc(hba); 4806 if (ret) 4807 goto out; 4808 } 4809 4810 /* Include any host controller configuration via UIC commands */ 4811 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE); 4812 if (ret) 4813 goto out; 4814 4815 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */ 4816 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER); 4817 ret = ufshcd_make_hba_operational(hba); 4818 out: 4819 if (ret) { 4820 dev_err(hba->dev, "link startup failed %d\n", ret); 4821 ufshcd_print_host_state(hba); 4822 ufshcd_print_pwr_info(hba); 4823 ufshcd_print_evt_hist(hba); 4824 } 4825 return ret; 4826 } 4827 4828 /** 4829 * ufshcd_verify_dev_init() - Verify device initialization 4830 * @hba: per-adapter instance 4831 * 4832 * Send NOP OUT UPIU and wait for NOP IN response to check whether the 4833 * device Transport Protocol (UTP) layer is ready after a reset. 4834 * If the UTP layer at the device side is not initialized, it may 4835 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT 4836 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations. 4837 */ 4838 static int ufshcd_verify_dev_init(struct ufs_hba *hba) 4839 { 4840 int err = 0; 4841 int retries; 4842 4843 ufshcd_hold(hba, false); 4844 mutex_lock(&hba->dev_cmd.lock); 4845 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) { 4846 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP, 4847 hba->nop_out_timeout); 4848 4849 if (!err || err == -ETIMEDOUT) 4850 break; 4851 4852 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err); 4853 } 4854 mutex_unlock(&hba->dev_cmd.lock); 4855 ufshcd_release(hba); 4856 4857 if (err) 4858 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err); 4859 return err; 4860 } 4861 4862 /** 4863 * ufshcd_set_queue_depth - set lun queue depth 4864 * @sdev: pointer to SCSI device 4865 * 4866 * Read bLUQueueDepth value and activate scsi tagged command 4867 * queueing. For WLUN, queue depth is set to 1. For best-effort 4868 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum 4869 * value that host can queue. 4870 */ 4871 static void ufshcd_set_queue_depth(struct scsi_device *sdev) 4872 { 4873 int ret = 0; 4874 u8 lun_qdepth; 4875 struct ufs_hba *hba; 4876 4877 hba = shost_priv(sdev->host); 4878 4879 lun_qdepth = hba->nutrs; 4880 ret = ufshcd_read_unit_desc_param(hba, 4881 ufshcd_scsi_to_upiu_lun(sdev->lun), 4882 UNIT_DESC_PARAM_LU_Q_DEPTH, 4883 &lun_qdepth, 4884 sizeof(lun_qdepth)); 4885 4886 /* Some WLUN doesn't support unit descriptor */ 4887 if (ret == -EOPNOTSUPP) 4888 lun_qdepth = 1; 4889 else if (!lun_qdepth) 4890 /* eventually, we can figure out the real queue depth */ 4891 lun_qdepth = hba->nutrs; 4892 else 4893 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs); 4894 4895 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n", 4896 __func__, lun_qdepth); 4897 scsi_change_queue_depth(sdev, lun_qdepth); 4898 } 4899 4900 /* 4901 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR 4902 * @hba: per-adapter instance 4903 * @lun: UFS device lun id 4904 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info 4905 * 4906 * Returns 0 in case of success and b_lu_write_protect status would be returned 4907 * @b_lu_write_protect parameter. 4908 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported. 4909 * Returns -EINVAL in case of invalid parameters passed to this function. 4910 */ 4911 static int ufshcd_get_lu_wp(struct ufs_hba *hba, 4912 u8 lun, 4913 u8 *b_lu_write_protect) 4914 { 4915 int ret; 4916 4917 if (!b_lu_write_protect) 4918 ret = -EINVAL; 4919 /* 4920 * According to UFS device spec, RPMB LU can't be write 4921 * protected so skip reading bLUWriteProtect parameter for 4922 * it. For other W-LUs, UNIT DESCRIPTOR is not available. 4923 */ 4924 else if (lun >= hba->dev_info.max_lu_supported) 4925 ret = -ENOTSUPP; 4926 else 4927 ret = ufshcd_read_unit_desc_param(hba, 4928 lun, 4929 UNIT_DESC_PARAM_LU_WR_PROTECT, 4930 b_lu_write_protect, 4931 sizeof(*b_lu_write_protect)); 4932 return ret; 4933 } 4934 4935 /** 4936 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect 4937 * status 4938 * @hba: per-adapter instance 4939 * @sdev: pointer to SCSI device 4940 * 4941 */ 4942 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba, 4943 const struct scsi_device *sdev) 4944 { 4945 if (hba->dev_info.f_power_on_wp_en && 4946 !hba->dev_info.is_lu_power_on_wp) { 4947 u8 b_lu_write_protect; 4948 4949 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun), 4950 &b_lu_write_protect) && 4951 (b_lu_write_protect == UFS_LU_POWER_ON_WP)) 4952 hba->dev_info.is_lu_power_on_wp = true; 4953 } 4954 } 4955 4956 /** 4957 * ufshcd_setup_links - associate link b/w device wlun and other luns 4958 * @sdev: pointer to SCSI device 4959 * @hba: pointer to ufs hba 4960 */ 4961 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev) 4962 { 4963 struct device_link *link; 4964 4965 /* 4966 * Device wlun is the supplier & rest of the luns are consumers. 4967 * This ensures that device wlun suspends after all other luns. 4968 */ 4969 if (hba->ufs_device_wlun) { 4970 link = device_link_add(&sdev->sdev_gendev, 4971 &hba->ufs_device_wlun->sdev_gendev, 4972 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE); 4973 if (!link) { 4974 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n", 4975 dev_name(&hba->ufs_device_wlun->sdev_gendev)); 4976 return; 4977 } 4978 hba->luns_avail--; 4979 /* Ignore REPORT_LUN wlun probing */ 4980 if (hba->luns_avail == 1) { 4981 ufshcd_rpm_put(hba); 4982 return; 4983 } 4984 } else { 4985 /* 4986 * Device wlun is probed. The assumption is that WLUNs are 4987 * scanned before other LUNs. 4988 */ 4989 hba->luns_avail--; 4990 } 4991 } 4992 4993 /** 4994 * ufshcd_slave_alloc - handle initial SCSI device configurations 4995 * @sdev: pointer to SCSI device 4996 * 4997 * Returns success 4998 */ 4999 static int ufshcd_slave_alloc(struct scsi_device *sdev) 5000 { 5001 struct ufs_hba *hba; 5002 5003 hba = shost_priv(sdev->host); 5004 5005 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */ 5006 sdev->use_10_for_ms = 1; 5007 5008 /* DBD field should be set to 1 in mode sense(10) */ 5009 sdev->set_dbd_for_ms = 1; 5010 5011 /* allow SCSI layer to restart the device in case of errors */ 5012 sdev->allow_restart = 1; 5013 5014 /* REPORT SUPPORTED OPERATION CODES is not supported */ 5015 sdev->no_report_opcodes = 1; 5016 5017 /* WRITE_SAME command is not supported */ 5018 sdev->no_write_same = 1; 5019 5020 ufshcd_set_queue_depth(sdev); 5021 5022 ufshcd_get_lu_power_on_wp_status(hba, sdev); 5023 5024 ufshcd_setup_links(hba, sdev); 5025 5026 return 0; 5027 } 5028 5029 /** 5030 * ufshcd_change_queue_depth - change queue depth 5031 * @sdev: pointer to SCSI device 5032 * @depth: required depth to set 5033 * 5034 * Change queue depth and make sure the max. limits are not crossed. 5035 */ 5036 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth) 5037 { 5038 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue)); 5039 } 5040 5041 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev) 5042 { 5043 /* skip well-known LU */ 5044 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) || 5045 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba)) 5046 return; 5047 5048 ufshpb_destroy_lu(hba, sdev); 5049 } 5050 5051 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev) 5052 { 5053 /* skip well-known LU */ 5054 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) || 5055 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba)) 5056 return; 5057 5058 ufshpb_init_hpb_lu(hba, sdev); 5059 } 5060 5061 /** 5062 * ufshcd_slave_configure - adjust SCSI device configurations 5063 * @sdev: pointer to SCSI device 5064 */ 5065 static int ufshcd_slave_configure(struct scsi_device *sdev) 5066 { 5067 struct ufs_hba *hba = shost_priv(sdev->host); 5068 struct request_queue *q = sdev->request_queue; 5069 5070 ufshcd_hpb_configure(hba, sdev); 5071 5072 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1); 5073 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE) 5074 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1); 5075 /* 5076 * Block runtime-pm until all consumers are added. 5077 * Refer ufshcd_setup_links(). 5078 */ 5079 if (is_device_wlun(sdev)) 5080 pm_runtime_get_noresume(&sdev->sdev_gendev); 5081 else if (ufshcd_is_rpm_autosuspend_allowed(hba)) 5082 sdev->rpm_autosuspend = 1; 5083 /* 5084 * Do not print messages during runtime PM to avoid never-ending cycles 5085 * of messages written back to storage by user space causing runtime 5086 * resume, causing more messages and so on. 5087 */ 5088 sdev->silence_suspend = 1; 5089 5090 ufshcd_crypto_register(hba, q); 5091 5092 return 0; 5093 } 5094 5095 /** 5096 * ufshcd_slave_destroy - remove SCSI device configurations 5097 * @sdev: pointer to SCSI device 5098 */ 5099 static void ufshcd_slave_destroy(struct scsi_device *sdev) 5100 { 5101 struct ufs_hba *hba; 5102 unsigned long flags; 5103 5104 hba = shost_priv(sdev->host); 5105 5106 ufshcd_hpb_destroy(hba, sdev); 5107 5108 /* Drop the reference as it won't be needed anymore */ 5109 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) { 5110 spin_lock_irqsave(hba->host->host_lock, flags); 5111 hba->ufs_device_wlun = NULL; 5112 spin_unlock_irqrestore(hba->host->host_lock, flags); 5113 } else if (hba->ufs_device_wlun) { 5114 struct device *supplier = NULL; 5115 5116 /* Ensure UFS Device WLUN exists and does not disappear */ 5117 spin_lock_irqsave(hba->host->host_lock, flags); 5118 if (hba->ufs_device_wlun) { 5119 supplier = &hba->ufs_device_wlun->sdev_gendev; 5120 get_device(supplier); 5121 } 5122 spin_unlock_irqrestore(hba->host->host_lock, flags); 5123 5124 if (supplier) { 5125 /* 5126 * If a LUN fails to probe (e.g. absent BOOT WLUN), the 5127 * device will not have been registered but can still 5128 * have a device link holding a reference to the device. 5129 */ 5130 device_link_remove(&sdev->sdev_gendev, supplier); 5131 put_device(supplier); 5132 } 5133 } 5134 } 5135 5136 /** 5137 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status 5138 * @lrbp: pointer to local reference block of completed command 5139 * @scsi_status: SCSI command status 5140 * 5141 * Returns value base on SCSI command status 5142 */ 5143 static inline int 5144 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status) 5145 { 5146 int result = 0; 5147 5148 switch (scsi_status) { 5149 case SAM_STAT_CHECK_CONDITION: 5150 ufshcd_copy_sense_data(lrbp); 5151 fallthrough; 5152 case SAM_STAT_GOOD: 5153 result |= DID_OK << 16 | scsi_status; 5154 break; 5155 case SAM_STAT_TASK_SET_FULL: 5156 case SAM_STAT_BUSY: 5157 case SAM_STAT_TASK_ABORTED: 5158 ufshcd_copy_sense_data(lrbp); 5159 result |= scsi_status; 5160 break; 5161 default: 5162 result |= DID_ERROR << 16; 5163 break; 5164 } /* end of switch */ 5165 5166 return result; 5167 } 5168 5169 /** 5170 * ufshcd_transfer_rsp_status - Get overall status of the response 5171 * @hba: per adapter instance 5172 * @lrbp: pointer to local reference block of completed command 5173 * 5174 * Returns result of the command to notify SCSI midlayer 5175 */ 5176 static inline int 5177 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp) 5178 { 5179 int result = 0; 5180 int scsi_status; 5181 enum utp_ocs ocs; 5182 5183 /* overall command status of utrd */ 5184 ocs = ufshcd_get_tr_ocs(lrbp); 5185 5186 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) { 5187 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) & 5188 MASK_RSP_UPIU_RESULT) 5189 ocs = OCS_SUCCESS; 5190 } 5191 5192 switch (ocs) { 5193 case OCS_SUCCESS: 5194 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr); 5195 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0); 5196 switch (result) { 5197 case UPIU_TRANSACTION_RESPONSE: 5198 /* 5199 * get the response UPIU result to extract 5200 * the SCSI command status 5201 */ 5202 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr); 5203 5204 /* 5205 * get the result based on SCSI status response 5206 * to notify the SCSI midlayer of the command status 5207 */ 5208 scsi_status = result & MASK_SCSI_STATUS; 5209 result = ufshcd_scsi_cmd_status(lrbp, scsi_status); 5210 5211 /* 5212 * Currently we are only supporting BKOPs exception 5213 * events hence we can ignore BKOPs exception event 5214 * during power management callbacks. BKOPs exception 5215 * event is not expected to be raised in runtime suspend 5216 * callback as it allows the urgent bkops. 5217 * During system suspend, we are anyway forcefully 5218 * disabling the bkops and if urgent bkops is needed 5219 * it will be enabled on system resume. Long term 5220 * solution could be to abort the system suspend if 5221 * UFS device needs urgent BKOPs. 5222 */ 5223 if (!hba->pm_op_in_progress && 5224 !ufshcd_eh_in_progress(hba) && 5225 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr)) 5226 /* Flushed in suspend */ 5227 schedule_work(&hba->eeh_work); 5228 5229 if (scsi_status == SAM_STAT_GOOD) 5230 ufshpb_rsp_upiu(hba, lrbp); 5231 break; 5232 case UPIU_TRANSACTION_REJECT_UPIU: 5233 /* TODO: handle Reject UPIU Response */ 5234 result = DID_ERROR << 16; 5235 dev_err(hba->dev, 5236 "Reject UPIU not fully implemented\n"); 5237 break; 5238 default: 5239 dev_err(hba->dev, 5240 "Unexpected request response code = %x\n", 5241 result); 5242 result = DID_ERROR << 16; 5243 break; 5244 } 5245 break; 5246 case OCS_ABORTED: 5247 result |= DID_ABORT << 16; 5248 break; 5249 case OCS_INVALID_COMMAND_STATUS: 5250 result |= DID_REQUEUE << 16; 5251 break; 5252 case OCS_INVALID_CMD_TABLE_ATTR: 5253 case OCS_INVALID_PRDT_ATTR: 5254 case OCS_MISMATCH_DATA_BUF_SIZE: 5255 case OCS_MISMATCH_RESP_UPIU_SIZE: 5256 case OCS_PEER_COMM_FAILURE: 5257 case OCS_FATAL_ERROR: 5258 case OCS_DEVICE_FATAL_ERROR: 5259 case OCS_INVALID_CRYPTO_CONFIG: 5260 case OCS_GENERAL_CRYPTO_ERROR: 5261 default: 5262 result |= DID_ERROR << 16; 5263 dev_err(hba->dev, 5264 "OCS error from controller = %x for tag %d\n", 5265 ocs, lrbp->task_tag); 5266 ufshcd_print_evt_hist(hba); 5267 ufshcd_print_host_state(hba); 5268 break; 5269 } /* end of switch */ 5270 5271 if ((host_byte(result) != DID_OK) && 5272 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs) 5273 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true); 5274 return result; 5275 } 5276 5277 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba, 5278 u32 intr_mask) 5279 { 5280 if (!ufshcd_is_auto_hibern8_supported(hba) || 5281 !ufshcd_is_auto_hibern8_enabled(hba)) 5282 return false; 5283 5284 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK)) 5285 return false; 5286 5287 if (hba->active_uic_cmd && 5288 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER || 5289 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT)) 5290 return false; 5291 5292 return true; 5293 } 5294 5295 /** 5296 * ufshcd_uic_cmd_compl - handle completion of uic command 5297 * @hba: per adapter instance 5298 * @intr_status: interrupt status generated by the controller 5299 * 5300 * Returns 5301 * IRQ_HANDLED - If interrupt is valid 5302 * IRQ_NONE - If invalid interrupt 5303 */ 5304 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status) 5305 { 5306 irqreturn_t retval = IRQ_NONE; 5307 5308 spin_lock(hba->host->host_lock); 5309 if (ufshcd_is_auto_hibern8_error(hba, intr_status)) 5310 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status); 5311 5312 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) { 5313 hba->active_uic_cmd->argument2 |= 5314 ufshcd_get_uic_cmd_result(hba); 5315 hba->active_uic_cmd->argument3 = 5316 ufshcd_get_dme_attr_val(hba); 5317 if (!hba->uic_async_done) 5318 hba->active_uic_cmd->cmd_active = 0; 5319 complete(&hba->active_uic_cmd->done); 5320 retval = IRQ_HANDLED; 5321 } 5322 5323 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) { 5324 hba->active_uic_cmd->cmd_active = 0; 5325 complete(hba->uic_async_done); 5326 retval = IRQ_HANDLED; 5327 } 5328 5329 if (retval == IRQ_HANDLED) 5330 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd, 5331 UFS_CMD_COMP); 5332 spin_unlock(hba->host->host_lock); 5333 return retval; 5334 } 5335 5336 /* Release the resources allocated for processing a SCSI command. */ 5337 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba, 5338 struct ufshcd_lrb *lrbp) 5339 { 5340 struct scsi_cmnd *cmd = lrbp->cmd; 5341 5342 scsi_dma_unmap(cmd); 5343 lrbp->cmd = NULL; /* Mark the command as completed. */ 5344 ufshcd_release(hba); 5345 ufshcd_clk_scaling_update_busy(hba); 5346 } 5347 5348 /** 5349 * __ufshcd_transfer_req_compl - handle SCSI and query command completion 5350 * @hba: per adapter instance 5351 * @completed_reqs: bitmask that indicates which requests to complete 5352 */ 5353 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba, 5354 unsigned long completed_reqs) 5355 { 5356 struct ufshcd_lrb *lrbp; 5357 struct scsi_cmnd *cmd; 5358 int index; 5359 5360 for_each_set_bit(index, &completed_reqs, hba->nutrs) { 5361 lrbp = &hba->lrb[index]; 5362 lrbp->compl_time_stamp = ktime_get(); 5363 lrbp->compl_time_stamp_local_clock = local_clock(); 5364 cmd = lrbp->cmd; 5365 if (cmd) { 5366 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp))) 5367 ufshcd_update_monitor(hba, lrbp); 5368 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP); 5369 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp); 5370 ufshcd_release_scsi_cmd(hba, lrbp); 5371 /* Do not touch lrbp after scsi done */ 5372 scsi_done(cmd); 5373 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE || 5374 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) { 5375 if (hba->dev_cmd.complete) { 5376 ufshcd_add_command_trace(hba, index, 5377 UFS_DEV_COMP); 5378 complete(hba->dev_cmd.complete); 5379 ufshcd_clk_scaling_update_busy(hba); 5380 } 5381 } 5382 } 5383 } 5384 5385 /* 5386 * Returns > 0 if one or more commands have been completed or 0 if no 5387 * requests have been completed. 5388 */ 5389 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num) 5390 { 5391 struct ufs_hba *hba = shost_priv(shost); 5392 unsigned long completed_reqs, flags; 5393 u32 tr_doorbell; 5394 5395 spin_lock_irqsave(&hba->outstanding_lock, flags); 5396 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 5397 completed_reqs = ~tr_doorbell & hba->outstanding_reqs; 5398 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs, 5399 "completed: %#lx; outstanding: %#lx\n", completed_reqs, 5400 hba->outstanding_reqs); 5401 hba->outstanding_reqs &= ~completed_reqs; 5402 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 5403 5404 if (completed_reqs) 5405 __ufshcd_transfer_req_compl(hba, completed_reqs); 5406 5407 return completed_reqs; 5408 } 5409 5410 /** 5411 * ufshcd_transfer_req_compl - handle SCSI and query command completion 5412 * @hba: per adapter instance 5413 * 5414 * Returns 5415 * IRQ_HANDLED - If interrupt is valid 5416 * IRQ_NONE - If invalid interrupt 5417 */ 5418 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba) 5419 { 5420 /* Resetting interrupt aggregation counters first and reading the 5421 * DOOR_BELL afterward allows us to handle all the completed requests. 5422 * In order to prevent other interrupts starvation the DB is read once 5423 * after reset. The down side of this solution is the possibility of 5424 * false interrupt if device completes another request after resetting 5425 * aggregation and before reading the DB. 5426 */ 5427 if (ufshcd_is_intr_aggr_allowed(hba) && 5428 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR)) 5429 ufshcd_reset_intr_aggr(hba); 5430 5431 if (ufs_fail_completion()) 5432 return IRQ_HANDLED; 5433 5434 /* 5435 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we 5436 * do not want polling to trigger spurious interrupt complaints. 5437 */ 5438 ufshcd_poll(hba->host, 0); 5439 5440 return IRQ_HANDLED; 5441 } 5442 5443 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask) 5444 { 5445 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, 5446 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, 5447 &ee_ctrl_mask); 5448 } 5449 5450 int ufshcd_write_ee_control(struct ufs_hba *hba) 5451 { 5452 int err; 5453 5454 mutex_lock(&hba->ee_ctrl_mutex); 5455 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask); 5456 mutex_unlock(&hba->ee_ctrl_mutex); 5457 if (err) 5458 dev_err(hba->dev, "%s: failed to write ee control %d\n", 5459 __func__, err); 5460 return err; 5461 } 5462 5463 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, 5464 const u16 *other_mask, u16 set, u16 clr) 5465 { 5466 u16 new_mask, ee_ctrl_mask; 5467 int err = 0; 5468 5469 mutex_lock(&hba->ee_ctrl_mutex); 5470 new_mask = (*mask & ~clr) | set; 5471 ee_ctrl_mask = new_mask | *other_mask; 5472 if (ee_ctrl_mask != hba->ee_ctrl_mask) 5473 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask); 5474 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */ 5475 if (!err) { 5476 hba->ee_ctrl_mask = ee_ctrl_mask; 5477 *mask = new_mask; 5478 } 5479 mutex_unlock(&hba->ee_ctrl_mutex); 5480 return err; 5481 } 5482 5483 /** 5484 * ufshcd_disable_ee - disable exception event 5485 * @hba: per-adapter instance 5486 * @mask: exception event to disable 5487 * 5488 * Disables exception event in the device so that the EVENT_ALERT 5489 * bit is not set. 5490 * 5491 * Returns zero on success, non-zero error value on failure. 5492 */ 5493 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask) 5494 { 5495 return ufshcd_update_ee_drv_mask(hba, 0, mask); 5496 } 5497 5498 /** 5499 * ufshcd_enable_ee - enable exception event 5500 * @hba: per-adapter instance 5501 * @mask: exception event to enable 5502 * 5503 * Enable corresponding exception event in the device to allow 5504 * device to alert host in critical scenarios. 5505 * 5506 * Returns zero on success, non-zero error value on failure. 5507 */ 5508 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask) 5509 { 5510 return ufshcd_update_ee_drv_mask(hba, mask, 0); 5511 } 5512 5513 /** 5514 * ufshcd_enable_auto_bkops - Allow device managed BKOPS 5515 * @hba: per-adapter instance 5516 * 5517 * Allow device to manage background operations on its own. Enabling 5518 * this might lead to inconsistent latencies during normal data transfers 5519 * as the device is allowed to manage its own way of handling background 5520 * operations. 5521 * 5522 * Returns zero on success, non-zero on failure. 5523 */ 5524 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba) 5525 { 5526 int err = 0; 5527 5528 if (hba->auto_bkops_enabled) 5529 goto out; 5530 5531 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG, 5532 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL); 5533 if (err) { 5534 dev_err(hba->dev, "%s: failed to enable bkops %d\n", 5535 __func__, err); 5536 goto out; 5537 } 5538 5539 hba->auto_bkops_enabled = true; 5540 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled"); 5541 5542 /* No need of URGENT_BKOPS exception from the device */ 5543 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS); 5544 if (err) 5545 dev_err(hba->dev, "%s: failed to disable exception event %d\n", 5546 __func__, err); 5547 out: 5548 return err; 5549 } 5550 5551 /** 5552 * ufshcd_disable_auto_bkops - block device in doing background operations 5553 * @hba: per-adapter instance 5554 * 5555 * Disabling background operations improves command response latency but 5556 * has drawback of device moving into critical state where the device is 5557 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the 5558 * host is idle so that BKOPS are managed effectively without any negative 5559 * impacts. 5560 * 5561 * Returns zero on success, non-zero on failure. 5562 */ 5563 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba) 5564 { 5565 int err = 0; 5566 5567 if (!hba->auto_bkops_enabled) 5568 goto out; 5569 5570 /* 5571 * If host assisted BKOPs is to be enabled, make sure 5572 * urgent bkops exception is allowed. 5573 */ 5574 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS); 5575 if (err) { 5576 dev_err(hba->dev, "%s: failed to enable exception event %d\n", 5577 __func__, err); 5578 goto out; 5579 } 5580 5581 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG, 5582 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL); 5583 if (err) { 5584 dev_err(hba->dev, "%s: failed to disable bkops %d\n", 5585 __func__, err); 5586 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS); 5587 goto out; 5588 } 5589 5590 hba->auto_bkops_enabled = false; 5591 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled"); 5592 hba->is_urgent_bkops_lvl_checked = false; 5593 out: 5594 return err; 5595 } 5596 5597 /** 5598 * ufshcd_force_reset_auto_bkops - force reset auto bkops state 5599 * @hba: per adapter instance 5600 * 5601 * After a device reset the device may toggle the BKOPS_EN flag 5602 * to default value. The s/w tracking variables should be updated 5603 * as well. This function would change the auto-bkops state based on 5604 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND. 5605 */ 5606 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba) 5607 { 5608 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) { 5609 hba->auto_bkops_enabled = false; 5610 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS; 5611 ufshcd_enable_auto_bkops(hba); 5612 } else { 5613 hba->auto_bkops_enabled = true; 5614 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS; 5615 ufshcd_disable_auto_bkops(hba); 5616 } 5617 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT; 5618 hba->is_urgent_bkops_lvl_checked = false; 5619 } 5620 5621 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status) 5622 { 5623 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5624 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status); 5625 } 5626 5627 /** 5628 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status 5629 * @hba: per-adapter instance 5630 * @status: bkops_status value 5631 * 5632 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn 5633 * flag in the device to permit background operations if the device 5634 * bkops_status is greater than or equal to "status" argument passed to 5635 * this function, disable otherwise. 5636 * 5637 * Returns 0 for success, non-zero in case of failure. 5638 * 5639 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag 5640 * to know whether auto bkops is enabled or disabled after this function 5641 * returns control to it. 5642 */ 5643 static int ufshcd_bkops_ctrl(struct ufs_hba *hba, 5644 enum bkops_status status) 5645 { 5646 int err; 5647 u32 curr_status = 0; 5648 5649 err = ufshcd_get_bkops_status(hba, &curr_status); 5650 if (err) { 5651 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n", 5652 __func__, err); 5653 goto out; 5654 } else if (curr_status > BKOPS_STATUS_MAX) { 5655 dev_err(hba->dev, "%s: invalid BKOPS status %d\n", 5656 __func__, curr_status); 5657 err = -EINVAL; 5658 goto out; 5659 } 5660 5661 if (curr_status >= status) 5662 err = ufshcd_enable_auto_bkops(hba); 5663 else 5664 err = ufshcd_disable_auto_bkops(hba); 5665 out: 5666 return err; 5667 } 5668 5669 /** 5670 * ufshcd_urgent_bkops - handle urgent bkops exception event 5671 * @hba: per-adapter instance 5672 * 5673 * Enable fBackgroundOpsEn flag in the device to permit background 5674 * operations. 5675 * 5676 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled 5677 * and negative error value for any other failure. 5678 */ 5679 static int ufshcd_urgent_bkops(struct ufs_hba *hba) 5680 { 5681 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl); 5682 } 5683 5684 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status) 5685 { 5686 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5687 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status); 5688 } 5689 5690 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba) 5691 { 5692 int err; 5693 u32 curr_status = 0; 5694 5695 if (hba->is_urgent_bkops_lvl_checked) 5696 goto enable_auto_bkops; 5697 5698 err = ufshcd_get_bkops_status(hba, &curr_status); 5699 if (err) { 5700 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n", 5701 __func__, err); 5702 goto out; 5703 } 5704 5705 /* 5706 * We are seeing that some devices are raising the urgent bkops 5707 * exception events even when BKOPS status doesn't indicate performace 5708 * impacted or critical. Handle these device by determining their urgent 5709 * bkops status at runtime. 5710 */ 5711 if (curr_status < BKOPS_STATUS_PERF_IMPACT) { 5712 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n", 5713 __func__, curr_status); 5714 /* update the current status as the urgent bkops level */ 5715 hba->urgent_bkops_lvl = curr_status; 5716 hba->is_urgent_bkops_lvl_checked = true; 5717 } 5718 5719 enable_auto_bkops: 5720 err = ufshcd_enable_auto_bkops(hba); 5721 out: 5722 if (err < 0) 5723 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n", 5724 __func__, err); 5725 } 5726 5727 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status) 5728 { 5729 u32 value; 5730 5731 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5732 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value)) 5733 return; 5734 5735 dev_info(hba->dev, "exception Tcase %d\n", value - 80); 5736 5737 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP); 5738 5739 /* 5740 * A placeholder for the platform vendors to add whatever additional 5741 * steps required 5742 */ 5743 } 5744 5745 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn) 5746 { 5747 u8 index; 5748 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG : 5749 UPIU_QUERY_OPCODE_CLEAR_FLAG; 5750 5751 index = ufshcd_wb_get_query_index(hba); 5752 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL); 5753 } 5754 5755 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable) 5756 { 5757 int ret; 5758 5759 if (!ufshcd_is_wb_allowed(hba) || 5760 hba->dev_info.wb_enabled == enable) 5761 return 0; 5762 5763 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN); 5764 if (ret) { 5765 dev_err(hba->dev, "%s: Write Booster %s failed %d\n", 5766 __func__, enable ? "enabling" : "disabling", ret); 5767 return ret; 5768 } 5769 5770 hba->dev_info.wb_enabled = enable; 5771 dev_dbg(hba->dev, "%s: Write Booster %s\n", 5772 __func__, enable ? "enabled" : "disabled"); 5773 5774 return ret; 5775 } 5776 5777 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba, 5778 bool enable) 5779 { 5780 int ret; 5781 5782 ret = __ufshcd_wb_toggle(hba, enable, 5783 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8); 5784 if (ret) { 5785 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n", 5786 __func__, enable ? "enabling" : "disabling", ret); 5787 return; 5788 } 5789 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n", 5790 __func__, enable ? "enabled" : "disabled"); 5791 } 5792 5793 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable) 5794 { 5795 int ret; 5796 5797 if (!ufshcd_is_wb_allowed(hba) || 5798 hba->dev_info.wb_buf_flush_enabled == enable) 5799 return 0; 5800 5801 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN); 5802 if (ret) { 5803 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n", 5804 __func__, enable ? "enabling" : "disabling", ret); 5805 return ret; 5806 } 5807 5808 hba->dev_info.wb_buf_flush_enabled = enable; 5809 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n", 5810 __func__, enable ? "enabled" : "disabled"); 5811 5812 return ret; 5813 } 5814 5815 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba, 5816 u32 avail_buf) 5817 { 5818 u32 cur_buf; 5819 int ret; 5820 u8 index; 5821 5822 index = ufshcd_wb_get_query_index(hba); 5823 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5824 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE, 5825 index, 0, &cur_buf); 5826 if (ret) { 5827 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n", 5828 __func__, ret); 5829 return false; 5830 } 5831 5832 if (!cur_buf) { 5833 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n", 5834 cur_buf); 5835 return false; 5836 } 5837 /* Let it continue to flush when available buffer exceeds threshold */ 5838 return avail_buf < hba->vps->wb_flush_threshold; 5839 } 5840 5841 static void ufshcd_wb_force_disable(struct ufs_hba *hba) 5842 { 5843 if (ufshcd_is_wb_buf_flush_allowed(hba)) 5844 ufshcd_wb_toggle_buf_flush(hba, false); 5845 5846 ufshcd_wb_toggle_buf_flush_during_h8(hba, false); 5847 ufshcd_wb_toggle(hba, false); 5848 hba->caps &= ~UFSHCD_CAP_WB_EN; 5849 5850 dev_info(hba->dev, "%s: WB force disabled\n", __func__); 5851 } 5852 5853 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba) 5854 { 5855 u32 lifetime; 5856 int ret; 5857 u8 index; 5858 5859 index = ufshcd_wb_get_query_index(hba); 5860 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5861 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST, 5862 index, 0, &lifetime); 5863 if (ret) { 5864 dev_err(hba->dev, 5865 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n", 5866 __func__, ret); 5867 return false; 5868 } 5869 5870 if (lifetime == UFS_WB_EXCEED_LIFETIME) { 5871 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n", 5872 __func__, lifetime); 5873 return false; 5874 } 5875 5876 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n", 5877 __func__, lifetime); 5878 5879 return true; 5880 } 5881 5882 static bool ufshcd_wb_need_flush(struct ufs_hba *hba) 5883 { 5884 int ret; 5885 u32 avail_buf; 5886 u8 index; 5887 5888 if (!ufshcd_is_wb_allowed(hba)) 5889 return false; 5890 5891 if (!ufshcd_is_wb_buf_lifetime_available(hba)) { 5892 ufshcd_wb_force_disable(hba); 5893 return false; 5894 } 5895 5896 /* 5897 * The ufs device needs the vcc to be ON to flush. 5898 * With user-space reduction enabled, it's enough to enable flush 5899 * by checking only the available buffer. The threshold 5900 * defined here is > 90% full. 5901 * With user-space preserved enabled, the current-buffer 5902 * should be checked too because the wb buffer size can reduce 5903 * when disk tends to be full. This info is provided by current 5904 * buffer (dCurrentWriteBoosterBufferSize). There's no point in 5905 * keeping vcc on when current buffer is empty. 5906 */ 5907 index = ufshcd_wb_get_query_index(hba); 5908 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 5909 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE, 5910 index, 0, &avail_buf); 5911 if (ret) { 5912 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n", 5913 __func__, ret); 5914 return false; 5915 } 5916 5917 if (!hba->dev_info.b_presrv_uspc_en) 5918 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10); 5919 5920 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf); 5921 } 5922 5923 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work) 5924 { 5925 struct ufs_hba *hba = container_of(to_delayed_work(work), 5926 struct ufs_hba, 5927 rpm_dev_flush_recheck_work); 5928 /* 5929 * To prevent unnecessary VCC power drain after device finishes 5930 * WriteBooster buffer flush or Auto BKOPs, force runtime resume 5931 * after a certain delay to recheck the threshold by next runtime 5932 * suspend. 5933 */ 5934 ufshcd_rpm_get_sync(hba); 5935 ufshcd_rpm_put_sync(hba); 5936 } 5937 5938 /** 5939 * ufshcd_exception_event_handler - handle exceptions raised by device 5940 * @work: pointer to work data 5941 * 5942 * Read bExceptionEventStatus attribute from the device and handle the 5943 * exception event accordingly. 5944 */ 5945 static void ufshcd_exception_event_handler(struct work_struct *work) 5946 { 5947 struct ufs_hba *hba; 5948 int err; 5949 u32 status = 0; 5950 hba = container_of(work, struct ufs_hba, eeh_work); 5951 5952 ufshcd_scsi_block_requests(hba); 5953 err = ufshcd_get_ee_status(hba, &status); 5954 if (err) { 5955 dev_err(hba->dev, "%s: failed to get exception status %d\n", 5956 __func__, err); 5957 goto out; 5958 } 5959 5960 trace_ufshcd_exception_event(dev_name(hba->dev), status); 5961 5962 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS) 5963 ufshcd_bkops_exception_event_handler(hba); 5964 5965 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP) 5966 ufshcd_temp_exception_event_handler(hba, status); 5967 5968 ufs_debugfs_exception_event(hba, status); 5969 out: 5970 ufshcd_scsi_unblock_requests(hba); 5971 } 5972 5973 /* Complete requests that have door-bell cleared */ 5974 static void ufshcd_complete_requests(struct ufs_hba *hba) 5975 { 5976 ufshcd_transfer_req_compl(hba); 5977 ufshcd_tmc_handler(hba); 5978 } 5979 5980 /** 5981 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is 5982 * to recover from the DL NAC errors or not. 5983 * @hba: per-adapter instance 5984 * 5985 * Returns true if error handling is required, false otherwise 5986 */ 5987 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba) 5988 { 5989 unsigned long flags; 5990 bool err_handling = true; 5991 5992 spin_lock_irqsave(hba->host->host_lock, flags); 5993 /* 5994 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the 5995 * device fatal error and/or DL NAC & REPLAY timeout errors. 5996 */ 5997 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR)) 5998 goto out; 5999 6000 if ((hba->saved_err & DEVICE_FATAL_ERROR) || 6001 ((hba->saved_err & UIC_ERROR) && 6002 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR))) 6003 goto out; 6004 6005 if ((hba->saved_err & UIC_ERROR) && 6006 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) { 6007 int err; 6008 /* 6009 * wait for 50ms to see if we can get any other errors or not. 6010 */ 6011 spin_unlock_irqrestore(hba->host->host_lock, flags); 6012 msleep(50); 6013 spin_lock_irqsave(hba->host->host_lock, flags); 6014 6015 /* 6016 * now check if we have got any other severe errors other than 6017 * DL NAC error? 6018 */ 6019 if ((hba->saved_err & INT_FATAL_ERRORS) || 6020 ((hba->saved_err & UIC_ERROR) && 6021 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR))) 6022 goto out; 6023 6024 /* 6025 * As DL NAC is the only error received so far, send out NOP 6026 * command to confirm if link is still active or not. 6027 * - If we don't get any response then do error recovery. 6028 * - If we get response then clear the DL NAC error bit. 6029 */ 6030 6031 spin_unlock_irqrestore(hba->host->host_lock, flags); 6032 err = ufshcd_verify_dev_init(hba); 6033 spin_lock_irqsave(hba->host->host_lock, flags); 6034 6035 if (err) 6036 goto out; 6037 6038 /* Link seems to be alive hence ignore the DL NAC errors */ 6039 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR) 6040 hba->saved_err &= ~UIC_ERROR; 6041 /* clear NAC error */ 6042 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR; 6043 if (!hba->saved_uic_err) 6044 err_handling = false; 6045 } 6046 out: 6047 spin_unlock_irqrestore(hba->host->host_lock, flags); 6048 return err_handling; 6049 } 6050 6051 /* host lock must be held before calling this func */ 6052 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba) 6053 { 6054 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) || 6055 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)); 6056 } 6057 6058 void ufshcd_schedule_eh_work(struct ufs_hba *hba) 6059 { 6060 lockdep_assert_held(hba->host->host_lock); 6061 6062 /* handle fatal errors only when link is not in error state */ 6063 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) { 6064 if (hba->force_reset || ufshcd_is_link_broken(hba) || 6065 ufshcd_is_saved_err_fatal(hba)) 6066 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL; 6067 else 6068 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL; 6069 queue_work(hba->eh_wq, &hba->eh_work); 6070 } 6071 } 6072 6073 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow) 6074 { 6075 down_write(&hba->clk_scaling_lock); 6076 hba->clk_scaling.is_allowed = allow; 6077 up_write(&hba->clk_scaling_lock); 6078 } 6079 6080 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend) 6081 { 6082 if (suspend) { 6083 if (hba->clk_scaling.is_enabled) 6084 ufshcd_suspend_clkscaling(hba); 6085 ufshcd_clk_scaling_allow(hba, false); 6086 } else { 6087 ufshcd_clk_scaling_allow(hba, true); 6088 if (hba->clk_scaling.is_enabled) 6089 ufshcd_resume_clkscaling(hba); 6090 } 6091 } 6092 6093 static void ufshcd_err_handling_prepare(struct ufs_hba *hba) 6094 { 6095 ufshcd_rpm_get_sync(hba); 6096 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) || 6097 hba->is_sys_suspended) { 6098 enum ufs_pm_op pm_op; 6099 6100 /* 6101 * Don't assume anything of resume, if 6102 * resume fails, irq and clocks can be OFF, and powers 6103 * can be OFF or in LPM. 6104 */ 6105 ufshcd_setup_hba_vreg(hba, true); 6106 ufshcd_enable_irq(hba); 6107 ufshcd_setup_vreg(hba, true); 6108 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq); 6109 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2); 6110 ufshcd_hold(hba, false); 6111 if (!ufshcd_is_clkgating_allowed(hba)) 6112 ufshcd_setup_clocks(hba, true); 6113 ufshcd_release(hba); 6114 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM; 6115 ufshcd_vops_resume(hba, pm_op); 6116 } else { 6117 ufshcd_hold(hba, false); 6118 if (ufshcd_is_clkscaling_supported(hba) && 6119 hba->clk_scaling.is_enabled) 6120 ufshcd_suspend_clkscaling(hba); 6121 ufshcd_clk_scaling_allow(hba, false); 6122 } 6123 ufshcd_scsi_block_requests(hba); 6124 /* Drain ufshcd_queuecommand() */ 6125 synchronize_rcu(); 6126 cancel_work_sync(&hba->eeh_work); 6127 } 6128 6129 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba) 6130 { 6131 ufshcd_scsi_unblock_requests(hba); 6132 ufshcd_release(hba); 6133 if (ufshcd_is_clkscaling_supported(hba)) 6134 ufshcd_clk_scaling_suspend(hba, false); 6135 ufshcd_rpm_put(hba); 6136 } 6137 6138 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba) 6139 { 6140 return (!hba->is_powered || hba->shutting_down || 6141 !hba->ufs_device_wlun || 6142 hba->ufshcd_state == UFSHCD_STATE_ERROR || 6143 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset || 6144 ufshcd_is_link_broken(hba)))); 6145 } 6146 6147 #ifdef CONFIG_PM 6148 static void ufshcd_recover_pm_error(struct ufs_hba *hba) 6149 { 6150 struct Scsi_Host *shost = hba->host; 6151 struct scsi_device *sdev; 6152 struct request_queue *q; 6153 int ret; 6154 6155 hba->is_sys_suspended = false; 6156 /* 6157 * Set RPM status of wlun device to RPM_ACTIVE, 6158 * this also clears its runtime error. 6159 */ 6160 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev); 6161 6162 /* hba device might have a runtime error otherwise */ 6163 if (ret) 6164 ret = pm_runtime_set_active(hba->dev); 6165 /* 6166 * If wlun device had runtime error, we also need to resume those 6167 * consumer scsi devices in case any of them has failed to be 6168 * resumed due to supplier runtime resume failure. This is to unblock 6169 * blk_queue_enter in case there are bios waiting inside it. 6170 */ 6171 if (!ret) { 6172 shost_for_each_device(sdev, shost) { 6173 q = sdev->request_queue; 6174 if (q->dev && (q->rpm_status == RPM_SUSPENDED || 6175 q->rpm_status == RPM_SUSPENDING)) 6176 pm_request_resume(q->dev); 6177 } 6178 } 6179 } 6180 #else 6181 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba) 6182 { 6183 } 6184 #endif 6185 6186 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba) 6187 { 6188 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info; 6189 u32 mode; 6190 6191 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode); 6192 6193 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK)) 6194 return true; 6195 6196 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK)) 6197 return true; 6198 6199 return false; 6200 } 6201 6202 /** 6203 * ufshcd_err_handler - handle UFS errors that require s/w attention 6204 * @work: pointer to work structure 6205 */ 6206 static void ufshcd_err_handler(struct work_struct *work) 6207 { 6208 int retries = MAX_ERR_HANDLER_RETRIES; 6209 struct ufs_hba *hba; 6210 unsigned long flags; 6211 bool needs_restore; 6212 bool needs_reset; 6213 bool err_xfer; 6214 bool err_tm; 6215 int pmc_err; 6216 int tag; 6217 6218 hba = container_of(work, struct ufs_hba, eh_work); 6219 6220 dev_info(hba->dev, 6221 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n", 6222 __func__, ufshcd_state_name[hba->ufshcd_state], 6223 hba->is_powered, hba->shutting_down, hba->saved_err, 6224 hba->saved_uic_err, hba->force_reset, 6225 ufshcd_is_link_broken(hba) ? "; link is broken" : ""); 6226 6227 down(&hba->host_sem); 6228 spin_lock_irqsave(hba->host->host_lock, flags); 6229 if (ufshcd_err_handling_should_stop(hba)) { 6230 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) 6231 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL; 6232 spin_unlock_irqrestore(hba->host->host_lock, flags); 6233 up(&hba->host_sem); 6234 return; 6235 } 6236 ufshcd_set_eh_in_progress(hba); 6237 spin_unlock_irqrestore(hba->host->host_lock, flags); 6238 ufshcd_err_handling_prepare(hba); 6239 /* Complete requests that have door-bell cleared by h/w */ 6240 ufshcd_complete_requests(hba); 6241 spin_lock_irqsave(hba->host->host_lock, flags); 6242 again: 6243 needs_restore = false; 6244 needs_reset = false; 6245 err_xfer = false; 6246 err_tm = false; 6247 6248 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) 6249 hba->ufshcd_state = UFSHCD_STATE_RESET; 6250 /* 6251 * A full reset and restore might have happened after preparation 6252 * is finished, double check whether we should stop. 6253 */ 6254 if (ufshcd_err_handling_should_stop(hba)) 6255 goto skip_err_handling; 6256 6257 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) { 6258 bool ret; 6259 6260 spin_unlock_irqrestore(hba->host->host_lock, flags); 6261 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */ 6262 ret = ufshcd_quirk_dl_nac_errors(hba); 6263 spin_lock_irqsave(hba->host->host_lock, flags); 6264 if (!ret && ufshcd_err_handling_should_stop(hba)) 6265 goto skip_err_handling; 6266 } 6267 6268 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) || 6269 (hba->saved_uic_err && 6270 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) { 6271 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR); 6272 6273 spin_unlock_irqrestore(hba->host->host_lock, flags); 6274 ufshcd_print_host_state(hba); 6275 ufshcd_print_pwr_info(hba); 6276 ufshcd_print_evt_hist(hba); 6277 ufshcd_print_tmrs(hba, hba->outstanding_tasks); 6278 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt); 6279 spin_lock_irqsave(hba->host->host_lock, flags); 6280 } 6281 6282 /* 6283 * if host reset is required then skip clearing the pending 6284 * transfers forcefully because they will get cleared during 6285 * host reset and restore 6286 */ 6287 if (hba->force_reset || ufshcd_is_link_broken(hba) || 6288 ufshcd_is_saved_err_fatal(hba) || 6289 ((hba->saved_err & UIC_ERROR) && 6290 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR | 6291 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) { 6292 needs_reset = true; 6293 goto do_reset; 6294 } 6295 6296 /* 6297 * If LINERESET was caught, UFS might have been put to PWM mode, 6298 * check if power mode restore is needed. 6299 */ 6300 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) { 6301 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR; 6302 if (!hba->saved_uic_err) 6303 hba->saved_err &= ~UIC_ERROR; 6304 spin_unlock_irqrestore(hba->host->host_lock, flags); 6305 if (ufshcd_is_pwr_mode_restore_needed(hba)) 6306 needs_restore = true; 6307 spin_lock_irqsave(hba->host->host_lock, flags); 6308 if (!hba->saved_err && !needs_restore) 6309 goto skip_err_handling; 6310 } 6311 6312 hba->silence_err_logs = true; 6313 /* release lock as clear command might sleep */ 6314 spin_unlock_irqrestore(hba->host->host_lock, flags); 6315 /* Clear pending transfer requests */ 6316 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) { 6317 if (ufshcd_try_to_abort_task(hba, tag)) { 6318 err_xfer = true; 6319 goto lock_skip_pending_xfer_clear; 6320 } 6321 dev_err(hba->dev, "Aborted tag %d / CDB %#02x\n", tag, 6322 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1); 6323 } 6324 6325 /* Clear pending task management requests */ 6326 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) { 6327 if (ufshcd_clear_tm_cmd(hba, tag)) { 6328 err_tm = true; 6329 goto lock_skip_pending_xfer_clear; 6330 } 6331 } 6332 6333 lock_skip_pending_xfer_clear: 6334 /* Complete the requests that are cleared by s/w */ 6335 ufshcd_complete_requests(hba); 6336 6337 spin_lock_irqsave(hba->host->host_lock, flags); 6338 hba->silence_err_logs = false; 6339 if (err_xfer || err_tm) { 6340 needs_reset = true; 6341 goto do_reset; 6342 } 6343 6344 /* 6345 * After all reqs and tasks are cleared from doorbell, 6346 * now it is safe to retore power mode. 6347 */ 6348 if (needs_restore) { 6349 spin_unlock_irqrestore(hba->host->host_lock, flags); 6350 /* 6351 * Hold the scaling lock just in case dev cmds 6352 * are sent via bsg and/or sysfs. 6353 */ 6354 down_write(&hba->clk_scaling_lock); 6355 hba->force_pmc = true; 6356 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info)); 6357 if (pmc_err) { 6358 needs_reset = true; 6359 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n", 6360 __func__, pmc_err); 6361 } 6362 hba->force_pmc = false; 6363 ufshcd_print_pwr_info(hba); 6364 up_write(&hba->clk_scaling_lock); 6365 spin_lock_irqsave(hba->host->host_lock, flags); 6366 } 6367 6368 do_reset: 6369 /* Fatal errors need reset */ 6370 if (needs_reset) { 6371 int err; 6372 6373 hba->force_reset = false; 6374 spin_unlock_irqrestore(hba->host->host_lock, flags); 6375 err = ufshcd_reset_and_restore(hba); 6376 if (err) 6377 dev_err(hba->dev, "%s: reset and restore failed with err %d\n", 6378 __func__, err); 6379 else 6380 ufshcd_recover_pm_error(hba); 6381 spin_lock_irqsave(hba->host->host_lock, flags); 6382 } 6383 6384 skip_err_handling: 6385 if (!needs_reset) { 6386 if (hba->ufshcd_state == UFSHCD_STATE_RESET) 6387 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL; 6388 if (hba->saved_err || hba->saved_uic_err) 6389 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x", 6390 __func__, hba->saved_err, hba->saved_uic_err); 6391 } 6392 /* Exit in an operational state or dead */ 6393 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL && 6394 hba->ufshcd_state != UFSHCD_STATE_ERROR) { 6395 if (--retries) 6396 goto again; 6397 hba->ufshcd_state = UFSHCD_STATE_ERROR; 6398 } 6399 ufshcd_clear_eh_in_progress(hba); 6400 spin_unlock_irqrestore(hba->host->host_lock, flags); 6401 ufshcd_err_handling_unprepare(hba); 6402 up(&hba->host_sem); 6403 6404 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__, 6405 ufshcd_state_name[hba->ufshcd_state]); 6406 } 6407 6408 /** 6409 * ufshcd_update_uic_error - check and set fatal UIC error flags. 6410 * @hba: per-adapter instance 6411 * 6412 * Returns 6413 * IRQ_HANDLED - If interrupt is valid 6414 * IRQ_NONE - If invalid interrupt 6415 */ 6416 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba) 6417 { 6418 u32 reg; 6419 irqreturn_t retval = IRQ_NONE; 6420 6421 /* PHY layer error */ 6422 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER); 6423 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) && 6424 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) { 6425 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg); 6426 /* 6427 * To know whether this error is fatal or not, DB timeout 6428 * must be checked but this error is handled separately. 6429 */ 6430 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK) 6431 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", 6432 __func__); 6433 6434 /* Got a LINERESET indication. */ 6435 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) { 6436 struct uic_command *cmd = NULL; 6437 6438 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR; 6439 if (hba->uic_async_done && hba->active_uic_cmd) 6440 cmd = hba->active_uic_cmd; 6441 /* 6442 * Ignore the LINERESET during power mode change 6443 * operation via DME_SET command. 6444 */ 6445 if (cmd && (cmd->command == UIC_CMD_DME_SET)) 6446 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR; 6447 } 6448 retval |= IRQ_HANDLED; 6449 } 6450 6451 /* PA_INIT_ERROR is fatal and needs UIC reset */ 6452 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER); 6453 if ((reg & UIC_DATA_LINK_LAYER_ERROR) && 6454 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) { 6455 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg); 6456 6457 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT) 6458 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR; 6459 else if (hba->dev_quirks & 6460 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) { 6461 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED) 6462 hba->uic_error |= 6463 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR; 6464 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT) 6465 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR; 6466 } 6467 retval |= IRQ_HANDLED; 6468 } 6469 6470 /* UIC NL/TL/DME errors needs software retry */ 6471 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER); 6472 if ((reg & UIC_NETWORK_LAYER_ERROR) && 6473 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) { 6474 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg); 6475 hba->uic_error |= UFSHCD_UIC_NL_ERROR; 6476 retval |= IRQ_HANDLED; 6477 } 6478 6479 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER); 6480 if ((reg & UIC_TRANSPORT_LAYER_ERROR) && 6481 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) { 6482 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg); 6483 hba->uic_error |= UFSHCD_UIC_TL_ERROR; 6484 retval |= IRQ_HANDLED; 6485 } 6486 6487 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME); 6488 if ((reg & UIC_DME_ERROR) && 6489 (reg & UIC_DME_ERROR_CODE_MASK)) { 6490 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg); 6491 hba->uic_error |= UFSHCD_UIC_DME_ERROR; 6492 retval |= IRQ_HANDLED; 6493 } 6494 6495 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n", 6496 __func__, hba->uic_error); 6497 return retval; 6498 } 6499 6500 /** 6501 * ufshcd_check_errors - Check for errors that need s/w attention 6502 * @hba: per-adapter instance 6503 * @intr_status: interrupt status generated by the controller 6504 * 6505 * Returns 6506 * IRQ_HANDLED - If interrupt is valid 6507 * IRQ_NONE - If invalid interrupt 6508 */ 6509 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status) 6510 { 6511 bool queue_eh_work = false; 6512 irqreturn_t retval = IRQ_NONE; 6513 6514 spin_lock(hba->host->host_lock); 6515 hba->errors |= UFSHCD_ERROR_MASK & intr_status; 6516 6517 if (hba->errors & INT_FATAL_ERRORS) { 6518 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR, 6519 hba->errors); 6520 queue_eh_work = true; 6521 } 6522 6523 if (hba->errors & UIC_ERROR) { 6524 hba->uic_error = 0; 6525 retval = ufshcd_update_uic_error(hba); 6526 if (hba->uic_error) 6527 queue_eh_work = true; 6528 } 6529 6530 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) { 6531 dev_err(hba->dev, 6532 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n", 6533 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ? 6534 "Enter" : "Exit", 6535 hba->errors, ufshcd_get_upmcrs(hba)); 6536 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR, 6537 hba->errors); 6538 ufshcd_set_link_broken(hba); 6539 queue_eh_work = true; 6540 } 6541 6542 if (queue_eh_work) { 6543 /* 6544 * update the transfer error masks to sticky bits, let's do this 6545 * irrespective of current ufshcd_state. 6546 */ 6547 hba->saved_err |= hba->errors; 6548 hba->saved_uic_err |= hba->uic_error; 6549 6550 /* dump controller state before resetting */ 6551 if ((hba->saved_err & 6552 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) || 6553 (hba->saved_uic_err && 6554 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) { 6555 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n", 6556 __func__, hba->saved_err, 6557 hba->saved_uic_err); 6558 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, 6559 "host_regs: "); 6560 ufshcd_print_pwr_info(hba); 6561 } 6562 ufshcd_schedule_eh_work(hba); 6563 retval |= IRQ_HANDLED; 6564 } 6565 /* 6566 * if (!queue_eh_work) - 6567 * Other errors are either non-fatal where host recovers 6568 * itself without s/w intervention or errors that will be 6569 * handled by the SCSI core layer. 6570 */ 6571 hba->errors = 0; 6572 hba->uic_error = 0; 6573 spin_unlock(hba->host->host_lock); 6574 return retval; 6575 } 6576 6577 /** 6578 * ufshcd_tmc_handler - handle task management function completion 6579 * @hba: per adapter instance 6580 * 6581 * Returns 6582 * IRQ_HANDLED - If interrupt is valid 6583 * IRQ_NONE - If invalid interrupt 6584 */ 6585 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba) 6586 { 6587 unsigned long flags, pending, issued; 6588 irqreturn_t ret = IRQ_NONE; 6589 int tag; 6590 6591 spin_lock_irqsave(hba->host->host_lock, flags); 6592 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL); 6593 issued = hba->outstanding_tasks & ~pending; 6594 for_each_set_bit(tag, &issued, hba->nutmrs) { 6595 struct request *req = hba->tmf_rqs[tag]; 6596 struct completion *c = req->end_io_data; 6597 6598 complete(c); 6599 ret = IRQ_HANDLED; 6600 } 6601 spin_unlock_irqrestore(hba->host->host_lock, flags); 6602 6603 return ret; 6604 } 6605 6606 /** 6607 * ufshcd_sl_intr - Interrupt service routine 6608 * @hba: per adapter instance 6609 * @intr_status: contains interrupts generated by the controller 6610 * 6611 * Returns 6612 * IRQ_HANDLED - If interrupt is valid 6613 * IRQ_NONE - If invalid interrupt 6614 */ 6615 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status) 6616 { 6617 irqreturn_t retval = IRQ_NONE; 6618 6619 if (intr_status & UFSHCD_UIC_MASK) 6620 retval |= ufshcd_uic_cmd_compl(hba, intr_status); 6621 6622 if (intr_status & UFSHCD_ERROR_MASK || hba->errors) 6623 retval |= ufshcd_check_errors(hba, intr_status); 6624 6625 if (intr_status & UTP_TASK_REQ_COMPL) 6626 retval |= ufshcd_tmc_handler(hba); 6627 6628 if (intr_status & UTP_TRANSFER_REQ_COMPL) 6629 retval |= ufshcd_transfer_req_compl(hba); 6630 6631 return retval; 6632 } 6633 6634 /** 6635 * ufshcd_intr - Main interrupt service routine 6636 * @irq: irq number 6637 * @__hba: pointer to adapter instance 6638 * 6639 * Returns 6640 * IRQ_HANDLED - If interrupt is valid 6641 * IRQ_NONE - If invalid interrupt 6642 */ 6643 static irqreturn_t ufshcd_intr(int irq, void *__hba) 6644 { 6645 u32 intr_status, enabled_intr_status = 0; 6646 irqreturn_t retval = IRQ_NONE; 6647 struct ufs_hba *hba = __hba; 6648 int retries = hba->nutrs; 6649 6650 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS); 6651 hba->ufs_stats.last_intr_status = intr_status; 6652 hba->ufs_stats.last_intr_ts = local_clock(); 6653 6654 /* 6655 * There could be max of hba->nutrs reqs in flight and in worst case 6656 * if the reqs get finished 1 by 1 after the interrupt status is 6657 * read, make sure we handle them by checking the interrupt status 6658 * again in a loop until we process all of the reqs before returning. 6659 */ 6660 while (intr_status && retries--) { 6661 enabled_intr_status = 6662 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE); 6663 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS); 6664 if (enabled_intr_status) 6665 retval |= ufshcd_sl_intr(hba, enabled_intr_status); 6666 6667 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS); 6668 } 6669 6670 if (enabled_intr_status && retval == IRQ_NONE && 6671 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) || 6672 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) { 6673 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n", 6674 __func__, 6675 intr_status, 6676 hba->ufs_stats.last_intr_status, 6677 enabled_intr_status); 6678 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: "); 6679 } 6680 6681 return retval; 6682 } 6683 6684 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag) 6685 { 6686 int err = 0; 6687 u32 mask = 1 << tag; 6688 unsigned long flags; 6689 6690 if (!test_bit(tag, &hba->outstanding_tasks)) 6691 goto out; 6692 6693 spin_lock_irqsave(hba->host->host_lock, flags); 6694 ufshcd_utmrl_clear(hba, tag); 6695 spin_unlock_irqrestore(hba->host->host_lock, flags); 6696 6697 /* poll for max. 1 sec to clear door bell register by h/w */ 6698 err = ufshcd_wait_for_register(hba, 6699 REG_UTP_TASK_REQ_DOOR_BELL, 6700 mask, 0, 1000, 1000); 6701 6702 dev_err(hba->dev, "Clearing task management function with tag %d %s\n", 6703 tag, err ? "succeeded" : "failed"); 6704 6705 out: 6706 return err; 6707 } 6708 6709 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba, 6710 struct utp_task_req_desc *treq, u8 tm_function) 6711 { 6712 struct request_queue *q = hba->tmf_queue; 6713 struct Scsi_Host *host = hba->host; 6714 DECLARE_COMPLETION_ONSTACK(wait); 6715 struct request *req; 6716 unsigned long flags; 6717 int task_tag, err; 6718 6719 /* 6720 * blk_mq_alloc_request() is used here only to get a free tag. 6721 */ 6722 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0); 6723 if (IS_ERR(req)) 6724 return PTR_ERR(req); 6725 6726 req->end_io_data = &wait; 6727 ufshcd_hold(hba, false); 6728 6729 spin_lock_irqsave(host->host_lock, flags); 6730 6731 task_tag = req->tag; 6732 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n", 6733 task_tag); 6734 hba->tmf_rqs[req->tag] = req; 6735 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag); 6736 6737 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq)); 6738 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function); 6739 6740 /* send command to the controller */ 6741 __set_bit(task_tag, &hba->outstanding_tasks); 6742 6743 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL); 6744 /* Make sure that doorbell is committed immediately */ 6745 wmb(); 6746 6747 spin_unlock_irqrestore(host->host_lock, flags); 6748 6749 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND); 6750 6751 /* wait until the task management command is completed */ 6752 err = wait_for_completion_io_timeout(&wait, 6753 msecs_to_jiffies(TM_CMD_TIMEOUT)); 6754 if (!err) { 6755 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR); 6756 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n", 6757 __func__, tm_function); 6758 if (ufshcd_clear_tm_cmd(hba, task_tag)) 6759 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n", 6760 __func__, task_tag); 6761 err = -ETIMEDOUT; 6762 } else { 6763 err = 0; 6764 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq)); 6765 6766 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP); 6767 } 6768 6769 spin_lock_irqsave(hba->host->host_lock, flags); 6770 hba->tmf_rqs[req->tag] = NULL; 6771 __clear_bit(task_tag, &hba->outstanding_tasks); 6772 spin_unlock_irqrestore(hba->host->host_lock, flags); 6773 6774 ufshcd_release(hba); 6775 blk_mq_free_request(req); 6776 6777 return err; 6778 } 6779 6780 /** 6781 * ufshcd_issue_tm_cmd - issues task management commands to controller 6782 * @hba: per adapter instance 6783 * @lun_id: LUN ID to which TM command is sent 6784 * @task_id: task ID to which the TM command is applicable 6785 * @tm_function: task management function opcode 6786 * @tm_response: task management service response return value 6787 * 6788 * Returns non-zero value on error, zero on success. 6789 */ 6790 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id, 6791 u8 tm_function, u8 *tm_response) 6792 { 6793 struct utp_task_req_desc treq = { { 0 }, }; 6794 enum utp_ocs ocs_value; 6795 int err; 6796 6797 /* Configure task request descriptor */ 6798 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD); 6799 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS); 6800 6801 /* Configure task request UPIU */ 6802 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) | 6803 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24); 6804 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16); 6805 6806 /* 6807 * The host shall provide the same value for LUN field in the basic 6808 * header and for Input Parameter. 6809 */ 6810 treq.upiu_req.input_param1 = cpu_to_be32(lun_id); 6811 treq.upiu_req.input_param2 = cpu_to_be32(task_id); 6812 6813 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function); 6814 if (err == -ETIMEDOUT) 6815 return err; 6816 6817 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS; 6818 if (ocs_value != OCS_SUCCESS) 6819 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", 6820 __func__, ocs_value); 6821 else if (tm_response) 6822 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) & 6823 MASK_TM_SERVICE_RESP; 6824 return err; 6825 } 6826 6827 /** 6828 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests 6829 * @hba: per-adapter instance 6830 * @req_upiu: upiu request 6831 * @rsp_upiu: upiu reply 6832 * @desc_buff: pointer to descriptor buffer, NULL if NA 6833 * @buff_len: descriptor size, 0 if NA 6834 * @cmd_type: specifies the type (NOP, Query...) 6835 * @desc_op: descriptor operation 6836 * 6837 * Those type of requests uses UTP Transfer Request Descriptor - utrd. 6838 * Therefore, it "rides" the device management infrastructure: uses its tag and 6839 * tasks work queues. 6840 * 6841 * Since there is only one available tag for device management commands, 6842 * the caller is expected to hold the hba->dev_cmd.lock mutex. 6843 */ 6844 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba, 6845 struct utp_upiu_req *req_upiu, 6846 struct utp_upiu_req *rsp_upiu, 6847 u8 *desc_buff, int *buff_len, 6848 enum dev_cmd_type cmd_type, 6849 enum query_opcode desc_op) 6850 { 6851 DECLARE_COMPLETION_ONSTACK(wait); 6852 const u32 tag = hba->reserved_slot; 6853 struct ufshcd_lrb *lrbp; 6854 int err = 0; 6855 u8 upiu_flags; 6856 6857 /* Protects use of hba->reserved_slot. */ 6858 lockdep_assert_held(&hba->dev_cmd.lock); 6859 6860 down_read(&hba->clk_scaling_lock); 6861 6862 lrbp = &hba->lrb[tag]; 6863 WARN_ON(lrbp->cmd); 6864 lrbp->cmd = NULL; 6865 lrbp->task_tag = tag; 6866 lrbp->lun = 0; 6867 lrbp->intr_cmd = true; 6868 ufshcd_prepare_lrbp_crypto(NULL, lrbp); 6869 hba->dev_cmd.type = cmd_type; 6870 6871 if (hba->ufs_version <= ufshci_version(1, 1)) 6872 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE; 6873 else 6874 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE; 6875 6876 /* update the task tag in the request upiu */ 6877 req_upiu->header.dword_0 |= cpu_to_be32(tag); 6878 6879 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE); 6880 6881 /* just copy the upiu request as it is */ 6882 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr)); 6883 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) { 6884 /* The Data Segment Area is optional depending upon the query 6885 * function value. for WRITE DESCRIPTOR, the data segment 6886 * follows right after the tsf. 6887 */ 6888 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len); 6889 *buff_len = 0; 6890 } 6891 6892 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp)); 6893 6894 hba->dev_cmd.complete = &wait; 6895 6896 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr); 6897 6898 ufshcd_send_command(hba, tag); 6899 /* 6900 * ignore the returning value here - ufshcd_check_query_response is 6901 * bound to fail since dev_cmd.query and dev_cmd.type were left empty. 6902 * read the response directly ignoring all errors. 6903 */ 6904 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT); 6905 6906 /* just copy the upiu response as it is */ 6907 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu)); 6908 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) { 6909 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu); 6910 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) & 6911 MASK_QUERY_DATA_SEG_LEN; 6912 6913 if (*buff_len >= resp_len) { 6914 memcpy(desc_buff, descp, resp_len); 6915 *buff_len = resp_len; 6916 } else { 6917 dev_warn(hba->dev, 6918 "%s: rsp size %d is bigger than buffer size %d", 6919 __func__, resp_len, *buff_len); 6920 *buff_len = 0; 6921 err = -EINVAL; 6922 } 6923 } 6924 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP, 6925 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr); 6926 6927 up_read(&hba->clk_scaling_lock); 6928 return err; 6929 } 6930 6931 /** 6932 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands 6933 * @hba: per-adapter instance 6934 * @req_upiu: upiu request 6935 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands 6936 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target 6937 * @desc_buff: pointer to descriptor buffer, NULL if NA 6938 * @buff_len: descriptor size, 0 if NA 6939 * @desc_op: descriptor operation 6940 * 6941 * Supports UTP Transfer requests (nop and query), and UTP Task 6942 * Management requests. 6943 * It is up to the caller to fill the upiu conent properly, as it will 6944 * be copied without any further input validations. 6945 */ 6946 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba, 6947 struct utp_upiu_req *req_upiu, 6948 struct utp_upiu_req *rsp_upiu, 6949 int msgcode, 6950 u8 *desc_buff, int *buff_len, 6951 enum query_opcode desc_op) 6952 { 6953 int err; 6954 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY; 6955 struct utp_task_req_desc treq = { { 0 }, }; 6956 enum utp_ocs ocs_value; 6957 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC; 6958 6959 switch (msgcode) { 6960 case UPIU_TRANSACTION_NOP_OUT: 6961 cmd_type = DEV_CMD_TYPE_NOP; 6962 fallthrough; 6963 case UPIU_TRANSACTION_QUERY_REQ: 6964 ufshcd_hold(hba, false); 6965 mutex_lock(&hba->dev_cmd.lock); 6966 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu, 6967 desc_buff, buff_len, 6968 cmd_type, desc_op); 6969 mutex_unlock(&hba->dev_cmd.lock); 6970 ufshcd_release(hba); 6971 6972 break; 6973 case UPIU_TRANSACTION_TASK_REQ: 6974 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD); 6975 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS); 6976 6977 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu)); 6978 6979 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f); 6980 if (err == -ETIMEDOUT) 6981 break; 6982 6983 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS; 6984 if (ocs_value != OCS_SUCCESS) { 6985 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__, 6986 ocs_value); 6987 break; 6988 } 6989 6990 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu)); 6991 6992 break; 6993 default: 6994 err = -EINVAL; 6995 6996 break; 6997 } 6998 6999 return err; 7000 } 7001 7002 /** 7003 * ufshcd_eh_device_reset_handler() - Reset a single logical unit. 7004 * @cmd: SCSI command pointer 7005 * 7006 * Returns SUCCESS/FAILED 7007 */ 7008 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd) 7009 { 7010 unsigned long flags, pending_reqs = 0, not_cleared = 0; 7011 struct Scsi_Host *host; 7012 struct ufs_hba *hba; 7013 u32 pos; 7014 int err; 7015 u8 resp = 0xF, lun; 7016 7017 host = cmd->device->host; 7018 hba = shost_priv(host); 7019 7020 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun); 7021 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp); 7022 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) { 7023 if (!err) 7024 err = resp; 7025 goto out; 7026 } 7027 7028 /* clear the commands that were pending for corresponding LUN */ 7029 spin_lock_irqsave(&hba->outstanding_lock, flags); 7030 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) 7031 if (hba->lrb[pos].lun == lun) 7032 __set_bit(pos, &pending_reqs); 7033 hba->outstanding_reqs &= ~pending_reqs; 7034 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 7035 7036 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) { 7037 spin_lock_irqsave(&hba->outstanding_lock, flags); 7038 not_cleared = pending_reqs & 7039 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 7040 hba->outstanding_reqs |= not_cleared; 7041 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 7042 7043 dev_err(hba->dev, "%s: failed to clear requests %#lx\n", 7044 __func__, not_cleared); 7045 } 7046 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared); 7047 7048 out: 7049 hba->req_abort_count = 0; 7050 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err); 7051 if (!err) { 7052 err = SUCCESS; 7053 } else { 7054 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err); 7055 err = FAILED; 7056 } 7057 return err; 7058 } 7059 7060 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap) 7061 { 7062 struct ufshcd_lrb *lrbp; 7063 int tag; 7064 7065 for_each_set_bit(tag, &bitmap, hba->nutrs) { 7066 lrbp = &hba->lrb[tag]; 7067 lrbp->req_abort_skip = true; 7068 } 7069 } 7070 7071 /** 7072 * ufshcd_try_to_abort_task - abort a specific task 7073 * @hba: Pointer to adapter instance 7074 * @tag: Task tag/index to be aborted 7075 * 7076 * Abort the pending command in device by sending UFS_ABORT_TASK task management 7077 * command, and in host controller by clearing the door-bell register. There can 7078 * be race between controller sending the command to the device while abort is 7079 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is 7080 * really issued and then try to abort it. 7081 * 7082 * Returns zero on success, non-zero on failure 7083 */ 7084 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag) 7085 { 7086 struct ufshcd_lrb *lrbp = &hba->lrb[tag]; 7087 int err = 0; 7088 int poll_cnt; 7089 u8 resp = 0xF; 7090 u32 reg; 7091 7092 for (poll_cnt = 100; poll_cnt; poll_cnt--) { 7093 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag, 7094 UFS_QUERY_TASK, &resp); 7095 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) { 7096 /* cmd pending in the device */ 7097 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n", 7098 __func__, tag); 7099 break; 7100 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) { 7101 /* 7102 * cmd not pending in the device, check if it is 7103 * in transition. 7104 */ 7105 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n", 7106 __func__, tag); 7107 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 7108 if (reg & (1 << tag)) { 7109 /* sleep for max. 200us to stabilize */ 7110 usleep_range(100, 200); 7111 continue; 7112 } 7113 /* command completed already */ 7114 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n", 7115 __func__, tag); 7116 goto out; 7117 } else { 7118 dev_err(hba->dev, 7119 "%s: no response from device. tag = %d, err %d\n", 7120 __func__, tag, err); 7121 if (!err) 7122 err = resp; /* service response error */ 7123 goto out; 7124 } 7125 } 7126 7127 if (!poll_cnt) { 7128 err = -EBUSY; 7129 goto out; 7130 } 7131 7132 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag, 7133 UFS_ABORT_TASK, &resp); 7134 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) { 7135 if (!err) { 7136 err = resp; /* service response error */ 7137 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n", 7138 __func__, tag, err); 7139 } 7140 goto out; 7141 } 7142 7143 err = ufshcd_clear_cmds(hba, 1U << tag); 7144 if (err) 7145 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n", 7146 __func__, tag, err); 7147 7148 out: 7149 return err; 7150 } 7151 7152 /** 7153 * ufshcd_abort - scsi host template eh_abort_handler callback 7154 * @cmd: SCSI command pointer 7155 * 7156 * Returns SUCCESS/FAILED 7157 */ 7158 static int ufshcd_abort(struct scsi_cmnd *cmd) 7159 { 7160 struct Scsi_Host *host = cmd->device->host; 7161 struct ufs_hba *hba = shost_priv(host); 7162 int tag = scsi_cmd_to_rq(cmd)->tag; 7163 struct ufshcd_lrb *lrbp = &hba->lrb[tag]; 7164 unsigned long flags; 7165 int err = FAILED; 7166 bool outstanding; 7167 u32 reg; 7168 7169 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag); 7170 7171 ufshcd_hold(hba, false); 7172 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL); 7173 /* If command is already aborted/completed, return FAILED. */ 7174 if (!(test_bit(tag, &hba->outstanding_reqs))) { 7175 dev_err(hba->dev, 7176 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n", 7177 __func__, tag, hba->outstanding_reqs, reg); 7178 goto release; 7179 } 7180 7181 /* Print Transfer Request of aborted task */ 7182 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag); 7183 7184 /* 7185 * Print detailed info about aborted request. 7186 * As more than one request might get aborted at the same time, 7187 * print full information only for the first aborted request in order 7188 * to reduce repeated printouts. For other aborted requests only print 7189 * basic details. 7190 */ 7191 scsi_print_command(cmd); 7192 if (!hba->req_abort_count) { 7193 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag); 7194 ufshcd_print_evt_hist(hba); 7195 ufshcd_print_host_state(hba); 7196 ufshcd_print_pwr_info(hba); 7197 ufshcd_print_trs(hba, 1 << tag, true); 7198 } else { 7199 ufshcd_print_trs(hba, 1 << tag, false); 7200 } 7201 hba->req_abort_count++; 7202 7203 if (!(reg & (1 << tag))) { 7204 dev_err(hba->dev, 7205 "%s: cmd was completed, but without a notifying intr, tag = %d", 7206 __func__, tag); 7207 __ufshcd_transfer_req_compl(hba, 1UL << tag); 7208 goto release; 7209 } 7210 7211 /* 7212 * Task abort to the device W-LUN is illegal. When this command 7213 * will fail, due to spec violation, scsi err handling next step 7214 * will be to send LU reset which, again, is a spec violation. 7215 * To avoid these unnecessary/illegal steps, first we clean up 7216 * the lrb taken by this cmd and re-set it in outstanding_reqs, 7217 * then queue the eh_work and bail. 7218 */ 7219 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) { 7220 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun); 7221 7222 spin_lock_irqsave(host->host_lock, flags); 7223 hba->force_reset = true; 7224 ufshcd_schedule_eh_work(hba); 7225 spin_unlock_irqrestore(host->host_lock, flags); 7226 goto release; 7227 } 7228 7229 /* Skip task abort in case previous aborts failed and report failure */ 7230 if (lrbp->req_abort_skip) { 7231 dev_err(hba->dev, "%s: skipping abort\n", __func__); 7232 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs); 7233 goto release; 7234 } 7235 7236 err = ufshcd_try_to_abort_task(hba, tag); 7237 if (err) { 7238 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err); 7239 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs); 7240 err = FAILED; 7241 goto release; 7242 } 7243 7244 /* 7245 * Clear the corresponding bit from outstanding_reqs since the command 7246 * has been aborted successfully. 7247 */ 7248 spin_lock_irqsave(&hba->outstanding_lock, flags); 7249 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs); 7250 spin_unlock_irqrestore(&hba->outstanding_lock, flags); 7251 7252 if (outstanding) 7253 ufshcd_release_scsi_cmd(hba, lrbp); 7254 7255 err = SUCCESS; 7256 7257 release: 7258 /* Matches the ufshcd_hold() call at the start of this function. */ 7259 ufshcd_release(hba); 7260 return err; 7261 } 7262 7263 /** 7264 * ufshcd_host_reset_and_restore - reset and restore host controller 7265 * @hba: per-adapter instance 7266 * 7267 * Note that host controller reset may issue DME_RESET to 7268 * local and remote (device) Uni-Pro stack and the attributes 7269 * are reset to default state. 7270 * 7271 * Returns zero on success, non-zero on failure 7272 */ 7273 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba) 7274 { 7275 int err; 7276 7277 /* 7278 * Stop the host controller and complete the requests 7279 * cleared by h/w 7280 */ 7281 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET); 7282 ufshcd_hba_stop(hba); 7283 hba->silence_err_logs = true; 7284 ufshcd_complete_requests(hba); 7285 hba->silence_err_logs = false; 7286 7287 /* scale up clocks to max frequency before full reinitialization */ 7288 ufshcd_scale_clks(hba, true); 7289 7290 err = ufshcd_hba_enable(hba); 7291 7292 /* Establish the link again and restore the device */ 7293 if (!err) 7294 err = ufshcd_probe_hba(hba, false); 7295 7296 if (err) 7297 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err); 7298 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err); 7299 return err; 7300 } 7301 7302 /** 7303 * ufshcd_reset_and_restore - reset and re-initialize host/device 7304 * @hba: per-adapter instance 7305 * 7306 * Reset and recover device, host and re-establish link. This 7307 * is helpful to recover the communication in fatal error conditions. 7308 * 7309 * Returns zero on success, non-zero on failure 7310 */ 7311 static int ufshcd_reset_and_restore(struct ufs_hba *hba) 7312 { 7313 u32 saved_err = 0; 7314 u32 saved_uic_err = 0; 7315 int err = 0; 7316 unsigned long flags; 7317 int retries = MAX_HOST_RESET_RETRIES; 7318 7319 spin_lock_irqsave(hba->host->host_lock, flags); 7320 do { 7321 /* 7322 * This is a fresh start, cache and clear saved error first, 7323 * in case new error generated during reset and restore. 7324 */ 7325 saved_err |= hba->saved_err; 7326 saved_uic_err |= hba->saved_uic_err; 7327 hba->saved_err = 0; 7328 hba->saved_uic_err = 0; 7329 hba->force_reset = false; 7330 hba->ufshcd_state = UFSHCD_STATE_RESET; 7331 spin_unlock_irqrestore(hba->host->host_lock, flags); 7332 7333 /* Reset the attached device */ 7334 ufshcd_device_reset(hba); 7335 7336 err = ufshcd_host_reset_and_restore(hba); 7337 7338 spin_lock_irqsave(hba->host->host_lock, flags); 7339 if (err) 7340 continue; 7341 /* Do not exit unless operational or dead */ 7342 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL && 7343 hba->ufshcd_state != UFSHCD_STATE_ERROR && 7344 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL) 7345 err = -EAGAIN; 7346 } while (err && --retries); 7347 7348 /* 7349 * Inform scsi mid-layer that we did reset and allow to handle 7350 * Unit Attention properly. 7351 */ 7352 scsi_report_bus_reset(hba->host, 0); 7353 if (err) { 7354 hba->ufshcd_state = UFSHCD_STATE_ERROR; 7355 hba->saved_err |= saved_err; 7356 hba->saved_uic_err |= saved_uic_err; 7357 } 7358 spin_unlock_irqrestore(hba->host->host_lock, flags); 7359 7360 return err; 7361 } 7362 7363 /** 7364 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer 7365 * @cmd: SCSI command pointer 7366 * 7367 * Returns SUCCESS/FAILED 7368 */ 7369 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd) 7370 { 7371 int err = SUCCESS; 7372 unsigned long flags; 7373 struct ufs_hba *hba; 7374 7375 hba = shost_priv(cmd->device->host); 7376 7377 spin_lock_irqsave(hba->host->host_lock, flags); 7378 hba->force_reset = true; 7379 ufshcd_schedule_eh_work(hba); 7380 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__); 7381 spin_unlock_irqrestore(hba->host->host_lock, flags); 7382 7383 flush_work(&hba->eh_work); 7384 7385 spin_lock_irqsave(hba->host->host_lock, flags); 7386 if (hba->ufshcd_state == UFSHCD_STATE_ERROR) 7387 err = FAILED; 7388 spin_unlock_irqrestore(hba->host->host_lock, flags); 7389 7390 return err; 7391 } 7392 7393 /** 7394 * ufshcd_get_max_icc_level - calculate the ICC level 7395 * @sup_curr_uA: max. current supported by the regulator 7396 * @start_scan: row at the desc table to start scan from 7397 * @buff: power descriptor buffer 7398 * 7399 * Returns calculated max ICC level for specific regulator 7400 */ 7401 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, 7402 const char *buff) 7403 { 7404 int i; 7405 int curr_uA; 7406 u16 data; 7407 u16 unit; 7408 7409 for (i = start_scan; i >= 0; i--) { 7410 data = get_unaligned_be16(&buff[2 * i]); 7411 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >> 7412 ATTR_ICC_LVL_UNIT_OFFSET; 7413 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK; 7414 switch (unit) { 7415 case UFSHCD_NANO_AMP: 7416 curr_uA = curr_uA / 1000; 7417 break; 7418 case UFSHCD_MILI_AMP: 7419 curr_uA = curr_uA * 1000; 7420 break; 7421 case UFSHCD_AMP: 7422 curr_uA = curr_uA * 1000 * 1000; 7423 break; 7424 case UFSHCD_MICRO_AMP: 7425 default: 7426 break; 7427 } 7428 if (sup_curr_uA >= curr_uA) 7429 break; 7430 } 7431 if (i < 0) { 7432 i = 0; 7433 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i); 7434 } 7435 7436 return (u32)i; 7437 } 7438 7439 /** 7440 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level 7441 * In case regulators are not initialized we'll return 0 7442 * @hba: per-adapter instance 7443 * @desc_buf: power descriptor buffer to extract ICC levels from. 7444 * @len: length of desc_buff 7445 * 7446 * Returns calculated ICC level 7447 */ 7448 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba, 7449 const u8 *desc_buf, int len) 7450 { 7451 u32 icc_level = 0; 7452 7453 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq || 7454 !hba->vreg_info.vccq2) { 7455 /* 7456 * Using dev_dbg to avoid messages during runtime PM to avoid 7457 * never-ending cycles of messages written back to storage by 7458 * user space causing runtime resume, causing more messages and 7459 * so on. 7460 */ 7461 dev_dbg(hba->dev, 7462 "%s: Regulator capability was not set, actvIccLevel=%d", 7463 __func__, icc_level); 7464 goto out; 7465 } 7466 7467 if (hba->vreg_info.vcc->max_uA) 7468 icc_level = ufshcd_get_max_icc_level( 7469 hba->vreg_info.vcc->max_uA, 7470 POWER_DESC_MAX_ACTV_ICC_LVLS - 1, 7471 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]); 7472 7473 if (hba->vreg_info.vccq->max_uA) 7474 icc_level = ufshcd_get_max_icc_level( 7475 hba->vreg_info.vccq->max_uA, 7476 icc_level, 7477 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]); 7478 7479 if (hba->vreg_info.vccq2->max_uA) 7480 icc_level = ufshcd_get_max_icc_level( 7481 hba->vreg_info.vccq2->max_uA, 7482 icc_level, 7483 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]); 7484 out: 7485 return icc_level; 7486 } 7487 7488 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba) 7489 { 7490 int ret; 7491 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER]; 7492 u8 *desc_buf; 7493 u32 icc_level; 7494 7495 desc_buf = kmalloc(buff_len, GFP_KERNEL); 7496 if (!desc_buf) 7497 return; 7498 7499 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0, 7500 desc_buf, buff_len); 7501 if (ret) { 7502 dev_err(hba->dev, 7503 "%s: Failed reading power descriptor.len = %d ret = %d", 7504 __func__, buff_len, ret); 7505 goto out; 7506 } 7507 7508 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf, 7509 buff_len); 7510 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level); 7511 7512 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, 7513 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level); 7514 7515 if (ret) 7516 dev_err(hba->dev, 7517 "%s: Failed configuring bActiveICCLevel = %d ret = %d", 7518 __func__, icc_level, ret); 7519 7520 out: 7521 kfree(desc_buf); 7522 } 7523 7524 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev) 7525 { 7526 scsi_autopm_get_device(sdev); 7527 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev); 7528 if (sdev->rpm_autosuspend) 7529 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev, 7530 RPM_AUTOSUSPEND_DELAY_MS); 7531 scsi_autopm_put_device(sdev); 7532 } 7533 7534 /** 7535 * ufshcd_scsi_add_wlus - Adds required W-LUs 7536 * @hba: per-adapter instance 7537 * 7538 * UFS device specification requires the UFS devices to support 4 well known 7539 * logical units: 7540 * "REPORT_LUNS" (address: 01h) 7541 * "UFS Device" (address: 50h) 7542 * "RPMB" (address: 44h) 7543 * "BOOT" (address: 30h) 7544 * UFS device's power management needs to be controlled by "POWER CONDITION" 7545 * field of SSU (START STOP UNIT) command. But this "power condition" field 7546 * will take effect only when its sent to "UFS device" well known logical unit 7547 * hence we require the scsi_device instance to represent this logical unit in 7548 * order for the UFS host driver to send the SSU command for power management. 7549 * 7550 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory 7551 * Block) LU so user space process can control this LU. User space may also 7552 * want to have access to BOOT LU. 7553 * 7554 * This function adds scsi device instances for each of all well known LUs 7555 * (except "REPORT LUNS" LU). 7556 * 7557 * Returns zero on success (all required W-LUs are added successfully), 7558 * non-zero error value on failure (if failed to add any of the required W-LU). 7559 */ 7560 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba) 7561 { 7562 int ret = 0; 7563 struct scsi_device *sdev_boot, *sdev_rpmb; 7564 7565 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0, 7566 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL); 7567 if (IS_ERR(hba->ufs_device_wlun)) { 7568 ret = PTR_ERR(hba->ufs_device_wlun); 7569 hba->ufs_device_wlun = NULL; 7570 goto out; 7571 } 7572 scsi_device_put(hba->ufs_device_wlun); 7573 7574 sdev_rpmb = __scsi_add_device(hba->host, 0, 0, 7575 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL); 7576 if (IS_ERR(sdev_rpmb)) { 7577 ret = PTR_ERR(sdev_rpmb); 7578 goto remove_ufs_device_wlun; 7579 } 7580 ufshcd_blk_pm_runtime_init(sdev_rpmb); 7581 scsi_device_put(sdev_rpmb); 7582 7583 sdev_boot = __scsi_add_device(hba->host, 0, 0, 7584 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL); 7585 if (IS_ERR(sdev_boot)) { 7586 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__); 7587 } else { 7588 ufshcd_blk_pm_runtime_init(sdev_boot); 7589 scsi_device_put(sdev_boot); 7590 } 7591 goto out; 7592 7593 remove_ufs_device_wlun: 7594 scsi_remove_device(hba->ufs_device_wlun); 7595 out: 7596 return ret; 7597 } 7598 7599 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf) 7600 { 7601 struct ufs_dev_info *dev_info = &hba->dev_info; 7602 u8 lun; 7603 u32 d_lu_wb_buf_alloc; 7604 u32 ext_ufs_feature; 7605 7606 if (!ufshcd_is_wb_allowed(hba)) 7607 return; 7608 7609 /* 7610 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or 7611 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES 7612 * enabled 7613 */ 7614 if (!(dev_info->wspecversion >= 0x310 || 7615 dev_info->wspecversion == 0x220 || 7616 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES))) 7617 goto wb_disabled; 7618 7619 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] < 7620 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4) 7621 goto wb_disabled; 7622 7623 ext_ufs_feature = get_unaligned_be32(desc_buf + 7624 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP); 7625 7626 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP)) 7627 goto wb_disabled; 7628 7629 /* 7630 * WB may be supported but not configured while provisioning. The spec 7631 * says, in dedicated wb buffer mode, a max of 1 lun would have wb 7632 * buffer configured. 7633 */ 7634 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE]; 7635 7636 dev_info->b_presrv_uspc_en = 7637 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN]; 7638 7639 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) { 7640 if (!get_unaligned_be32(desc_buf + 7641 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS)) 7642 goto wb_disabled; 7643 } else { 7644 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) { 7645 d_lu_wb_buf_alloc = 0; 7646 ufshcd_read_unit_desc_param(hba, 7647 lun, 7648 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS, 7649 (u8 *)&d_lu_wb_buf_alloc, 7650 sizeof(d_lu_wb_buf_alloc)); 7651 if (d_lu_wb_buf_alloc) { 7652 dev_info->wb_dedicated_lu = lun; 7653 break; 7654 } 7655 } 7656 7657 if (!d_lu_wb_buf_alloc) 7658 goto wb_disabled; 7659 } 7660 7661 if (!ufshcd_is_wb_buf_lifetime_available(hba)) 7662 goto wb_disabled; 7663 7664 return; 7665 7666 wb_disabled: 7667 hba->caps &= ~UFSHCD_CAP_WB_EN; 7668 } 7669 7670 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf) 7671 { 7672 struct ufs_dev_info *dev_info = &hba->dev_info; 7673 u32 ext_ufs_feature; 7674 u8 mask = 0; 7675 7676 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300) 7677 return; 7678 7679 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP); 7680 7681 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF) 7682 mask |= MASK_EE_TOO_LOW_TEMP; 7683 7684 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF) 7685 mask |= MASK_EE_TOO_HIGH_TEMP; 7686 7687 if (mask) { 7688 ufshcd_enable_ee(hba, mask); 7689 ufs_hwmon_probe(hba, mask); 7690 } 7691 } 7692 7693 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, 7694 const struct ufs_dev_quirk *fixups) 7695 { 7696 const struct ufs_dev_quirk *f; 7697 struct ufs_dev_info *dev_info = &hba->dev_info; 7698 7699 if (!fixups) 7700 return; 7701 7702 for (f = fixups; f->quirk; f++) { 7703 if ((f->wmanufacturerid == dev_info->wmanufacturerid || 7704 f->wmanufacturerid == UFS_ANY_VENDOR) && 7705 ((dev_info->model && 7706 STR_PRFX_EQUAL(f->model, dev_info->model)) || 7707 !strcmp(f->model, UFS_ANY_MODEL))) 7708 hba->dev_quirks |= f->quirk; 7709 } 7710 } 7711 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks); 7712 7713 static void ufs_fixup_device_setup(struct ufs_hba *hba) 7714 { 7715 /* fix by general quirk table */ 7716 ufshcd_fixup_dev_quirks(hba, ufs_fixups); 7717 7718 /* allow vendors to fix quirks */ 7719 ufshcd_vops_fixup_dev_quirks(hba); 7720 } 7721 7722 static int ufs_get_device_desc(struct ufs_hba *hba) 7723 { 7724 int err; 7725 u8 model_index; 7726 u8 b_ufs_feature_sup; 7727 u8 *desc_buf; 7728 struct ufs_dev_info *dev_info = &hba->dev_info; 7729 7730 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL); 7731 if (!desc_buf) { 7732 err = -ENOMEM; 7733 goto out; 7734 } 7735 7736 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf, 7737 hba->desc_size[QUERY_DESC_IDN_DEVICE]); 7738 if (err) { 7739 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n", 7740 __func__, err); 7741 goto out; 7742 } 7743 7744 /* 7745 * getting vendor (manufacturerID) and Bank Index in big endian 7746 * format 7747 */ 7748 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 | 7749 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1]; 7750 7751 /* getting Specification Version in big endian format */ 7752 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 | 7753 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1]; 7754 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT]; 7755 7756 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME]; 7757 7758 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION && 7759 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) { 7760 bool hpb_en = false; 7761 7762 ufshpb_get_dev_info(hba, desc_buf); 7763 7764 if (!ufshpb_is_legacy(hba)) 7765 err = ufshcd_query_flag_retry(hba, 7766 UPIU_QUERY_OPCODE_READ_FLAG, 7767 QUERY_FLAG_IDN_HPB_EN, 0, 7768 &hpb_en); 7769 7770 if (ufshpb_is_legacy(hba) || (!err && hpb_en)) 7771 dev_info->hpb_enabled = true; 7772 } 7773 7774 err = ufshcd_read_string_desc(hba, model_index, 7775 &dev_info->model, SD_ASCII_STD); 7776 if (err < 0) { 7777 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n", 7778 __func__, err); 7779 goto out; 7780 } 7781 7782 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] + 7783 desc_buf[DEVICE_DESC_PARAM_NUM_WLU]; 7784 7785 ufs_fixup_device_setup(hba); 7786 7787 ufshcd_wb_probe(hba, desc_buf); 7788 7789 ufshcd_temp_notif_probe(hba, desc_buf); 7790 7791 /* 7792 * ufshcd_read_string_desc returns size of the string 7793 * reset the error value 7794 */ 7795 err = 0; 7796 7797 out: 7798 kfree(desc_buf); 7799 return err; 7800 } 7801 7802 static void ufs_put_device_desc(struct ufs_hba *hba) 7803 { 7804 struct ufs_dev_info *dev_info = &hba->dev_info; 7805 7806 kfree(dev_info->model); 7807 dev_info->model = NULL; 7808 } 7809 7810 /** 7811 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro 7812 * @hba: per-adapter instance 7813 * 7814 * PA_TActivate parameter can be tuned manually if UniPro version is less than 7815 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's 7816 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce 7817 * the hibern8 exit latency. 7818 * 7819 * Returns zero on success, non-zero error value on failure. 7820 */ 7821 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba) 7822 { 7823 int ret = 0; 7824 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate; 7825 7826 ret = ufshcd_dme_peer_get(hba, 7827 UIC_ARG_MIB_SEL( 7828 RX_MIN_ACTIVATETIME_CAPABILITY, 7829 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)), 7830 &peer_rx_min_activatetime); 7831 if (ret) 7832 goto out; 7833 7834 /* make sure proper unit conversion is applied */ 7835 tuned_pa_tactivate = 7836 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US) 7837 / PA_TACTIVATE_TIME_UNIT_US); 7838 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 7839 tuned_pa_tactivate); 7840 7841 out: 7842 return ret; 7843 } 7844 7845 /** 7846 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro 7847 * @hba: per-adapter instance 7848 * 7849 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than 7850 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's 7851 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY. 7852 * This optimal value can help reduce the hibern8 exit latency. 7853 * 7854 * Returns zero on success, non-zero error value on failure. 7855 */ 7856 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba) 7857 { 7858 int ret = 0; 7859 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0; 7860 u32 max_hibern8_time, tuned_pa_hibern8time; 7861 7862 ret = ufshcd_dme_get(hba, 7863 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY, 7864 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)), 7865 &local_tx_hibern8_time_cap); 7866 if (ret) 7867 goto out; 7868 7869 ret = ufshcd_dme_peer_get(hba, 7870 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY, 7871 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)), 7872 &peer_rx_hibern8_time_cap); 7873 if (ret) 7874 goto out; 7875 7876 max_hibern8_time = max(local_tx_hibern8_time_cap, 7877 peer_rx_hibern8_time_cap); 7878 /* make sure proper unit conversion is applied */ 7879 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US) 7880 / PA_HIBERN8_TIME_UNIT_US); 7881 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME), 7882 tuned_pa_hibern8time); 7883 out: 7884 return ret; 7885 } 7886 7887 /** 7888 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is 7889 * less than device PA_TACTIVATE time. 7890 * @hba: per-adapter instance 7891 * 7892 * Some UFS devices require host PA_TACTIVATE to be lower than device 7893 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk 7894 * for such devices. 7895 * 7896 * Returns zero on success, non-zero error value on failure. 7897 */ 7898 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba) 7899 { 7900 int ret = 0; 7901 u32 granularity, peer_granularity; 7902 u32 pa_tactivate, peer_pa_tactivate; 7903 u32 pa_tactivate_us, peer_pa_tactivate_us; 7904 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100}; 7905 7906 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY), 7907 &granularity); 7908 if (ret) 7909 goto out; 7910 7911 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY), 7912 &peer_granularity); 7913 if (ret) 7914 goto out; 7915 7916 if ((granularity < PA_GRANULARITY_MIN_VAL) || 7917 (granularity > PA_GRANULARITY_MAX_VAL)) { 7918 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d", 7919 __func__, granularity); 7920 return -EINVAL; 7921 } 7922 7923 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) || 7924 (peer_granularity > PA_GRANULARITY_MAX_VAL)) { 7925 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d", 7926 __func__, peer_granularity); 7927 return -EINVAL; 7928 } 7929 7930 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate); 7931 if (ret) 7932 goto out; 7933 7934 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE), 7935 &peer_pa_tactivate); 7936 if (ret) 7937 goto out; 7938 7939 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1]; 7940 peer_pa_tactivate_us = peer_pa_tactivate * 7941 gran_to_us_table[peer_granularity - 1]; 7942 7943 if (pa_tactivate_us >= peer_pa_tactivate_us) { 7944 u32 new_peer_pa_tactivate; 7945 7946 new_peer_pa_tactivate = pa_tactivate_us / 7947 gran_to_us_table[peer_granularity - 1]; 7948 new_peer_pa_tactivate++; 7949 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 7950 new_peer_pa_tactivate); 7951 } 7952 7953 out: 7954 return ret; 7955 } 7956 7957 static void ufshcd_tune_unipro_params(struct ufs_hba *hba) 7958 { 7959 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) { 7960 ufshcd_tune_pa_tactivate(hba); 7961 ufshcd_tune_pa_hibern8time(hba); 7962 } 7963 7964 ufshcd_vops_apply_dev_quirks(hba); 7965 7966 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE) 7967 /* set 1ms timeout for PA_TACTIVATE */ 7968 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10); 7969 7970 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE) 7971 ufshcd_quirk_tune_host_pa_tactivate(hba); 7972 } 7973 7974 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba) 7975 { 7976 hba->ufs_stats.hibern8_exit_cnt = 0; 7977 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0); 7978 hba->req_abort_count = 0; 7979 } 7980 7981 static int ufshcd_device_geo_params_init(struct ufs_hba *hba) 7982 { 7983 int err; 7984 size_t buff_len; 7985 u8 *desc_buf; 7986 7987 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY]; 7988 desc_buf = kmalloc(buff_len, GFP_KERNEL); 7989 if (!desc_buf) { 7990 err = -ENOMEM; 7991 goto out; 7992 } 7993 7994 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0, 7995 desc_buf, buff_len); 7996 if (err) { 7997 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n", 7998 __func__, err); 7999 goto out; 8000 } 8001 8002 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1) 8003 hba->dev_info.max_lu_supported = 32; 8004 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0) 8005 hba->dev_info.max_lu_supported = 8; 8006 8007 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >= 8008 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS) 8009 ufshpb_get_geo_info(hba, desc_buf); 8010 8011 out: 8012 kfree(desc_buf); 8013 return err; 8014 } 8015 8016 struct ufs_ref_clk { 8017 unsigned long freq_hz; 8018 enum ufs_ref_clk_freq val; 8019 }; 8020 8021 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = { 8022 {19200000, REF_CLK_FREQ_19_2_MHZ}, 8023 {26000000, REF_CLK_FREQ_26_MHZ}, 8024 {38400000, REF_CLK_FREQ_38_4_MHZ}, 8025 {52000000, REF_CLK_FREQ_52_MHZ}, 8026 {0, REF_CLK_FREQ_INVAL}, 8027 }; 8028 8029 static enum ufs_ref_clk_freq 8030 ufs_get_bref_clk_from_hz(unsigned long freq) 8031 { 8032 int i; 8033 8034 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++) 8035 if (ufs_ref_clk_freqs[i].freq_hz == freq) 8036 return ufs_ref_clk_freqs[i].val; 8037 8038 return REF_CLK_FREQ_INVAL; 8039 } 8040 8041 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk) 8042 { 8043 unsigned long freq; 8044 8045 freq = clk_get_rate(refclk); 8046 8047 hba->dev_ref_clk_freq = 8048 ufs_get_bref_clk_from_hz(freq); 8049 8050 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL) 8051 dev_err(hba->dev, 8052 "invalid ref_clk setting = %ld\n", freq); 8053 } 8054 8055 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba) 8056 { 8057 int err; 8058 u32 ref_clk; 8059 u32 freq = hba->dev_ref_clk_freq; 8060 8061 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR, 8062 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk); 8063 8064 if (err) { 8065 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n", 8066 err); 8067 goto out; 8068 } 8069 8070 if (ref_clk == freq) 8071 goto out; /* nothing to update */ 8072 8073 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, 8074 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq); 8075 8076 if (err) { 8077 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n", 8078 ufs_ref_clk_freqs[freq].freq_hz); 8079 goto out; 8080 } 8081 8082 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n", 8083 ufs_ref_clk_freqs[freq].freq_hz); 8084 8085 out: 8086 return err; 8087 } 8088 8089 static int ufshcd_device_params_init(struct ufs_hba *hba) 8090 { 8091 bool flag; 8092 int ret, i; 8093 8094 /* Init device descriptor sizes */ 8095 for (i = 0; i < QUERY_DESC_IDN_MAX; i++) 8096 hba->desc_size[i] = QUERY_DESC_MAX_SIZE; 8097 8098 /* Init UFS geometry descriptor related parameters */ 8099 ret = ufshcd_device_geo_params_init(hba); 8100 if (ret) 8101 goto out; 8102 8103 /* Check and apply UFS device quirks */ 8104 ret = ufs_get_device_desc(hba); 8105 if (ret) { 8106 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n", 8107 __func__, ret); 8108 goto out; 8109 } 8110 8111 ufshcd_get_ref_clk_gating_wait(hba); 8112 8113 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG, 8114 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag)) 8115 hba->dev_info.f_power_on_wp_en = flag; 8116 8117 /* Probe maximum power mode co-supported by both UFS host and device */ 8118 if (ufshcd_get_max_pwr_mode(hba)) 8119 dev_err(hba->dev, 8120 "%s: Failed getting max supported power mode\n", 8121 __func__); 8122 out: 8123 return ret; 8124 } 8125 8126 /** 8127 * ufshcd_add_lus - probe and add UFS logical units 8128 * @hba: per-adapter instance 8129 */ 8130 static int ufshcd_add_lus(struct ufs_hba *hba) 8131 { 8132 int ret; 8133 8134 /* Add required well known logical units to scsi mid layer */ 8135 ret = ufshcd_scsi_add_wlus(hba); 8136 if (ret) 8137 goto out; 8138 8139 /* Initialize devfreq after UFS device is detected */ 8140 if (ufshcd_is_clkscaling_supported(hba)) { 8141 memcpy(&hba->clk_scaling.saved_pwr_info.info, 8142 &hba->pwr_info, 8143 sizeof(struct ufs_pa_layer_attr)); 8144 hba->clk_scaling.saved_pwr_info.is_valid = true; 8145 hba->clk_scaling.is_allowed = true; 8146 8147 ret = ufshcd_devfreq_init(hba); 8148 if (ret) 8149 goto out; 8150 8151 hba->clk_scaling.is_enabled = true; 8152 ufshcd_init_clk_scaling_sysfs(hba); 8153 } 8154 8155 ufs_bsg_probe(hba); 8156 ufshpb_init(hba); 8157 scsi_scan_host(hba->host); 8158 pm_runtime_put_sync(hba->dev); 8159 8160 out: 8161 return ret; 8162 } 8163 8164 /** 8165 * ufshcd_probe_hba - probe hba to detect device and initialize it 8166 * @hba: per-adapter instance 8167 * @init_dev_params: whether or not to call ufshcd_device_params_init(). 8168 * 8169 * Execute link-startup and verify device initialization 8170 */ 8171 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params) 8172 { 8173 int ret; 8174 unsigned long flags; 8175 ktime_t start = ktime_get(); 8176 8177 hba->ufshcd_state = UFSHCD_STATE_RESET; 8178 8179 ret = ufshcd_link_startup(hba); 8180 if (ret) 8181 goto out; 8182 8183 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION) 8184 goto out; 8185 8186 /* Debug counters initialization */ 8187 ufshcd_clear_dbg_ufs_stats(hba); 8188 8189 /* UniPro link is active now */ 8190 ufshcd_set_link_active(hba); 8191 8192 /* Verify device initialization by sending NOP OUT UPIU */ 8193 ret = ufshcd_verify_dev_init(hba); 8194 if (ret) 8195 goto out; 8196 8197 /* Initiate UFS initialization, and waiting until completion */ 8198 ret = ufshcd_complete_dev_init(hba); 8199 if (ret) 8200 goto out; 8201 8202 /* 8203 * Initialize UFS device parameters used by driver, these 8204 * parameters are associated with UFS descriptors. 8205 */ 8206 if (init_dev_params) { 8207 ret = ufshcd_device_params_init(hba); 8208 if (ret) 8209 goto out; 8210 } 8211 8212 ufshcd_tune_unipro_params(hba); 8213 8214 /* UFS device is also active now */ 8215 ufshcd_set_ufs_dev_active(hba); 8216 ufshcd_force_reset_auto_bkops(hba); 8217 8218 /* Gear up to HS gear if supported */ 8219 if (hba->max_pwr_info.is_valid) { 8220 /* 8221 * Set the right value to bRefClkFreq before attempting to 8222 * switch to HS gears. 8223 */ 8224 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL) 8225 ufshcd_set_dev_ref_clk(hba); 8226 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info); 8227 if (ret) { 8228 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n", 8229 __func__, ret); 8230 goto out; 8231 } 8232 ufshcd_print_pwr_info(hba); 8233 } 8234 8235 /* 8236 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec) 8237 * and for removable UFS card as well, hence always set the parameter. 8238 * Note: Error handler may issue the device reset hence resetting 8239 * bActiveICCLevel as well so it is always safe to set this here. 8240 */ 8241 ufshcd_set_active_icc_lvl(hba); 8242 8243 /* Enable UFS Write Booster if supported */ 8244 ufshcd_configure_wb(hba); 8245 8246 if (hba->ee_usr_mask) 8247 ufshcd_write_ee_control(hba); 8248 /* Enable Auto-Hibernate if configured */ 8249 ufshcd_auto_hibern8_enable(hba); 8250 8251 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT); 8252 out: 8253 spin_lock_irqsave(hba->host->host_lock, flags); 8254 if (ret) 8255 hba->ufshcd_state = UFSHCD_STATE_ERROR; 8256 else if (hba->ufshcd_state == UFSHCD_STATE_RESET) 8257 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL; 8258 spin_unlock_irqrestore(hba->host->host_lock, flags); 8259 8260 trace_ufshcd_init(dev_name(hba->dev), ret, 8261 ktime_to_us(ktime_sub(ktime_get(), start)), 8262 hba->curr_dev_pwr_mode, hba->uic_link_state); 8263 return ret; 8264 } 8265 8266 /** 8267 * ufshcd_async_scan - asynchronous execution for probing hba 8268 * @data: data pointer to pass to this function 8269 * @cookie: cookie data 8270 */ 8271 static void ufshcd_async_scan(void *data, async_cookie_t cookie) 8272 { 8273 struct ufs_hba *hba = (struct ufs_hba *)data; 8274 int ret; 8275 8276 down(&hba->host_sem); 8277 /* Initialize hba, detect and initialize UFS device */ 8278 ret = ufshcd_probe_hba(hba, true); 8279 up(&hba->host_sem); 8280 if (ret) 8281 goto out; 8282 8283 /* Probe and add UFS logical units */ 8284 ret = ufshcd_add_lus(hba); 8285 out: 8286 /* 8287 * If we failed to initialize the device or the device is not 8288 * present, turn off the power/clocks etc. 8289 */ 8290 if (ret) { 8291 pm_runtime_put_sync(hba->dev); 8292 ufshcd_hba_exit(hba); 8293 } 8294 } 8295 8296 static const struct attribute_group *ufshcd_driver_groups[] = { 8297 &ufs_sysfs_unit_descriptor_group, 8298 &ufs_sysfs_lun_attributes_group, 8299 #ifdef CONFIG_SCSI_UFS_HPB 8300 &ufs_sysfs_hpb_stat_group, 8301 &ufs_sysfs_hpb_param_group, 8302 #endif 8303 NULL, 8304 }; 8305 8306 static struct ufs_hba_variant_params ufs_hba_vps = { 8307 .hba_enable_delay_us = 1000, 8308 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40), 8309 .devfreq_profile.polling_ms = 100, 8310 .devfreq_profile.target = ufshcd_devfreq_target, 8311 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status, 8312 .ondemand_data.upthreshold = 70, 8313 .ondemand_data.downdifferential = 5, 8314 }; 8315 8316 static struct scsi_host_template ufshcd_driver_template = { 8317 .module = THIS_MODULE, 8318 .name = UFSHCD, 8319 .proc_name = UFSHCD, 8320 .map_queues = ufshcd_map_queues, 8321 .queuecommand = ufshcd_queuecommand, 8322 .mq_poll = ufshcd_poll, 8323 .slave_alloc = ufshcd_slave_alloc, 8324 .slave_configure = ufshcd_slave_configure, 8325 .slave_destroy = ufshcd_slave_destroy, 8326 .change_queue_depth = ufshcd_change_queue_depth, 8327 .eh_abort_handler = ufshcd_abort, 8328 .eh_device_reset_handler = ufshcd_eh_device_reset_handler, 8329 .eh_host_reset_handler = ufshcd_eh_host_reset_handler, 8330 .this_id = -1, 8331 .sg_tablesize = SG_ALL, 8332 .cmd_per_lun = UFSHCD_CMD_PER_LUN, 8333 .can_queue = UFSHCD_CAN_QUEUE, 8334 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX, 8335 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */ 8336 .max_host_blocked = 1, 8337 .track_queue_depth = 1, 8338 .sdev_groups = ufshcd_driver_groups, 8339 .dma_boundary = PAGE_SIZE - 1, 8340 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS, 8341 }; 8342 8343 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg, 8344 int ua) 8345 { 8346 int ret; 8347 8348 if (!vreg) 8349 return 0; 8350 8351 /* 8352 * "set_load" operation shall be required on those regulators 8353 * which specifically configured current limitation. Otherwise 8354 * zero max_uA may cause unexpected behavior when regulator is 8355 * enabled or set as high power mode. 8356 */ 8357 if (!vreg->max_uA) 8358 return 0; 8359 8360 ret = regulator_set_load(vreg->reg, ua); 8361 if (ret < 0) { 8362 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n", 8363 __func__, vreg->name, ua, ret); 8364 } 8365 8366 return ret; 8367 } 8368 8369 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba, 8370 struct ufs_vreg *vreg) 8371 { 8372 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA); 8373 } 8374 8375 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba, 8376 struct ufs_vreg *vreg) 8377 { 8378 if (!vreg) 8379 return 0; 8380 8381 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA); 8382 } 8383 8384 static int ufshcd_config_vreg(struct device *dev, 8385 struct ufs_vreg *vreg, bool on) 8386 { 8387 if (regulator_count_voltages(vreg->reg) <= 0) 8388 return 0; 8389 8390 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0); 8391 } 8392 8393 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg) 8394 { 8395 int ret = 0; 8396 8397 if (!vreg || vreg->enabled) 8398 goto out; 8399 8400 ret = ufshcd_config_vreg(dev, vreg, true); 8401 if (!ret) 8402 ret = regulator_enable(vreg->reg); 8403 8404 if (!ret) 8405 vreg->enabled = true; 8406 else 8407 dev_err(dev, "%s: %s enable failed, err=%d\n", 8408 __func__, vreg->name, ret); 8409 out: 8410 return ret; 8411 } 8412 8413 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg) 8414 { 8415 int ret = 0; 8416 8417 if (!vreg || !vreg->enabled || vreg->always_on) 8418 goto out; 8419 8420 ret = regulator_disable(vreg->reg); 8421 8422 if (!ret) { 8423 /* ignore errors on applying disable config */ 8424 ufshcd_config_vreg(dev, vreg, false); 8425 vreg->enabled = false; 8426 } else { 8427 dev_err(dev, "%s: %s disable failed, err=%d\n", 8428 __func__, vreg->name, ret); 8429 } 8430 out: 8431 return ret; 8432 } 8433 8434 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on) 8435 { 8436 int ret = 0; 8437 struct device *dev = hba->dev; 8438 struct ufs_vreg_info *info = &hba->vreg_info; 8439 8440 ret = ufshcd_toggle_vreg(dev, info->vcc, on); 8441 if (ret) 8442 goto out; 8443 8444 ret = ufshcd_toggle_vreg(dev, info->vccq, on); 8445 if (ret) 8446 goto out; 8447 8448 ret = ufshcd_toggle_vreg(dev, info->vccq2, on); 8449 8450 out: 8451 if (ret) { 8452 ufshcd_toggle_vreg(dev, info->vccq2, false); 8453 ufshcd_toggle_vreg(dev, info->vccq, false); 8454 ufshcd_toggle_vreg(dev, info->vcc, false); 8455 } 8456 return ret; 8457 } 8458 8459 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on) 8460 { 8461 struct ufs_vreg_info *info = &hba->vreg_info; 8462 8463 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on); 8464 } 8465 8466 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg) 8467 { 8468 int ret = 0; 8469 8470 if (!vreg) 8471 goto out; 8472 8473 vreg->reg = devm_regulator_get(dev, vreg->name); 8474 if (IS_ERR(vreg->reg)) { 8475 ret = PTR_ERR(vreg->reg); 8476 dev_err(dev, "%s: %s get failed, err=%d\n", 8477 __func__, vreg->name, ret); 8478 } 8479 out: 8480 return ret; 8481 } 8482 EXPORT_SYMBOL_GPL(ufshcd_get_vreg); 8483 8484 static int ufshcd_init_vreg(struct ufs_hba *hba) 8485 { 8486 int ret = 0; 8487 struct device *dev = hba->dev; 8488 struct ufs_vreg_info *info = &hba->vreg_info; 8489 8490 ret = ufshcd_get_vreg(dev, info->vcc); 8491 if (ret) 8492 goto out; 8493 8494 ret = ufshcd_get_vreg(dev, info->vccq); 8495 if (!ret) 8496 ret = ufshcd_get_vreg(dev, info->vccq2); 8497 out: 8498 return ret; 8499 } 8500 8501 static int ufshcd_init_hba_vreg(struct ufs_hba *hba) 8502 { 8503 struct ufs_vreg_info *info = &hba->vreg_info; 8504 8505 return ufshcd_get_vreg(hba->dev, info->vdd_hba); 8506 } 8507 8508 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on) 8509 { 8510 int ret = 0; 8511 struct ufs_clk_info *clki; 8512 struct list_head *head = &hba->clk_list_head; 8513 unsigned long flags; 8514 ktime_t start = ktime_get(); 8515 bool clk_state_changed = false; 8516 8517 if (list_empty(head)) 8518 goto out; 8519 8520 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE); 8521 if (ret) 8522 return ret; 8523 8524 list_for_each_entry(clki, head, list) { 8525 if (!IS_ERR_OR_NULL(clki->clk)) { 8526 /* 8527 * Don't disable clocks which are needed 8528 * to keep the link active. 8529 */ 8530 if (ufshcd_is_link_active(hba) && 8531 clki->keep_link_active) 8532 continue; 8533 8534 clk_state_changed = on ^ clki->enabled; 8535 if (on && !clki->enabled) { 8536 ret = clk_prepare_enable(clki->clk); 8537 if (ret) { 8538 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n", 8539 __func__, clki->name, ret); 8540 goto out; 8541 } 8542 } else if (!on && clki->enabled) { 8543 clk_disable_unprepare(clki->clk); 8544 } 8545 clki->enabled = on; 8546 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__, 8547 clki->name, on ? "en" : "dis"); 8548 } 8549 } 8550 8551 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE); 8552 if (ret) 8553 return ret; 8554 8555 out: 8556 if (ret) { 8557 list_for_each_entry(clki, head, list) { 8558 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled) 8559 clk_disable_unprepare(clki->clk); 8560 } 8561 } else if (!ret && on) { 8562 spin_lock_irqsave(hba->host->host_lock, flags); 8563 hba->clk_gating.state = CLKS_ON; 8564 trace_ufshcd_clk_gating(dev_name(hba->dev), 8565 hba->clk_gating.state); 8566 spin_unlock_irqrestore(hba->host->host_lock, flags); 8567 } 8568 8569 if (clk_state_changed) 8570 trace_ufshcd_profile_clk_gating(dev_name(hba->dev), 8571 (on ? "on" : "off"), 8572 ktime_to_us(ktime_sub(ktime_get(), start)), ret); 8573 return ret; 8574 } 8575 8576 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba) 8577 { 8578 u32 freq; 8579 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq); 8580 8581 if (ret) { 8582 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret); 8583 return REF_CLK_FREQ_INVAL; 8584 } 8585 8586 return ufs_get_bref_clk_from_hz(freq); 8587 } 8588 8589 static int ufshcd_init_clocks(struct ufs_hba *hba) 8590 { 8591 int ret = 0; 8592 struct ufs_clk_info *clki; 8593 struct device *dev = hba->dev; 8594 struct list_head *head = &hba->clk_list_head; 8595 8596 if (list_empty(head)) 8597 goto out; 8598 8599 list_for_each_entry(clki, head, list) { 8600 if (!clki->name) 8601 continue; 8602 8603 clki->clk = devm_clk_get(dev, clki->name); 8604 if (IS_ERR(clki->clk)) { 8605 ret = PTR_ERR(clki->clk); 8606 dev_err(dev, "%s: %s clk get failed, %d\n", 8607 __func__, clki->name, ret); 8608 goto out; 8609 } 8610 8611 /* 8612 * Parse device ref clk freq as per device tree "ref_clk". 8613 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL 8614 * in ufshcd_alloc_host(). 8615 */ 8616 if (!strcmp(clki->name, "ref_clk")) 8617 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk); 8618 8619 if (clki->max_freq) { 8620 ret = clk_set_rate(clki->clk, clki->max_freq); 8621 if (ret) { 8622 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n", 8623 __func__, clki->name, 8624 clki->max_freq, ret); 8625 goto out; 8626 } 8627 clki->curr_freq = clki->max_freq; 8628 } 8629 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__, 8630 clki->name, clk_get_rate(clki->clk)); 8631 } 8632 out: 8633 return ret; 8634 } 8635 8636 static int ufshcd_variant_hba_init(struct ufs_hba *hba) 8637 { 8638 int err = 0; 8639 8640 if (!hba->vops) 8641 goto out; 8642 8643 err = ufshcd_vops_init(hba); 8644 if (err) 8645 dev_err(hba->dev, "%s: variant %s init failed err %d\n", 8646 __func__, ufshcd_get_var_name(hba), err); 8647 out: 8648 return err; 8649 } 8650 8651 static void ufshcd_variant_hba_exit(struct ufs_hba *hba) 8652 { 8653 if (!hba->vops) 8654 return; 8655 8656 ufshcd_vops_exit(hba); 8657 } 8658 8659 static int ufshcd_hba_init(struct ufs_hba *hba) 8660 { 8661 int err; 8662 8663 /* 8664 * Handle host controller power separately from the UFS device power 8665 * rails as it will help controlling the UFS host controller power 8666 * collapse easily which is different than UFS device power collapse. 8667 * Also, enable the host controller power before we go ahead with rest 8668 * of the initialization here. 8669 */ 8670 err = ufshcd_init_hba_vreg(hba); 8671 if (err) 8672 goto out; 8673 8674 err = ufshcd_setup_hba_vreg(hba, true); 8675 if (err) 8676 goto out; 8677 8678 err = ufshcd_init_clocks(hba); 8679 if (err) 8680 goto out_disable_hba_vreg; 8681 8682 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL) 8683 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba); 8684 8685 err = ufshcd_setup_clocks(hba, true); 8686 if (err) 8687 goto out_disable_hba_vreg; 8688 8689 err = ufshcd_init_vreg(hba); 8690 if (err) 8691 goto out_disable_clks; 8692 8693 err = ufshcd_setup_vreg(hba, true); 8694 if (err) 8695 goto out_disable_clks; 8696 8697 err = ufshcd_variant_hba_init(hba); 8698 if (err) 8699 goto out_disable_vreg; 8700 8701 ufs_debugfs_hba_init(hba); 8702 8703 hba->is_powered = true; 8704 goto out; 8705 8706 out_disable_vreg: 8707 ufshcd_setup_vreg(hba, false); 8708 out_disable_clks: 8709 ufshcd_setup_clocks(hba, false); 8710 out_disable_hba_vreg: 8711 ufshcd_setup_hba_vreg(hba, false); 8712 out: 8713 return err; 8714 } 8715 8716 static void ufshcd_hba_exit(struct ufs_hba *hba) 8717 { 8718 if (hba->is_powered) { 8719 ufshcd_exit_clk_scaling(hba); 8720 ufshcd_exit_clk_gating(hba); 8721 if (hba->eh_wq) 8722 destroy_workqueue(hba->eh_wq); 8723 ufs_debugfs_hba_exit(hba); 8724 ufshcd_variant_hba_exit(hba); 8725 ufshcd_setup_vreg(hba, false); 8726 ufshcd_setup_clocks(hba, false); 8727 ufshcd_setup_hba_vreg(hba, false); 8728 hba->is_powered = false; 8729 ufs_put_device_desc(hba); 8730 } 8731 } 8732 8733 /** 8734 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device 8735 * power mode 8736 * @hba: per adapter instance 8737 * @pwr_mode: device power mode to set 8738 * 8739 * Returns 0 if requested power mode is set successfully 8740 * Returns < 0 if failed to set the requested power mode 8741 */ 8742 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba, 8743 enum ufs_dev_pwr_mode pwr_mode) 8744 { 8745 unsigned char cmd[6] = { START_STOP }; 8746 struct scsi_sense_hdr sshdr; 8747 struct scsi_device *sdp; 8748 unsigned long flags; 8749 int ret, retries; 8750 unsigned long deadline; 8751 int32_t remaining; 8752 8753 spin_lock_irqsave(hba->host->host_lock, flags); 8754 sdp = hba->ufs_device_wlun; 8755 if (sdp) { 8756 ret = scsi_device_get(sdp); 8757 if (!ret && !scsi_device_online(sdp)) { 8758 ret = -ENODEV; 8759 scsi_device_put(sdp); 8760 } 8761 } else { 8762 ret = -ENODEV; 8763 } 8764 spin_unlock_irqrestore(hba->host->host_lock, flags); 8765 8766 if (ret) 8767 return ret; 8768 8769 /* 8770 * If scsi commands fail, the scsi mid-layer schedules scsi error- 8771 * handling, which would wait for host to be resumed. Since we know 8772 * we are functional while we are here, skip host resume in error 8773 * handling context. 8774 */ 8775 hba->host->eh_noresume = 1; 8776 8777 cmd[4] = pwr_mode << 4; 8778 8779 /* 8780 * Current function would be generally called from the power management 8781 * callbacks hence set the RQF_PM flag so that it doesn't resume the 8782 * already suspended childs. 8783 */ 8784 deadline = jiffies + 10 * HZ; 8785 for (retries = 3; retries > 0; --retries) { 8786 ret = -ETIMEDOUT; 8787 remaining = deadline - jiffies; 8788 if (remaining <= 0) 8789 break; 8790 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr, 8791 remaining / HZ, 0, 0, RQF_PM, NULL); 8792 if (!scsi_status_is_check_condition(ret) || 8793 !scsi_sense_valid(&sshdr) || 8794 sshdr.sense_key != UNIT_ATTENTION) 8795 break; 8796 } 8797 if (ret) { 8798 sdev_printk(KERN_WARNING, sdp, 8799 "START_STOP failed for power mode: %d, result %x\n", 8800 pwr_mode, ret); 8801 if (ret > 0) { 8802 if (scsi_sense_valid(&sshdr)) 8803 scsi_print_sense_hdr(sdp, NULL, &sshdr); 8804 ret = -EIO; 8805 } 8806 } 8807 8808 if (!ret) 8809 hba->curr_dev_pwr_mode = pwr_mode; 8810 8811 scsi_device_put(sdp); 8812 hba->host->eh_noresume = 0; 8813 return ret; 8814 } 8815 8816 static int ufshcd_link_state_transition(struct ufs_hba *hba, 8817 enum uic_link_state req_link_state, 8818 int check_for_bkops) 8819 { 8820 int ret = 0; 8821 8822 if (req_link_state == hba->uic_link_state) 8823 return 0; 8824 8825 if (req_link_state == UIC_LINK_HIBERN8_STATE) { 8826 ret = ufshcd_uic_hibern8_enter(hba); 8827 if (!ret) { 8828 ufshcd_set_link_hibern8(hba); 8829 } else { 8830 dev_err(hba->dev, "%s: hibern8 enter failed %d\n", 8831 __func__, ret); 8832 goto out; 8833 } 8834 } 8835 /* 8836 * If autobkops is enabled, link can't be turned off because 8837 * turning off the link would also turn off the device, except in the 8838 * case of DeepSleep where the device is expected to remain powered. 8839 */ 8840 else if ((req_link_state == UIC_LINK_OFF_STATE) && 8841 (!check_for_bkops || !hba->auto_bkops_enabled)) { 8842 /* 8843 * Let's make sure that link is in low power mode, we are doing 8844 * this currently by putting the link in Hibern8. Otherway to 8845 * put the link in low power mode is to send the DME end point 8846 * to device and then send the DME reset command to local 8847 * unipro. But putting the link in hibern8 is much faster. 8848 * 8849 * Note also that putting the link in Hibern8 is a requirement 8850 * for entering DeepSleep. 8851 */ 8852 ret = ufshcd_uic_hibern8_enter(hba); 8853 if (ret) { 8854 dev_err(hba->dev, "%s: hibern8 enter failed %d\n", 8855 __func__, ret); 8856 goto out; 8857 } 8858 /* 8859 * Change controller state to "reset state" which 8860 * should also put the link in off/reset state 8861 */ 8862 ufshcd_hba_stop(hba); 8863 /* 8864 * TODO: Check if we need any delay to make sure that 8865 * controller is reset 8866 */ 8867 ufshcd_set_link_off(hba); 8868 } 8869 8870 out: 8871 return ret; 8872 } 8873 8874 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba) 8875 { 8876 bool vcc_off = false; 8877 8878 /* 8879 * It seems some UFS devices may keep drawing more than sleep current 8880 * (atleast for 500us) from UFS rails (especially from VCCQ rail). 8881 * To avoid this situation, add 2ms delay before putting these UFS 8882 * rails in LPM mode. 8883 */ 8884 if (!ufshcd_is_link_active(hba) && 8885 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM) 8886 usleep_range(2000, 2100); 8887 8888 /* 8889 * If UFS device is either in UFS_Sleep turn off VCC rail to save some 8890 * power. 8891 * 8892 * If UFS device and link is in OFF state, all power supplies (VCC, 8893 * VCCQ, VCCQ2) can be turned off if power on write protect is not 8894 * required. If UFS link is inactive (Hibern8 or OFF state) and device 8895 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode. 8896 * 8897 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway 8898 * in low power state which would save some power. 8899 * 8900 * If Write Booster is enabled and the device needs to flush the WB 8901 * buffer OR if bkops status is urgent for WB, keep Vcc on. 8902 */ 8903 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) && 8904 !hba->dev_info.is_lu_power_on_wp) { 8905 ufshcd_setup_vreg(hba, false); 8906 vcc_off = true; 8907 } else if (!ufshcd_is_ufs_dev_active(hba)) { 8908 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false); 8909 vcc_off = true; 8910 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) { 8911 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq); 8912 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2); 8913 } 8914 } 8915 8916 /* 8917 * Some UFS devices require delay after VCC power rail is turned-off. 8918 */ 8919 if (vcc_off && hba->vreg_info.vcc && 8920 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM) 8921 usleep_range(5000, 5100); 8922 } 8923 8924 #ifdef CONFIG_PM 8925 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba) 8926 { 8927 int ret = 0; 8928 8929 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) && 8930 !hba->dev_info.is_lu_power_on_wp) { 8931 ret = ufshcd_setup_vreg(hba, true); 8932 } else if (!ufshcd_is_ufs_dev_active(hba)) { 8933 if (!ufshcd_is_link_active(hba)) { 8934 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq); 8935 if (ret) 8936 goto vcc_disable; 8937 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2); 8938 if (ret) 8939 goto vccq_lpm; 8940 } 8941 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true); 8942 } 8943 goto out; 8944 8945 vccq_lpm: 8946 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq); 8947 vcc_disable: 8948 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false); 8949 out: 8950 return ret; 8951 } 8952 #endif /* CONFIG_PM */ 8953 8954 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba) 8955 { 8956 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba)) 8957 ufshcd_setup_hba_vreg(hba, false); 8958 } 8959 8960 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba) 8961 { 8962 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba)) 8963 ufshcd_setup_hba_vreg(hba, true); 8964 } 8965 8966 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op) 8967 { 8968 int ret = 0; 8969 int check_for_bkops; 8970 enum ufs_pm_level pm_lvl; 8971 enum ufs_dev_pwr_mode req_dev_pwr_mode; 8972 enum uic_link_state req_link_state; 8973 8974 hba->pm_op_in_progress = true; 8975 if (pm_op != UFS_SHUTDOWN_PM) { 8976 pm_lvl = pm_op == UFS_RUNTIME_PM ? 8977 hba->rpm_lvl : hba->spm_lvl; 8978 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl); 8979 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl); 8980 } else { 8981 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE; 8982 req_link_state = UIC_LINK_OFF_STATE; 8983 } 8984 8985 ufshpb_suspend(hba); 8986 8987 /* 8988 * If we can't transition into any of the low power modes 8989 * just gate the clocks. 8990 */ 8991 ufshcd_hold(hba, false); 8992 hba->clk_gating.is_suspended = true; 8993 8994 if (ufshcd_is_clkscaling_supported(hba)) 8995 ufshcd_clk_scaling_suspend(hba, true); 8996 8997 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE && 8998 req_link_state == UIC_LINK_ACTIVE_STATE) { 8999 goto vops_suspend; 9000 } 9001 9002 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) && 9003 (req_link_state == hba->uic_link_state)) 9004 goto enable_scaling; 9005 9006 /* UFS device & link must be active before we enter in this function */ 9007 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) { 9008 ret = -EINVAL; 9009 goto enable_scaling; 9010 } 9011 9012 if (pm_op == UFS_RUNTIME_PM) { 9013 if (ufshcd_can_autobkops_during_suspend(hba)) { 9014 /* 9015 * The device is idle with no requests in the queue, 9016 * allow background operations if bkops status shows 9017 * that performance might be impacted. 9018 */ 9019 ret = ufshcd_urgent_bkops(hba); 9020 if (ret) 9021 goto enable_scaling; 9022 } else { 9023 /* make sure that auto bkops is disabled */ 9024 ufshcd_disable_auto_bkops(hba); 9025 } 9026 /* 9027 * If device needs to do BKOP or WB buffer flush during 9028 * Hibern8, keep device power mode as "active power mode" 9029 * and VCC supply. 9030 */ 9031 hba->dev_info.b_rpm_dev_flush_capable = 9032 hba->auto_bkops_enabled || 9033 (((req_link_state == UIC_LINK_HIBERN8_STATE) || 9034 ((req_link_state == UIC_LINK_ACTIVE_STATE) && 9035 ufshcd_is_auto_hibern8_enabled(hba))) && 9036 ufshcd_wb_need_flush(hba)); 9037 } 9038 9039 flush_work(&hba->eeh_work); 9040 9041 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE); 9042 if (ret) 9043 goto enable_scaling; 9044 9045 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) { 9046 if (pm_op != UFS_RUNTIME_PM) 9047 /* ensure that bkops is disabled */ 9048 ufshcd_disable_auto_bkops(hba); 9049 9050 if (!hba->dev_info.b_rpm_dev_flush_capable) { 9051 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode); 9052 if (ret) 9053 goto enable_scaling; 9054 } 9055 } 9056 9057 /* 9058 * In the case of DeepSleep, the device is expected to remain powered 9059 * with the link off, so do not check for bkops. 9060 */ 9061 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba); 9062 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops); 9063 if (ret) 9064 goto set_dev_active; 9065 9066 vops_suspend: 9067 /* 9068 * Call vendor specific suspend callback. As these callbacks may access 9069 * vendor specific host controller register space call them before the 9070 * host clocks are ON. 9071 */ 9072 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE); 9073 if (ret) 9074 goto set_link_active; 9075 goto out; 9076 9077 set_link_active: 9078 /* 9079 * Device hardware reset is required to exit DeepSleep. Also, for 9080 * DeepSleep, the link is off so host reset and restore will be done 9081 * further below. 9082 */ 9083 if (ufshcd_is_ufs_dev_deepsleep(hba)) { 9084 ufshcd_device_reset(hba); 9085 WARN_ON(!ufshcd_is_link_off(hba)); 9086 } 9087 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba)) 9088 ufshcd_set_link_active(hba); 9089 else if (ufshcd_is_link_off(hba)) 9090 ufshcd_host_reset_and_restore(hba); 9091 set_dev_active: 9092 /* Can also get here needing to exit DeepSleep */ 9093 if (ufshcd_is_ufs_dev_deepsleep(hba)) { 9094 ufshcd_device_reset(hba); 9095 ufshcd_host_reset_and_restore(hba); 9096 } 9097 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE)) 9098 ufshcd_disable_auto_bkops(hba); 9099 enable_scaling: 9100 if (ufshcd_is_clkscaling_supported(hba)) 9101 ufshcd_clk_scaling_suspend(hba, false); 9102 9103 hba->dev_info.b_rpm_dev_flush_capable = false; 9104 out: 9105 if (hba->dev_info.b_rpm_dev_flush_capable) { 9106 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work, 9107 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS)); 9108 } 9109 9110 if (ret) { 9111 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret); 9112 hba->clk_gating.is_suspended = false; 9113 ufshcd_release(hba); 9114 ufshpb_resume(hba); 9115 } 9116 hba->pm_op_in_progress = false; 9117 return ret; 9118 } 9119 9120 #ifdef CONFIG_PM 9121 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op) 9122 { 9123 int ret; 9124 enum uic_link_state old_link_state = hba->uic_link_state; 9125 9126 hba->pm_op_in_progress = true; 9127 9128 /* 9129 * Call vendor specific resume callback. As these callbacks may access 9130 * vendor specific host controller register space call them when the 9131 * host clocks are ON. 9132 */ 9133 ret = ufshcd_vops_resume(hba, pm_op); 9134 if (ret) 9135 goto out; 9136 9137 /* For DeepSleep, the only supported option is to have the link off */ 9138 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba)); 9139 9140 if (ufshcd_is_link_hibern8(hba)) { 9141 ret = ufshcd_uic_hibern8_exit(hba); 9142 if (!ret) { 9143 ufshcd_set_link_active(hba); 9144 } else { 9145 dev_err(hba->dev, "%s: hibern8 exit failed %d\n", 9146 __func__, ret); 9147 goto vendor_suspend; 9148 } 9149 } else if (ufshcd_is_link_off(hba)) { 9150 /* 9151 * A full initialization of the host and the device is 9152 * required since the link was put to off during suspend. 9153 * Note, in the case of DeepSleep, the device will exit 9154 * DeepSleep due to device reset. 9155 */ 9156 ret = ufshcd_reset_and_restore(hba); 9157 /* 9158 * ufshcd_reset_and_restore() should have already 9159 * set the link state as active 9160 */ 9161 if (ret || !ufshcd_is_link_active(hba)) 9162 goto vendor_suspend; 9163 } 9164 9165 if (!ufshcd_is_ufs_dev_active(hba)) { 9166 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE); 9167 if (ret) 9168 goto set_old_link_state; 9169 } 9170 9171 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) 9172 ufshcd_enable_auto_bkops(hba); 9173 else 9174 /* 9175 * If BKOPs operations are urgently needed at this moment then 9176 * keep auto-bkops enabled or else disable it. 9177 */ 9178 ufshcd_urgent_bkops(hba); 9179 9180 if (hba->ee_usr_mask) 9181 ufshcd_write_ee_control(hba); 9182 9183 if (ufshcd_is_clkscaling_supported(hba)) 9184 ufshcd_clk_scaling_suspend(hba, false); 9185 9186 if (hba->dev_info.b_rpm_dev_flush_capable) { 9187 hba->dev_info.b_rpm_dev_flush_capable = false; 9188 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work); 9189 } 9190 9191 /* Enable Auto-Hibernate if configured */ 9192 ufshcd_auto_hibern8_enable(hba); 9193 9194 ufshpb_resume(hba); 9195 goto out; 9196 9197 set_old_link_state: 9198 ufshcd_link_state_transition(hba, old_link_state, 0); 9199 vendor_suspend: 9200 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE); 9201 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE); 9202 out: 9203 if (ret) 9204 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret); 9205 hba->clk_gating.is_suspended = false; 9206 ufshcd_release(hba); 9207 hba->pm_op_in_progress = false; 9208 return ret; 9209 } 9210 9211 static int ufshcd_wl_runtime_suspend(struct device *dev) 9212 { 9213 struct scsi_device *sdev = to_scsi_device(dev); 9214 struct ufs_hba *hba; 9215 int ret; 9216 ktime_t start = ktime_get(); 9217 9218 hba = shost_priv(sdev->host); 9219 9220 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM); 9221 if (ret) 9222 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9223 9224 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret, 9225 ktime_to_us(ktime_sub(ktime_get(), start)), 9226 hba->curr_dev_pwr_mode, hba->uic_link_state); 9227 9228 return ret; 9229 } 9230 9231 static int ufshcd_wl_runtime_resume(struct device *dev) 9232 { 9233 struct scsi_device *sdev = to_scsi_device(dev); 9234 struct ufs_hba *hba; 9235 int ret = 0; 9236 ktime_t start = ktime_get(); 9237 9238 hba = shost_priv(sdev->host); 9239 9240 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM); 9241 if (ret) 9242 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9243 9244 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret, 9245 ktime_to_us(ktime_sub(ktime_get(), start)), 9246 hba->curr_dev_pwr_mode, hba->uic_link_state); 9247 9248 return ret; 9249 } 9250 #endif 9251 9252 #ifdef CONFIG_PM_SLEEP 9253 static int ufshcd_wl_suspend(struct device *dev) 9254 { 9255 struct scsi_device *sdev = to_scsi_device(dev); 9256 struct ufs_hba *hba; 9257 int ret = 0; 9258 ktime_t start = ktime_get(); 9259 9260 hba = shost_priv(sdev->host); 9261 down(&hba->host_sem); 9262 9263 if (pm_runtime_suspended(dev)) 9264 goto out; 9265 9266 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM); 9267 if (ret) { 9268 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9269 up(&hba->host_sem); 9270 } 9271 9272 out: 9273 if (!ret) 9274 hba->is_sys_suspended = true; 9275 trace_ufshcd_wl_suspend(dev_name(dev), ret, 9276 ktime_to_us(ktime_sub(ktime_get(), start)), 9277 hba->curr_dev_pwr_mode, hba->uic_link_state); 9278 9279 return ret; 9280 } 9281 9282 static int ufshcd_wl_resume(struct device *dev) 9283 { 9284 struct scsi_device *sdev = to_scsi_device(dev); 9285 struct ufs_hba *hba; 9286 int ret = 0; 9287 ktime_t start = ktime_get(); 9288 9289 hba = shost_priv(sdev->host); 9290 9291 if (pm_runtime_suspended(dev)) 9292 goto out; 9293 9294 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM); 9295 if (ret) 9296 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret); 9297 out: 9298 trace_ufshcd_wl_resume(dev_name(dev), ret, 9299 ktime_to_us(ktime_sub(ktime_get(), start)), 9300 hba->curr_dev_pwr_mode, hba->uic_link_state); 9301 if (!ret) 9302 hba->is_sys_suspended = false; 9303 up(&hba->host_sem); 9304 return ret; 9305 } 9306 #endif 9307 9308 static void ufshcd_wl_shutdown(struct device *dev) 9309 { 9310 struct scsi_device *sdev = to_scsi_device(dev); 9311 struct ufs_hba *hba; 9312 9313 hba = shost_priv(sdev->host); 9314 9315 down(&hba->host_sem); 9316 hba->shutting_down = true; 9317 up(&hba->host_sem); 9318 9319 /* Turn on everything while shutting down */ 9320 ufshcd_rpm_get_sync(hba); 9321 scsi_device_quiesce(sdev); 9322 shost_for_each_device(sdev, hba->host) { 9323 if (sdev == hba->ufs_device_wlun) 9324 continue; 9325 scsi_device_quiesce(sdev); 9326 } 9327 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM); 9328 } 9329 9330 /** 9331 * ufshcd_suspend - helper function for suspend operations 9332 * @hba: per adapter instance 9333 * 9334 * This function will put disable irqs, turn off clocks 9335 * and set vreg and hba-vreg in lpm mode. 9336 */ 9337 static int ufshcd_suspend(struct ufs_hba *hba) 9338 { 9339 int ret; 9340 9341 if (!hba->is_powered) 9342 return 0; 9343 /* 9344 * Disable the host irq as host controller as there won't be any 9345 * host controller transaction expected till resume. 9346 */ 9347 ufshcd_disable_irq(hba); 9348 ret = ufshcd_setup_clocks(hba, false); 9349 if (ret) { 9350 ufshcd_enable_irq(hba); 9351 return ret; 9352 } 9353 if (ufshcd_is_clkgating_allowed(hba)) { 9354 hba->clk_gating.state = CLKS_OFF; 9355 trace_ufshcd_clk_gating(dev_name(hba->dev), 9356 hba->clk_gating.state); 9357 } 9358 9359 ufshcd_vreg_set_lpm(hba); 9360 /* Put the host controller in low power mode if possible */ 9361 ufshcd_hba_vreg_set_lpm(hba); 9362 return ret; 9363 } 9364 9365 #ifdef CONFIG_PM 9366 /** 9367 * ufshcd_resume - helper function for resume operations 9368 * @hba: per adapter instance 9369 * 9370 * This function basically turns on the regulators, clocks and 9371 * irqs of the hba. 9372 * 9373 * Returns 0 for success and non-zero for failure 9374 */ 9375 static int ufshcd_resume(struct ufs_hba *hba) 9376 { 9377 int ret; 9378 9379 if (!hba->is_powered) 9380 return 0; 9381 9382 ufshcd_hba_vreg_set_hpm(hba); 9383 ret = ufshcd_vreg_set_hpm(hba); 9384 if (ret) 9385 goto out; 9386 9387 /* Make sure clocks are enabled before accessing controller */ 9388 ret = ufshcd_setup_clocks(hba, true); 9389 if (ret) 9390 goto disable_vreg; 9391 9392 /* enable the host irq as host controller would be active soon */ 9393 ufshcd_enable_irq(hba); 9394 goto out; 9395 9396 disable_vreg: 9397 ufshcd_vreg_set_lpm(hba); 9398 out: 9399 if (ret) 9400 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret); 9401 return ret; 9402 } 9403 #endif /* CONFIG_PM */ 9404 9405 #ifdef CONFIG_PM_SLEEP 9406 /** 9407 * ufshcd_system_suspend - system suspend callback 9408 * @dev: Device associated with the UFS controller. 9409 * 9410 * Executed before putting the system into a sleep state in which the contents 9411 * of main memory are preserved. 9412 * 9413 * Returns 0 for success and non-zero for failure 9414 */ 9415 int ufshcd_system_suspend(struct device *dev) 9416 { 9417 struct ufs_hba *hba = dev_get_drvdata(dev); 9418 int ret = 0; 9419 ktime_t start = ktime_get(); 9420 9421 if (pm_runtime_suspended(hba->dev)) 9422 goto out; 9423 9424 ret = ufshcd_suspend(hba); 9425 out: 9426 trace_ufshcd_system_suspend(dev_name(hba->dev), ret, 9427 ktime_to_us(ktime_sub(ktime_get(), start)), 9428 hba->curr_dev_pwr_mode, hba->uic_link_state); 9429 return ret; 9430 } 9431 EXPORT_SYMBOL(ufshcd_system_suspend); 9432 9433 /** 9434 * ufshcd_system_resume - system resume callback 9435 * @dev: Device associated with the UFS controller. 9436 * 9437 * Executed after waking the system up from a sleep state in which the contents 9438 * of main memory were preserved. 9439 * 9440 * Returns 0 for success and non-zero for failure 9441 */ 9442 int ufshcd_system_resume(struct device *dev) 9443 { 9444 struct ufs_hba *hba = dev_get_drvdata(dev); 9445 ktime_t start = ktime_get(); 9446 int ret = 0; 9447 9448 if (pm_runtime_suspended(hba->dev)) 9449 goto out; 9450 9451 ret = ufshcd_resume(hba); 9452 9453 out: 9454 trace_ufshcd_system_resume(dev_name(hba->dev), ret, 9455 ktime_to_us(ktime_sub(ktime_get(), start)), 9456 hba->curr_dev_pwr_mode, hba->uic_link_state); 9457 9458 return ret; 9459 } 9460 EXPORT_SYMBOL(ufshcd_system_resume); 9461 #endif /* CONFIG_PM_SLEEP */ 9462 9463 #ifdef CONFIG_PM 9464 /** 9465 * ufshcd_runtime_suspend - runtime suspend callback 9466 * @dev: Device associated with the UFS controller. 9467 * 9468 * Check the description of ufshcd_suspend() function for more details. 9469 * 9470 * Returns 0 for success and non-zero for failure 9471 */ 9472 int ufshcd_runtime_suspend(struct device *dev) 9473 { 9474 struct ufs_hba *hba = dev_get_drvdata(dev); 9475 int ret; 9476 ktime_t start = ktime_get(); 9477 9478 ret = ufshcd_suspend(hba); 9479 9480 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret, 9481 ktime_to_us(ktime_sub(ktime_get(), start)), 9482 hba->curr_dev_pwr_mode, hba->uic_link_state); 9483 return ret; 9484 } 9485 EXPORT_SYMBOL(ufshcd_runtime_suspend); 9486 9487 /** 9488 * ufshcd_runtime_resume - runtime resume routine 9489 * @dev: Device associated with the UFS controller. 9490 * 9491 * This function basically brings controller 9492 * to active state. Following operations are done in this function: 9493 * 9494 * 1. Turn on all the controller related clocks 9495 * 2. Turn ON VCC rail 9496 */ 9497 int ufshcd_runtime_resume(struct device *dev) 9498 { 9499 struct ufs_hba *hba = dev_get_drvdata(dev); 9500 int ret; 9501 ktime_t start = ktime_get(); 9502 9503 ret = ufshcd_resume(hba); 9504 9505 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret, 9506 ktime_to_us(ktime_sub(ktime_get(), start)), 9507 hba->curr_dev_pwr_mode, hba->uic_link_state); 9508 return ret; 9509 } 9510 EXPORT_SYMBOL(ufshcd_runtime_resume); 9511 #endif /* CONFIG_PM */ 9512 9513 /** 9514 * ufshcd_shutdown - shutdown routine 9515 * @hba: per adapter instance 9516 * 9517 * This function would turn off both UFS device and UFS hba 9518 * regulators. It would also disable clocks. 9519 * 9520 * Returns 0 always to allow force shutdown even in case of errors. 9521 */ 9522 int ufshcd_shutdown(struct ufs_hba *hba) 9523 { 9524 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba)) 9525 ufshcd_suspend(hba); 9526 9527 hba->is_powered = false; 9528 /* allow force shutdown even in case of errors */ 9529 return 0; 9530 } 9531 EXPORT_SYMBOL(ufshcd_shutdown); 9532 9533 /** 9534 * ufshcd_remove - de-allocate SCSI host and host memory space 9535 * data structure memory 9536 * @hba: per adapter instance 9537 */ 9538 void ufshcd_remove(struct ufs_hba *hba) 9539 { 9540 if (hba->ufs_device_wlun) 9541 ufshcd_rpm_get_sync(hba); 9542 ufs_hwmon_remove(hba); 9543 ufs_bsg_remove(hba); 9544 ufshpb_remove(hba); 9545 ufs_sysfs_remove_nodes(hba->dev); 9546 blk_mq_destroy_queue(hba->tmf_queue); 9547 blk_mq_free_tag_set(&hba->tmf_tag_set); 9548 scsi_remove_host(hba->host); 9549 /* disable interrupts */ 9550 ufshcd_disable_intr(hba, hba->intr_mask); 9551 ufshcd_hba_stop(hba); 9552 ufshcd_hba_exit(hba); 9553 } 9554 EXPORT_SYMBOL_GPL(ufshcd_remove); 9555 9556 /** 9557 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA) 9558 * @hba: pointer to Host Bus Adapter (HBA) 9559 */ 9560 void ufshcd_dealloc_host(struct ufs_hba *hba) 9561 { 9562 scsi_host_put(hba->host); 9563 } 9564 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host); 9565 9566 /** 9567 * ufshcd_set_dma_mask - Set dma mask based on the controller 9568 * addressing capability 9569 * @hba: per adapter instance 9570 * 9571 * Returns 0 for success, non-zero for failure 9572 */ 9573 static int ufshcd_set_dma_mask(struct ufs_hba *hba) 9574 { 9575 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) { 9576 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64))) 9577 return 0; 9578 } 9579 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32)); 9580 } 9581 9582 /** 9583 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA) 9584 * @dev: pointer to device handle 9585 * @hba_handle: driver private handle 9586 * Returns 0 on success, non-zero value on failure 9587 */ 9588 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle) 9589 { 9590 struct Scsi_Host *host; 9591 struct ufs_hba *hba; 9592 int err = 0; 9593 9594 if (!dev) { 9595 dev_err(dev, 9596 "Invalid memory reference for dev is NULL\n"); 9597 err = -ENODEV; 9598 goto out_error; 9599 } 9600 9601 host = scsi_host_alloc(&ufshcd_driver_template, 9602 sizeof(struct ufs_hba)); 9603 if (!host) { 9604 dev_err(dev, "scsi_host_alloc failed\n"); 9605 err = -ENOMEM; 9606 goto out_error; 9607 } 9608 host->nr_maps = HCTX_TYPE_POLL + 1; 9609 hba = shost_priv(host); 9610 hba->host = host; 9611 hba->dev = dev; 9612 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL; 9613 hba->nop_out_timeout = NOP_OUT_TIMEOUT; 9614 INIT_LIST_HEAD(&hba->clk_list_head); 9615 spin_lock_init(&hba->outstanding_lock); 9616 9617 *hba_handle = hba; 9618 9619 out_error: 9620 return err; 9621 } 9622 EXPORT_SYMBOL(ufshcd_alloc_host); 9623 9624 /* This function exists because blk_mq_alloc_tag_set() requires this. */ 9625 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx, 9626 const struct blk_mq_queue_data *qd) 9627 { 9628 WARN_ON_ONCE(true); 9629 return BLK_STS_NOTSUPP; 9630 } 9631 9632 static const struct blk_mq_ops ufshcd_tmf_ops = { 9633 .queue_rq = ufshcd_queue_tmf, 9634 }; 9635 9636 /** 9637 * ufshcd_init - Driver initialization routine 9638 * @hba: per-adapter instance 9639 * @mmio_base: base register address 9640 * @irq: Interrupt line of device 9641 * Returns 0 on success, non-zero value on failure 9642 */ 9643 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) 9644 { 9645 int err; 9646 struct Scsi_Host *host = hba->host; 9647 struct device *dev = hba->dev; 9648 char eh_wq_name[sizeof("ufs_eh_wq_00")]; 9649 9650 /* 9651 * dev_set_drvdata() must be called before any callbacks are registered 9652 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon, 9653 * sysfs). 9654 */ 9655 dev_set_drvdata(dev, hba); 9656 9657 if (!mmio_base) { 9658 dev_err(hba->dev, 9659 "Invalid memory reference for mmio_base is NULL\n"); 9660 err = -ENODEV; 9661 goto out_error; 9662 } 9663 9664 hba->mmio_base = mmio_base; 9665 hba->irq = irq; 9666 hba->vps = &ufs_hba_vps; 9667 9668 err = ufshcd_hba_init(hba); 9669 if (err) 9670 goto out_error; 9671 9672 /* Read capabilities registers */ 9673 err = ufshcd_hba_capabilities(hba); 9674 if (err) 9675 goto out_disable; 9676 9677 /* Get UFS version supported by the controller */ 9678 hba->ufs_version = ufshcd_get_ufs_version(hba); 9679 9680 /* Get Interrupt bit mask per version */ 9681 hba->intr_mask = ufshcd_get_intr_mask(hba); 9682 9683 err = ufshcd_set_dma_mask(hba); 9684 if (err) { 9685 dev_err(hba->dev, "set dma mask failed\n"); 9686 goto out_disable; 9687 } 9688 9689 /* Allocate memory for host memory space */ 9690 err = ufshcd_memory_alloc(hba); 9691 if (err) { 9692 dev_err(hba->dev, "Memory allocation failed\n"); 9693 goto out_disable; 9694 } 9695 9696 /* Configure LRB */ 9697 ufshcd_host_memory_configure(hba); 9698 9699 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED; 9700 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED; 9701 host->max_id = UFSHCD_MAX_ID; 9702 host->max_lun = UFS_MAX_LUNS; 9703 host->max_channel = UFSHCD_MAX_CHANNEL; 9704 host->unique_id = host->host_no; 9705 host->max_cmd_len = UFS_CDB_SIZE; 9706 9707 hba->max_pwr_info.is_valid = false; 9708 9709 /* Initialize work queues */ 9710 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d", 9711 hba->host->host_no); 9712 hba->eh_wq = create_singlethread_workqueue(eh_wq_name); 9713 if (!hba->eh_wq) { 9714 dev_err(hba->dev, "%s: failed to create eh workqueue\n", 9715 __func__); 9716 err = -ENOMEM; 9717 goto out_disable; 9718 } 9719 INIT_WORK(&hba->eh_work, ufshcd_err_handler); 9720 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler); 9721 9722 sema_init(&hba->host_sem, 1); 9723 9724 /* Initialize UIC command mutex */ 9725 mutex_init(&hba->uic_cmd_mutex); 9726 9727 /* Initialize mutex for device management commands */ 9728 mutex_init(&hba->dev_cmd.lock); 9729 9730 /* Initialize mutex for exception event control */ 9731 mutex_init(&hba->ee_ctrl_mutex); 9732 9733 init_rwsem(&hba->clk_scaling_lock); 9734 9735 ufshcd_init_clk_gating(hba); 9736 9737 ufshcd_init_clk_scaling(hba); 9738 9739 /* 9740 * In order to avoid any spurious interrupt immediately after 9741 * registering UFS controller interrupt handler, clear any pending UFS 9742 * interrupt status and disable all the UFS interrupts. 9743 */ 9744 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS), 9745 REG_INTERRUPT_STATUS); 9746 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE); 9747 /* 9748 * Make sure that UFS interrupts are disabled and any pending interrupt 9749 * status is cleared before registering UFS interrupt handler. 9750 */ 9751 mb(); 9752 9753 /* IRQ registration */ 9754 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba); 9755 if (err) { 9756 dev_err(hba->dev, "request irq failed\n"); 9757 goto out_disable; 9758 } else { 9759 hba->is_irq_enabled = true; 9760 } 9761 9762 err = scsi_add_host(host, hba->dev); 9763 if (err) { 9764 dev_err(hba->dev, "scsi_add_host failed\n"); 9765 goto out_disable; 9766 } 9767 9768 hba->tmf_tag_set = (struct blk_mq_tag_set) { 9769 .nr_hw_queues = 1, 9770 .queue_depth = hba->nutmrs, 9771 .ops = &ufshcd_tmf_ops, 9772 .flags = BLK_MQ_F_NO_SCHED, 9773 }; 9774 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set); 9775 if (err < 0) 9776 goto out_remove_scsi_host; 9777 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set); 9778 if (IS_ERR(hba->tmf_queue)) { 9779 err = PTR_ERR(hba->tmf_queue); 9780 goto free_tmf_tag_set; 9781 } 9782 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs, 9783 sizeof(*hba->tmf_rqs), GFP_KERNEL); 9784 if (!hba->tmf_rqs) { 9785 err = -ENOMEM; 9786 goto free_tmf_queue; 9787 } 9788 9789 /* Reset the attached device */ 9790 ufshcd_device_reset(hba); 9791 9792 ufshcd_init_crypto(hba); 9793 9794 /* Host controller enable */ 9795 err = ufshcd_hba_enable(hba); 9796 if (err) { 9797 dev_err(hba->dev, "Host controller enable failed\n"); 9798 ufshcd_print_evt_hist(hba); 9799 ufshcd_print_host_state(hba); 9800 goto free_tmf_queue; 9801 } 9802 9803 /* 9804 * Set the default power management level for runtime and system PM. 9805 * Default power saving mode is to keep UFS link in Hibern8 state 9806 * and UFS device in sleep state. 9807 */ 9808 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state( 9809 UFS_SLEEP_PWR_MODE, 9810 UIC_LINK_HIBERN8_STATE); 9811 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state( 9812 UFS_SLEEP_PWR_MODE, 9813 UIC_LINK_HIBERN8_STATE); 9814 9815 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, 9816 ufshcd_rpm_dev_flush_recheck_work); 9817 9818 /* Set the default auto-hiberate idle timer value to 150 ms */ 9819 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) { 9820 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) | 9821 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3); 9822 } 9823 9824 /* Hold auto suspend until async scan completes */ 9825 pm_runtime_get_sync(dev); 9826 atomic_set(&hba->scsi_block_reqs_cnt, 0); 9827 /* 9828 * We are assuming that device wasn't put in sleep/power-down 9829 * state exclusively during the boot stage before kernel. 9830 * This assumption helps avoid doing link startup twice during 9831 * ufshcd_probe_hba(). 9832 */ 9833 ufshcd_set_ufs_dev_active(hba); 9834 9835 async_schedule(ufshcd_async_scan, hba); 9836 ufs_sysfs_add_nodes(hba->dev); 9837 9838 device_enable_async_suspend(dev); 9839 return 0; 9840 9841 free_tmf_queue: 9842 blk_mq_destroy_queue(hba->tmf_queue); 9843 free_tmf_tag_set: 9844 blk_mq_free_tag_set(&hba->tmf_tag_set); 9845 out_remove_scsi_host: 9846 scsi_remove_host(hba->host); 9847 out_disable: 9848 hba->is_irq_enabled = false; 9849 ufshcd_hba_exit(hba); 9850 out_error: 9851 return err; 9852 } 9853 EXPORT_SYMBOL_GPL(ufshcd_init); 9854 9855 void ufshcd_resume_complete(struct device *dev) 9856 { 9857 struct ufs_hba *hba = dev_get_drvdata(dev); 9858 9859 if (hba->complete_put) { 9860 ufshcd_rpm_put(hba); 9861 hba->complete_put = false; 9862 } 9863 } 9864 EXPORT_SYMBOL_GPL(ufshcd_resume_complete); 9865 9866 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba) 9867 { 9868 struct device *dev = &hba->ufs_device_wlun->sdev_gendev; 9869 enum ufs_dev_pwr_mode dev_pwr_mode; 9870 enum uic_link_state link_state; 9871 unsigned long flags; 9872 bool res; 9873 9874 spin_lock_irqsave(&dev->power.lock, flags); 9875 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl); 9876 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl); 9877 res = pm_runtime_suspended(dev) && 9878 hba->curr_dev_pwr_mode == dev_pwr_mode && 9879 hba->uic_link_state == link_state && 9880 !hba->dev_info.b_rpm_dev_flush_capable; 9881 spin_unlock_irqrestore(&dev->power.lock, flags); 9882 9883 return res; 9884 } 9885 9886 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm) 9887 { 9888 struct ufs_hba *hba = dev_get_drvdata(dev); 9889 int ret; 9890 9891 /* 9892 * SCSI assumes that runtime-pm and system-pm for scsi drivers 9893 * are same. And it doesn't wake up the device for system-suspend 9894 * if it's runtime suspended. But ufs doesn't follow that. 9895 * Refer ufshcd_resume_complete() 9896 */ 9897 if (hba->ufs_device_wlun) { 9898 /* Prevent runtime suspend */ 9899 ufshcd_rpm_get_noresume(hba); 9900 /* 9901 * Check if already runtime suspended in same state as system 9902 * suspend would be. 9903 */ 9904 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) { 9905 /* RPM state is not ok for SPM, so runtime resume */ 9906 ret = ufshcd_rpm_resume(hba); 9907 if (ret < 0 && ret != -EACCES) { 9908 ufshcd_rpm_put(hba); 9909 return ret; 9910 } 9911 } 9912 hba->complete_put = true; 9913 } 9914 return 0; 9915 } 9916 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare); 9917 9918 int ufshcd_suspend_prepare(struct device *dev) 9919 { 9920 return __ufshcd_suspend_prepare(dev, true); 9921 } 9922 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare); 9923 9924 #ifdef CONFIG_PM_SLEEP 9925 static int ufshcd_wl_poweroff(struct device *dev) 9926 { 9927 struct scsi_device *sdev = to_scsi_device(dev); 9928 struct ufs_hba *hba = shost_priv(sdev->host); 9929 9930 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM); 9931 return 0; 9932 } 9933 #endif 9934 9935 static int ufshcd_wl_probe(struct device *dev) 9936 { 9937 struct scsi_device *sdev = to_scsi_device(dev); 9938 9939 if (!is_device_wlun(sdev)) 9940 return -ENODEV; 9941 9942 blk_pm_runtime_init(sdev->request_queue, dev); 9943 pm_runtime_set_autosuspend_delay(dev, 0); 9944 pm_runtime_allow(dev); 9945 9946 return 0; 9947 } 9948 9949 static int ufshcd_wl_remove(struct device *dev) 9950 { 9951 pm_runtime_forbid(dev); 9952 return 0; 9953 } 9954 9955 static const struct dev_pm_ops ufshcd_wl_pm_ops = { 9956 #ifdef CONFIG_PM_SLEEP 9957 .suspend = ufshcd_wl_suspend, 9958 .resume = ufshcd_wl_resume, 9959 .freeze = ufshcd_wl_suspend, 9960 .thaw = ufshcd_wl_resume, 9961 .poweroff = ufshcd_wl_poweroff, 9962 .restore = ufshcd_wl_resume, 9963 #endif 9964 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL) 9965 }; 9966 9967 /* 9968 * ufs_dev_wlun_template - describes ufs device wlun 9969 * ufs-device wlun - used to send pm commands 9970 * All luns are consumers of ufs-device wlun. 9971 * 9972 * Currently, no sd driver is present for wluns. 9973 * Hence the no specific pm operations are performed. 9974 * With ufs design, SSU should be sent to ufs-device wlun. 9975 * Hence register a scsi driver for ufs wluns only. 9976 */ 9977 static struct scsi_driver ufs_dev_wlun_template = { 9978 .gendrv = { 9979 .name = "ufs_device_wlun", 9980 .owner = THIS_MODULE, 9981 .probe = ufshcd_wl_probe, 9982 .remove = ufshcd_wl_remove, 9983 .pm = &ufshcd_wl_pm_ops, 9984 .shutdown = ufshcd_wl_shutdown, 9985 }, 9986 }; 9987 9988 static int __init ufshcd_core_init(void) 9989 { 9990 int ret; 9991 9992 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */ 9993 static_assert(sizeof(struct utp_transfer_cmd_desc) == 9994 2 * ALIGNED_UPIU_SIZE + 9995 SG_ALL * sizeof(struct ufshcd_sg_entry)); 9996 9997 ufs_debugfs_init(); 9998 9999 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv); 10000 if (ret) 10001 ufs_debugfs_exit(); 10002 return ret; 10003 } 10004 10005 static void __exit ufshcd_core_exit(void) 10006 { 10007 ufs_debugfs_exit(); 10008 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv); 10009 } 10010 10011 module_init(ufshcd_core_init); 10012 module_exit(ufshcd_core_exit); 10013 10014 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>"); 10015 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>"); 10016 MODULE_DESCRIPTION("Generic UFS host controller driver Core"); 10017 MODULE_LICENSE("GPL"); 10018