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