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