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