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