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