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