1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Copyright (C) 1999 Eric Youngdale 4 * Copyright (C) 2014 Christoph Hellwig 5 * 6 * SCSI queueing library. 7 * Initial versions: Eric Youngdale (eric@andante.org). 8 * Based upon conversations with large numbers 9 * of people at Linux Expo. 10 */ 11 12 #include <linux/bio.h> 13 #include <linux/bitops.h> 14 #include <linux/blkdev.h> 15 #include <linux/completion.h> 16 #include <linux/kernel.h> 17 #include <linux/export.h> 18 #include <linux/init.h> 19 #include <linux/pci.h> 20 #include <linux/delay.h> 21 #include <linux/hardirq.h> 22 #include <linux/scatterlist.h> 23 #include <linux/blk-mq.h> 24 #include <linux/ratelimit.h> 25 #include <asm/unaligned.h> 26 27 #include <scsi/scsi.h> 28 #include <scsi/scsi_cmnd.h> 29 #include <scsi/scsi_dbg.h> 30 #include <scsi/scsi_device.h> 31 #include <scsi/scsi_driver.h> 32 #include <scsi/scsi_eh.h> 33 #include <scsi/scsi_host.h> 34 #include <scsi/scsi_transport.h> /* __scsi_init_queue() */ 35 #include <scsi/scsi_dh.h> 36 37 #include <trace/events/scsi.h> 38 39 #include "scsi_debugfs.h" 40 #include "scsi_priv.h" 41 #include "scsi_logging.h" 42 43 /* 44 * Size of integrity metadata is usually small, 1 inline sg should 45 * cover normal cases. 46 */ 47 #ifdef CONFIG_ARCH_NO_SG_CHAIN 48 #define SCSI_INLINE_PROT_SG_CNT 0 49 #define SCSI_INLINE_SG_CNT 0 50 #else 51 #define SCSI_INLINE_PROT_SG_CNT 1 52 #define SCSI_INLINE_SG_CNT 2 53 #endif 54 55 static struct kmem_cache *scsi_sense_cache; 56 static DEFINE_MUTEX(scsi_sense_cache_mutex); 57 58 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd); 59 60 int scsi_init_sense_cache(struct Scsi_Host *shost) 61 { 62 int ret = 0; 63 64 mutex_lock(&scsi_sense_cache_mutex); 65 if (!scsi_sense_cache) { 66 scsi_sense_cache = 67 kmem_cache_create_usercopy("scsi_sense_cache", 68 SCSI_SENSE_BUFFERSIZE, 0, SLAB_HWCACHE_ALIGN, 69 0, SCSI_SENSE_BUFFERSIZE, NULL); 70 if (!scsi_sense_cache) 71 ret = -ENOMEM; 72 } 73 mutex_unlock(&scsi_sense_cache_mutex); 74 return ret; 75 } 76 77 /* 78 * When to reinvoke queueing after a resource shortage. It's 3 msecs to 79 * not change behaviour from the previous unplug mechanism, experimentation 80 * may prove this needs changing. 81 */ 82 #define SCSI_QUEUE_DELAY 3 83 84 static void 85 scsi_set_blocked(struct scsi_cmnd *cmd, int reason) 86 { 87 struct Scsi_Host *host = cmd->device->host; 88 struct scsi_device *device = cmd->device; 89 struct scsi_target *starget = scsi_target(device); 90 91 /* 92 * Set the appropriate busy bit for the device/host. 93 * 94 * If the host/device isn't busy, assume that something actually 95 * completed, and that we should be able to queue a command now. 96 * 97 * Note that the prior mid-layer assumption that any host could 98 * always queue at least one command is now broken. The mid-layer 99 * will implement a user specifiable stall (see 100 * scsi_host.max_host_blocked and scsi_device.max_device_blocked) 101 * if a command is requeued with no other commands outstanding 102 * either for the device or for the host. 103 */ 104 switch (reason) { 105 case SCSI_MLQUEUE_HOST_BUSY: 106 atomic_set(&host->host_blocked, host->max_host_blocked); 107 break; 108 case SCSI_MLQUEUE_DEVICE_BUSY: 109 case SCSI_MLQUEUE_EH_RETRY: 110 atomic_set(&device->device_blocked, 111 device->max_device_blocked); 112 break; 113 case SCSI_MLQUEUE_TARGET_BUSY: 114 atomic_set(&starget->target_blocked, 115 starget->max_target_blocked); 116 break; 117 } 118 } 119 120 static void scsi_mq_requeue_cmd(struct scsi_cmnd *cmd) 121 { 122 if (cmd->request->rq_flags & RQF_DONTPREP) { 123 cmd->request->rq_flags &= ~RQF_DONTPREP; 124 scsi_mq_uninit_cmd(cmd); 125 } else { 126 WARN_ON_ONCE(true); 127 } 128 blk_mq_requeue_request(cmd->request, true); 129 } 130 131 /** 132 * __scsi_queue_insert - private queue insertion 133 * @cmd: The SCSI command being requeued 134 * @reason: The reason for the requeue 135 * @unbusy: Whether the queue should be unbusied 136 * 137 * This is a private queue insertion. The public interface 138 * scsi_queue_insert() always assumes the queue should be unbusied 139 * because it's always called before the completion. This function is 140 * for a requeue after completion, which should only occur in this 141 * file. 142 */ 143 static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, bool unbusy) 144 { 145 struct scsi_device *device = cmd->device; 146 147 SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd, 148 "Inserting command %p into mlqueue\n", cmd)); 149 150 scsi_set_blocked(cmd, reason); 151 152 /* 153 * Decrement the counters, since these commands are no longer 154 * active on the host/device. 155 */ 156 if (unbusy) 157 scsi_device_unbusy(device, cmd); 158 159 /* 160 * Requeue this command. It will go before all other commands 161 * that are already in the queue. Schedule requeue work under 162 * lock such that the kblockd_schedule_work() call happens 163 * before blk_cleanup_queue() finishes. 164 */ 165 cmd->result = 0; 166 167 blk_mq_requeue_request(cmd->request, true); 168 } 169 170 /** 171 * scsi_queue_insert - Reinsert a command in the queue. 172 * @cmd: command that we are adding to queue. 173 * @reason: why we are inserting command to queue. 174 * 175 * We do this for one of two cases. Either the host is busy and it cannot accept 176 * any more commands for the time being, or the device returned QUEUE_FULL and 177 * can accept no more commands. 178 * 179 * Context: This could be called either from an interrupt context or a normal 180 * process context. 181 */ 182 void scsi_queue_insert(struct scsi_cmnd *cmd, int reason) 183 { 184 __scsi_queue_insert(cmd, reason, true); 185 } 186 187 188 /** 189 * __scsi_execute - insert request and wait for the result 190 * @sdev: scsi device 191 * @cmd: scsi command 192 * @data_direction: data direction 193 * @buffer: data buffer 194 * @bufflen: len of buffer 195 * @sense: optional sense buffer 196 * @sshdr: optional decoded sense header 197 * @timeout: request timeout in seconds 198 * @retries: number of times to retry request 199 * @flags: flags for ->cmd_flags 200 * @rq_flags: flags for ->rq_flags 201 * @resid: optional residual length 202 * 203 * Returns the scsi_cmnd result field if a command was executed, or a negative 204 * Linux error code if we didn't get that far. 205 */ 206 int __scsi_execute(struct scsi_device *sdev, const unsigned char *cmd, 207 int data_direction, void *buffer, unsigned bufflen, 208 unsigned char *sense, struct scsi_sense_hdr *sshdr, 209 int timeout, int retries, u64 flags, req_flags_t rq_flags, 210 int *resid) 211 { 212 struct request *req; 213 struct scsi_request *rq; 214 int ret; 215 216 req = blk_get_request(sdev->request_queue, 217 data_direction == DMA_TO_DEVICE ? 218 REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN, 219 rq_flags & RQF_PM ? BLK_MQ_REQ_PM : 0); 220 if (IS_ERR(req)) 221 return PTR_ERR(req); 222 223 rq = scsi_req(req); 224 225 if (bufflen) { 226 ret = blk_rq_map_kern(sdev->request_queue, req, 227 buffer, bufflen, GFP_NOIO); 228 if (ret) 229 goto out; 230 } 231 rq->cmd_len = COMMAND_SIZE(cmd[0]); 232 memcpy(rq->cmd, cmd, rq->cmd_len); 233 rq->retries = retries; 234 req->timeout = timeout; 235 req->cmd_flags |= flags; 236 req->rq_flags |= rq_flags | RQF_QUIET; 237 238 /* 239 * head injection *required* here otherwise quiesce won't work 240 */ 241 blk_execute_rq(NULL, req, 1); 242 243 /* 244 * Some devices (USB mass-storage in particular) may transfer 245 * garbage data together with a residue indicating that the data 246 * is invalid. Prevent the garbage from being misinterpreted 247 * and prevent security leaks by zeroing out the excess data. 248 */ 249 if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen)) 250 memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len); 251 252 if (resid) 253 *resid = rq->resid_len; 254 if (sense && rq->sense_len) 255 memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE); 256 if (sshdr) 257 scsi_normalize_sense(rq->sense, rq->sense_len, sshdr); 258 ret = rq->result; 259 out: 260 blk_put_request(req); 261 262 return ret; 263 } 264 EXPORT_SYMBOL(__scsi_execute); 265 266 /* 267 * Wake up the error handler if necessary. Avoid as follows that the error 268 * handler is not woken up if host in-flight requests number == 269 * shost->host_failed: use call_rcu() in scsi_eh_scmd_add() in combination 270 * with an RCU read lock in this function to ensure that this function in 271 * its entirety either finishes before scsi_eh_scmd_add() increases the 272 * host_failed counter or that it notices the shost state change made by 273 * scsi_eh_scmd_add(). 274 */ 275 static void scsi_dec_host_busy(struct Scsi_Host *shost, struct scsi_cmnd *cmd) 276 { 277 unsigned long flags; 278 279 rcu_read_lock(); 280 __clear_bit(SCMD_STATE_INFLIGHT, &cmd->state); 281 if (unlikely(scsi_host_in_recovery(shost))) { 282 spin_lock_irqsave(shost->host_lock, flags); 283 if (shost->host_failed || shost->host_eh_scheduled) 284 scsi_eh_wakeup(shost); 285 spin_unlock_irqrestore(shost->host_lock, flags); 286 } 287 rcu_read_unlock(); 288 } 289 290 void scsi_device_unbusy(struct scsi_device *sdev, struct scsi_cmnd *cmd) 291 { 292 struct Scsi_Host *shost = sdev->host; 293 struct scsi_target *starget = scsi_target(sdev); 294 295 scsi_dec_host_busy(shost, cmd); 296 297 if (starget->can_queue > 0) 298 atomic_dec(&starget->target_busy); 299 300 sbitmap_put(&sdev->budget_map, cmd->budget_token); 301 cmd->budget_token = -1; 302 } 303 304 static void scsi_kick_queue(struct request_queue *q) 305 { 306 blk_mq_run_hw_queues(q, false); 307 } 308 309 /* 310 * Called for single_lun devices on IO completion. Clear starget_sdev_user, 311 * and call blk_run_queue for all the scsi_devices on the target - 312 * including current_sdev first. 313 * 314 * Called with *no* scsi locks held. 315 */ 316 static void scsi_single_lun_run(struct scsi_device *current_sdev) 317 { 318 struct Scsi_Host *shost = current_sdev->host; 319 struct scsi_device *sdev, *tmp; 320 struct scsi_target *starget = scsi_target(current_sdev); 321 unsigned long flags; 322 323 spin_lock_irqsave(shost->host_lock, flags); 324 starget->starget_sdev_user = NULL; 325 spin_unlock_irqrestore(shost->host_lock, flags); 326 327 /* 328 * Call blk_run_queue for all LUNs on the target, starting with 329 * current_sdev. We race with others (to set starget_sdev_user), 330 * but in most cases, we will be first. Ideally, each LU on the 331 * target would get some limited time or requests on the target. 332 */ 333 scsi_kick_queue(current_sdev->request_queue); 334 335 spin_lock_irqsave(shost->host_lock, flags); 336 if (starget->starget_sdev_user) 337 goto out; 338 list_for_each_entry_safe(sdev, tmp, &starget->devices, 339 same_target_siblings) { 340 if (sdev == current_sdev) 341 continue; 342 if (scsi_device_get(sdev)) 343 continue; 344 345 spin_unlock_irqrestore(shost->host_lock, flags); 346 scsi_kick_queue(sdev->request_queue); 347 spin_lock_irqsave(shost->host_lock, flags); 348 349 scsi_device_put(sdev); 350 } 351 out: 352 spin_unlock_irqrestore(shost->host_lock, flags); 353 } 354 355 static inline bool scsi_device_is_busy(struct scsi_device *sdev) 356 { 357 if (scsi_device_busy(sdev) >= sdev->queue_depth) 358 return true; 359 if (atomic_read(&sdev->device_blocked) > 0) 360 return true; 361 return false; 362 } 363 364 static inline bool scsi_target_is_busy(struct scsi_target *starget) 365 { 366 if (starget->can_queue > 0) { 367 if (atomic_read(&starget->target_busy) >= starget->can_queue) 368 return true; 369 if (atomic_read(&starget->target_blocked) > 0) 370 return true; 371 } 372 return false; 373 } 374 375 static inline bool scsi_host_is_busy(struct Scsi_Host *shost) 376 { 377 if (atomic_read(&shost->host_blocked) > 0) 378 return true; 379 if (shost->host_self_blocked) 380 return true; 381 return false; 382 } 383 384 static void scsi_starved_list_run(struct Scsi_Host *shost) 385 { 386 LIST_HEAD(starved_list); 387 struct scsi_device *sdev; 388 unsigned long flags; 389 390 spin_lock_irqsave(shost->host_lock, flags); 391 list_splice_init(&shost->starved_list, &starved_list); 392 393 while (!list_empty(&starved_list)) { 394 struct request_queue *slq; 395 396 /* 397 * As long as shost is accepting commands and we have 398 * starved queues, call blk_run_queue. scsi_request_fn 399 * drops the queue_lock and can add us back to the 400 * starved_list. 401 * 402 * host_lock protects the starved_list and starved_entry. 403 * scsi_request_fn must get the host_lock before checking 404 * or modifying starved_list or starved_entry. 405 */ 406 if (scsi_host_is_busy(shost)) 407 break; 408 409 sdev = list_entry(starved_list.next, 410 struct scsi_device, starved_entry); 411 list_del_init(&sdev->starved_entry); 412 if (scsi_target_is_busy(scsi_target(sdev))) { 413 list_move_tail(&sdev->starved_entry, 414 &shost->starved_list); 415 continue; 416 } 417 418 /* 419 * Once we drop the host lock, a racing scsi_remove_device() 420 * call may remove the sdev from the starved list and destroy 421 * it and the queue. Mitigate by taking a reference to the 422 * queue and never touching the sdev again after we drop the 423 * host lock. Note: if __scsi_remove_device() invokes 424 * blk_cleanup_queue() before the queue is run from this 425 * function then blk_run_queue() will return immediately since 426 * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING. 427 */ 428 slq = sdev->request_queue; 429 if (!blk_get_queue(slq)) 430 continue; 431 spin_unlock_irqrestore(shost->host_lock, flags); 432 433 scsi_kick_queue(slq); 434 blk_put_queue(slq); 435 436 spin_lock_irqsave(shost->host_lock, flags); 437 } 438 /* put any unprocessed entries back */ 439 list_splice(&starved_list, &shost->starved_list); 440 spin_unlock_irqrestore(shost->host_lock, flags); 441 } 442 443 /** 444 * scsi_run_queue - Select a proper request queue to serve next. 445 * @q: last request's queue 446 * 447 * The previous command was completely finished, start a new one if possible. 448 */ 449 static void scsi_run_queue(struct request_queue *q) 450 { 451 struct scsi_device *sdev = q->queuedata; 452 453 if (scsi_target(sdev)->single_lun) 454 scsi_single_lun_run(sdev); 455 if (!list_empty(&sdev->host->starved_list)) 456 scsi_starved_list_run(sdev->host); 457 458 blk_mq_run_hw_queues(q, false); 459 } 460 461 void scsi_requeue_run_queue(struct work_struct *work) 462 { 463 struct scsi_device *sdev; 464 struct request_queue *q; 465 466 sdev = container_of(work, struct scsi_device, requeue_work); 467 q = sdev->request_queue; 468 scsi_run_queue(q); 469 } 470 471 void scsi_run_host_queues(struct Scsi_Host *shost) 472 { 473 struct scsi_device *sdev; 474 475 shost_for_each_device(sdev, shost) 476 scsi_run_queue(sdev->request_queue); 477 } 478 479 static void scsi_uninit_cmd(struct scsi_cmnd *cmd) 480 { 481 if (!blk_rq_is_passthrough(cmd->request)) { 482 struct scsi_driver *drv = scsi_cmd_to_driver(cmd); 483 484 if (drv->uninit_command) 485 drv->uninit_command(cmd); 486 } 487 } 488 489 void scsi_free_sgtables(struct scsi_cmnd *cmd) 490 { 491 if (cmd->sdb.table.nents) 492 sg_free_table_chained(&cmd->sdb.table, 493 SCSI_INLINE_SG_CNT); 494 if (scsi_prot_sg_count(cmd)) 495 sg_free_table_chained(&cmd->prot_sdb->table, 496 SCSI_INLINE_PROT_SG_CNT); 497 } 498 EXPORT_SYMBOL_GPL(scsi_free_sgtables); 499 500 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd) 501 { 502 scsi_free_sgtables(cmd); 503 scsi_uninit_cmd(cmd); 504 } 505 506 static void scsi_run_queue_async(struct scsi_device *sdev) 507 { 508 if (scsi_target(sdev)->single_lun || 509 !list_empty(&sdev->host->starved_list)) { 510 kblockd_schedule_work(&sdev->requeue_work); 511 } else { 512 /* 513 * smp_mb() present in sbitmap_queue_clear() or implied in 514 * .end_io is for ordering writing .device_busy in 515 * scsi_device_unbusy() and reading sdev->restarts. 516 */ 517 int old = atomic_read(&sdev->restarts); 518 519 /* 520 * ->restarts has to be kept as non-zero if new budget 521 * contention occurs. 522 * 523 * No need to run queue when either another re-run 524 * queue wins in updating ->restarts or a new budget 525 * contention occurs. 526 */ 527 if (old && atomic_cmpxchg(&sdev->restarts, old, 0) == old) 528 blk_mq_run_hw_queues(sdev->request_queue, true); 529 } 530 } 531 532 /* Returns false when no more bytes to process, true if there are more */ 533 static bool scsi_end_request(struct request *req, blk_status_t error, 534 unsigned int bytes) 535 { 536 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req); 537 struct scsi_device *sdev = cmd->device; 538 struct request_queue *q = sdev->request_queue; 539 540 if (blk_update_request(req, error, bytes)) 541 return true; 542 543 if (blk_queue_add_random(q)) 544 add_disk_randomness(req->rq_disk); 545 546 if (!blk_rq_is_scsi(req)) { 547 WARN_ON_ONCE(!(cmd->flags & SCMD_INITIALIZED)); 548 cmd->flags &= ~SCMD_INITIALIZED; 549 } 550 551 /* 552 * Calling rcu_barrier() is not necessary here because the 553 * SCSI error handler guarantees that the function called by 554 * call_rcu() has been called before scsi_end_request() is 555 * called. 556 */ 557 destroy_rcu_head(&cmd->rcu); 558 559 /* 560 * In the MQ case the command gets freed by __blk_mq_end_request, 561 * so we have to do all cleanup that depends on it earlier. 562 * 563 * We also can't kick the queues from irq context, so we 564 * will have to defer it to a workqueue. 565 */ 566 scsi_mq_uninit_cmd(cmd); 567 568 /* 569 * queue is still alive, so grab the ref for preventing it 570 * from being cleaned up during running queue. 571 */ 572 percpu_ref_get(&q->q_usage_counter); 573 574 __blk_mq_end_request(req, error); 575 576 scsi_run_queue_async(sdev); 577 578 percpu_ref_put(&q->q_usage_counter); 579 return false; 580 } 581 582 /** 583 * scsi_result_to_blk_status - translate a SCSI result code into blk_status_t 584 * @cmd: SCSI command 585 * @result: scsi error code 586 * 587 * Translate a SCSI result code into a blk_status_t value. May reset the host 588 * byte of @cmd->result. 589 */ 590 static blk_status_t scsi_result_to_blk_status(struct scsi_cmnd *cmd, int result) 591 { 592 switch (host_byte(result)) { 593 case DID_OK: 594 /* 595 * Also check the other bytes than the status byte in result 596 */ 597 if (scsi_status_is_good(result) && (result & ~0xff) == 0) 598 return BLK_STS_OK; 599 return BLK_STS_IOERR; 600 case DID_TRANSPORT_FAILFAST: 601 case DID_TRANSPORT_MARGINAL: 602 return BLK_STS_TRANSPORT; 603 case DID_TARGET_FAILURE: 604 set_host_byte(cmd, DID_OK); 605 return BLK_STS_TARGET; 606 case DID_NEXUS_FAILURE: 607 set_host_byte(cmd, DID_OK); 608 return BLK_STS_NEXUS; 609 case DID_ALLOC_FAILURE: 610 set_host_byte(cmd, DID_OK); 611 return BLK_STS_NOSPC; 612 case DID_MEDIUM_ERROR: 613 set_host_byte(cmd, DID_OK); 614 return BLK_STS_MEDIUM; 615 default: 616 return BLK_STS_IOERR; 617 } 618 } 619 620 /* Helper for scsi_io_completion() when "reprep" action required. */ 621 static void scsi_io_completion_reprep(struct scsi_cmnd *cmd, 622 struct request_queue *q) 623 { 624 /* A new command will be prepared and issued. */ 625 scsi_mq_requeue_cmd(cmd); 626 } 627 628 static bool scsi_cmd_runtime_exceeced(struct scsi_cmnd *cmd) 629 { 630 struct request *req = cmd->request; 631 unsigned long wait_for; 632 633 if (cmd->allowed == SCSI_CMD_RETRIES_NO_LIMIT) 634 return false; 635 636 wait_for = (cmd->allowed + 1) * req->timeout; 637 if (time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) { 638 scmd_printk(KERN_ERR, cmd, "timing out command, waited %lus\n", 639 wait_for/HZ); 640 return true; 641 } 642 return false; 643 } 644 645 /* Helper for scsi_io_completion() when special action required. */ 646 static void scsi_io_completion_action(struct scsi_cmnd *cmd, int result) 647 { 648 struct request_queue *q = cmd->device->request_queue; 649 struct request *req = cmd->request; 650 int level = 0; 651 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY, 652 ACTION_DELAYED_RETRY} action; 653 struct scsi_sense_hdr sshdr; 654 bool sense_valid; 655 bool sense_current = true; /* false implies "deferred sense" */ 656 blk_status_t blk_stat; 657 658 sense_valid = scsi_command_normalize_sense(cmd, &sshdr); 659 if (sense_valid) 660 sense_current = !scsi_sense_is_deferred(&sshdr); 661 662 blk_stat = scsi_result_to_blk_status(cmd, result); 663 664 if (host_byte(result) == DID_RESET) { 665 /* Third party bus reset or reset for error recovery 666 * reasons. Just retry the command and see what 667 * happens. 668 */ 669 action = ACTION_RETRY; 670 } else if (sense_valid && sense_current) { 671 switch (sshdr.sense_key) { 672 case UNIT_ATTENTION: 673 if (cmd->device->removable) { 674 /* Detected disc change. Set a bit 675 * and quietly refuse further access. 676 */ 677 cmd->device->changed = 1; 678 action = ACTION_FAIL; 679 } else { 680 /* Must have been a power glitch, or a 681 * bus reset. Could not have been a 682 * media change, so we just retry the 683 * command and see what happens. 684 */ 685 action = ACTION_RETRY; 686 } 687 break; 688 case ILLEGAL_REQUEST: 689 /* If we had an ILLEGAL REQUEST returned, then 690 * we may have performed an unsupported 691 * command. The only thing this should be 692 * would be a ten byte read where only a six 693 * byte read was supported. Also, on a system 694 * where READ CAPACITY failed, we may have 695 * read past the end of the disk. 696 */ 697 if ((cmd->device->use_10_for_rw && 698 sshdr.asc == 0x20 && sshdr.ascq == 0x00) && 699 (cmd->cmnd[0] == READ_10 || 700 cmd->cmnd[0] == WRITE_10)) { 701 /* This will issue a new 6-byte command. */ 702 cmd->device->use_10_for_rw = 0; 703 action = ACTION_REPREP; 704 } else if (sshdr.asc == 0x10) /* DIX */ { 705 action = ACTION_FAIL; 706 blk_stat = BLK_STS_PROTECTION; 707 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */ 708 } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) { 709 action = ACTION_FAIL; 710 blk_stat = BLK_STS_TARGET; 711 } else 712 action = ACTION_FAIL; 713 break; 714 case ABORTED_COMMAND: 715 action = ACTION_FAIL; 716 if (sshdr.asc == 0x10) /* DIF */ 717 blk_stat = BLK_STS_PROTECTION; 718 break; 719 case NOT_READY: 720 /* If the device is in the process of becoming 721 * ready, or has a temporary blockage, retry. 722 */ 723 if (sshdr.asc == 0x04) { 724 switch (sshdr.ascq) { 725 case 0x01: /* becoming ready */ 726 case 0x04: /* format in progress */ 727 case 0x05: /* rebuild in progress */ 728 case 0x06: /* recalculation in progress */ 729 case 0x07: /* operation in progress */ 730 case 0x08: /* Long write in progress */ 731 case 0x09: /* self test in progress */ 732 case 0x14: /* space allocation in progress */ 733 case 0x1a: /* start stop unit in progress */ 734 case 0x1b: /* sanitize in progress */ 735 case 0x1d: /* configuration in progress */ 736 case 0x24: /* depopulation in progress */ 737 action = ACTION_DELAYED_RETRY; 738 break; 739 case 0x0a: /* ALUA state transition */ 740 blk_stat = BLK_STS_AGAIN; 741 fallthrough; 742 default: 743 action = ACTION_FAIL; 744 break; 745 } 746 } else 747 action = ACTION_FAIL; 748 break; 749 case VOLUME_OVERFLOW: 750 /* See SSC3rXX or current. */ 751 action = ACTION_FAIL; 752 break; 753 case DATA_PROTECT: 754 action = ACTION_FAIL; 755 if ((sshdr.asc == 0x0C && sshdr.ascq == 0x12) || 756 (sshdr.asc == 0x55 && 757 (sshdr.ascq == 0x0E || sshdr.ascq == 0x0F))) { 758 /* Insufficient zone resources */ 759 blk_stat = BLK_STS_ZONE_OPEN_RESOURCE; 760 } 761 break; 762 default: 763 action = ACTION_FAIL; 764 break; 765 } 766 } else 767 action = ACTION_FAIL; 768 769 if (action != ACTION_FAIL && scsi_cmd_runtime_exceeced(cmd)) 770 action = ACTION_FAIL; 771 772 switch (action) { 773 case ACTION_FAIL: 774 /* Give up and fail the remainder of the request */ 775 if (!(req->rq_flags & RQF_QUIET)) { 776 static DEFINE_RATELIMIT_STATE(_rs, 777 DEFAULT_RATELIMIT_INTERVAL, 778 DEFAULT_RATELIMIT_BURST); 779 780 if (unlikely(scsi_logging_level)) 781 level = 782 SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT, 783 SCSI_LOG_MLCOMPLETE_BITS); 784 785 /* 786 * if logging is enabled the failure will be printed 787 * in scsi_log_completion(), so avoid duplicate messages 788 */ 789 if (!level && __ratelimit(&_rs)) { 790 scsi_print_result(cmd, NULL, FAILED); 791 if (sense_valid) 792 scsi_print_sense(cmd); 793 scsi_print_command(cmd); 794 } 795 } 796 if (!scsi_end_request(req, blk_stat, blk_rq_err_bytes(req))) 797 return; 798 fallthrough; 799 case ACTION_REPREP: 800 scsi_io_completion_reprep(cmd, q); 801 break; 802 case ACTION_RETRY: 803 /* Retry the same command immediately */ 804 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, false); 805 break; 806 case ACTION_DELAYED_RETRY: 807 /* Retry the same command after a delay */ 808 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, false); 809 break; 810 } 811 } 812 813 /* 814 * Helper for scsi_io_completion() when cmd->result is non-zero. Returns a 815 * new result that may suppress further error checking. Also modifies 816 * *blk_statp in some cases. 817 */ 818 static int scsi_io_completion_nz_result(struct scsi_cmnd *cmd, int result, 819 blk_status_t *blk_statp) 820 { 821 bool sense_valid; 822 bool sense_current = true; /* false implies "deferred sense" */ 823 struct request *req = cmd->request; 824 struct scsi_sense_hdr sshdr; 825 826 sense_valid = scsi_command_normalize_sense(cmd, &sshdr); 827 if (sense_valid) 828 sense_current = !scsi_sense_is_deferred(&sshdr); 829 830 if (blk_rq_is_passthrough(req)) { 831 if (sense_valid) { 832 /* 833 * SG_IO wants current and deferred errors 834 */ 835 scsi_req(req)->sense_len = 836 min(8 + cmd->sense_buffer[7], 837 SCSI_SENSE_BUFFERSIZE); 838 } 839 if (sense_current) 840 *blk_statp = scsi_result_to_blk_status(cmd, result); 841 } else if (blk_rq_bytes(req) == 0 && sense_current) { 842 /* 843 * Flush commands do not transfers any data, and thus cannot use 844 * good_bytes != blk_rq_bytes(req) as the signal for an error. 845 * This sets *blk_statp explicitly for the problem case. 846 */ 847 *blk_statp = scsi_result_to_blk_status(cmd, result); 848 } 849 /* 850 * Recovered errors need reporting, but they're always treated as 851 * success, so fiddle the result code here. For passthrough requests 852 * we already took a copy of the original into sreq->result which 853 * is what gets returned to the user 854 */ 855 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) { 856 bool do_print = true; 857 /* 858 * if ATA PASS-THROUGH INFORMATION AVAILABLE [0x0, 0x1d] 859 * skip print since caller wants ATA registers. Only occurs 860 * on SCSI ATA PASS_THROUGH commands when CK_COND=1 861 */ 862 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d)) 863 do_print = false; 864 else if (req->rq_flags & RQF_QUIET) 865 do_print = false; 866 if (do_print) 867 scsi_print_sense(cmd); 868 result = 0; 869 /* for passthrough, *blk_statp may be set */ 870 *blk_statp = BLK_STS_OK; 871 } 872 /* 873 * Another corner case: the SCSI status byte is non-zero but 'good'. 874 * Example: PRE-FETCH command returns SAM_STAT_CONDITION_MET when 875 * it is able to fit nominated LBs in its cache (and SAM_STAT_GOOD 876 * if it can't fit). Treat SAM_STAT_CONDITION_MET and the related 877 * intermediate statuses (both obsolete in SAM-4) as good. 878 */ 879 if (status_byte(result) && scsi_status_is_good(result)) { 880 result = 0; 881 *blk_statp = BLK_STS_OK; 882 } 883 return result; 884 } 885 886 /** 887 * scsi_io_completion - Completion processing for SCSI commands. 888 * @cmd: command that is finished. 889 * @good_bytes: number of processed bytes. 890 * 891 * We will finish off the specified number of sectors. If we are done, the 892 * command block will be released and the queue function will be goosed. If we 893 * are not done then we have to figure out what to do next: 894 * 895 * a) We can call scsi_io_completion_reprep(). The request will be 896 * unprepared and put back on the queue. Then a new command will 897 * be created for it. This should be used if we made forward 898 * progress, or if we want to switch from READ(10) to READ(6) for 899 * example. 900 * 901 * b) We can call scsi_io_completion_action(). The request will be 902 * put back on the queue and retried using the same command as 903 * before, possibly after a delay. 904 * 905 * c) We can call scsi_end_request() with blk_stat other than 906 * BLK_STS_OK, to fail the remainder of the request. 907 */ 908 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes) 909 { 910 int result = cmd->result; 911 struct request_queue *q = cmd->device->request_queue; 912 struct request *req = cmd->request; 913 blk_status_t blk_stat = BLK_STS_OK; 914 915 if (unlikely(result)) /* a nz result may or may not be an error */ 916 result = scsi_io_completion_nz_result(cmd, result, &blk_stat); 917 918 if (unlikely(blk_rq_is_passthrough(req))) { 919 /* 920 * scsi_result_to_blk_status may have reset the host_byte 921 */ 922 scsi_req(req)->result = cmd->result; 923 } 924 925 /* 926 * Next deal with any sectors which we were able to correctly 927 * handle. 928 */ 929 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd, 930 "%u sectors total, %d bytes done.\n", 931 blk_rq_sectors(req), good_bytes)); 932 933 /* 934 * Failed, zero length commands always need to drop down 935 * to retry code. Fast path should return in this block. 936 */ 937 if (likely(blk_rq_bytes(req) > 0 || blk_stat == BLK_STS_OK)) { 938 if (likely(!scsi_end_request(req, blk_stat, good_bytes))) 939 return; /* no bytes remaining */ 940 } 941 942 /* Kill remainder if no retries. */ 943 if (unlikely(blk_stat && scsi_noretry_cmd(cmd))) { 944 if (scsi_end_request(req, blk_stat, blk_rq_bytes(req))) 945 WARN_ONCE(true, 946 "Bytes remaining after failed, no-retry command"); 947 return; 948 } 949 950 /* 951 * If there had been no error, but we have leftover bytes in the 952 * requeues just queue the command up again. 953 */ 954 if (likely(result == 0)) 955 scsi_io_completion_reprep(cmd, q); 956 else 957 scsi_io_completion_action(cmd, result); 958 } 959 960 static inline bool scsi_cmd_needs_dma_drain(struct scsi_device *sdev, 961 struct request *rq) 962 { 963 return sdev->dma_drain_len && blk_rq_is_passthrough(rq) && 964 !op_is_write(req_op(rq)) && 965 sdev->host->hostt->dma_need_drain(rq); 966 } 967 968 /** 969 * scsi_alloc_sgtables - Allocate and initialize data and integrity scatterlists 970 * @cmd: SCSI command data structure to initialize. 971 * 972 * Initializes @cmd->sdb and also @cmd->prot_sdb if data integrity is enabled 973 * for @cmd. 974 * 975 * Returns: 976 * * BLK_STS_OK - on success 977 * * BLK_STS_RESOURCE - if the failure is retryable 978 * * BLK_STS_IOERR - if the failure is fatal 979 */ 980 blk_status_t scsi_alloc_sgtables(struct scsi_cmnd *cmd) 981 { 982 struct scsi_device *sdev = cmd->device; 983 struct request *rq = cmd->request; 984 unsigned short nr_segs = blk_rq_nr_phys_segments(rq); 985 struct scatterlist *last_sg = NULL; 986 blk_status_t ret; 987 bool need_drain = scsi_cmd_needs_dma_drain(sdev, rq); 988 int count; 989 990 if (WARN_ON_ONCE(!nr_segs)) 991 return BLK_STS_IOERR; 992 993 /* 994 * Make sure there is space for the drain. The driver must adjust 995 * max_hw_segments to be prepared for this. 996 */ 997 if (need_drain) 998 nr_segs++; 999 1000 /* 1001 * If sg table allocation fails, requeue request later. 1002 */ 1003 if (unlikely(sg_alloc_table_chained(&cmd->sdb.table, nr_segs, 1004 cmd->sdb.table.sgl, SCSI_INLINE_SG_CNT))) 1005 return BLK_STS_RESOURCE; 1006 1007 /* 1008 * Next, walk the list, and fill in the addresses and sizes of 1009 * each segment. 1010 */ 1011 count = __blk_rq_map_sg(rq->q, rq, cmd->sdb.table.sgl, &last_sg); 1012 1013 if (blk_rq_bytes(rq) & rq->q->dma_pad_mask) { 1014 unsigned int pad_len = 1015 (rq->q->dma_pad_mask & ~blk_rq_bytes(rq)) + 1; 1016 1017 last_sg->length += pad_len; 1018 cmd->extra_len += pad_len; 1019 } 1020 1021 if (need_drain) { 1022 sg_unmark_end(last_sg); 1023 last_sg = sg_next(last_sg); 1024 sg_set_buf(last_sg, sdev->dma_drain_buf, sdev->dma_drain_len); 1025 sg_mark_end(last_sg); 1026 1027 cmd->extra_len += sdev->dma_drain_len; 1028 count++; 1029 } 1030 1031 BUG_ON(count > cmd->sdb.table.nents); 1032 cmd->sdb.table.nents = count; 1033 cmd->sdb.length = blk_rq_payload_bytes(rq); 1034 1035 if (blk_integrity_rq(rq)) { 1036 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb; 1037 int ivecs; 1038 1039 if (WARN_ON_ONCE(!prot_sdb)) { 1040 /* 1041 * This can happen if someone (e.g. multipath) 1042 * queues a command to a device on an adapter 1043 * that does not support DIX. 1044 */ 1045 ret = BLK_STS_IOERR; 1046 goto out_free_sgtables; 1047 } 1048 1049 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio); 1050 1051 if (sg_alloc_table_chained(&prot_sdb->table, ivecs, 1052 prot_sdb->table.sgl, 1053 SCSI_INLINE_PROT_SG_CNT)) { 1054 ret = BLK_STS_RESOURCE; 1055 goto out_free_sgtables; 1056 } 1057 1058 count = blk_rq_map_integrity_sg(rq->q, rq->bio, 1059 prot_sdb->table.sgl); 1060 BUG_ON(count > ivecs); 1061 BUG_ON(count > queue_max_integrity_segments(rq->q)); 1062 1063 cmd->prot_sdb = prot_sdb; 1064 cmd->prot_sdb->table.nents = count; 1065 } 1066 1067 return BLK_STS_OK; 1068 out_free_sgtables: 1069 scsi_free_sgtables(cmd); 1070 return ret; 1071 } 1072 EXPORT_SYMBOL(scsi_alloc_sgtables); 1073 1074 /** 1075 * scsi_initialize_rq - initialize struct scsi_cmnd partially 1076 * @rq: Request associated with the SCSI command to be initialized. 1077 * 1078 * This function initializes the members of struct scsi_cmnd that must be 1079 * initialized before request processing starts and that won't be 1080 * reinitialized if a SCSI command is requeued. 1081 * 1082 * Called from inside blk_get_request() for pass-through requests and from 1083 * inside scsi_init_command() for filesystem requests. 1084 */ 1085 static void scsi_initialize_rq(struct request *rq) 1086 { 1087 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq); 1088 1089 scsi_req_init(&cmd->req); 1090 init_rcu_head(&cmd->rcu); 1091 cmd->jiffies_at_alloc = jiffies; 1092 cmd->retries = 0; 1093 } 1094 1095 /* 1096 * Only called when the request isn't completed by SCSI, and not freed by 1097 * SCSI 1098 */ 1099 static void scsi_cleanup_rq(struct request *rq) 1100 { 1101 if (rq->rq_flags & RQF_DONTPREP) { 1102 scsi_mq_uninit_cmd(blk_mq_rq_to_pdu(rq)); 1103 rq->rq_flags &= ~RQF_DONTPREP; 1104 } 1105 } 1106 1107 /* Called before a request is prepared. See also scsi_mq_prep_fn(). */ 1108 void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd) 1109 { 1110 void *buf = cmd->sense_buffer; 1111 void *prot = cmd->prot_sdb; 1112 struct request *rq = blk_mq_rq_from_pdu(cmd); 1113 unsigned int flags = cmd->flags & SCMD_PRESERVED_FLAGS; 1114 unsigned long jiffies_at_alloc; 1115 int retries, to_clear; 1116 bool in_flight; 1117 int budget_token = cmd->budget_token; 1118 1119 if (!blk_rq_is_scsi(rq) && !(flags & SCMD_INITIALIZED)) { 1120 flags |= SCMD_INITIALIZED; 1121 scsi_initialize_rq(rq); 1122 } 1123 1124 jiffies_at_alloc = cmd->jiffies_at_alloc; 1125 retries = cmd->retries; 1126 in_flight = test_bit(SCMD_STATE_INFLIGHT, &cmd->state); 1127 /* 1128 * Zero out the cmd, except for the embedded scsi_request. Only clear 1129 * the driver-private command data if the LLD does not supply a 1130 * function to initialize that data. 1131 */ 1132 to_clear = sizeof(*cmd) - sizeof(cmd->req); 1133 if (!dev->host->hostt->init_cmd_priv) 1134 to_clear += dev->host->hostt->cmd_size; 1135 memset((char *)cmd + sizeof(cmd->req), 0, to_clear); 1136 1137 cmd->device = dev; 1138 cmd->sense_buffer = buf; 1139 cmd->prot_sdb = prot; 1140 cmd->flags = flags; 1141 INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler); 1142 cmd->jiffies_at_alloc = jiffies_at_alloc; 1143 cmd->retries = retries; 1144 if (in_flight) 1145 __set_bit(SCMD_STATE_INFLIGHT, &cmd->state); 1146 cmd->budget_token = budget_token; 1147 1148 } 1149 1150 static blk_status_t scsi_setup_scsi_cmnd(struct scsi_device *sdev, 1151 struct request *req) 1152 { 1153 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req); 1154 1155 /* 1156 * Passthrough requests may transfer data, in which case they must 1157 * a bio attached to them. Or they might contain a SCSI command 1158 * that does not transfer data, in which case they may optionally 1159 * submit a request without an attached bio. 1160 */ 1161 if (req->bio) { 1162 blk_status_t ret = scsi_alloc_sgtables(cmd); 1163 if (unlikely(ret != BLK_STS_OK)) 1164 return ret; 1165 } else { 1166 BUG_ON(blk_rq_bytes(req)); 1167 1168 memset(&cmd->sdb, 0, sizeof(cmd->sdb)); 1169 } 1170 1171 cmd->cmd_len = scsi_req(req)->cmd_len; 1172 if (cmd->cmd_len == 0) 1173 cmd->cmd_len = scsi_command_size(cmd->cmnd); 1174 cmd->cmnd = scsi_req(req)->cmd; 1175 cmd->transfersize = blk_rq_bytes(req); 1176 cmd->allowed = scsi_req(req)->retries; 1177 return BLK_STS_OK; 1178 } 1179 1180 static blk_status_t 1181 scsi_device_state_check(struct scsi_device *sdev, struct request *req) 1182 { 1183 switch (sdev->sdev_state) { 1184 case SDEV_CREATED: 1185 return BLK_STS_OK; 1186 case SDEV_OFFLINE: 1187 case SDEV_TRANSPORT_OFFLINE: 1188 /* 1189 * If the device is offline we refuse to process any 1190 * commands. The device must be brought online 1191 * before trying any recovery commands. 1192 */ 1193 if (!sdev->offline_already) { 1194 sdev->offline_already = true; 1195 sdev_printk(KERN_ERR, sdev, 1196 "rejecting I/O to offline device\n"); 1197 } 1198 return BLK_STS_IOERR; 1199 case SDEV_DEL: 1200 /* 1201 * If the device is fully deleted, we refuse to 1202 * process any commands as well. 1203 */ 1204 sdev_printk(KERN_ERR, sdev, 1205 "rejecting I/O to dead device\n"); 1206 return BLK_STS_IOERR; 1207 case SDEV_BLOCK: 1208 case SDEV_CREATED_BLOCK: 1209 return BLK_STS_RESOURCE; 1210 case SDEV_QUIESCE: 1211 /* 1212 * If the device is blocked we only accept power management 1213 * commands. 1214 */ 1215 if (req && WARN_ON_ONCE(!(req->rq_flags & RQF_PM))) 1216 return BLK_STS_RESOURCE; 1217 return BLK_STS_OK; 1218 default: 1219 /* 1220 * For any other not fully online state we only allow 1221 * power management commands. 1222 */ 1223 if (req && !(req->rq_flags & RQF_PM)) 1224 return BLK_STS_IOERR; 1225 return BLK_STS_OK; 1226 } 1227 } 1228 1229 /* 1230 * scsi_dev_queue_ready: if we can send requests to sdev, assign one token 1231 * and return the token else return -1. 1232 */ 1233 static inline int scsi_dev_queue_ready(struct request_queue *q, 1234 struct scsi_device *sdev) 1235 { 1236 int token; 1237 1238 token = sbitmap_get(&sdev->budget_map); 1239 if (atomic_read(&sdev->device_blocked)) { 1240 if (token < 0) 1241 goto out; 1242 1243 if (scsi_device_busy(sdev) > 1) 1244 goto out_dec; 1245 1246 /* 1247 * unblock after device_blocked iterates to zero 1248 */ 1249 if (atomic_dec_return(&sdev->device_blocked) > 0) 1250 goto out_dec; 1251 SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev, 1252 "unblocking device at zero depth\n")); 1253 } 1254 1255 return token; 1256 out_dec: 1257 if (token >= 0) 1258 sbitmap_put(&sdev->budget_map, token); 1259 out: 1260 return -1; 1261 } 1262 1263 /* 1264 * scsi_target_queue_ready: checks if there we can send commands to target 1265 * @sdev: scsi device on starget to check. 1266 */ 1267 static inline int scsi_target_queue_ready(struct Scsi_Host *shost, 1268 struct scsi_device *sdev) 1269 { 1270 struct scsi_target *starget = scsi_target(sdev); 1271 unsigned int busy; 1272 1273 if (starget->single_lun) { 1274 spin_lock_irq(shost->host_lock); 1275 if (starget->starget_sdev_user && 1276 starget->starget_sdev_user != sdev) { 1277 spin_unlock_irq(shost->host_lock); 1278 return 0; 1279 } 1280 starget->starget_sdev_user = sdev; 1281 spin_unlock_irq(shost->host_lock); 1282 } 1283 1284 if (starget->can_queue <= 0) 1285 return 1; 1286 1287 busy = atomic_inc_return(&starget->target_busy) - 1; 1288 if (atomic_read(&starget->target_blocked) > 0) { 1289 if (busy) 1290 goto starved; 1291 1292 /* 1293 * unblock after target_blocked iterates to zero 1294 */ 1295 if (atomic_dec_return(&starget->target_blocked) > 0) 1296 goto out_dec; 1297 1298 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget, 1299 "unblocking target at zero depth\n")); 1300 } 1301 1302 if (busy >= starget->can_queue) 1303 goto starved; 1304 1305 return 1; 1306 1307 starved: 1308 spin_lock_irq(shost->host_lock); 1309 list_move_tail(&sdev->starved_entry, &shost->starved_list); 1310 spin_unlock_irq(shost->host_lock); 1311 out_dec: 1312 if (starget->can_queue > 0) 1313 atomic_dec(&starget->target_busy); 1314 return 0; 1315 } 1316 1317 /* 1318 * scsi_host_queue_ready: if we can send requests to shost, return 1 else 1319 * return 0. We must end up running the queue again whenever 0 is 1320 * returned, else IO can hang. 1321 */ 1322 static inline int scsi_host_queue_ready(struct request_queue *q, 1323 struct Scsi_Host *shost, 1324 struct scsi_device *sdev, 1325 struct scsi_cmnd *cmd) 1326 { 1327 if (scsi_host_in_recovery(shost)) 1328 return 0; 1329 1330 if (atomic_read(&shost->host_blocked) > 0) { 1331 if (scsi_host_busy(shost) > 0) 1332 goto starved; 1333 1334 /* 1335 * unblock after host_blocked iterates to zero 1336 */ 1337 if (atomic_dec_return(&shost->host_blocked) > 0) 1338 goto out_dec; 1339 1340 SCSI_LOG_MLQUEUE(3, 1341 shost_printk(KERN_INFO, shost, 1342 "unblocking host at zero depth\n")); 1343 } 1344 1345 if (shost->host_self_blocked) 1346 goto starved; 1347 1348 /* We're OK to process the command, so we can't be starved */ 1349 if (!list_empty(&sdev->starved_entry)) { 1350 spin_lock_irq(shost->host_lock); 1351 if (!list_empty(&sdev->starved_entry)) 1352 list_del_init(&sdev->starved_entry); 1353 spin_unlock_irq(shost->host_lock); 1354 } 1355 1356 __set_bit(SCMD_STATE_INFLIGHT, &cmd->state); 1357 1358 return 1; 1359 1360 starved: 1361 spin_lock_irq(shost->host_lock); 1362 if (list_empty(&sdev->starved_entry)) 1363 list_add_tail(&sdev->starved_entry, &shost->starved_list); 1364 spin_unlock_irq(shost->host_lock); 1365 out_dec: 1366 scsi_dec_host_busy(shost, cmd); 1367 return 0; 1368 } 1369 1370 /* 1371 * Busy state exporting function for request stacking drivers. 1372 * 1373 * For efficiency, no lock is taken to check the busy state of 1374 * shost/starget/sdev, since the returned value is not guaranteed and 1375 * may be changed after request stacking drivers call the function, 1376 * regardless of taking lock or not. 1377 * 1378 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi 1379 * needs to return 'not busy'. Otherwise, request stacking drivers 1380 * may hold requests forever. 1381 */ 1382 static bool scsi_mq_lld_busy(struct request_queue *q) 1383 { 1384 struct scsi_device *sdev = q->queuedata; 1385 struct Scsi_Host *shost; 1386 1387 if (blk_queue_dying(q)) 1388 return false; 1389 1390 shost = sdev->host; 1391 1392 /* 1393 * Ignore host/starget busy state. 1394 * Since block layer does not have a concept of fairness across 1395 * multiple queues, congestion of host/starget needs to be handled 1396 * in SCSI layer. 1397 */ 1398 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev)) 1399 return true; 1400 1401 return false; 1402 } 1403 1404 /* 1405 * Block layer request completion callback. May be called from interrupt 1406 * context. 1407 */ 1408 static void scsi_complete(struct request *rq) 1409 { 1410 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq); 1411 enum scsi_disposition disposition; 1412 1413 INIT_LIST_HEAD(&cmd->eh_entry); 1414 1415 atomic_inc(&cmd->device->iodone_cnt); 1416 if (cmd->result) 1417 atomic_inc(&cmd->device->ioerr_cnt); 1418 1419 disposition = scsi_decide_disposition(cmd); 1420 if (disposition != SUCCESS && scsi_cmd_runtime_exceeced(cmd)) 1421 disposition = SUCCESS; 1422 1423 scsi_log_completion(cmd, disposition); 1424 1425 switch (disposition) { 1426 case SUCCESS: 1427 scsi_finish_command(cmd); 1428 break; 1429 case NEEDS_RETRY: 1430 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY); 1431 break; 1432 case ADD_TO_MLQUEUE: 1433 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY); 1434 break; 1435 default: 1436 scsi_eh_scmd_add(cmd); 1437 break; 1438 } 1439 } 1440 1441 /** 1442 * scsi_dispatch_cmd - Dispatch a command to the low-level driver. 1443 * @cmd: command block we are dispatching. 1444 * 1445 * Return: nonzero return request was rejected and device's queue needs to be 1446 * plugged. 1447 */ 1448 static int scsi_dispatch_cmd(struct scsi_cmnd *cmd) 1449 { 1450 struct Scsi_Host *host = cmd->device->host; 1451 int rtn = 0; 1452 1453 atomic_inc(&cmd->device->iorequest_cnt); 1454 1455 /* check if the device is still usable */ 1456 if (unlikely(cmd->device->sdev_state == SDEV_DEL)) { 1457 /* in SDEV_DEL we error all commands. DID_NO_CONNECT 1458 * returns an immediate error upwards, and signals 1459 * that the device is no longer present */ 1460 cmd->result = DID_NO_CONNECT << 16; 1461 goto done; 1462 } 1463 1464 /* Check to see if the scsi lld made this device blocked. */ 1465 if (unlikely(scsi_device_blocked(cmd->device))) { 1466 /* 1467 * in blocked state, the command is just put back on 1468 * the device queue. The suspend state has already 1469 * blocked the queue so future requests should not 1470 * occur until the device transitions out of the 1471 * suspend state. 1472 */ 1473 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd, 1474 "queuecommand : device blocked\n")); 1475 return SCSI_MLQUEUE_DEVICE_BUSY; 1476 } 1477 1478 /* Store the LUN value in cmnd, if needed. */ 1479 if (cmd->device->lun_in_cdb) 1480 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) | 1481 (cmd->device->lun << 5 & 0xe0); 1482 1483 scsi_log_send(cmd); 1484 1485 /* 1486 * Before we queue this command, check if the command 1487 * length exceeds what the host adapter can handle. 1488 */ 1489 if (cmd->cmd_len > cmd->device->host->max_cmd_len) { 1490 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd, 1491 "queuecommand : command too long. " 1492 "cdb_size=%d host->max_cmd_len=%d\n", 1493 cmd->cmd_len, cmd->device->host->max_cmd_len)); 1494 cmd->result = (DID_ABORT << 16); 1495 goto done; 1496 } 1497 1498 if (unlikely(host->shost_state == SHOST_DEL)) { 1499 cmd->result = (DID_NO_CONNECT << 16); 1500 goto done; 1501 1502 } 1503 1504 trace_scsi_dispatch_cmd_start(cmd); 1505 rtn = host->hostt->queuecommand(host, cmd); 1506 if (rtn) { 1507 trace_scsi_dispatch_cmd_error(cmd, rtn); 1508 if (rtn != SCSI_MLQUEUE_DEVICE_BUSY && 1509 rtn != SCSI_MLQUEUE_TARGET_BUSY) 1510 rtn = SCSI_MLQUEUE_HOST_BUSY; 1511 1512 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd, 1513 "queuecommand : request rejected\n")); 1514 } 1515 1516 return rtn; 1517 done: 1518 cmd->scsi_done(cmd); 1519 return 0; 1520 } 1521 1522 /* Size in bytes of the sg-list stored in the scsi-mq command-private data. */ 1523 static unsigned int scsi_mq_inline_sgl_size(struct Scsi_Host *shost) 1524 { 1525 return min_t(unsigned int, shost->sg_tablesize, SCSI_INLINE_SG_CNT) * 1526 sizeof(struct scatterlist); 1527 } 1528 1529 static blk_status_t scsi_prepare_cmd(struct request *req) 1530 { 1531 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req); 1532 struct scsi_device *sdev = req->q->queuedata; 1533 struct Scsi_Host *shost = sdev->host; 1534 struct scatterlist *sg; 1535 1536 scsi_init_command(sdev, cmd); 1537 1538 cmd->request = req; 1539 cmd->tag = req->tag; 1540 cmd->prot_op = SCSI_PROT_NORMAL; 1541 if (blk_rq_bytes(req)) 1542 cmd->sc_data_direction = rq_dma_dir(req); 1543 else 1544 cmd->sc_data_direction = DMA_NONE; 1545 1546 sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size; 1547 cmd->sdb.table.sgl = sg; 1548 1549 if (scsi_host_get_prot(shost)) { 1550 memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer)); 1551 1552 cmd->prot_sdb->table.sgl = 1553 (struct scatterlist *)(cmd->prot_sdb + 1); 1554 } 1555 1556 /* 1557 * Special handling for passthrough commands, which don't go to the ULP 1558 * at all: 1559 */ 1560 if (blk_rq_is_scsi(req)) 1561 return scsi_setup_scsi_cmnd(sdev, req); 1562 1563 if (sdev->handler && sdev->handler->prep_fn) { 1564 blk_status_t ret = sdev->handler->prep_fn(sdev, req); 1565 1566 if (ret != BLK_STS_OK) 1567 return ret; 1568 } 1569 1570 cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd; 1571 memset(cmd->cmnd, 0, BLK_MAX_CDB); 1572 return scsi_cmd_to_driver(cmd)->init_command(cmd); 1573 } 1574 1575 static void scsi_mq_done(struct scsi_cmnd *cmd) 1576 { 1577 if (unlikely(blk_should_fake_timeout(cmd->request->q))) 1578 return; 1579 if (unlikely(test_and_set_bit(SCMD_STATE_COMPLETE, &cmd->state))) 1580 return; 1581 trace_scsi_dispatch_cmd_done(cmd); 1582 blk_mq_complete_request(cmd->request); 1583 } 1584 1585 static void scsi_mq_put_budget(struct request_queue *q, int budget_token) 1586 { 1587 struct scsi_device *sdev = q->queuedata; 1588 1589 sbitmap_put(&sdev->budget_map, budget_token); 1590 } 1591 1592 static int scsi_mq_get_budget(struct request_queue *q) 1593 { 1594 struct scsi_device *sdev = q->queuedata; 1595 int token = scsi_dev_queue_ready(q, sdev); 1596 1597 if (token >= 0) 1598 return token; 1599 1600 atomic_inc(&sdev->restarts); 1601 1602 /* 1603 * Orders atomic_inc(&sdev->restarts) and atomic_read(&sdev->device_busy). 1604 * .restarts must be incremented before .device_busy is read because the 1605 * code in scsi_run_queue_async() depends on the order of these operations. 1606 */ 1607 smp_mb__after_atomic(); 1608 1609 /* 1610 * If all in-flight requests originated from this LUN are completed 1611 * before reading .device_busy, sdev->device_busy will be observed as 1612 * zero, then blk_mq_delay_run_hw_queues() will dispatch this request 1613 * soon. Otherwise, completion of one of these requests will observe 1614 * the .restarts flag, and the request queue will be run for handling 1615 * this request, see scsi_end_request(). 1616 */ 1617 if (unlikely(scsi_device_busy(sdev) == 0 && 1618 !scsi_device_blocked(sdev))) 1619 blk_mq_delay_run_hw_queues(sdev->request_queue, SCSI_QUEUE_DELAY); 1620 return -1; 1621 } 1622 1623 static void scsi_mq_set_rq_budget_token(struct request *req, int token) 1624 { 1625 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req); 1626 1627 cmd->budget_token = token; 1628 } 1629 1630 static int scsi_mq_get_rq_budget_token(struct request *req) 1631 { 1632 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req); 1633 1634 return cmd->budget_token; 1635 } 1636 1637 static blk_status_t scsi_queue_rq(struct blk_mq_hw_ctx *hctx, 1638 const struct blk_mq_queue_data *bd) 1639 { 1640 struct request *req = bd->rq; 1641 struct request_queue *q = req->q; 1642 struct scsi_device *sdev = q->queuedata; 1643 struct Scsi_Host *shost = sdev->host; 1644 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req); 1645 blk_status_t ret; 1646 int reason; 1647 1648 WARN_ON_ONCE(cmd->budget_token < 0); 1649 1650 /* 1651 * If the device is not in running state we will reject some or all 1652 * commands. 1653 */ 1654 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) { 1655 ret = scsi_device_state_check(sdev, req); 1656 if (ret != BLK_STS_OK) 1657 goto out_put_budget; 1658 } 1659 1660 ret = BLK_STS_RESOURCE; 1661 if (!scsi_target_queue_ready(shost, sdev)) 1662 goto out_put_budget; 1663 if (!scsi_host_queue_ready(q, shost, sdev, cmd)) 1664 goto out_dec_target_busy; 1665 1666 if (!(req->rq_flags & RQF_DONTPREP)) { 1667 ret = scsi_prepare_cmd(req); 1668 if (ret != BLK_STS_OK) 1669 goto out_dec_host_busy; 1670 req->rq_flags |= RQF_DONTPREP; 1671 } else { 1672 clear_bit(SCMD_STATE_COMPLETE, &cmd->state); 1673 } 1674 1675 cmd->flags &= SCMD_PRESERVED_FLAGS; 1676 if (sdev->simple_tags) 1677 cmd->flags |= SCMD_TAGGED; 1678 if (bd->last) 1679 cmd->flags |= SCMD_LAST; 1680 1681 scsi_set_resid(cmd, 0); 1682 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE); 1683 cmd->scsi_done = scsi_mq_done; 1684 1685 blk_mq_start_request(req); 1686 reason = scsi_dispatch_cmd(cmd); 1687 if (reason) { 1688 scsi_set_blocked(cmd, reason); 1689 ret = BLK_STS_RESOURCE; 1690 goto out_dec_host_busy; 1691 } 1692 1693 return BLK_STS_OK; 1694 1695 out_dec_host_busy: 1696 scsi_dec_host_busy(shost, cmd); 1697 out_dec_target_busy: 1698 if (scsi_target(sdev)->can_queue > 0) 1699 atomic_dec(&scsi_target(sdev)->target_busy); 1700 out_put_budget: 1701 scsi_mq_put_budget(q, cmd->budget_token); 1702 cmd->budget_token = -1; 1703 switch (ret) { 1704 case BLK_STS_OK: 1705 break; 1706 case BLK_STS_RESOURCE: 1707 case BLK_STS_ZONE_RESOURCE: 1708 if (scsi_device_blocked(sdev)) 1709 ret = BLK_STS_DEV_RESOURCE; 1710 break; 1711 case BLK_STS_AGAIN: 1712 scsi_req(req)->result = DID_BUS_BUSY << 16; 1713 if (req->rq_flags & RQF_DONTPREP) 1714 scsi_mq_uninit_cmd(cmd); 1715 break; 1716 default: 1717 if (unlikely(!scsi_device_online(sdev))) 1718 scsi_req(req)->result = DID_NO_CONNECT << 16; 1719 else 1720 scsi_req(req)->result = DID_ERROR << 16; 1721 /* 1722 * Make sure to release all allocated resources when 1723 * we hit an error, as we will never see this command 1724 * again. 1725 */ 1726 if (req->rq_flags & RQF_DONTPREP) 1727 scsi_mq_uninit_cmd(cmd); 1728 scsi_run_queue_async(sdev); 1729 break; 1730 } 1731 return ret; 1732 } 1733 1734 static enum blk_eh_timer_return scsi_timeout(struct request *req, 1735 bool reserved) 1736 { 1737 if (reserved) 1738 return BLK_EH_RESET_TIMER; 1739 return scsi_times_out(req); 1740 } 1741 1742 static int scsi_mq_init_request(struct blk_mq_tag_set *set, struct request *rq, 1743 unsigned int hctx_idx, unsigned int numa_node) 1744 { 1745 struct Scsi_Host *shost = set->driver_data; 1746 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq); 1747 struct scatterlist *sg; 1748 int ret = 0; 1749 1750 cmd->sense_buffer = 1751 kmem_cache_alloc_node(scsi_sense_cache, GFP_KERNEL, numa_node); 1752 if (!cmd->sense_buffer) 1753 return -ENOMEM; 1754 cmd->req.sense = cmd->sense_buffer; 1755 1756 if (scsi_host_get_prot(shost)) { 1757 sg = (void *)cmd + sizeof(struct scsi_cmnd) + 1758 shost->hostt->cmd_size; 1759 cmd->prot_sdb = (void *)sg + scsi_mq_inline_sgl_size(shost); 1760 } 1761 1762 if (shost->hostt->init_cmd_priv) { 1763 ret = shost->hostt->init_cmd_priv(shost, cmd); 1764 if (ret < 0) 1765 kmem_cache_free(scsi_sense_cache, cmd->sense_buffer); 1766 } 1767 1768 return ret; 1769 } 1770 1771 static void scsi_mq_exit_request(struct blk_mq_tag_set *set, struct request *rq, 1772 unsigned int hctx_idx) 1773 { 1774 struct Scsi_Host *shost = set->driver_data; 1775 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq); 1776 1777 if (shost->hostt->exit_cmd_priv) 1778 shost->hostt->exit_cmd_priv(shost, cmd); 1779 kmem_cache_free(scsi_sense_cache, cmd->sense_buffer); 1780 } 1781 1782 1783 static int scsi_mq_poll(struct blk_mq_hw_ctx *hctx) 1784 { 1785 struct Scsi_Host *shost = hctx->driver_data; 1786 1787 if (shost->hostt->mq_poll) 1788 return shost->hostt->mq_poll(shost, hctx->queue_num); 1789 1790 return 0; 1791 } 1792 1793 static int scsi_init_hctx(struct blk_mq_hw_ctx *hctx, void *data, 1794 unsigned int hctx_idx) 1795 { 1796 struct Scsi_Host *shost = data; 1797 1798 hctx->driver_data = shost; 1799 return 0; 1800 } 1801 1802 static int scsi_map_queues(struct blk_mq_tag_set *set) 1803 { 1804 struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set); 1805 1806 if (shost->hostt->map_queues) 1807 return shost->hostt->map_queues(shost); 1808 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]); 1809 } 1810 1811 void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q) 1812 { 1813 struct device *dev = shost->dma_dev; 1814 1815 /* 1816 * this limit is imposed by hardware restrictions 1817 */ 1818 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize, 1819 SG_MAX_SEGMENTS)); 1820 1821 if (scsi_host_prot_dma(shost)) { 1822 shost->sg_prot_tablesize = 1823 min_not_zero(shost->sg_prot_tablesize, 1824 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS); 1825 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize); 1826 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize); 1827 } 1828 1829 if (dev->dma_mask) { 1830 shost->max_sectors = min_t(unsigned int, shost->max_sectors, 1831 dma_max_mapping_size(dev) >> SECTOR_SHIFT); 1832 } 1833 blk_queue_max_hw_sectors(q, shost->max_sectors); 1834 blk_queue_segment_boundary(q, shost->dma_boundary); 1835 dma_set_seg_boundary(dev, shost->dma_boundary); 1836 1837 blk_queue_max_segment_size(q, shost->max_segment_size); 1838 blk_queue_virt_boundary(q, shost->virt_boundary_mask); 1839 dma_set_max_seg_size(dev, queue_max_segment_size(q)); 1840 1841 /* 1842 * Set a reasonable default alignment: The larger of 32-byte (dword), 1843 * which is a common minimum for HBAs, and the minimum DMA alignment, 1844 * which is set by the platform. 1845 * 1846 * Devices that require a bigger alignment can increase it later. 1847 */ 1848 blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1); 1849 } 1850 EXPORT_SYMBOL_GPL(__scsi_init_queue); 1851 1852 static const struct blk_mq_ops scsi_mq_ops_no_commit = { 1853 .get_budget = scsi_mq_get_budget, 1854 .put_budget = scsi_mq_put_budget, 1855 .queue_rq = scsi_queue_rq, 1856 .complete = scsi_complete, 1857 .timeout = scsi_timeout, 1858 #ifdef CONFIG_BLK_DEBUG_FS 1859 .show_rq = scsi_show_rq, 1860 #endif 1861 .init_request = scsi_mq_init_request, 1862 .exit_request = scsi_mq_exit_request, 1863 .initialize_rq_fn = scsi_initialize_rq, 1864 .cleanup_rq = scsi_cleanup_rq, 1865 .busy = scsi_mq_lld_busy, 1866 .map_queues = scsi_map_queues, 1867 .init_hctx = scsi_init_hctx, 1868 .poll = scsi_mq_poll, 1869 .set_rq_budget_token = scsi_mq_set_rq_budget_token, 1870 .get_rq_budget_token = scsi_mq_get_rq_budget_token, 1871 }; 1872 1873 1874 static void scsi_commit_rqs(struct blk_mq_hw_ctx *hctx) 1875 { 1876 struct Scsi_Host *shost = hctx->driver_data; 1877 1878 shost->hostt->commit_rqs(shost, hctx->queue_num); 1879 } 1880 1881 static const struct blk_mq_ops scsi_mq_ops = { 1882 .get_budget = scsi_mq_get_budget, 1883 .put_budget = scsi_mq_put_budget, 1884 .queue_rq = scsi_queue_rq, 1885 .commit_rqs = scsi_commit_rqs, 1886 .complete = scsi_complete, 1887 .timeout = scsi_timeout, 1888 #ifdef CONFIG_BLK_DEBUG_FS 1889 .show_rq = scsi_show_rq, 1890 #endif 1891 .init_request = scsi_mq_init_request, 1892 .exit_request = scsi_mq_exit_request, 1893 .initialize_rq_fn = scsi_initialize_rq, 1894 .cleanup_rq = scsi_cleanup_rq, 1895 .busy = scsi_mq_lld_busy, 1896 .map_queues = scsi_map_queues, 1897 .init_hctx = scsi_init_hctx, 1898 .poll = scsi_mq_poll, 1899 .set_rq_budget_token = scsi_mq_set_rq_budget_token, 1900 .get_rq_budget_token = scsi_mq_get_rq_budget_token, 1901 }; 1902 1903 struct request_queue *scsi_mq_alloc_queue(struct scsi_device *sdev) 1904 { 1905 sdev->request_queue = blk_mq_init_queue(&sdev->host->tag_set); 1906 if (IS_ERR(sdev->request_queue)) 1907 return NULL; 1908 1909 sdev->request_queue->queuedata = sdev; 1910 __scsi_init_queue(sdev->host, sdev->request_queue); 1911 blk_queue_flag_set(QUEUE_FLAG_SCSI_PASSTHROUGH, sdev->request_queue); 1912 return sdev->request_queue; 1913 } 1914 1915 int scsi_mq_setup_tags(struct Scsi_Host *shost) 1916 { 1917 unsigned int cmd_size, sgl_size; 1918 struct blk_mq_tag_set *tag_set = &shost->tag_set; 1919 1920 sgl_size = max_t(unsigned int, sizeof(struct scatterlist), 1921 scsi_mq_inline_sgl_size(shost)); 1922 cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size; 1923 if (scsi_host_get_prot(shost)) 1924 cmd_size += sizeof(struct scsi_data_buffer) + 1925 sizeof(struct scatterlist) * SCSI_INLINE_PROT_SG_CNT; 1926 1927 memset(tag_set, 0, sizeof(*tag_set)); 1928 if (shost->hostt->commit_rqs) 1929 tag_set->ops = &scsi_mq_ops; 1930 else 1931 tag_set->ops = &scsi_mq_ops_no_commit; 1932 tag_set->nr_hw_queues = shost->nr_hw_queues ? : 1; 1933 tag_set->nr_maps = shost->nr_maps ? : 1; 1934 tag_set->queue_depth = shost->can_queue; 1935 tag_set->cmd_size = cmd_size; 1936 tag_set->numa_node = NUMA_NO_NODE; 1937 tag_set->flags = BLK_MQ_F_SHOULD_MERGE; 1938 tag_set->flags |= 1939 BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy); 1940 tag_set->driver_data = shost; 1941 if (shost->host_tagset) 1942 tag_set->flags |= BLK_MQ_F_TAG_HCTX_SHARED; 1943 1944 return blk_mq_alloc_tag_set(tag_set); 1945 } 1946 1947 void scsi_mq_destroy_tags(struct Scsi_Host *shost) 1948 { 1949 blk_mq_free_tag_set(&shost->tag_set); 1950 } 1951 1952 /** 1953 * scsi_device_from_queue - return sdev associated with a request_queue 1954 * @q: The request queue to return the sdev from 1955 * 1956 * Return the sdev associated with a request queue or NULL if the 1957 * request_queue does not reference a SCSI device. 1958 */ 1959 struct scsi_device *scsi_device_from_queue(struct request_queue *q) 1960 { 1961 struct scsi_device *sdev = NULL; 1962 1963 if (q->mq_ops == &scsi_mq_ops_no_commit || 1964 q->mq_ops == &scsi_mq_ops) 1965 sdev = q->queuedata; 1966 if (!sdev || !get_device(&sdev->sdev_gendev)) 1967 sdev = NULL; 1968 1969 return sdev; 1970 } 1971 1972 /** 1973 * scsi_block_requests - Utility function used by low-level drivers to prevent 1974 * further commands from being queued to the device. 1975 * @shost: host in question 1976 * 1977 * There is no timer nor any other means by which the requests get unblocked 1978 * other than the low-level driver calling scsi_unblock_requests(). 1979 */ 1980 void scsi_block_requests(struct Scsi_Host *shost) 1981 { 1982 shost->host_self_blocked = 1; 1983 } 1984 EXPORT_SYMBOL(scsi_block_requests); 1985 1986 /** 1987 * scsi_unblock_requests - Utility function used by low-level drivers to allow 1988 * further commands to be queued to the device. 1989 * @shost: host in question 1990 * 1991 * There is no timer nor any other means by which the requests get unblocked 1992 * other than the low-level driver calling scsi_unblock_requests(). This is done 1993 * as an API function so that changes to the internals of the scsi mid-layer 1994 * won't require wholesale changes to drivers that use this feature. 1995 */ 1996 void scsi_unblock_requests(struct Scsi_Host *shost) 1997 { 1998 shost->host_self_blocked = 0; 1999 scsi_run_host_queues(shost); 2000 } 2001 EXPORT_SYMBOL(scsi_unblock_requests); 2002 2003 void scsi_exit_queue(void) 2004 { 2005 kmem_cache_destroy(scsi_sense_cache); 2006 } 2007 2008 /** 2009 * scsi_mode_select - issue a mode select 2010 * @sdev: SCSI device to be queried 2011 * @pf: Page format bit (1 == standard, 0 == vendor specific) 2012 * @sp: Save page bit (0 == don't save, 1 == save) 2013 * @modepage: mode page being requested 2014 * @buffer: request buffer (may not be smaller than eight bytes) 2015 * @len: length of request buffer. 2016 * @timeout: command timeout 2017 * @retries: number of retries before failing 2018 * @data: returns a structure abstracting the mode header data 2019 * @sshdr: place to put sense data (or NULL if no sense to be collected). 2020 * must be SCSI_SENSE_BUFFERSIZE big. 2021 * 2022 * Returns zero if successful; negative error number or scsi 2023 * status on error 2024 * 2025 */ 2026 int 2027 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage, 2028 unsigned char *buffer, int len, int timeout, int retries, 2029 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr) 2030 { 2031 unsigned char cmd[10]; 2032 unsigned char *real_buffer; 2033 int ret; 2034 2035 memset(cmd, 0, sizeof(cmd)); 2036 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0); 2037 2038 if (sdev->use_10_for_ms) { 2039 if (len > 65535) 2040 return -EINVAL; 2041 real_buffer = kmalloc(8 + len, GFP_KERNEL); 2042 if (!real_buffer) 2043 return -ENOMEM; 2044 memcpy(real_buffer + 8, buffer, len); 2045 len += 8; 2046 real_buffer[0] = 0; 2047 real_buffer[1] = 0; 2048 real_buffer[2] = data->medium_type; 2049 real_buffer[3] = data->device_specific; 2050 real_buffer[4] = data->longlba ? 0x01 : 0; 2051 real_buffer[5] = 0; 2052 real_buffer[6] = data->block_descriptor_length >> 8; 2053 real_buffer[7] = data->block_descriptor_length; 2054 2055 cmd[0] = MODE_SELECT_10; 2056 cmd[7] = len >> 8; 2057 cmd[8] = len; 2058 } else { 2059 if (len > 255 || data->block_descriptor_length > 255 || 2060 data->longlba) 2061 return -EINVAL; 2062 2063 real_buffer = kmalloc(4 + len, GFP_KERNEL); 2064 if (!real_buffer) 2065 return -ENOMEM; 2066 memcpy(real_buffer + 4, buffer, len); 2067 len += 4; 2068 real_buffer[0] = 0; 2069 real_buffer[1] = data->medium_type; 2070 real_buffer[2] = data->device_specific; 2071 real_buffer[3] = data->block_descriptor_length; 2072 2073 cmd[0] = MODE_SELECT; 2074 cmd[4] = len; 2075 } 2076 2077 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len, 2078 sshdr, timeout, retries, NULL); 2079 kfree(real_buffer); 2080 return ret; 2081 } 2082 EXPORT_SYMBOL_GPL(scsi_mode_select); 2083 2084 /** 2085 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary. 2086 * @sdev: SCSI device to be queried 2087 * @dbd: set if mode sense will allow block descriptors to be returned 2088 * @modepage: mode page being requested 2089 * @buffer: request buffer (may not be smaller than eight bytes) 2090 * @len: length of request buffer. 2091 * @timeout: command timeout 2092 * @retries: number of retries before failing 2093 * @data: returns a structure abstracting the mode header data 2094 * @sshdr: place to put sense data (or NULL if no sense to be collected). 2095 * must be SCSI_SENSE_BUFFERSIZE big. 2096 * 2097 * Returns zero if successful, or a negative error number on failure 2098 */ 2099 int 2100 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage, 2101 unsigned char *buffer, int len, int timeout, int retries, 2102 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr) 2103 { 2104 unsigned char cmd[12]; 2105 int use_10_for_ms; 2106 int header_length; 2107 int result, retry_count = retries; 2108 struct scsi_sense_hdr my_sshdr; 2109 2110 memset(data, 0, sizeof(*data)); 2111 memset(&cmd[0], 0, 12); 2112 2113 dbd = sdev->set_dbd_for_ms ? 8 : dbd; 2114 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */ 2115 cmd[2] = modepage; 2116 2117 /* caller might not be interested in sense, but we need it */ 2118 if (!sshdr) 2119 sshdr = &my_sshdr; 2120 2121 retry: 2122 use_10_for_ms = sdev->use_10_for_ms; 2123 2124 if (use_10_for_ms) { 2125 if (len < 8) 2126 len = 8; 2127 2128 cmd[0] = MODE_SENSE_10; 2129 cmd[8] = len; 2130 header_length = 8; 2131 } else { 2132 if (len < 4) 2133 len = 4; 2134 2135 cmd[0] = MODE_SENSE; 2136 cmd[4] = len; 2137 header_length = 4; 2138 } 2139 2140 memset(buffer, 0, len); 2141 2142 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len, 2143 sshdr, timeout, retries, NULL); 2144 if (result < 0) 2145 return result; 2146 2147 /* This code looks awful: what it's doing is making sure an 2148 * ILLEGAL REQUEST sense return identifies the actual command 2149 * byte as the problem. MODE_SENSE commands can return 2150 * ILLEGAL REQUEST if the code page isn't supported */ 2151 2152 if (!scsi_status_is_good(result)) { 2153 if (scsi_sense_valid(sshdr)) { 2154 if ((sshdr->sense_key == ILLEGAL_REQUEST) && 2155 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) { 2156 /* 2157 * Invalid command operation code 2158 */ 2159 if (use_10_for_ms) { 2160 sdev->use_10_for_ms = 0; 2161 goto retry; 2162 } 2163 } 2164 if (scsi_status_is_check_condition(result) && 2165 sshdr->sense_key == UNIT_ATTENTION && 2166 retry_count) { 2167 retry_count--; 2168 goto retry; 2169 } 2170 } 2171 return -EIO; 2172 } 2173 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b && 2174 (modepage == 6 || modepage == 8))) { 2175 /* Initio breakage? */ 2176 header_length = 0; 2177 data->length = 13; 2178 data->medium_type = 0; 2179 data->device_specific = 0; 2180 data->longlba = 0; 2181 data->block_descriptor_length = 0; 2182 } else if (use_10_for_ms) { 2183 data->length = buffer[0]*256 + buffer[1] + 2; 2184 data->medium_type = buffer[2]; 2185 data->device_specific = buffer[3]; 2186 data->longlba = buffer[4] & 0x01; 2187 data->block_descriptor_length = buffer[6]*256 2188 + buffer[7]; 2189 } else { 2190 data->length = buffer[0] + 1; 2191 data->medium_type = buffer[1]; 2192 data->device_specific = buffer[2]; 2193 data->block_descriptor_length = buffer[3]; 2194 } 2195 data->header_length = header_length; 2196 2197 return 0; 2198 } 2199 EXPORT_SYMBOL(scsi_mode_sense); 2200 2201 /** 2202 * scsi_test_unit_ready - test if unit is ready 2203 * @sdev: scsi device to change the state of. 2204 * @timeout: command timeout 2205 * @retries: number of retries before failing 2206 * @sshdr: outpout pointer for decoded sense information. 2207 * 2208 * Returns zero if unsuccessful or an error if TUR failed. For 2209 * removable media, UNIT_ATTENTION sets ->changed flag. 2210 **/ 2211 int 2212 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries, 2213 struct scsi_sense_hdr *sshdr) 2214 { 2215 char cmd[] = { 2216 TEST_UNIT_READY, 0, 0, 0, 0, 0, 2217 }; 2218 int result; 2219 2220 /* try to eat the UNIT_ATTENTION if there are enough retries */ 2221 do { 2222 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr, 2223 timeout, 1, NULL); 2224 if (sdev->removable && scsi_sense_valid(sshdr) && 2225 sshdr->sense_key == UNIT_ATTENTION) 2226 sdev->changed = 1; 2227 } while (scsi_sense_valid(sshdr) && 2228 sshdr->sense_key == UNIT_ATTENTION && --retries); 2229 2230 return result; 2231 } 2232 EXPORT_SYMBOL(scsi_test_unit_ready); 2233 2234 /** 2235 * scsi_device_set_state - Take the given device through the device state model. 2236 * @sdev: scsi device to change the state of. 2237 * @state: state to change to. 2238 * 2239 * Returns zero if successful or an error if the requested 2240 * transition is illegal. 2241 */ 2242 int 2243 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state) 2244 { 2245 enum scsi_device_state oldstate = sdev->sdev_state; 2246 2247 if (state == oldstate) 2248 return 0; 2249 2250 switch (state) { 2251 case SDEV_CREATED: 2252 switch (oldstate) { 2253 case SDEV_CREATED_BLOCK: 2254 break; 2255 default: 2256 goto illegal; 2257 } 2258 break; 2259 2260 case SDEV_RUNNING: 2261 switch (oldstate) { 2262 case SDEV_CREATED: 2263 case SDEV_OFFLINE: 2264 case SDEV_TRANSPORT_OFFLINE: 2265 case SDEV_QUIESCE: 2266 case SDEV_BLOCK: 2267 break; 2268 default: 2269 goto illegal; 2270 } 2271 break; 2272 2273 case SDEV_QUIESCE: 2274 switch (oldstate) { 2275 case SDEV_RUNNING: 2276 case SDEV_OFFLINE: 2277 case SDEV_TRANSPORT_OFFLINE: 2278 break; 2279 default: 2280 goto illegal; 2281 } 2282 break; 2283 2284 case SDEV_OFFLINE: 2285 case SDEV_TRANSPORT_OFFLINE: 2286 switch (oldstate) { 2287 case SDEV_CREATED: 2288 case SDEV_RUNNING: 2289 case SDEV_QUIESCE: 2290 case SDEV_BLOCK: 2291 break; 2292 default: 2293 goto illegal; 2294 } 2295 break; 2296 2297 case SDEV_BLOCK: 2298 switch (oldstate) { 2299 case SDEV_RUNNING: 2300 case SDEV_CREATED_BLOCK: 2301 case SDEV_QUIESCE: 2302 case SDEV_OFFLINE: 2303 break; 2304 default: 2305 goto illegal; 2306 } 2307 break; 2308 2309 case SDEV_CREATED_BLOCK: 2310 switch (oldstate) { 2311 case SDEV_CREATED: 2312 break; 2313 default: 2314 goto illegal; 2315 } 2316 break; 2317 2318 case SDEV_CANCEL: 2319 switch (oldstate) { 2320 case SDEV_CREATED: 2321 case SDEV_RUNNING: 2322 case SDEV_QUIESCE: 2323 case SDEV_OFFLINE: 2324 case SDEV_TRANSPORT_OFFLINE: 2325 break; 2326 default: 2327 goto illegal; 2328 } 2329 break; 2330 2331 case SDEV_DEL: 2332 switch (oldstate) { 2333 case SDEV_CREATED: 2334 case SDEV_RUNNING: 2335 case SDEV_OFFLINE: 2336 case SDEV_TRANSPORT_OFFLINE: 2337 case SDEV_CANCEL: 2338 case SDEV_BLOCK: 2339 case SDEV_CREATED_BLOCK: 2340 break; 2341 default: 2342 goto illegal; 2343 } 2344 break; 2345 2346 } 2347 sdev->offline_already = false; 2348 sdev->sdev_state = state; 2349 return 0; 2350 2351 illegal: 2352 SCSI_LOG_ERROR_RECOVERY(1, 2353 sdev_printk(KERN_ERR, sdev, 2354 "Illegal state transition %s->%s", 2355 scsi_device_state_name(oldstate), 2356 scsi_device_state_name(state)) 2357 ); 2358 return -EINVAL; 2359 } 2360 EXPORT_SYMBOL(scsi_device_set_state); 2361 2362 /** 2363 * scsi_evt_emit - emit a single SCSI device uevent 2364 * @sdev: associated SCSI device 2365 * @evt: event to emit 2366 * 2367 * Send a single uevent (scsi_event) to the associated scsi_device. 2368 */ 2369 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt) 2370 { 2371 int idx = 0; 2372 char *envp[3]; 2373 2374 switch (evt->evt_type) { 2375 case SDEV_EVT_MEDIA_CHANGE: 2376 envp[idx++] = "SDEV_MEDIA_CHANGE=1"; 2377 break; 2378 case SDEV_EVT_INQUIRY_CHANGE_REPORTED: 2379 scsi_rescan_device(&sdev->sdev_gendev); 2380 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED"; 2381 break; 2382 case SDEV_EVT_CAPACITY_CHANGE_REPORTED: 2383 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED"; 2384 break; 2385 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED: 2386 envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED"; 2387 break; 2388 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED: 2389 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED"; 2390 break; 2391 case SDEV_EVT_LUN_CHANGE_REPORTED: 2392 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED"; 2393 break; 2394 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED: 2395 envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED"; 2396 break; 2397 case SDEV_EVT_POWER_ON_RESET_OCCURRED: 2398 envp[idx++] = "SDEV_UA=POWER_ON_RESET_OCCURRED"; 2399 break; 2400 default: 2401 /* do nothing */ 2402 break; 2403 } 2404 2405 envp[idx++] = NULL; 2406 2407 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp); 2408 } 2409 2410 /** 2411 * scsi_evt_thread - send a uevent for each scsi event 2412 * @work: work struct for scsi_device 2413 * 2414 * Dispatch queued events to their associated scsi_device kobjects 2415 * as uevents. 2416 */ 2417 void scsi_evt_thread(struct work_struct *work) 2418 { 2419 struct scsi_device *sdev; 2420 enum scsi_device_event evt_type; 2421 LIST_HEAD(event_list); 2422 2423 sdev = container_of(work, struct scsi_device, event_work); 2424 2425 for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++) 2426 if (test_and_clear_bit(evt_type, sdev->pending_events)) 2427 sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL); 2428 2429 while (1) { 2430 struct scsi_event *evt; 2431 struct list_head *this, *tmp; 2432 unsigned long flags; 2433 2434 spin_lock_irqsave(&sdev->list_lock, flags); 2435 list_splice_init(&sdev->event_list, &event_list); 2436 spin_unlock_irqrestore(&sdev->list_lock, flags); 2437 2438 if (list_empty(&event_list)) 2439 break; 2440 2441 list_for_each_safe(this, tmp, &event_list) { 2442 evt = list_entry(this, struct scsi_event, node); 2443 list_del(&evt->node); 2444 scsi_evt_emit(sdev, evt); 2445 kfree(evt); 2446 } 2447 } 2448 } 2449 2450 /** 2451 * sdev_evt_send - send asserted event to uevent thread 2452 * @sdev: scsi_device event occurred on 2453 * @evt: event to send 2454 * 2455 * Assert scsi device event asynchronously. 2456 */ 2457 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt) 2458 { 2459 unsigned long flags; 2460 2461 #if 0 2462 /* FIXME: currently this check eliminates all media change events 2463 * for polled devices. Need to update to discriminate between AN 2464 * and polled events */ 2465 if (!test_bit(evt->evt_type, sdev->supported_events)) { 2466 kfree(evt); 2467 return; 2468 } 2469 #endif 2470 2471 spin_lock_irqsave(&sdev->list_lock, flags); 2472 list_add_tail(&evt->node, &sdev->event_list); 2473 schedule_work(&sdev->event_work); 2474 spin_unlock_irqrestore(&sdev->list_lock, flags); 2475 } 2476 EXPORT_SYMBOL_GPL(sdev_evt_send); 2477 2478 /** 2479 * sdev_evt_alloc - allocate a new scsi event 2480 * @evt_type: type of event to allocate 2481 * @gfpflags: GFP flags for allocation 2482 * 2483 * Allocates and returns a new scsi_event. 2484 */ 2485 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type, 2486 gfp_t gfpflags) 2487 { 2488 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags); 2489 if (!evt) 2490 return NULL; 2491 2492 evt->evt_type = evt_type; 2493 INIT_LIST_HEAD(&evt->node); 2494 2495 /* evt_type-specific initialization, if any */ 2496 switch (evt_type) { 2497 case SDEV_EVT_MEDIA_CHANGE: 2498 case SDEV_EVT_INQUIRY_CHANGE_REPORTED: 2499 case SDEV_EVT_CAPACITY_CHANGE_REPORTED: 2500 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED: 2501 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED: 2502 case SDEV_EVT_LUN_CHANGE_REPORTED: 2503 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED: 2504 case SDEV_EVT_POWER_ON_RESET_OCCURRED: 2505 default: 2506 /* do nothing */ 2507 break; 2508 } 2509 2510 return evt; 2511 } 2512 EXPORT_SYMBOL_GPL(sdev_evt_alloc); 2513 2514 /** 2515 * sdev_evt_send_simple - send asserted event to uevent thread 2516 * @sdev: scsi_device event occurred on 2517 * @evt_type: type of event to send 2518 * @gfpflags: GFP flags for allocation 2519 * 2520 * Assert scsi device event asynchronously, given an event type. 2521 */ 2522 void sdev_evt_send_simple(struct scsi_device *sdev, 2523 enum scsi_device_event evt_type, gfp_t gfpflags) 2524 { 2525 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags); 2526 if (!evt) { 2527 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n", 2528 evt_type); 2529 return; 2530 } 2531 2532 sdev_evt_send(sdev, evt); 2533 } 2534 EXPORT_SYMBOL_GPL(sdev_evt_send_simple); 2535 2536 /** 2537 * scsi_device_quiesce - Block all commands except power management. 2538 * @sdev: scsi device to quiesce. 2539 * 2540 * This works by trying to transition to the SDEV_QUIESCE state 2541 * (which must be a legal transition). When the device is in this 2542 * state, only power management requests will be accepted, all others will 2543 * be deferred. 2544 * 2545 * Must be called with user context, may sleep. 2546 * 2547 * Returns zero if unsuccessful or an error if not. 2548 */ 2549 int 2550 scsi_device_quiesce(struct scsi_device *sdev) 2551 { 2552 struct request_queue *q = sdev->request_queue; 2553 int err; 2554 2555 /* 2556 * It is allowed to call scsi_device_quiesce() multiple times from 2557 * the same context but concurrent scsi_device_quiesce() calls are 2558 * not allowed. 2559 */ 2560 WARN_ON_ONCE(sdev->quiesced_by && sdev->quiesced_by != current); 2561 2562 if (sdev->quiesced_by == current) 2563 return 0; 2564 2565 blk_set_pm_only(q); 2566 2567 blk_mq_freeze_queue(q); 2568 /* 2569 * Ensure that the effect of blk_set_pm_only() will be visible 2570 * for percpu_ref_tryget() callers that occur after the queue 2571 * unfreeze even if the queue was already frozen before this function 2572 * was called. See also https://lwn.net/Articles/573497/. 2573 */ 2574 synchronize_rcu(); 2575 blk_mq_unfreeze_queue(q); 2576 2577 mutex_lock(&sdev->state_mutex); 2578 err = scsi_device_set_state(sdev, SDEV_QUIESCE); 2579 if (err == 0) 2580 sdev->quiesced_by = current; 2581 else 2582 blk_clear_pm_only(q); 2583 mutex_unlock(&sdev->state_mutex); 2584 2585 return err; 2586 } 2587 EXPORT_SYMBOL(scsi_device_quiesce); 2588 2589 /** 2590 * scsi_device_resume - Restart user issued commands to a quiesced device. 2591 * @sdev: scsi device to resume. 2592 * 2593 * Moves the device from quiesced back to running and restarts the 2594 * queues. 2595 * 2596 * Must be called with user context, may sleep. 2597 */ 2598 void scsi_device_resume(struct scsi_device *sdev) 2599 { 2600 /* check if the device state was mutated prior to resume, and if 2601 * so assume the state is being managed elsewhere (for example 2602 * device deleted during suspend) 2603 */ 2604 mutex_lock(&sdev->state_mutex); 2605 if (sdev->sdev_state == SDEV_QUIESCE) 2606 scsi_device_set_state(sdev, SDEV_RUNNING); 2607 if (sdev->quiesced_by) { 2608 sdev->quiesced_by = NULL; 2609 blk_clear_pm_only(sdev->request_queue); 2610 } 2611 mutex_unlock(&sdev->state_mutex); 2612 } 2613 EXPORT_SYMBOL(scsi_device_resume); 2614 2615 static void 2616 device_quiesce_fn(struct scsi_device *sdev, void *data) 2617 { 2618 scsi_device_quiesce(sdev); 2619 } 2620 2621 void 2622 scsi_target_quiesce(struct scsi_target *starget) 2623 { 2624 starget_for_each_device(starget, NULL, device_quiesce_fn); 2625 } 2626 EXPORT_SYMBOL(scsi_target_quiesce); 2627 2628 static void 2629 device_resume_fn(struct scsi_device *sdev, void *data) 2630 { 2631 scsi_device_resume(sdev); 2632 } 2633 2634 void 2635 scsi_target_resume(struct scsi_target *starget) 2636 { 2637 starget_for_each_device(starget, NULL, device_resume_fn); 2638 } 2639 EXPORT_SYMBOL(scsi_target_resume); 2640 2641 /** 2642 * scsi_internal_device_block_nowait - try to transition to the SDEV_BLOCK state 2643 * @sdev: device to block 2644 * 2645 * Pause SCSI command processing on the specified device. Does not sleep. 2646 * 2647 * Returns zero if successful or a negative error code upon failure. 2648 * 2649 * Notes: 2650 * This routine transitions the device to the SDEV_BLOCK state (which must be 2651 * a legal transition). When the device is in this state, command processing 2652 * is paused until the device leaves the SDEV_BLOCK state. See also 2653 * scsi_internal_device_unblock_nowait(). 2654 */ 2655 int scsi_internal_device_block_nowait(struct scsi_device *sdev) 2656 { 2657 struct request_queue *q = sdev->request_queue; 2658 int err = 0; 2659 2660 err = scsi_device_set_state(sdev, SDEV_BLOCK); 2661 if (err) { 2662 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK); 2663 2664 if (err) 2665 return err; 2666 } 2667 2668 /* 2669 * The device has transitioned to SDEV_BLOCK. Stop the 2670 * block layer from calling the midlayer with this device's 2671 * request queue. 2672 */ 2673 blk_mq_quiesce_queue_nowait(q); 2674 return 0; 2675 } 2676 EXPORT_SYMBOL_GPL(scsi_internal_device_block_nowait); 2677 2678 /** 2679 * scsi_internal_device_block - try to transition to the SDEV_BLOCK state 2680 * @sdev: device to block 2681 * 2682 * Pause SCSI command processing on the specified device and wait until all 2683 * ongoing scsi_request_fn() / scsi_queue_rq() calls have finished. May sleep. 2684 * 2685 * Returns zero if successful or a negative error code upon failure. 2686 * 2687 * Note: 2688 * This routine transitions the device to the SDEV_BLOCK state (which must be 2689 * a legal transition). When the device is in this state, command processing 2690 * is paused until the device leaves the SDEV_BLOCK state. See also 2691 * scsi_internal_device_unblock(). 2692 */ 2693 static int scsi_internal_device_block(struct scsi_device *sdev) 2694 { 2695 struct request_queue *q = sdev->request_queue; 2696 int err; 2697 2698 mutex_lock(&sdev->state_mutex); 2699 err = scsi_internal_device_block_nowait(sdev); 2700 if (err == 0) 2701 blk_mq_quiesce_queue(q); 2702 mutex_unlock(&sdev->state_mutex); 2703 2704 return err; 2705 } 2706 2707 void scsi_start_queue(struct scsi_device *sdev) 2708 { 2709 struct request_queue *q = sdev->request_queue; 2710 2711 blk_mq_unquiesce_queue(q); 2712 } 2713 2714 /** 2715 * scsi_internal_device_unblock_nowait - resume a device after a block request 2716 * @sdev: device to resume 2717 * @new_state: state to set the device to after unblocking 2718 * 2719 * Restart the device queue for a previously suspended SCSI device. Does not 2720 * sleep. 2721 * 2722 * Returns zero if successful or a negative error code upon failure. 2723 * 2724 * Notes: 2725 * This routine transitions the device to the SDEV_RUNNING state or to one of 2726 * the offline states (which must be a legal transition) allowing the midlayer 2727 * to goose the queue for this device. 2728 */ 2729 int scsi_internal_device_unblock_nowait(struct scsi_device *sdev, 2730 enum scsi_device_state new_state) 2731 { 2732 switch (new_state) { 2733 case SDEV_RUNNING: 2734 case SDEV_TRANSPORT_OFFLINE: 2735 break; 2736 default: 2737 return -EINVAL; 2738 } 2739 2740 /* 2741 * Try to transition the scsi device to SDEV_RUNNING or one of the 2742 * offlined states and goose the device queue if successful. 2743 */ 2744 switch (sdev->sdev_state) { 2745 case SDEV_BLOCK: 2746 case SDEV_TRANSPORT_OFFLINE: 2747 sdev->sdev_state = new_state; 2748 break; 2749 case SDEV_CREATED_BLOCK: 2750 if (new_state == SDEV_TRANSPORT_OFFLINE || 2751 new_state == SDEV_OFFLINE) 2752 sdev->sdev_state = new_state; 2753 else 2754 sdev->sdev_state = SDEV_CREATED; 2755 break; 2756 case SDEV_CANCEL: 2757 case SDEV_OFFLINE: 2758 break; 2759 default: 2760 return -EINVAL; 2761 } 2762 scsi_start_queue(sdev); 2763 2764 return 0; 2765 } 2766 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock_nowait); 2767 2768 /** 2769 * scsi_internal_device_unblock - resume a device after a block request 2770 * @sdev: device to resume 2771 * @new_state: state to set the device to after unblocking 2772 * 2773 * Restart the device queue for a previously suspended SCSI device. May sleep. 2774 * 2775 * Returns zero if successful or a negative error code upon failure. 2776 * 2777 * Notes: 2778 * This routine transitions the device to the SDEV_RUNNING state or to one of 2779 * the offline states (which must be a legal transition) allowing the midlayer 2780 * to goose the queue for this device. 2781 */ 2782 static int scsi_internal_device_unblock(struct scsi_device *sdev, 2783 enum scsi_device_state new_state) 2784 { 2785 int ret; 2786 2787 mutex_lock(&sdev->state_mutex); 2788 ret = scsi_internal_device_unblock_nowait(sdev, new_state); 2789 mutex_unlock(&sdev->state_mutex); 2790 2791 return ret; 2792 } 2793 2794 static void 2795 device_block(struct scsi_device *sdev, void *data) 2796 { 2797 int ret; 2798 2799 ret = scsi_internal_device_block(sdev); 2800 2801 WARN_ONCE(ret, "scsi_internal_device_block(%s) failed: ret = %d\n", 2802 dev_name(&sdev->sdev_gendev), ret); 2803 } 2804 2805 static int 2806 target_block(struct device *dev, void *data) 2807 { 2808 if (scsi_is_target_device(dev)) 2809 starget_for_each_device(to_scsi_target(dev), NULL, 2810 device_block); 2811 return 0; 2812 } 2813 2814 void 2815 scsi_target_block(struct device *dev) 2816 { 2817 if (scsi_is_target_device(dev)) 2818 starget_for_each_device(to_scsi_target(dev), NULL, 2819 device_block); 2820 else 2821 device_for_each_child(dev, NULL, target_block); 2822 } 2823 EXPORT_SYMBOL_GPL(scsi_target_block); 2824 2825 static void 2826 device_unblock(struct scsi_device *sdev, void *data) 2827 { 2828 scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data); 2829 } 2830 2831 static int 2832 target_unblock(struct device *dev, void *data) 2833 { 2834 if (scsi_is_target_device(dev)) 2835 starget_for_each_device(to_scsi_target(dev), data, 2836 device_unblock); 2837 return 0; 2838 } 2839 2840 void 2841 scsi_target_unblock(struct device *dev, enum scsi_device_state new_state) 2842 { 2843 if (scsi_is_target_device(dev)) 2844 starget_for_each_device(to_scsi_target(dev), &new_state, 2845 device_unblock); 2846 else 2847 device_for_each_child(dev, &new_state, target_unblock); 2848 } 2849 EXPORT_SYMBOL_GPL(scsi_target_unblock); 2850 2851 int 2852 scsi_host_block(struct Scsi_Host *shost) 2853 { 2854 struct scsi_device *sdev; 2855 int ret = 0; 2856 2857 /* 2858 * Call scsi_internal_device_block_nowait so we can avoid 2859 * calling synchronize_rcu() for each LUN. 2860 */ 2861 shost_for_each_device(sdev, shost) { 2862 mutex_lock(&sdev->state_mutex); 2863 ret = scsi_internal_device_block_nowait(sdev); 2864 mutex_unlock(&sdev->state_mutex); 2865 if (ret) { 2866 scsi_device_put(sdev); 2867 break; 2868 } 2869 } 2870 2871 /* 2872 * SCSI never enables blk-mq's BLK_MQ_F_BLOCKING flag so 2873 * calling synchronize_rcu() once is enough. 2874 */ 2875 WARN_ON_ONCE(shost->tag_set.flags & BLK_MQ_F_BLOCKING); 2876 2877 if (!ret) 2878 synchronize_rcu(); 2879 2880 return ret; 2881 } 2882 EXPORT_SYMBOL_GPL(scsi_host_block); 2883 2884 int 2885 scsi_host_unblock(struct Scsi_Host *shost, int new_state) 2886 { 2887 struct scsi_device *sdev; 2888 int ret = 0; 2889 2890 shost_for_each_device(sdev, shost) { 2891 ret = scsi_internal_device_unblock(sdev, new_state); 2892 if (ret) { 2893 scsi_device_put(sdev); 2894 break; 2895 } 2896 } 2897 return ret; 2898 } 2899 EXPORT_SYMBOL_GPL(scsi_host_unblock); 2900 2901 /** 2902 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt 2903 * @sgl: scatter-gather list 2904 * @sg_count: number of segments in sg 2905 * @offset: offset in bytes into sg, on return offset into the mapped area 2906 * @len: bytes to map, on return number of bytes mapped 2907 * 2908 * Returns virtual address of the start of the mapped page 2909 */ 2910 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count, 2911 size_t *offset, size_t *len) 2912 { 2913 int i; 2914 size_t sg_len = 0, len_complete = 0; 2915 struct scatterlist *sg; 2916 struct page *page; 2917 2918 WARN_ON(!irqs_disabled()); 2919 2920 for_each_sg(sgl, sg, sg_count, i) { 2921 len_complete = sg_len; /* Complete sg-entries */ 2922 sg_len += sg->length; 2923 if (sg_len > *offset) 2924 break; 2925 } 2926 2927 if (unlikely(i == sg_count)) { 2928 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, " 2929 "elements %d\n", 2930 __func__, sg_len, *offset, sg_count); 2931 WARN_ON(1); 2932 return NULL; 2933 } 2934 2935 /* Offset starting from the beginning of first page in this sg-entry */ 2936 *offset = *offset - len_complete + sg->offset; 2937 2938 /* Assumption: contiguous pages can be accessed as "page + i" */ 2939 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT)); 2940 *offset &= ~PAGE_MASK; 2941 2942 /* Bytes in this sg-entry from *offset to the end of the page */ 2943 sg_len = PAGE_SIZE - *offset; 2944 if (*len > sg_len) 2945 *len = sg_len; 2946 2947 return kmap_atomic(page); 2948 } 2949 EXPORT_SYMBOL(scsi_kmap_atomic_sg); 2950 2951 /** 2952 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg 2953 * @virt: virtual address to be unmapped 2954 */ 2955 void scsi_kunmap_atomic_sg(void *virt) 2956 { 2957 kunmap_atomic(virt); 2958 } 2959 EXPORT_SYMBOL(scsi_kunmap_atomic_sg); 2960 2961 void sdev_disable_disk_events(struct scsi_device *sdev) 2962 { 2963 atomic_inc(&sdev->disk_events_disable_depth); 2964 } 2965 EXPORT_SYMBOL(sdev_disable_disk_events); 2966 2967 void sdev_enable_disk_events(struct scsi_device *sdev) 2968 { 2969 if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0)) 2970 return; 2971 atomic_dec(&sdev->disk_events_disable_depth); 2972 } 2973 EXPORT_SYMBOL(sdev_enable_disk_events); 2974 2975 static unsigned char designator_prio(const unsigned char *d) 2976 { 2977 if (d[1] & 0x30) 2978 /* not associated with LUN */ 2979 return 0; 2980 2981 if (d[3] == 0) 2982 /* invalid length */ 2983 return 0; 2984 2985 /* 2986 * Order of preference for lun descriptor: 2987 * - SCSI name string 2988 * - NAA IEEE Registered Extended 2989 * - EUI-64 based 16-byte 2990 * - EUI-64 based 12-byte 2991 * - NAA IEEE Registered 2992 * - NAA IEEE Extended 2993 * - EUI-64 based 8-byte 2994 * - SCSI name string (truncated) 2995 * - T10 Vendor ID 2996 * as longer descriptors reduce the likelyhood 2997 * of identification clashes. 2998 */ 2999 3000 switch (d[1] & 0xf) { 3001 case 8: 3002 /* SCSI name string, variable-length UTF-8 */ 3003 return 9; 3004 case 3: 3005 switch (d[4] >> 4) { 3006 case 6: 3007 /* NAA registered extended */ 3008 return 8; 3009 case 5: 3010 /* NAA registered */ 3011 return 5; 3012 case 4: 3013 /* NAA extended */ 3014 return 4; 3015 case 3: 3016 /* NAA locally assigned */ 3017 return 1; 3018 default: 3019 break; 3020 } 3021 break; 3022 case 2: 3023 switch (d[3]) { 3024 case 16: 3025 /* EUI64-based, 16 byte */ 3026 return 7; 3027 case 12: 3028 /* EUI64-based, 12 byte */ 3029 return 6; 3030 case 8: 3031 /* EUI64-based, 8 byte */ 3032 return 3; 3033 default: 3034 break; 3035 } 3036 break; 3037 case 1: 3038 /* T10 vendor ID */ 3039 return 1; 3040 default: 3041 break; 3042 } 3043 3044 return 0; 3045 } 3046 3047 /** 3048 * scsi_vpd_lun_id - return a unique device identification 3049 * @sdev: SCSI device 3050 * @id: buffer for the identification 3051 * @id_len: length of the buffer 3052 * 3053 * Copies a unique device identification into @id based 3054 * on the information in the VPD page 0x83 of the device. 3055 * The string will be formatted as a SCSI name string. 3056 * 3057 * Returns the length of the identification or error on failure. 3058 * If the identifier is longer than the supplied buffer the actual 3059 * identifier length is returned and the buffer is not zero-padded. 3060 */ 3061 int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len) 3062 { 3063 u8 cur_id_prio = 0; 3064 u8 cur_id_size = 0; 3065 const unsigned char *d, *cur_id_str; 3066 const struct scsi_vpd *vpd_pg83; 3067 int id_size = -EINVAL; 3068 3069 rcu_read_lock(); 3070 vpd_pg83 = rcu_dereference(sdev->vpd_pg83); 3071 if (!vpd_pg83) { 3072 rcu_read_unlock(); 3073 return -ENXIO; 3074 } 3075 3076 /* The id string must be at least 20 bytes + terminating NULL byte */ 3077 if (id_len < 21) { 3078 rcu_read_unlock(); 3079 return -EINVAL; 3080 } 3081 3082 memset(id, 0, id_len); 3083 for (d = vpd_pg83->data + 4; 3084 d < vpd_pg83->data + vpd_pg83->len; 3085 d += d[3] + 4) { 3086 u8 prio = designator_prio(d); 3087 3088 if (prio == 0 || cur_id_prio > prio) 3089 continue; 3090 3091 switch (d[1] & 0xf) { 3092 case 0x1: 3093 /* T10 Vendor ID */ 3094 if (cur_id_size > d[3]) 3095 break; 3096 cur_id_prio = prio; 3097 cur_id_size = d[3]; 3098 if (cur_id_size + 4 > id_len) 3099 cur_id_size = id_len - 4; 3100 cur_id_str = d + 4; 3101 id_size = snprintf(id, id_len, "t10.%*pE", 3102 cur_id_size, cur_id_str); 3103 break; 3104 case 0x2: 3105 /* EUI-64 */ 3106 cur_id_prio = prio; 3107 cur_id_size = d[3]; 3108 cur_id_str = d + 4; 3109 switch (cur_id_size) { 3110 case 8: 3111 id_size = snprintf(id, id_len, 3112 "eui.%8phN", 3113 cur_id_str); 3114 break; 3115 case 12: 3116 id_size = snprintf(id, id_len, 3117 "eui.%12phN", 3118 cur_id_str); 3119 break; 3120 case 16: 3121 id_size = snprintf(id, id_len, 3122 "eui.%16phN", 3123 cur_id_str); 3124 break; 3125 default: 3126 break; 3127 } 3128 break; 3129 case 0x3: 3130 /* NAA */ 3131 cur_id_prio = prio; 3132 cur_id_size = d[3]; 3133 cur_id_str = d + 4; 3134 switch (cur_id_size) { 3135 case 8: 3136 id_size = snprintf(id, id_len, 3137 "naa.%8phN", 3138 cur_id_str); 3139 break; 3140 case 16: 3141 id_size = snprintf(id, id_len, 3142 "naa.%16phN", 3143 cur_id_str); 3144 break; 3145 default: 3146 break; 3147 } 3148 break; 3149 case 0x8: 3150 /* SCSI name string */ 3151 if (cur_id_size > d[3]) 3152 break; 3153 /* Prefer others for truncated descriptor */ 3154 if (d[3] > id_len) { 3155 prio = 2; 3156 if (cur_id_prio > prio) 3157 break; 3158 } 3159 cur_id_prio = prio; 3160 cur_id_size = id_size = d[3]; 3161 cur_id_str = d + 4; 3162 if (cur_id_size >= id_len) 3163 cur_id_size = id_len - 1; 3164 memcpy(id, cur_id_str, cur_id_size); 3165 break; 3166 default: 3167 break; 3168 } 3169 } 3170 rcu_read_unlock(); 3171 3172 return id_size; 3173 } 3174 EXPORT_SYMBOL(scsi_vpd_lun_id); 3175 3176 /* 3177 * scsi_vpd_tpg_id - return a target port group identifier 3178 * @sdev: SCSI device 3179 * 3180 * Returns the Target Port Group identifier from the information 3181 * froom VPD page 0x83 of the device. 3182 * 3183 * Returns the identifier or error on failure. 3184 */ 3185 int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id) 3186 { 3187 const unsigned char *d; 3188 const struct scsi_vpd *vpd_pg83; 3189 int group_id = -EAGAIN, rel_port = -1; 3190 3191 rcu_read_lock(); 3192 vpd_pg83 = rcu_dereference(sdev->vpd_pg83); 3193 if (!vpd_pg83) { 3194 rcu_read_unlock(); 3195 return -ENXIO; 3196 } 3197 3198 d = vpd_pg83->data + 4; 3199 while (d < vpd_pg83->data + vpd_pg83->len) { 3200 switch (d[1] & 0xf) { 3201 case 0x4: 3202 /* Relative target port */ 3203 rel_port = get_unaligned_be16(&d[6]); 3204 break; 3205 case 0x5: 3206 /* Target port group */ 3207 group_id = get_unaligned_be16(&d[6]); 3208 break; 3209 default: 3210 break; 3211 } 3212 d += d[3] + 4; 3213 } 3214 rcu_read_unlock(); 3215 3216 if (group_id >= 0 && rel_id && rel_port != -1) 3217 *rel_id = rel_port; 3218 3219 return group_id; 3220 } 3221 EXPORT_SYMBOL(scsi_vpd_tpg_id); 3222 3223 /** 3224 * scsi_build_sense - build sense data for a command 3225 * @scmd: scsi command for which the sense should be formatted 3226 * @desc: Sense format (non-zero == descriptor format, 3227 * 0 == fixed format) 3228 * @key: Sense key 3229 * @asc: Additional sense code 3230 * @ascq: Additional sense code qualifier 3231 * 3232 **/ 3233 void scsi_build_sense(struct scsi_cmnd *scmd, int desc, u8 key, u8 asc, u8 ascq) 3234 { 3235 scsi_build_sense_buffer(desc, scmd->sense_buffer, key, asc, ascq); 3236 scmd->result = SAM_STAT_CHECK_CONDITION; 3237 } 3238 EXPORT_SYMBOL_GPL(scsi_build_sense); 3239