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