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