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