1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 1999 Eric Youngdale
4 * Copyright (C) 2014 Christoph Hellwig
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.
12 #include <linux/bio.h>
13 #include <linux/bitops.h>
14 #include <linux/blkdev.h>
15 #include <linux/completion.h>
16 #include <linux/kernel.h>
17 #include <linux/export.h>
18 #include <linux/init.h>
19 #include <linux/pci.h>
20 #include <linux/delay.h>
21 #include <linux/hardirq.h>
22 #include <linux/scatterlist.h>
23 #include <linux/blk-mq.h>
24 #include <linux/ratelimit.h>
25 #include <asm/unaligned.h>
27 #include <scsi/scsi.h>
28 #include <scsi/scsi_cmnd.h>
29 #include <scsi/scsi_dbg.h>
30 #include <scsi/scsi_device.h>
31 #include <scsi/scsi_driver.h>
32 #include <scsi/scsi_eh.h>
33 #include <scsi/scsi_host.h>
34 #include <scsi/scsi_transport.h> /* __scsi_init_queue() */
35 #include <scsi/scsi_dh.h>
37 #include <trace/events/scsi.h>
39 #include "scsi_debugfs.h"
40 #include "scsi_priv.h"
41 #include "scsi_logging.h"
44 * Size of integrity metadata is usually small, 1 inline sg should
47 #ifdef CONFIG_ARCH_NO_SG_CHAIN
48 #define SCSI_INLINE_PROT_SG_CNT 0
49 #define SCSI_INLINE_SG_CNT 0
51 #define SCSI_INLINE_PROT_SG_CNT 1
52 #define SCSI_INLINE_SG_CNT 2
55 static struct kmem_cache *scsi_sense_cache;
56 static DEFINE_MUTEX(scsi_sense_cache_mutex);
58 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd);
60 int scsi_init_sense_cache(struct Scsi_Host *shost)
64 mutex_lock(&scsi_sense_cache_mutex);
65 if (!scsi_sense_cache) {
67 kmem_cache_create_usercopy("scsi_sense_cache",
68 SCSI_SENSE_BUFFERSIZE, 0, SLAB_HWCACHE_ALIGN,
69 0, SCSI_SENSE_BUFFERSIZE, NULL);
70 if (!scsi_sense_cache)
73 mutex_unlock(&scsi_sense_cache_mutex);
78 * When to reinvoke queueing after a resource shortage. It's 3 msecs to
79 * not change behaviour from the previous unplug mechanism, experimentation
80 * may prove this needs changing.
82 #define SCSI_QUEUE_DELAY 3
85 scsi_set_blocked(struct scsi_cmnd *cmd, int reason)
87 struct Scsi_Host *host = cmd->device->host;
88 struct scsi_device *device = cmd->device;
89 struct scsi_target *starget = scsi_target(device);
92 * Set the appropriate busy bit for the device/host.
94 * If the host/device isn't busy, assume that something actually
95 * completed, and that we should be able to queue a command now.
97 * Note that the prior mid-layer assumption that any host could
98 * always queue at least one command is now broken. The mid-layer
99 * will implement a user specifiable stall (see
100 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
101 * if a command is requeued with no other commands outstanding
102 * either for the device or for the host.
105 case SCSI_MLQUEUE_HOST_BUSY:
106 atomic_set(&host->host_blocked, host->max_host_blocked);
108 case SCSI_MLQUEUE_DEVICE_BUSY:
109 case SCSI_MLQUEUE_EH_RETRY:
110 atomic_set(&device->device_blocked,
111 device->max_device_blocked);
113 case SCSI_MLQUEUE_TARGET_BUSY:
114 atomic_set(&starget->target_blocked,
115 starget->max_target_blocked);
120 static void scsi_mq_requeue_cmd(struct scsi_cmnd *cmd)
122 struct request *rq = scsi_cmd_to_rq(cmd);
124 if (rq->rq_flags & RQF_DONTPREP) {
125 rq->rq_flags &= ~RQF_DONTPREP;
126 scsi_mq_uninit_cmd(cmd);
130 blk_mq_requeue_request(rq, true);
134 * __scsi_queue_insert - private queue insertion
135 * @cmd: The SCSI command being requeued
136 * @reason: The reason for the requeue
137 * @unbusy: Whether the queue should be unbusied
139 * This is a private queue insertion. The public interface
140 * scsi_queue_insert() always assumes the queue should be unbusied
141 * because it's always called before the completion. This function is
142 * for a requeue after completion, which should only occur in this
145 static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, bool unbusy)
147 struct scsi_device *device = cmd->device;
149 SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd,
150 "Inserting command %p into mlqueue\n", cmd));
152 scsi_set_blocked(cmd, reason);
155 * Decrement the counters, since these commands are no longer
156 * active on the host/device.
159 scsi_device_unbusy(device, cmd);
162 * Requeue this command. It will go before all other commands
163 * that are already in the queue. Schedule requeue work under
164 * lock such that the kblockd_schedule_work() call happens
165 * before blk_cleanup_queue() finishes.
169 blk_mq_requeue_request(scsi_cmd_to_rq(cmd), true);
173 * scsi_queue_insert - Reinsert a command in the queue.
174 * @cmd: command that we are adding to queue.
175 * @reason: why we are inserting command to queue.
177 * We do this for one of two cases. Either the host is busy and it cannot accept
178 * any more commands for the time being, or the device returned QUEUE_FULL and
179 * can accept no more commands.
181 * Context: This could be called either from an interrupt context or a normal
184 void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
186 __scsi_queue_insert(cmd, reason, true);
191 * __scsi_execute - insert request and wait for the result
194 * @data_direction: data direction
195 * @buffer: data buffer
196 * @bufflen: len of buffer
197 * @sense: optional sense buffer
198 * @sshdr: optional decoded sense header
199 * @timeout: request timeout in HZ
200 * @retries: number of times to retry request
201 * @flags: flags for ->cmd_flags
202 * @rq_flags: flags for ->rq_flags
203 * @resid: optional residual length
205 * Returns the scsi_cmnd result field if a command was executed, or a negative
206 * Linux error code if we didn't get that far.
208 int __scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
209 int data_direction, void *buffer, unsigned bufflen,
210 unsigned char *sense, struct scsi_sense_hdr *sshdr,
211 int timeout, int retries, u64 flags, req_flags_t rq_flags,
215 struct scsi_request *rq;
218 req = blk_get_request(sdev->request_queue,
219 data_direction == DMA_TO_DEVICE ?
220 REQ_OP_DRV_OUT : REQ_OP_DRV_IN,
221 rq_flags & RQF_PM ? BLK_MQ_REQ_PM : 0);
228 ret = blk_rq_map_kern(sdev->request_queue, req,
229 buffer, bufflen, GFP_NOIO);
233 rq->cmd_len = COMMAND_SIZE(cmd[0]);
234 memcpy(rq->cmd, cmd, rq->cmd_len);
235 rq->retries = retries;
236 req->timeout = timeout;
237 req->cmd_flags |= flags;
238 req->rq_flags |= rq_flags | RQF_QUIET;
241 * head injection *required* here otherwise quiesce won't work
243 blk_execute_rq(NULL, req, 1);
246 * Some devices (USB mass-storage in particular) may transfer
247 * garbage data together with a residue indicating that the data
248 * is invalid. Prevent the garbage from being misinterpreted
249 * and prevent security leaks by zeroing out the excess data.
251 if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen))
252 memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len);
255 *resid = rq->resid_len;
256 if (sense && rq->sense_len)
257 memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE);
259 scsi_normalize_sense(rq->sense, rq->sense_len, sshdr);
262 blk_put_request(req);
266 EXPORT_SYMBOL(__scsi_execute);
269 * Wake up the error handler if necessary. Avoid as follows that the error
270 * handler is not woken up if host in-flight requests number ==
271 * shost->host_failed: use call_rcu() in scsi_eh_scmd_add() in combination
272 * with an RCU read lock in this function to ensure that this function in
273 * its entirety either finishes before scsi_eh_scmd_add() increases the
274 * host_failed counter or that it notices the shost state change made by
275 * scsi_eh_scmd_add().
277 static void scsi_dec_host_busy(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
282 __clear_bit(SCMD_STATE_INFLIGHT, &cmd->state);
283 if (unlikely(scsi_host_in_recovery(shost))) {
284 spin_lock_irqsave(shost->host_lock, flags);
285 if (shost->host_failed || shost->host_eh_scheduled)
286 scsi_eh_wakeup(shost);
287 spin_unlock_irqrestore(shost->host_lock, flags);
292 void scsi_device_unbusy(struct scsi_device *sdev, struct scsi_cmnd *cmd)
294 struct Scsi_Host *shost = sdev->host;
295 struct scsi_target *starget = scsi_target(sdev);
297 scsi_dec_host_busy(shost, cmd);
299 if (starget->can_queue > 0)
300 atomic_dec(&starget->target_busy);
302 sbitmap_put(&sdev->budget_map, cmd->budget_token);
303 cmd->budget_token = -1;
306 static void scsi_kick_queue(struct request_queue *q)
308 blk_mq_run_hw_queues(q, false);
312 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
313 * and call blk_run_queue for all the scsi_devices on the target -
314 * including current_sdev first.
316 * Called with *no* scsi locks held.
318 static void scsi_single_lun_run(struct scsi_device *current_sdev)
320 struct Scsi_Host *shost = current_sdev->host;
321 struct scsi_device *sdev, *tmp;
322 struct scsi_target *starget = scsi_target(current_sdev);
325 spin_lock_irqsave(shost->host_lock, flags);
326 starget->starget_sdev_user = NULL;
327 spin_unlock_irqrestore(shost->host_lock, flags);
330 * Call blk_run_queue for all LUNs on the target, starting with
331 * current_sdev. We race with others (to set starget_sdev_user),
332 * but in most cases, we will be first. Ideally, each LU on the
333 * target would get some limited time or requests on the target.
335 scsi_kick_queue(current_sdev->request_queue);
337 spin_lock_irqsave(shost->host_lock, flags);
338 if (starget->starget_sdev_user)
340 list_for_each_entry_safe(sdev, tmp, &starget->devices,
341 same_target_siblings) {
342 if (sdev == current_sdev)
344 if (scsi_device_get(sdev))
347 spin_unlock_irqrestore(shost->host_lock, flags);
348 scsi_kick_queue(sdev->request_queue);
349 spin_lock_irqsave(shost->host_lock, flags);
351 scsi_device_put(sdev);
354 spin_unlock_irqrestore(shost->host_lock, flags);
357 static inline bool scsi_device_is_busy(struct scsi_device *sdev)
359 if (scsi_device_busy(sdev) >= sdev->queue_depth)
361 if (atomic_read(&sdev->device_blocked) > 0)
366 static inline bool scsi_target_is_busy(struct scsi_target *starget)
368 if (starget->can_queue > 0) {
369 if (atomic_read(&starget->target_busy) >= starget->can_queue)
371 if (atomic_read(&starget->target_blocked) > 0)
377 static inline bool scsi_host_is_busy(struct Scsi_Host *shost)
379 if (atomic_read(&shost->host_blocked) > 0)
381 if (shost->host_self_blocked)
386 static void scsi_starved_list_run(struct Scsi_Host *shost)
388 LIST_HEAD(starved_list);
389 struct scsi_device *sdev;
392 spin_lock_irqsave(shost->host_lock, flags);
393 list_splice_init(&shost->starved_list, &starved_list);
395 while (!list_empty(&starved_list)) {
396 struct request_queue *slq;
399 * As long as shost is accepting commands and we have
400 * starved queues, call blk_run_queue. scsi_request_fn
401 * drops the queue_lock and can add us back to the
404 * host_lock protects the starved_list and starved_entry.
405 * scsi_request_fn must get the host_lock before checking
406 * or modifying starved_list or starved_entry.
408 if (scsi_host_is_busy(shost))
411 sdev = list_entry(starved_list.next,
412 struct scsi_device, starved_entry);
413 list_del_init(&sdev->starved_entry);
414 if (scsi_target_is_busy(scsi_target(sdev))) {
415 list_move_tail(&sdev->starved_entry,
416 &shost->starved_list);
421 * Once we drop the host lock, a racing scsi_remove_device()
422 * call may remove the sdev from the starved list and destroy
423 * it and the queue. Mitigate by taking a reference to the
424 * queue and never touching the sdev again after we drop the
425 * host lock. Note: if __scsi_remove_device() invokes
426 * blk_cleanup_queue() before the queue is run from this
427 * function then blk_run_queue() will return immediately since
428 * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
430 slq = sdev->request_queue;
431 if (!blk_get_queue(slq))
433 spin_unlock_irqrestore(shost->host_lock, flags);
435 scsi_kick_queue(slq);
438 spin_lock_irqsave(shost->host_lock, flags);
440 /* put any unprocessed entries back */
441 list_splice(&starved_list, &shost->starved_list);
442 spin_unlock_irqrestore(shost->host_lock, flags);
446 * scsi_run_queue - Select a proper request queue to serve next.
447 * @q: last request's queue
449 * The previous command was completely finished, start a new one if possible.
451 static void scsi_run_queue(struct request_queue *q)
453 struct scsi_device *sdev = q->queuedata;
455 if (scsi_target(sdev)->single_lun)
456 scsi_single_lun_run(sdev);
457 if (!list_empty(&sdev->host->starved_list))
458 scsi_starved_list_run(sdev->host);
460 blk_mq_run_hw_queues(q, false);
463 void scsi_requeue_run_queue(struct work_struct *work)
465 struct scsi_device *sdev;
466 struct request_queue *q;
468 sdev = container_of(work, struct scsi_device, requeue_work);
469 q = sdev->request_queue;
473 void scsi_run_host_queues(struct Scsi_Host *shost)
475 struct scsi_device *sdev;
477 shost_for_each_device(sdev, shost)
478 scsi_run_queue(sdev->request_queue);
481 static void scsi_uninit_cmd(struct scsi_cmnd *cmd)
483 if (!blk_rq_is_passthrough(scsi_cmd_to_rq(cmd))) {
484 struct scsi_driver *drv = scsi_cmd_to_driver(cmd);
486 if (drv->uninit_command)
487 drv->uninit_command(cmd);
491 void scsi_free_sgtables(struct scsi_cmnd *cmd)
493 if (cmd->sdb.table.nents)
494 sg_free_table_chained(&cmd->sdb.table,
496 if (scsi_prot_sg_count(cmd))
497 sg_free_table_chained(&cmd->prot_sdb->table,
498 SCSI_INLINE_PROT_SG_CNT);
500 EXPORT_SYMBOL_GPL(scsi_free_sgtables);
502 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd)
504 scsi_free_sgtables(cmd);
505 scsi_uninit_cmd(cmd);
508 static void scsi_run_queue_async(struct scsi_device *sdev)
510 if (scsi_target(sdev)->single_lun ||
511 !list_empty(&sdev->host->starved_list)) {
512 kblockd_schedule_work(&sdev->requeue_work);
515 * smp_mb() present in sbitmap_queue_clear() or implied in
516 * .end_io is for ordering writing .device_busy in
517 * scsi_device_unbusy() and reading sdev->restarts.
519 int old = atomic_read(&sdev->restarts);
522 * ->restarts has to be kept as non-zero if new budget
525 * No need to run queue when either another re-run
526 * queue wins in updating ->restarts or a new budget
529 if (old && atomic_cmpxchg(&sdev->restarts, old, 0) == old)
530 blk_mq_run_hw_queues(sdev->request_queue, true);
534 /* Returns false when no more bytes to process, true if there are more */
535 static bool scsi_end_request(struct request *req, blk_status_t error,
538 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
539 struct scsi_device *sdev = cmd->device;
540 struct request_queue *q = sdev->request_queue;
542 if (blk_update_request(req, error, bytes))
545 if (blk_queue_add_random(q))
546 add_disk_randomness(req->rq_disk);
548 if (!blk_rq_is_passthrough(req)) {
549 WARN_ON_ONCE(!(cmd->flags & SCMD_INITIALIZED));
550 cmd->flags &= ~SCMD_INITIALIZED;
554 * Calling rcu_barrier() is not necessary here because the
555 * SCSI error handler guarantees that the function called by
556 * call_rcu() has been called before scsi_end_request() is
559 destroy_rcu_head(&cmd->rcu);
562 * In the MQ case the command gets freed by __blk_mq_end_request,
563 * so we have to do all cleanup that depends on it earlier.
565 * We also can't kick the queues from irq context, so we
566 * will have to defer it to a workqueue.
568 scsi_mq_uninit_cmd(cmd);
571 * queue is still alive, so grab the ref for preventing it
572 * from being cleaned up during running queue.
574 percpu_ref_get(&q->q_usage_counter);
576 __blk_mq_end_request(req, error);
578 scsi_run_queue_async(sdev);
580 percpu_ref_put(&q->q_usage_counter);
585 * scsi_result_to_blk_status - translate a SCSI result code into blk_status_t
587 * @result: scsi error code
589 * Translate a SCSI result code into a blk_status_t value. May reset the host
590 * byte of @cmd->result.
592 static blk_status_t scsi_result_to_blk_status(struct scsi_cmnd *cmd, int result)
594 switch (host_byte(result)) {
596 if (scsi_status_is_good(result))
598 return BLK_STS_IOERR;
599 case DID_TRANSPORT_FAILFAST:
600 case DID_TRANSPORT_MARGINAL:
601 return BLK_STS_TRANSPORT;
602 case DID_TARGET_FAILURE:
603 set_host_byte(cmd, DID_OK);
604 return BLK_STS_TARGET;
605 case DID_NEXUS_FAILURE:
606 set_host_byte(cmd, DID_OK);
607 return BLK_STS_NEXUS;
608 case DID_ALLOC_FAILURE:
609 set_host_byte(cmd, DID_OK);
610 return BLK_STS_NOSPC;
611 case DID_MEDIUM_ERROR:
612 set_host_byte(cmd, DID_OK);
613 return BLK_STS_MEDIUM;
615 return BLK_STS_IOERR;
619 /* Helper for scsi_io_completion() when "reprep" action required. */
620 static void scsi_io_completion_reprep(struct scsi_cmnd *cmd,
621 struct request_queue *q)
623 /* A new command will be prepared and issued. */
624 scsi_mq_requeue_cmd(cmd);
627 static bool scsi_cmd_runtime_exceeced(struct scsi_cmnd *cmd)
629 struct request *req = scsi_cmd_to_rq(cmd);
630 unsigned long wait_for;
632 if (cmd->allowed == SCSI_CMD_RETRIES_NO_LIMIT)
635 wait_for = (cmd->allowed + 1) * req->timeout;
636 if (time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
637 scmd_printk(KERN_ERR, cmd, "timing out command, waited %lus\n",
644 /* Helper for scsi_io_completion() when special action required. */
645 static void scsi_io_completion_action(struct scsi_cmnd *cmd, int result)
647 struct request_queue *q = cmd->device->request_queue;
648 struct request *req = scsi_cmd_to_rq(cmd);
650 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
651 ACTION_DELAYED_RETRY} action;
652 struct scsi_sense_hdr sshdr;
654 bool sense_current = true; /* false implies "deferred sense" */
655 blk_status_t blk_stat;
657 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
659 sense_current = !scsi_sense_is_deferred(&sshdr);
661 blk_stat = scsi_result_to_blk_status(cmd, result);
663 if (host_byte(result) == DID_RESET) {
664 /* Third party bus reset or reset for error recovery
665 * reasons. Just retry the command and see what
668 action = ACTION_RETRY;
669 } else if (sense_valid && sense_current) {
670 switch (sshdr.sense_key) {
672 if (cmd->device->removable) {
673 /* Detected disc change. Set a bit
674 * and quietly refuse further access.
676 cmd->device->changed = 1;
677 action = ACTION_FAIL;
679 /* Must have been a power glitch, or a
680 * bus reset. Could not have been a
681 * media change, so we just retry the
682 * command and see what happens.
684 action = ACTION_RETRY;
687 case ILLEGAL_REQUEST:
688 /* If we had an ILLEGAL REQUEST returned, then
689 * we may have performed an unsupported
690 * command. The only thing this should be
691 * would be a ten byte read where only a six
692 * byte read was supported. Also, on a system
693 * where READ CAPACITY failed, we may have
694 * read past the end of the disk.
696 if ((cmd->device->use_10_for_rw &&
697 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
698 (cmd->cmnd[0] == READ_10 ||
699 cmd->cmnd[0] == WRITE_10)) {
700 /* This will issue a new 6-byte command. */
701 cmd->device->use_10_for_rw = 0;
702 action = ACTION_REPREP;
703 } else if (sshdr.asc == 0x10) /* DIX */ {
704 action = ACTION_FAIL;
705 blk_stat = BLK_STS_PROTECTION;
706 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
707 } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
708 action = ACTION_FAIL;
709 blk_stat = BLK_STS_TARGET;
711 action = ACTION_FAIL;
713 case ABORTED_COMMAND:
714 action = ACTION_FAIL;
715 if (sshdr.asc == 0x10) /* DIF */
716 blk_stat = BLK_STS_PROTECTION;
719 /* If the device is in the process of becoming
720 * ready, or has a temporary blockage, retry.
722 if (sshdr.asc == 0x04) {
723 switch (sshdr.ascq) {
724 case 0x01: /* becoming ready */
725 case 0x04: /* format in progress */
726 case 0x05: /* rebuild in progress */
727 case 0x06: /* recalculation in progress */
728 case 0x07: /* operation in progress */
729 case 0x08: /* Long write in progress */
730 case 0x09: /* self test in progress */
731 case 0x11: /* notify (enable spinup) required */
732 case 0x14: /* space allocation in progress */
733 case 0x1a: /* start stop unit in progress */
734 case 0x1b: /* sanitize in progress */
735 case 0x1d: /* configuration in progress */
736 case 0x24: /* depopulation in progress */
737 action = ACTION_DELAYED_RETRY;
739 case 0x0a: /* ALUA state transition */
740 blk_stat = BLK_STS_AGAIN;
743 action = ACTION_FAIL;
747 action = ACTION_FAIL;
749 case VOLUME_OVERFLOW:
750 /* See SSC3rXX or current. */
751 action = ACTION_FAIL;
754 action = ACTION_FAIL;
755 if ((sshdr.asc == 0x0C && sshdr.ascq == 0x12) ||
756 (sshdr.asc == 0x55 &&
757 (sshdr.ascq == 0x0E || sshdr.ascq == 0x0F))) {
758 /* Insufficient zone resources */
759 blk_stat = BLK_STS_ZONE_OPEN_RESOURCE;
763 action = ACTION_FAIL;
767 action = ACTION_FAIL;
769 if (action != ACTION_FAIL && scsi_cmd_runtime_exceeced(cmd))
770 action = ACTION_FAIL;
774 /* Give up and fail the remainder of the request */
775 if (!(req->rq_flags & RQF_QUIET)) {
776 static DEFINE_RATELIMIT_STATE(_rs,
777 DEFAULT_RATELIMIT_INTERVAL,
778 DEFAULT_RATELIMIT_BURST);
780 if (unlikely(scsi_logging_level))
782 SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
783 SCSI_LOG_MLCOMPLETE_BITS);
786 * if logging is enabled the failure will be printed
787 * in scsi_log_completion(), so avoid duplicate messages
789 if (!level && __ratelimit(&_rs)) {
790 scsi_print_result(cmd, NULL, FAILED);
792 scsi_print_sense(cmd);
793 scsi_print_command(cmd);
796 if (!scsi_end_request(req, blk_stat, blk_rq_err_bytes(req)))
800 scsi_io_completion_reprep(cmd, q);
803 /* Retry the same command immediately */
804 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, false);
806 case ACTION_DELAYED_RETRY:
807 /* Retry the same command after a delay */
808 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, false);
814 * Helper for scsi_io_completion() when cmd->result is non-zero. Returns a
815 * new result that may suppress further error checking. Also modifies
816 * *blk_statp in some cases.
818 static int scsi_io_completion_nz_result(struct scsi_cmnd *cmd, int result,
819 blk_status_t *blk_statp)
822 bool sense_current = true; /* false implies "deferred sense" */
823 struct request *req = scsi_cmd_to_rq(cmd);
824 struct scsi_sense_hdr sshdr;
826 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
828 sense_current = !scsi_sense_is_deferred(&sshdr);
830 if (blk_rq_is_passthrough(req)) {
833 * SG_IO wants current and deferred errors
835 scsi_req(req)->sense_len =
836 min(8 + cmd->sense_buffer[7],
837 SCSI_SENSE_BUFFERSIZE);
840 *blk_statp = scsi_result_to_blk_status(cmd, result);
841 } else if (blk_rq_bytes(req) == 0 && sense_current) {
843 * Flush commands do not transfers any data, and thus cannot use
844 * good_bytes != blk_rq_bytes(req) as the signal for an error.
845 * This sets *blk_statp explicitly for the problem case.
847 *blk_statp = scsi_result_to_blk_status(cmd, result);
850 * Recovered errors need reporting, but they're always treated as
851 * success, so fiddle the result code here. For passthrough requests
852 * we already took a copy of the original into sreq->result which
853 * is what gets returned to the user
855 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
856 bool do_print = true;
858 * if ATA PASS-THROUGH INFORMATION AVAILABLE [0x0, 0x1d]
859 * skip print since caller wants ATA registers. Only occurs
860 * on SCSI ATA PASS_THROUGH commands when CK_COND=1
862 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
864 else if (req->rq_flags & RQF_QUIET)
867 scsi_print_sense(cmd);
869 /* for passthrough, *blk_statp may be set */
870 *blk_statp = BLK_STS_OK;
873 * Another corner case: the SCSI status byte is non-zero but 'good'.
874 * Example: PRE-FETCH command returns SAM_STAT_CONDITION_MET when
875 * it is able to fit nominated LBs in its cache (and SAM_STAT_GOOD
876 * if it can't fit). Treat SAM_STAT_CONDITION_MET and the related
877 * intermediate statuses (both obsolete in SAM-4) as good.
879 if ((result & 0xff) && scsi_status_is_good(result)) {
881 *blk_statp = BLK_STS_OK;
887 * scsi_io_completion - Completion processing for SCSI commands.
888 * @cmd: command that is finished.
889 * @good_bytes: number of processed bytes.
891 * We will finish off the specified number of sectors. If we are done, the
892 * command block will be released and the queue function will be goosed. If we
893 * are not done then we have to figure out what to do next:
895 * a) We can call scsi_io_completion_reprep(). The request will be
896 * unprepared and put back on the queue. Then a new command will
897 * be created for it. This should be used if we made forward
898 * progress, or if we want to switch from READ(10) to READ(6) for
901 * b) We can call scsi_io_completion_action(). The request will be
902 * put back on the queue and retried using the same command as
903 * before, possibly after a delay.
905 * c) We can call scsi_end_request() with blk_stat other than
906 * BLK_STS_OK, to fail the remainder of the request.
908 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
910 int result = cmd->result;
911 struct request_queue *q = cmd->device->request_queue;
912 struct request *req = scsi_cmd_to_rq(cmd);
913 blk_status_t blk_stat = BLK_STS_OK;
915 if (unlikely(result)) /* a nz result may or may not be an error */
916 result = scsi_io_completion_nz_result(cmd, result, &blk_stat);
918 if (unlikely(blk_rq_is_passthrough(req))) {
920 * scsi_result_to_blk_status may have reset the host_byte
922 scsi_req(req)->result = cmd->result;
926 * Next deal with any sectors which we were able to correctly
929 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd,
930 "%u sectors total, %d bytes done.\n",
931 blk_rq_sectors(req), good_bytes));
934 * Failed, zero length commands always need to drop down
935 * to retry code. Fast path should return in this block.
937 if (likely(blk_rq_bytes(req) > 0 || blk_stat == BLK_STS_OK)) {
938 if (likely(!scsi_end_request(req, blk_stat, good_bytes)))
939 return; /* no bytes remaining */
942 /* Kill remainder if no retries. */
943 if (unlikely(blk_stat && scsi_noretry_cmd(cmd))) {
944 if (scsi_end_request(req, blk_stat, blk_rq_bytes(req)))
946 "Bytes remaining after failed, no-retry command");
951 * If there had been no error, but we have leftover bytes in the
952 * requeues just queue the command up again.
954 if (likely(result == 0))
955 scsi_io_completion_reprep(cmd, q);
957 scsi_io_completion_action(cmd, result);
960 static inline bool scsi_cmd_needs_dma_drain(struct scsi_device *sdev,
963 return sdev->dma_drain_len && blk_rq_is_passthrough(rq) &&
964 !op_is_write(req_op(rq)) &&
965 sdev->host->hostt->dma_need_drain(rq);
969 * scsi_alloc_sgtables - Allocate and initialize data and integrity scatterlists
970 * @cmd: SCSI command data structure to initialize.
972 * Initializes @cmd->sdb and also @cmd->prot_sdb if data integrity is enabled
976 * * BLK_STS_OK - on success
977 * * BLK_STS_RESOURCE - if the failure is retryable
978 * * BLK_STS_IOERR - if the failure is fatal
980 blk_status_t scsi_alloc_sgtables(struct scsi_cmnd *cmd)
982 struct scsi_device *sdev = cmd->device;
983 struct request *rq = scsi_cmd_to_rq(cmd);
984 unsigned short nr_segs = blk_rq_nr_phys_segments(rq);
985 struct scatterlist *last_sg = NULL;
987 bool need_drain = scsi_cmd_needs_dma_drain(sdev, rq);
990 if (WARN_ON_ONCE(!nr_segs))
991 return BLK_STS_IOERR;
994 * Make sure there is space for the drain. The driver must adjust
995 * max_hw_segments to be prepared for this.
1001 * If sg table allocation fails, requeue request later.
1003 if (unlikely(sg_alloc_table_chained(&cmd->sdb.table, nr_segs,
1004 cmd->sdb.table.sgl, SCSI_INLINE_SG_CNT)))
1005 return BLK_STS_RESOURCE;
1008 * Next, walk the list, and fill in the addresses and sizes of
1011 count = __blk_rq_map_sg(rq->q, rq, cmd->sdb.table.sgl, &last_sg);
1013 if (blk_rq_bytes(rq) & rq->q->dma_pad_mask) {
1014 unsigned int pad_len =
1015 (rq->q->dma_pad_mask & ~blk_rq_bytes(rq)) + 1;
1017 last_sg->length += pad_len;
1018 cmd->extra_len += pad_len;
1022 sg_unmark_end(last_sg);
1023 last_sg = sg_next(last_sg);
1024 sg_set_buf(last_sg, sdev->dma_drain_buf, sdev->dma_drain_len);
1025 sg_mark_end(last_sg);
1027 cmd->extra_len += sdev->dma_drain_len;
1031 BUG_ON(count > cmd->sdb.table.nents);
1032 cmd->sdb.table.nents = count;
1033 cmd->sdb.length = blk_rq_payload_bytes(rq);
1035 if (blk_integrity_rq(rq)) {
1036 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1039 if (WARN_ON_ONCE(!prot_sdb)) {
1041 * This can happen if someone (e.g. multipath)
1042 * queues a command to a device on an adapter
1043 * that does not support DIX.
1045 ret = BLK_STS_IOERR;
1046 goto out_free_sgtables;
1049 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
1051 if (sg_alloc_table_chained(&prot_sdb->table, ivecs,
1052 prot_sdb->table.sgl,
1053 SCSI_INLINE_PROT_SG_CNT)) {
1054 ret = BLK_STS_RESOURCE;
1055 goto out_free_sgtables;
1058 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
1059 prot_sdb->table.sgl);
1060 BUG_ON(count > ivecs);
1061 BUG_ON(count > queue_max_integrity_segments(rq->q));
1063 cmd->prot_sdb = prot_sdb;
1064 cmd->prot_sdb->table.nents = count;
1069 scsi_free_sgtables(cmd);
1072 EXPORT_SYMBOL(scsi_alloc_sgtables);
1075 * scsi_initialize_rq - initialize struct scsi_cmnd partially
1076 * @rq: Request associated with the SCSI command to be initialized.
1078 * This function initializes the members of struct scsi_cmnd that must be
1079 * initialized before request processing starts and that won't be
1080 * reinitialized if a SCSI command is requeued.
1082 * Called from inside blk_get_request() for pass-through requests and from
1083 * inside scsi_init_command() for filesystem requests.
1085 static void scsi_initialize_rq(struct request *rq)
1087 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1088 struct scsi_request *req = &cmd->req;
1090 memset(req->__cmd, 0, sizeof(req->__cmd));
1091 req->cmd = req->__cmd;
1092 req->cmd_len = BLK_MAX_CDB;
1095 init_rcu_head(&cmd->rcu);
1096 cmd->jiffies_at_alloc = jiffies;
1101 * Only called when the request isn't completed by SCSI, and not freed by
1104 static void scsi_cleanup_rq(struct request *rq)
1106 if (rq->rq_flags & RQF_DONTPREP) {
1107 scsi_mq_uninit_cmd(blk_mq_rq_to_pdu(rq));
1108 rq->rq_flags &= ~RQF_DONTPREP;
1112 /* Called before a request is prepared. See also scsi_mq_prep_fn(). */
1113 void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd)
1115 void *buf = cmd->sense_buffer;
1116 void *prot = cmd->prot_sdb;
1117 struct request *rq = scsi_cmd_to_rq(cmd);
1118 unsigned int flags = cmd->flags & SCMD_PRESERVED_FLAGS;
1119 unsigned long jiffies_at_alloc;
1120 int retries, to_clear;
1122 int budget_token = cmd->budget_token;
1124 if (!blk_rq_is_passthrough(rq) && !(flags & SCMD_INITIALIZED)) {
1125 flags |= SCMD_INITIALIZED;
1126 scsi_initialize_rq(rq);
1129 jiffies_at_alloc = cmd->jiffies_at_alloc;
1130 retries = cmd->retries;
1131 in_flight = test_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1133 * Zero out the cmd, except for the embedded scsi_request. Only clear
1134 * the driver-private command data if the LLD does not supply a
1135 * function to initialize that data.
1137 to_clear = sizeof(*cmd) - sizeof(cmd->req);
1138 if (!dev->host->hostt->init_cmd_priv)
1139 to_clear += dev->host->hostt->cmd_size;
1140 memset((char *)cmd + sizeof(cmd->req), 0, to_clear);
1143 cmd->sense_buffer = buf;
1144 cmd->prot_sdb = prot;
1146 INIT_LIST_HEAD(&cmd->eh_entry);
1147 INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
1148 cmd->jiffies_at_alloc = jiffies_at_alloc;
1149 cmd->retries = retries;
1151 __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1152 cmd->budget_token = budget_token;
1156 static blk_status_t scsi_setup_scsi_cmnd(struct scsi_device *sdev,
1157 struct request *req)
1159 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1162 * Passthrough requests may transfer data, in which case they must
1163 * a bio attached to them. Or they might contain a SCSI command
1164 * that does not transfer data, in which case they may optionally
1165 * submit a request without an attached bio.
1168 blk_status_t ret = scsi_alloc_sgtables(cmd);
1169 if (unlikely(ret != BLK_STS_OK))
1172 BUG_ON(blk_rq_bytes(req));
1174 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1177 cmd->cmd_len = scsi_req(req)->cmd_len;
1178 cmd->cmnd = scsi_req(req)->cmd;
1179 cmd->transfersize = blk_rq_bytes(req);
1180 cmd->allowed = scsi_req(req)->retries;
1185 scsi_device_state_check(struct scsi_device *sdev, struct request *req)
1187 switch (sdev->sdev_state) {
1191 case SDEV_TRANSPORT_OFFLINE:
1193 * If the device is offline we refuse to process any
1194 * commands. The device must be brought online
1195 * before trying any recovery commands.
1197 if (!sdev->offline_already) {
1198 sdev->offline_already = true;
1199 sdev_printk(KERN_ERR, sdev,
1200 "rejecting I/O to offline device\n");
1202 return BLK_STS_IOERR;
1205 * If the device is fully deleted, we refuse to
1206 * process any commands as well.
1208 sdev_printk(KERN_ERR, sdev,
1209 "rejecting I/O to dead device\n");
1210 return BLK_STS_IOERR;
1212 case SDEV_CREATED_BLOCK:
1213 return BLK_STS_RESOURCE;
1216 * If the device is blocked we only accept power management
1219 if (req && WARN_ON_ONCE(!(req->rq_flags & RQF_PM)))
1220 return BLK_STS_RESOURCE;
1224 * For any other not fully online state we only allow
1225 * power management commands.
1227 if (req && !(req->rq_flags & RQF_PM))
1228 return BLK_STS_IOERR;
1234 * scsi_dev_queue_ready: if we can send requests to sdev, assign one token
1235 * and return the token else return -1.
1237 static inline int scsi_dev_queue_ready(struct request_queue *q,
1238 struct scsi_device *sdev)
1242 token = sbitmap_get(&sdev->budget_map);
1243 if (atomic_read(&sdev->device_blocked)) {
1247 if (scsi_device_busy(sdev) > 1)
1251 * unblock after device_blocked iterates to zero
1253 if (atomic_dec_return(&sdev->device_blocked) > 0)
1255 SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev,
1256 "unblocking device at zero depth\n"));
1262 sbitmap_put(&sdev->budget_map, token);
1268 * scsi_target_queue_ready: checks if there we can send commands to target
1269 * @sdev: scsi device on starget to check.
1271 static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1272 struct scsi_device *sdev)
1274 struct scsi_target *starget = scsi_target(sdev);
1277 if (starget->single_lun) {
1278 spin_lock_irq(shost->host_lock);
1279 if (starget->starget_sdev_user &&
1280 starget->starget_sdev_user != sdev) {
1281 spin_unlock_irq(shost->host_lock);
1284 starget->starget_sdev_user = sdev;
1285 spin_unlock_irq(shost->host_lock);
1288 if (starget->can_queue <= 0)
1291 busy = atomic_inc_return(&starget->target_busy) - 1;
1292 if (atomic_read(&starget->target_blocked) > 0) {
1297 * unblock after target_blocked iterates to zero
1299 if (atomic_dec_return(&starget->target_blocked) > 0)
1302 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1303 "unblocking target at zero depth\n"));
1306 if (busy >= starget->can_queue)
1312 spin_lock_irq(shost->host_lock);
1313 list_move_tail(&sdev->starved_entry, &shost->starved_list);
1314 spin_unlock_irq(shost->host_lock);
1316 if (starget->can_queue > 0)
1317 atomic_dec(&starget->target_busy);
1322 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1323 * return 0. We must end up running the queue again whenever 0 is
1324 * returned, else IO can hang.
1326 static inline int scsi_host_queue_ready(struct request_queue *q,
1327 struct Scsi_Host *shost,
1328 struct scsi_device *sdev,
1329 struct scsi_cmnd *cmd)
1331 if (scsi_host_in_recovery(shost))
1334 if (atomic_read(&shost->host_blocked) > 0) {
1335 if (scsi_host_busy(shost) > 0)
1339 * unblock after host_blocked iterates to zero
1341 if (atomic_dec_return(&shost->host_blocked) > 0)
1345 shost_printk(KERN_INFO, shost,
1346 "unblocking host at zero depth\n"));
1349 if (shost->host_self_blocked)
1352 /* We're OK to process the command, so we can't be starved */
1353 if (!list_empty(&sdev->starved_entry)) {
1354 spin_lock_irq(shost->host_lock);
1355 if (!list_empty(&sdev->starved_entry))
1356 list_del_init(&sdev->starved_entry);
1357 spin_unlock_irq(shost->host_lock);
1360 __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1365 spin_lock_irq(shost->host_lock);
1366 if (list_empty(&sdev->starved_entry))
1367 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1368 spin_unlock_irq(shost->host_lock);
1370 scsi_dec_host_busy(shost, cmd);
1375 * Busy state exporting function for request stacking drivers.
1377 * For efficiency, no lock is taken to check the busy state of
1378 * shost/starget/sdev, since the returned value is not guaranteed and
1379 * may be changed after request stacking drivers call the function,
1380 * regardless of taking lock or not.
1382 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1383 * needs to return 'not busy'. Otherwise, request stacking drivers
1384 * may hold requests forever.
1386 static bool scsi_mq_lld_busy(struct request_queue *q)
1388 struct scsi_device *sdev = q->queuedata;
1389 struct Scsi_Host *shost;
1391 if (blk_queue_dying(q))
1397 * Ignore host/starget busy state.
1398 * Since block layer does not have a concept of fairness across
1399 * multiple queues, congestion of host/starget needs to be handled
1402 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
1409 * Block layer request completion callback. May be called from interrupt
1412 static void scsi_complete(struct request *rq)
1414 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1415 enum scsi_disposition disposition;
1417 INIT_LIST_HEAD(&cmd->eh_entry);
1419 atomic_inc(&cmd->device->iodone_cnt);
1421 atomic_inc(&cmd->device->ioerr_cnt);
1423 disposition = scsi_decide_disposition(cmd);
1424 if (disposition != SUCCESS && scsi_cmd_runtime_exceeced(cmd))
1425 disposition = SUCCESS;
1427 scsi_log_completion(cmd, disposition);
1429 switch (disposition) {
1431 scsi_finish_command(cmd);
1434 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1436 case ADD_TO_MLQUEUE:
1437 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1440 scsi_eh_scmd_add(cmd);
1446 * scsi_dispatch_cmd - Dispatch a command to the low-level driver.
1447 * @cmd: command block we are dispatching.
1449 * Return: nonzero return request was rejected and device's queue needs to be
1452 static int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
1454 struct Scsi_Host *host = cmd->device->host;
1457 atomic_inc(&cmd->device->iorequest_cnt);
1459 /* check if the device is still usable */
1460 if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
1461 /* in SDEV_DEL we error all commands. DID_NO_CONNECT
1462 * returns an immediate error upwards, and signals
1463 * that the device is no longer present */
1464 cmd->result = DID_NO_CONNECT << 16;
1468 /* Check to see if the scsi lld made this device blocked. */
1469 if (unlikely(scsi_device_blocked(cmd->device))) {
1471 * in blocked state, the command is just put back on
1472 * the device queue. The suspend state has already
1473 * blocked the queue so future requests should not
1474 * occur until the device transitions out of the
1477 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1478 "queuecommand : device blocked\n"));
1479 return SCSI_MLQUEUE_DEVICE_BUSY;
1482 /* Store the LUN value in cmnd, if needed. */
1483 if (cmd->device->lun_in_cdb)
1484 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
1485 (cmd->device->lun << 5 & 0xe0);
1490 * Before we queue this command, check if the command
1491 * length exceeds what the host adapter can handle.
1493 if (cmd->cmd_len > cmd->device->host->max_cmd_len) {
1494 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1495 "queuecommand : command too long. "
1496 "cdb_size=%d host->max_cmd_len=%d\n",
1497 cmd->cmd_len, cmd->device->host->max_cmd_len));
1498 cmd->result = (DID_ABORT << 16);
1502 if (unlikely(host->shost_state == SHOST_DEL)) {
1503 cmd->result = (DID_NO_CONNECT << 16);
1508 trace_scsi_dispatch_cmd_start(cmd);
1509 rtn = host->hostt->queuecommand(host, cmd);
1511 trace_scsi_dispatch_cmd_error(cmd, rtn);
1512 if (rtn != SCSI_MLQUEUE_DEVICE_BUSY &&
1513 rtn != SCSI_MLQUEUE_TARGET_BUSY)
1514 rtn = SCSI_MLQUEUE_HOST_BUSY;
1516 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1517 "queuecommand : request rejected\n"));
1522 cmd->scsi_done(cmd);
1526 /* Size in bytes of the sg-list stored in the scsi-mq command-private data. */
1527 static unsigned int scsi_mq_inline_sgl_size(struct Scsi_Host *shost)
1529 return min_t(unsigned int, shost->sg_tablesize, SCSI_INLINE_SG_CNT) *
1530 sizeof(struct scatterlist);
1533 static blk_status_t scsi_prepare_cmd(struct request *req)
1535 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1536 struct scsi_device *sdev = req->q->queuedata;
1537 struct Scsi_Host *shost = sdev->host;
1538 struct scatterlist *sg;
1540 scsi_init_command(sdev, cmd);
1542 cmd->prot_op = SCSI_PROT_NORMAL;
1543 if (blk_rq_bytes(req))
1544 cmd->sc_data_direction = rq_dma_dir(req);
1546 cmd->sc_data_direction = DMA_NONE;
1548 sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
1549 cmd->sdb.table.sgl = sg;
1551 if (scsi_host_get_prot(shost)) {
1552 memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer));
1554 cmd->prot_sdb->table.sgl =
1555 (struct scatterlist *)(cmd->prot_sdb + 1);
1559 * Special handling for passthrough commands, which don't go to the ULP
1562 if (blk_rq_is_passthrough(req))
1563 return scsi_setup_scsi_cmnd(sdev, req);
1565 if (sdev->handler && sdev->handler->prep_fn) {
1566 blk_status_t ret = sdev->handler->prep_fn(sdev, req);
1568 if (ret != BLK_STS_OK)
1572 cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd;
1573 memset(cmd->cmnd, 0, BLK_MAX_CDB);
1574 return scsi_cmd_to_driver(cmd)->init_command(cmd);
1577 static void scsi_mq_done(struct scsi_cmnd *cmd)
1579 if (unlikely(blk_should_fake_timeout(scsi_cmd_to_rq(cmd)->q)))
1581 if (unlikely(test_and_set_bit(SCMD_STATE_COMPLETE, &cmd->state)))
1583 trace_scsi_dispatch_cmd_done(cmd);
1584 blk_mq_complete_request(scsi_cmd_to_rq(cmd));
1587 static void scsi_mq_put_budget(struct request_queue *q, int budget_token)
1589 struct scsi_device *sdev = q->queuedata;
1591 sbitmap_put(&sdev->budget_map, budget_token);
1594 static int scsi_mq_get_budget(struct request_queue *q)
1596 struct scsi_device *sdev = q->queuedata;
1597 int token = scsi_dev_queue_ready(q, sdev);
1602 atomic_inc(&sdev->restarts);
1605 * Orders atomic_inc(&sdev->restarts) and atomic_read(&sdev->device_busy).
1606 * .restarts must be incremented before .device_busy is read because the
1607 * code in scsi_run_queue_async() depends on the order of these operations.
1609 smp_mb__after_atomic();
1612 * If all in-flight requests originated from this LUN are completed
1613 * before reading .device_busy, sdev->device_busy will be observed as
1614 * zero, then blk_mq_delay_run_hw_queues() will dispatch this request
1615 * soon. Otherwise, completion of one of these requests will observe
1616 * the .restarts flag, and the request queue will be run for handling
1617 * this request, see scsi_end_request().
1619 if (unlikely(scsi_device_busy(sdev) == 0 &&
1620 !scsi_device_blocked(sdev)))
1621 blk_mq_delay_run_hw_queues(sdev->request_queue, SCSI_QUEUE_DELAY);
1625 static void scsi_mq_set_rq_budget_token(struct request *req, int token)
1627 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1629 cmd->budget_token = token;
1632 static int scsi_mq_get_rq_budget_token(struct request *req)
1634 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1636 return cmd->budget_token;
1639 static blk_status_t scsi_queue_rq(struct blk_mq_hw_ctx *hctx,
1640 const struct blk_mq_queue_data *bd)
1642 struct request *req = bd->rq;
1643 struct request_queue *q = req->q;
1644 struct scsi_device *sdev = q->queuedata;
1645 struct Scsi_Host *shost = sdev->host;
1646 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1650 WARN_ON_ONCE(cmd->budget_token < 0);
1653 * If the device is not in running state we will reject some or all
1656 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1657 ret = scsi_device_state_check(sdev, req);
1658 if (ret != BLK_STS_OK)
1659 goto out_put_budget;
1662 ret = BLK_STS_RESOURCE;
1663 if (!scsi_target_queue_ready(shost, sdev))
1664 goto out_put_budget;
1665 if (!scsi_host_queue_ready(q, shost, sdev, cmd))
1666 goto out_dec_target_busy;
1668 if (!(req->rq_flags & RQF_DONTPREP)) {
1669 ret = scsi_prepare_cmd(req);
1670 if (ret != BLK_STS_OK)
1671 goto out_dec_host_busy;
1672 req->rq_flags |= RQF_DONTPREP;
1674 clear_bit(SCMD_STATE_COMPLETE, &cmd->state);
1677 cmd->flags &= SCMD_PRESERVED_FLAGS;
1678 if (sdev->simple_tags)
1679 cmd->flags |= SCMD_TAGGED;
1681 cmd->flags |= SCMD_LAST;
1683 scsi_set_resid(cmd, 0);
1684 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1685 cmd->scsi_done = scsi_mq_done;
1687 blk_mq_start_request(req);
1688 reason = scsi_dispatch_cmd(cmd);
1690 scsi_set_blocked(cmd, reason);
1691 ret = BLK_STS_RESOURCE;
1692 goto out_dec_host_busy;
1698 scsi_dec_host_busy(shost, cmd);
1699 out_dec_target_busy:
1700 if (scsi_target(sdev)->can_queue > 0)
1701 atomic_dec(&scsi_target(sdev)->target_busy);
1703 scsi_mq_put_budget(q, cmd->budget_token);
1704 cmd->budget_token = -1;
1708 case BLK_STS_RESOURCE:
1709 case BLK_STS_ZONE_RESOURCE:
1710 if (scsi_device_blocked(sdev))
1711 ret = BLK_STS_DEV_RESOURCE;
1714 scsi_req(req)->result = DID_BUS_BUSY << 16;
1715 if (req->rq_flags & RQF_DONTPREP)
1716 scsi_mq_uninit_cmd(cmd);
1719 if (unlikely(!scsi_device_online(sdev)))
1720 scsi_req(req)->result = DID_NO_CONNECT << 16;
1722 scsi_req(req)->result = DID_ERROR << 16;
1724 * Make sure to release all allocated resources when
1725 * we hit an error, as we will never see this command
1728 if (req->rq_flags & RQF_DONTPREP)
1729 scsi_mq_uninit_cmd(cmd);
1730 scsi_run_queue_async(sdev);
1736 static enum blk_eh_timer_return scsi_timeout(struct request *req,
1740 return BLK_EH_RESET_TIMER;
1741 return scsi_times_out(req);
1744 static int scsi_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
1745 unsigned int hctx_idx, unsigned int numa_node)
1747 struct Scsi_Host *shost = set->driver_data;
1748 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1749 struct scatterlist *sg;
1753 kmem_cache_alloc_node(scsi_sense_cache, GFP_KERNEL, numa_node);
1754 if (!cmd->sense_buffer)
1756 cmd->req.sense = cmd->sense_buffer;
1758 if (scsi_host_get_prot(shost)) {
1759 sg = (void *)cmd + sizeof(struct scsi_cmnd) +
1760 shost->hostt->cmd_size;
1761 cmd->prot_sdb = (void *)sg + scsi_mq_inline_sgl_size(shost);
1764 if (shost->hostt->init_cmd_priv) {
1765 ret = shost->hostt->init_cmd_priv(shost, cmd);
1767 kmem_cache_free(scsi_sense_cache, cmd->sense_buffer);
1773 static void scsi_mq_exit_request(struct blk_mq_tag_set *set, struct request *rq,
1774 unsigned int hctx_idx)
1776 struct Scsi_Host *shost = set->driver_data;
1777 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1779 if (shost->hostt->exit_cmd_priv)
1780 shost->hostt->exit_cmd_priv(shost, cmd);
1781 kmem_cache_free(scsi_sense_cache, cmd->sense_buffer);
1785 static int scsi_mq_poll(struct blk_mq_hw_ctx *hctx)
1787 struct Scsi_Host *shost = hctx->driver_data;
1789 if (shost->hostt->mq_poll)
1790 return shost->hostt->mq_poll(shost, hctx->queue_num);
1795 static int scsi_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
1796 unsigned int hctx_idx)
1798 struct Scsi_Host *shost = data;
1800 hctx->driver_data = shost;
1804 static int scsi_map_queues(struct blk_mq_tag_set *set)
1806 struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set);
1808 if (shost->hostt->map_queues)
1809 return shost->hostt->map_queues(shost);
1810 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
1813 void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q)
1815 struct device *dev = shost->dma_dev;
1818 * this limit is imposed by hardware restrictions
1820 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
1823 if (scsi_host_prot_dma(shost)) {
1824 shost->sg_prot_tablesize =
1825 min_not_zero(shost->sg_prot_tablesize,
1826 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
1827 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
1828 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
1831 if (dev->dma_mask) {
1832 shost->max_sectors = min_t(unsigned int, shost->max_sectors,
1833 dma_max_mapping_size(dev) >> SECTOR_SHIFT);
1835 blk_queue_max_hw_sectors(q, shost->max_sectors);
1836 blk_queue_segment_boundary(q, shost->dma_boundary);
1837 dma_set_seg_boundary(dev, shost->dma_boundary);
1839 blk_queue_max_segment_size(q, shost->max_segment_size);
1840 blk_queue_virt_boundary(q, shost->virt_boundary_mask);
1841 dma_set_max_seg_size(dev, queue_max_segment_size(q));
1844 * Set a reasonable default alignment: The larger of 32-byte (dword),
1845 * which is a common minimum for HBAs, and the minimum DMA alignment,
1846 * which is set by the platform.
1848 * Devices that require a bigger alignment can increase it later.
1850 blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1);
1852 EXPORT_SYMBOL_GPL(__scsi_init_queue);
1854 static const struct blk_mq_ops scsi_mq_ops_no_commit = {
1855 .get_budget = scsi_mq_get_budget,
1856 .put_budget = scsi_mq_put_budget,
1857 .queue_rq = scsi_queue_rq,
1858 .complete = scsi_complete,
1859 .timeout = scsi_timeout,
1860 #ifdef CONFIG_BLK_DEBUG_FS
1861 .show_rq = scsi_show_rq,
1863 .init_request = scsi_mq_init_request,
1864 .exit_request = scsi_mq_exit_request,
1865 .initialize_rq_fn = scsi_initialize_rq,
1866 .cleanup_rq = scsi_cleanup_rq,
1867 .busy = scsi_mq_lld_busy,
1868 .map_queues = scsi_map_queues,
1869 .init_hctx = scsi_init_hctx,
1870 .poll = scsi_mq_poll,
1871 .set_rq_budget_token = scsi_mq_set_rq_budget_token,
1872 .get_rq_budget_token = scsi_mq_get_rq_budget_token,
1876 static void scsi_commit_rqs(struct blk_mq_hw_ctx *hctx)
1878 struct Scsi_Host *shost = hctx->driver_data;
1880 shost->hostt->commit_rqs(shost, hctx->queue_num);
1883 static const struct blk_mq_ops scsi_mq_ops = {
1884 .get_budget = scsi_mq_get_budget,
1885 .put_budget = scsi_mq_put_budget,
1886 .queue_rq = scsi_queue_rq,
1887 .commit_rqs = scsi_commit_rqs,
1888 .complete = scsi_complete,
1889 .timeout = scsi_timeout,
1890 #ifdef CONFIG_BLK_DEBUG_FS
1891 .show_rq = scsi_show_rq,
1893 .init_request = scsi_mq_init_request,
1894 .exit_request = scsi_mq_exit_request,
1895 .initialize_rq_fn = scsi_initialize_rq,
1896 .cleanup_rq = scsi_cleanup_rq,
1897 .busy = scsi_mq_lld_busy,
1898 .map_queues = scsi_map_queues,
1899 .init_hctx = scsi_init_hctx,
1900 .poll = scsi_mq_poll,
1901 .set_rq_budget_token = scsi_mq_set_rq_budget_token,
1902 .get_rq_budget_token = scsi_mq_get_rq_budget_token,
1905 int scsi_mq_setup_tags(struct Scsi_Host *shost)
1907 unsigned int cmd_size, sgl_size;
1908 struct blk_mq_tag_set *tag_set = &shost->tag_set;
1910 sgl_size = max_t(unsigned int, sizeof(struct scatterlist),
1911 scsi_mq_inline_sgl_size(shost));
1912 cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size;
1913 if (scsi_host_get_prot(shost))
1914 cmd_size += sizeof(struct scsi_data_buffer) +
1915 sizeof(struct scatterlist) * SCSI_INLINE_PROT_SG_CNT;
1917 memset(tag_set, 0, sizeof(*tag_set));
1918 if (shost->hostt->commit_rqs)
1919 tag_set->ops = &scsi_mq_ops;
1921 tag_set->ops = &scsi_mq_ops_no_commit;
1922 tag_set->nr_hw_queues = shost->nr_hw_queues ? : 1;
1923 tag_set->nr_maps = shost->nr_maps ? : 1;
1924 tag_set->queue_depth = shost->can_queue;
1925 tag_set->cmd_size = cmd_size;
1926 tag_set->numa_node = NUMA_NO_NODE;
1927 tag_set->flags = BLK_MQ_F_SHOULD_MERGE;
1929 BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy);
1930 tag_set->driver_data = shost;
1931 if (shost->host_tagset)
1932 tag_set->flags |= BLK_MQ_F_TAG_HCTX_SHARED;
1934 return blk_mq_alloc_tag_set(tag_set);
1937 void scsi_mq_destroy_tags(struct Scsi_Host *shost)
1939 blk_mq_free_tag_set(&shost->tag_set);
1943 * scsi_device_from_queue - return sdev associated with a request_queue
1944 * @q: The request queue to return the sdev from
1946 * Return the sdev associated with a request queue or NULL if the
1947 * request_queue does not reference a SCSI device.
1949 struct scsi_device *scsi_device_from_queue(struct request_queue *q)
1951 struct scsi_device *sdev = NULL;
1953 if (q->mq_ops == &scsi_mq_ops_no_commit ||
1954 q->mq_ops == &scsi_mq_ops)
1955 sdev = q->queuedata;
1956 if (!sdev || !get_device(&sdev->sdev_gendev))
1963 * scsi_block_requests - Utility function used by low-level drivers to prevent
1964 * further commands from being queued to the device.
1965 * @shost: host in question
1967 * There is no timer nor any other means by which the requests get unblocked
1968 * other than the low-level driver calling scsi_unblock_requests().
1970 void scsi_block_requests(struct Scsi_Host *shost)
1972 shost->host_self_blocked = 1;
1974 EXPORT_SYMBOL(scsi_block_requests);
1977 * scsi_unblock_requests - Utility function used by low-level drivers to allow
1978 * further commands to be queued to the device.
1979 * @shost: host in question
1981 * There is no timer nor any other means by which the requests get unblocked
1982 * other than the low-level driver calling scsi_unblock_requests(). This is done
1983 * as an API function so that changes to the internals of the scsi mid-layer
1984 * won't require wholesale changes to drivers that use this feature.
1986 void scsi_unblock_requests(struct Scsi_Host *shost)
1988 shost->host_self_blocked = 0;
1989 scsi_run_host_queues(shost);
1991 EXPORT_SYMBOL(scsi_unblock_requests);
1993 void scsi_exit_queue(void)
1995 kmem_cache_destroy(scsi_sense_cache);
1999 * scsi_mode_select - issue a mode select
2000 * @sdev: SCSI device to be queried
2001 * @pf: Page format bit (1 == standard, 0 == vendor specific)
2002 * @sp: Save page bit (0 == don't save, 1 == save)
2003 * @modepage: mode page being requested
2004 * @buffer: request buffer (may not be smaller than eight bytes)
2005 * @len: length of request buffer.
2006 * @timeout: command timeout
2007 * @retries: number of retries before failing
2008 * @data: returns a structure abstracting the mode header data
2009 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2010 * must be SCSI_SENSE_BUFFERSIZE big.
2012 * Returns zero if successful; negative error number or scsi
2017 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
2018 unsigned char *buffer, int len, int timeout, int retries,
2019 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2021 unsigned char cmd[10];
2022 unsigned char *real_buffer;
2025 memset(cmd, 0, sizeof(cmd));
2026 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
2028 if (sdev->use_10_for_ms) {
2031 real_buffer = kmalloc(8 + len, GFP_KERNEL);
2034 memcpy(real_buffer + 8, buffer, len);
2038 real_buffer[2] = data->medium_type;
2039 real_buffer[3] = data->device_specific;
2040 real_buffer[4] = data->longlba ? 0x01 : 0;
2042 real_buffer[6] = data->block_descriptor_length >> 8;
2043 real_buffer[7] = data->block_descriptor_length;
2045 cmd[0] = MODE_SELECT_10;
2049 if (len > 255 || data->block_descriptor_length > 255 ||
2053 real_buffer = kmalloc(4 + len, GFP_KERNEL);
2056 memcpy(real_buffer + 4, buffer, len);
2059 real_buffer[1] = data->medium_type;
2060 real_buffer[2] = data->device_specific;
2061 real_buffer[3] = data->block_descriptor_length;
2063 cmd[0] = MODE_SELECT;
2067 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
2068 sshdr, timeout, retries, NULL);
2072 EXPORT_SYMBOL_GPL(scsi_mode_select);
2075 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
2076 * @sdev: SCSI device to be queried
2077 * @dbd: set to prevent mode sense from returning block descriptors
2078 * @modepage: mode page being requested
2079 * @buffer: request buffer (may not be smaller than eight bytes)
2080 * @len: length of request buffer.
2081 * @timeout: command timeout
2082 * @retries: number of retries before failing
2083 * @data: returns a structure abstracting the mode header data
2084 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2085 * must be SCSI_SENSE_BUFFERSIZE big.
2087 * Returns zero if successful, or a negative error number on failure
2090 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
2091 unsigned char *buffer, int len, int timeout, int retries,
2092 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2094 unsigned char cmd[12];
2097 int result, retry_count = retries;
2098 struct scsi_sense_hdr my_sshdr;
2100 memset(data, 0, sizeof(*data));
2101 memset(&cmd[0], 0, 12);
2103 dbd = sdev->set_dbd_for_ms ? 8 : dbd;
2104 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
2107 /* caller might not be interested in sense, but we need it */
2112 use_10_for_ms = sdev->use_10_for_ms || len > 255;
2114 if (use_10_for_ms) {
2115 if (len < 8 || len > 65535)
2118 cmd[0] = MODE_SENSE_10;
2119 put_unaligned_be16(len, &cmd[7]);
2125 cmd[0] = MODE_SENSE;
2130 memset(buffer, 0, len);
2132 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
2133 sshdr, timeout, retries, NULL);
2137 /* This code looks awful: what it's doing is making sure an
2138 * ILLEGAL REQUEST sense return identifies the actual command
2139 * byte as the problem. MODE_SENSE commands can return
2140 * ILLEGAL REQUEST if the code page isn't supported */
2142 if (!scsi_status_is_good(result)) {
2143 if (scsi_sense_valid(sshdr)) {
2144 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
2145 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
2147 * Invalid command operation code: retry using
2148 * MODE SENSE(6) if this was a MODE SENSE(10)
2149 * request, except if the request mode page is
2150 * too large for MODE SENSE single byte
2151 * allocation length field.
2153 if (use_10_for_ms) {
2156 sdev->use_10_for_ms = 0;
2160 if (scsi_status_is_check_condition(result) &&
2161 sshdr->sense_key == UNIT_ATTENTION &&
2169 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
2170 (modepage == 6 || modepage == 8))) {
2171 /* Initio breakage? */
2174 data->medium_type = 0;
2175 data->device_specific = 0;
2177 data->block_descriptor_length = 0;
2178 } else if (use_10_for_ms) {
2179 data->length = get_unaligned_be16(&buffer[0]) + 2;
2180 data->medium_type = buffer[2];
2181 data->device_specific = buffer[3];
2182 data->longlba = buffer[4] & 0x01;
2183 data->block_descriptor_length = get_unaligned_be16(&buffer[6]);
2185 data->length = buffer[0] + 1;
2186 data->medium_type = buffer[1];
2187 data->device_specific = buffer[2];
2188 data->block_descriptor_length = buffer[3];
2190 data->header_length = header_length;
2194 EXPORT_SYMBOL(scsi_mode_sense);
2197 * scsi_test_unit_ready - test if unit is ready
2198 * @sdev: scsi device to change the state of.
2199 * @timeout: command timeout
2200 * @retries: number of retries before failing
2201 * @sshdr: outpout pointer for decoded sense information.
2203 * Returns zero if unsuccessful or an error if TUR failed. For
2204 * removable media, UNIT_ATTENTION sets ->changed flag.
2207 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2208 struct scsi_sense_hdr *sshdr)
2211 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2215 /* try to eat the UNIT_ATTENTION if there are enough retries */
2217 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
2219 if (sdev->removable && scsi_sense_valid(sshdr) &&
2220 sshdr->sense_key == UNIT_ATTENTION)
2222 } while (scsi_sense_valid(sshdr) &&
2223 sshdr->sense_key == UNIT_ATTENTION && --retries);
2227 EXPORT_SYMBOL(scsi_test_unit_ready);
2230 * scsi_device_set_state - Take the given device through the device state model.
2231 * @sdev: scsi device to change the state of.
2232 * @state: state to change to.
2234 * Returns zero if successful or an error if the requested
2235 * transition is illegal.
2238 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2240 enum scsi_device_state oldstate = sdev->sdev_state;
2242 if (state == oldstate)
2248 case SDEV_CREATED_BLOCK:
2259 case SDEV_TRANSPORT_OFFLINE:
2272 case SDEV_TRANSPORT_OFFLINE:
2280 case SDEV_TRANSPORT_OFFLINE:
2295 case SDEV_CREATED_BLOCK:
2304 case SDEV_CREATED_BLOCK:
2319 case SDEV_TRANSPORT_OFFLINE:
2331 case SDEV_TRANSPORT_OFFLINE:
2334 case SDEV_CREATED_BLOCK:
2342 sdev->offline_already = false;
2343 sdev->sdev_state = state;
2347 SCSI_LOG_ERROR_RECOVERY(1,
2348 sdev_printk(KERN_ERR, sdev,
2349 "Illegal state transition %s->%s",
2350 scsi_device_state_name(oldstate),
2351 scsi_device_state_name(state))
2355 EXPORT_SYMBOL(scsi_device_set_state);
2358 * scsi_evt_emit - emit a single SCSI device uevent
2359 * @sdev: associated SCSI device
2360 * @evt: event to emit
2362 * Send a single uevent (scsi_event) to the associated scsi_device.
2364 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2369 switch (evt->evt_type) {
2370 case SDEV_EVT_MEDIA_CHANGE:
2371 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2373 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2374 scsi_rescan_device(&sdev->sdev_gendev);
2375 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
2377 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2378 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
2380 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2381 envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
2383 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2384 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
2386 case SDEV_EVT_LUN_CHANGE_REPORTED:
2387 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
2389 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2390 envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED";
2392 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2393 envp[idx++] = "SDEV_UA=POWER_ON_RESET_OCCURRED";
2402 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2406 * scsi_evt_thread - send a uevent for each scsi event
2407 * @work: work struct for scsi_device
2409 * Dispatch queued events to their associated scsi_device kobjects
2412 void scsi_evt_thread(struct work_struct *work)
2414 struct scsi_device *sdev;
2415 enum scsi_device_event evt_type;
2416 LIST_HEAD(event_list);
2418 sdev = container_of(work, struct scsi_device, event_work);
2420 for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
2421 if (test_and_clear_bit(evt_type, sdev->pending_events))
2422 sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
2425 struct scsi_event *evt;
2426 struct list_head *this, *tmp;
2427 unsigned long flags;
2429 spin_lock_irqsave(&sdev->list_lock, flags);
2430 list_splice_init(&sdev->event_list, &event_list);
2431 spin_unlock_irqrestore(&sdev->list_lock, flags);
2433 if (list_empty(&event_list))
2436 list_for_each_safe(this, tmp, &event_list) {
2437 evt = list_entry(this, struct scsi_event, node);
2438 list_del(&evt->node);
2439 scsi_evt_emit(sdev, evt);
2446 * sdev_evt_send - send asserted event to uevent thread
2447 * @sdev: scsi_device event occurred on
2448 * @evt: event to send
2450 * Assert scsi device event asynchronously.
2452 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2454 unsigned long flags;
2457 /* FIXME: currently this check eliminates all media change events
2458 * for polled devices. Need to update to discriminate between AN
2459 * and polled events */
2460 if (!test_bit(evt->evt_type, sdev->supported_events)) {
2466 spin_lock_irqsave(&sdev->list_lock, flags);
2467 list_add_tail(&evt->node, &sdev->event_list);
2468 schedule_work(&sdev->event_work);
2469 spin_unlock_irqrestore(&sdev->list_lock, flags);
2471 EXPORT_SYMBOL_GPL(sdev_evt_send);
2474 * sdev_evt_alloc - allocate a new scsi event
2475 * @evt_type: type of event to allocate
2476 * @gfpflags: GFP flags for allocation
2478 * Allocates and returns a new scsi_event.
2480 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2483 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2487 evt->evt_type = evt_type;
2488 INIT_LIST_HEAD(&evt->node);
2490 /* evt_type-specific initialization, if any */
2492 case SDEV_EVT_MEDIA_CHANGE:
2493 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2494 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2495 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2496 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2497 case SDEV_EVT_LUN_CHANGE_REPORTED:
2498 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2499 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2507 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2510 * sdev_evt_send_simple - send asserted event to uevent thread
2511 * @sdev: scsi_device event occurred on
2512 * @evt_type: type of event to send
2513 * @gfpflags: GFP flags for allocation
2515 * Assert scsi device event asynchronously, given an event type.
2517 void sdev_evt_send_simple(struct scsi_device *sdev,
2518 enum scsi_device_event evt_type, gfp_t gfpflags)
2520 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2522 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2527 sdev_evt_send(sdev, evt);
2529 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2532 * scsi_device_quiesce - Block all commands except power management.
2533 * @sdev: scsi device to quiesce.
2535 * This works by trying to transition to the SDEV_QUIESCE state
2536 * (which must be a legal transition). When the device is in this
2537 * state, only power management requests will be accepted, all others will
2540 * Must be called with user context, may sleep.
2542 * Returns zero if unsuccessful or an error if not.
2545 scsi_device_quiesce(struct scsi_device *sdev)
2547 struct request_queue *q = sdev->request_queue;
2551 * It is allowed to call scsi_device_quiesce() multiple times from
2552 * the same context but concurrent scsi_device_quiesce() calls are
2555 WARN_ON_ONCE(sdev->quiesced_by && sdev->quiesced_by != current);
2557 if (sdev->quiesced_by == current)
2562 blk_mq_freeze_queue(q);
2564 * Ensure that the effect of blk_set_pm_only() will be visible
2565 * for percpu_ref_tryget() callers that occur after the queue
2566 * unfreeze even if the queue was already frozen before this function
2567 * was called. See also https://lwn.net/Articles/573497/.
2570 blk_mq_unfreeze_queue(q);
2572 mutex_lock(&sdev->state_mutex);
2573 err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2575 sdev->quiesced_by = current;
2577 blk_clear_pm_only(q);
2578 mutex_unlock(&sdev->state_mutex);
2582 EXPORT_SYMBOL(scsi_device_quiesce);
2585 * scsi_device_resume - Restart user issued commands to a quiesced device.
2586 * @sdev: scsi device to resume.
2588 * Moves the device from quiesced back to running and restarts the
2591 * Must be called with user context, may sleep.
2593 void scsi_device_resume(struct scsi_device *sdev)
2595 /* check if the device state was mutated prior to resume, and if
2596 * so assume the state is being managed elsewhere (for example
2597 * device deleted during suspend)
2599 mutex_lock(&sdev->state_mutex);
2600 if (sdev->sdev_state == SDEV_QUIESCE)
2601 scsi_device_set_state(sdev, SDEV_RUNNING);
2602 if (sdev->quiesced_by) {
2603 sdev->quiesced_by = NULL;
2604 blk_clear_pm_only(sdev->request_queue);
2606 mutex_unlock(&sdev->state_mutex);
2608 EXPORT_SYMBOL(scsi_device_resume);
2611 device_quiesce_fn(struct scsi_device *sdev, void *data)
2613 scsi_device_quiesce(sdev);
2617 scsi_target_quiesce(struct scsi_target *starget)
2619 starget_for_each_device(starget, NULL, device_quiesce_fn);
2621 EXPORT_SYMBOL(scsi_target_quiesce);
2624 device_resume_fn(struct scsi_device *sdev, void *data)
2626 scsi_device_resume(sdev);
2630 scsi_target_resume(struct scsi_target *starget)
2632 starget_for_each_device(starget, NULL, device_resume_fn);
2634 EXPORT_SYMBOL(scsi_target_resume);
2637 * scsi_internal_device_block_nowait - try to transition to the SDEV_BLOCK state
2638 * @sdev: device to block
2640 * Pause SCSI command processing on the specified device. Does not sleep.
2642 * Returns zero if successful or a negative error code upon failure.
2645 * This routine transitions the device to the SDEV_BLOCK state (which must be
2646 * a legal transition). When the device is in this state, command processing
2647 * is paused until the device leaves the SDEV_BLOCK state. See also
2648 * scsi_internal_device_unblock_nowait().
2650 int scsi_internal_device_block_nowait(struct scsi_device *sdev)
2652 struct request_queue *q = sdev->request_queue;
2655 err = scsi_device_set_state(sdev, SDEV_BLOCK);
2657 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
2664 * The device has transitioned to SDEV_BLOCK. Stop the
2665 * block layer from calling the midlayer with this device's
2668 blk_mq_quiesce_queue_nowait(q);
2671 EXPORT_SYMBOL_GPL(scsi_internal_device_block_nowait);
2674 * scsi_internal_device_block - try to transition to the SDEV_BLOCK state
2675 * @sdev: device to block
2677 * Pause SCSI command processing on the specified device and wait until all
2678 * ongoing scsi_request_fn() / scsi_queue_rq() calls have finished. May sleep.
2680 * Returns zero if successful or a negative error code upon failure.
2683 * This routine transitions the device to the SDEV_BLOCK state (which must be
2684 * a legal transition). When the device is in this state, command processing
2685 * is paused until the device leaves the SDEV_BLOCK state. See also
2686 * scsi_internal_device_unblock().
2688 static int scsi_internal_device_block(struct scsi_device *sdev)
2690 struct request_queue *q = sdev->request_queue;
2693 mutex_lock(&sdev->state_mutex);
2694 err = scsi_internal_device_block_nowait(sdev);
2696 blk_mq_quiesce_queue(q);
2697 mutex_unlock(&sdev->state_mutex);
2702 void scsi_start_queue(struct scsi_device *sdev)
2704 struct request_queue *q = sdev->request_queue;
2706 blk_mq_unquiesce_queue(q);
2710 * scsi_internal_device_unblock_nowait - resume a device after a block request
2711 * @sdev: device to resume
2712 * @new_state: state to set the device to after unblocking
2714 * Restart the device queue for a previously suspended SCSI device. Does not
2717 * Returns zero if successful or a negative error code upon failure.
2720 * This routine transitions the device to the SDEV_RUNNING state or to one of
2721 * the offline states (which must be a legal transition) allowing the midlayer
2722 * to goose the queue for this device.
2724 int scsi_internal_device_unblock_nowait(struct scsi_device *sdev,
2725 enum scsi_device_state new_state)
2727 switch (new_state) {
2729 case SDEV_TRANSPORT_OFFLINE:
2736 * Try to transition the scsi device to SDEV_RUNNING or one of the
2737 * offlined states and goose the device queue if successful.
2739 switch (sdev->sdev_state) {
2741 case SDEV_TRANSPORT_OFFLINE:
2742 sdev->sdev_state = new_state;
2744 case SDEV_CREATED_BLOCK:
2745 if (new_state == SDEV_TRANSPORT_OFFLINE ||
2746 new_state == SDEV_OFFLINE)
2747 sdev->sdev_state = new_state;
2749 sdev->sdev_state = SDEV_CREATED;
2757 scsi_start_queue(sdev);
2761 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock_nowait);
2764 * scsi_internal_device_unblock - resume a device after a block request
2765 * @sdev: device to resume
2766 * @new_state: state to set the device to after unblocking
2768 * Restart the device queue for a previously suspended SCSI device. May sleep.
2770 * Returns zero if successful or a negative error code upon failure.
2773 * This routine transitions the device to the SDEV_RUNNING state or to one of
2774 * the offline states (which must be a legal transition) allowing the midlayer
2775 * to goose the queue for this device.
2777 static int scsi_internal_device_unblock(struct scsi_device *sdev,
2778 enum scsi_device_state new_state)
2782 mutex_lock(&sdev->state_mutex);
2783 ret = scsi_internal_device_unblock_nowait(sdev, new_state);
2784 mutex_unlock(&sdev->state_mutex);
2790 device_block(struct scsi_device *sdev, void *data)
2794 ret = scsi_internal_device_block(sdev);
2796 WARN_ONCE(ret, "scsi_internal_device_block(%s) failed: ret = %d\n",
2797 dev_name(&sdev->sdev_gendev), ret);
2801 target_block(struct device *dev, void *data)
2803 if (scsi_is_target_device(dev))
2804 starget_for_each_device(to_scsi_target(dev), NULL,
2810 scsi_target_block(struct device *dev)
2812 if (scsi_is_target_device(dev))
2813 starget_for_each_device(to_scsi_target(dev), NULL,
2816 device_for_each_child(dev, NULL, target_block);
2818 EXPORT_SYMBOL_GPL(scsi_target_block);
2821 device_unblock(struct scsi_device *sdev, void *data)
2823 scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
2827 target_unblock(struct device *dev, void *data)
2829 if (scsi_is_target_device(dev))
2830 starget_for_each_device(to_scsi_target(dev), data,
2836 scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
2838 if (scsi_is_target_device(dev))
2839 starget_for_each_device(to_scsi_target(dev), &new_state,
2842 device_for_each_child(dev, &new_state, target_unblock);
2844 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2847 scsi_host_block(struct Scsi_Host *shost)
2849 struct scsi_device *sdev;
2853 * Call scsi_internal_device_block_nowait so we can avoid
2854 * calling synchronize_rcu() for each LUN.
2856 shost_for_each_device(sdev, shost) {
2857 mutex_lock(&sdev->state_mutex);
2858 ret = scsi_internal_device_block_nowait(sdev);
2859 mutex_unlock(&sdev->state_mutex);
2861 scsi_device_put(sdev);
2867 * SCSI never enables blk-mq's BLK_MQ_F_BLOCKING flag so
2868 * calling synchronize_rcu() once is enough.
2870 WARN_ON_ONCE(shost->tag_set.flags & BLK_MQ_F_BLOCKING);
2877 EXPORT_SYMBOL_GPL(scsi_host_block);
2880 scsi_host_unblock(struct Scsi_Host *shost, int new_state)
2882 struct scsi_device *sdev;
2885 shost_for_each_device(sdev, shost) {
2886 ret = scsi_internal_device_unblock(sdev, new_state);
2888 scsi_device_put(sdev);
2894 EXPORT_SYMBOL_GPL(scsi_host_unblock);
2897 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
2898 * @sgl: scatter-gather list
2899 * @sg_count: number of segments in sg
2900 * @offset: offset in bytes into sg, on return offset into the mapped area
2901 * @len: bytes to map, on return number of bytes mapped
2903 * Returns virtual address of the start of the mapped page
2905 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
2906 size_t *offset, size_t *len)
2909 size_t sg_len = 0, len_complete = 0;
2910 struct scatterlist *sg;
2913 WARN_ON(!irqs_disabled());
2915 for_each_sg(sgl, sg, sg_count, i) {
2916 len_complete = sg_len; /* Complete sg-entries */
2917 sg_len += sg->length;
2918 if (sg_len > *offset)
2922 if (unlikely(i == sg_count)) {
2923 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2925 __func__, sg_len, *offset, sg_count);
2930 /* Offset starting from the beginning of first page in this sg-entry */
2931 *offset = *offset - len_complete + sg->offset;
2933 /* Assumption: contiguous pages can be accessed as "page + i" */
2934 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
2935 *offset &= ~PAGE_MASK;
2937 /* Bytes in this sg-entry from *offset to the end of the page */
2938 sg_len = PAGE_SIZE - *offset;
2942 return kmap_atomic(page);
2944 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2947 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
2948 * @virt: virtual address to be unmapped
2950 void scsi_kunmap_atomic_sg(void *virt)
2952 kunmap_atomic(virt);
2954 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
2956 void sdev_disable_disk_events(struct scsi_device *sdev)
2958 atomic_inc(&sdev->disk_events_disable_depth);
2960 EXPORT_SYMBOL(sdev_disable_disk_events);
2962 void sdev_enable_disk_events(struct scsi_device *sdev)
2964 if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
2966 atomic_dec(&sdev->disk_events_disable_depth);
2968 EXPORT_SYMBOL(sdev_enable_disk_events);
2970 static unsigned char designator_prio(const unsigned char *d)
2973 /* not associated with LUN */
2977 /* invalid length */
2981 * Order of preference for lun descriptor:
2982 * - SCSI name string
2983 * - NAA IEEE Registered Extended
2984 * - EUI-64 based 16-byte
2985 * - EUI-64 based 12-byte
2986 * - NAA IEEE Registered
2987 * - NAA IEEE Extended
2988 * - EUI-64 based 8-byte
2989 * - SCSI name string (truncated)
2991 * as longer descriptors reduce the likelyhood
2992 * of identification clashes.
2995 switch (d[1] & 0xf) {
2997 /* SCSI name string, variable-length UTF-8 */
3000 switch (d[4] >> 4) {
3002 /* NAA registered extended */
3005 /* NAA registered */
3011 /* NAA locally assigned */
3020 /* EUI64-based, 16 byte */
3023 /* EUI64-based, 12 byte */
3026 /* EUI64-based, 8 byte */
3043 * scsi_vpd_lun_id - return a unique device identification
3044 * @sdev: SCSI device
3045 * @id: buffer for the identification
3046 * @id_len: length of the buffer
3048 * Copies a unique device identification into @id based
3049 * on the information in the VPD page 0x83 of the device.
3050 * The string will be formatted as a SCSI name string.
3052 * Returns the length of the identification or error on failure.
3053 * If the identifier is longer than the supplied buffer the actual
3054 * identifier length is returned and the buffer is not zero-padded.
3056 int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
3060 const unsigned char *d, *cur_id_str;
3061 const struct scsi_vpd *vpd_pg83;
3062 int id_size = -EINVAL;
3065 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3071 /* The id string must be at least 20 bytes + terminating NULL byte */
3077 memset(id, 0, id_len);
3078 for (d = vpd_pg83->data + 4;
3079 d < vpd_pg83->data + vpd_pg83->len;
3081 u8 prio = designator_prio(d);
3083 if (prio == 0 || cur_id_prio > prio)
3086 switch (d[1] & 0xf) {
3089 if (cur_id_size > d[3])
3093 if (cur_id_size + 4 > id_len)
3094 cur_id_size = id_len - 4;
3096 id_size = snprintf(id, id_len, "t10.%*pE",
3097 cur_id_size, cur_id_str);
3104 switch (cur_id_size) {
3106 id_size = snprintf(id, id_len,
3111 id_size = snprintf(id, id_len,
3116 id_size = snprintf(id, id_len,
3129 switch (cur_id_size) {
3131 id_size = snprintf(id, id_len,
3136 id_size = snprintf(id, id_len,
3145 /* SCSI name string */
3146 if (cur_id_size > d[3])
3148 /* Prefer others for truncated descriptor */
3149 if (d[3] > id_len) {
3151 if (cur_id_prio > prio)
3155 cur_id_size = id_size = d[3];
3157 if (cur_id_size >= id_len)
3158 cur_id_size = id_len - 1;
3159 memcpy(id, cur_id_str, cur_id_size);
3169 EXPORT_SYMBOL(scsi_vpd_lun_id);
3172 * scsi_vpd_tpg_id - return a target port group identifier
3173 * @sdev: SCSI device
3175 * Returns the Target Port Group identifier from the information
3176 * froom VPD page 0x83 of the device.
3178 * Returns the identifier or error on failure.
3180 int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
3182 const unsigned char *d;
3183 const struct scsi_vpd *vpd_pg83;
3184 int group_id = -EAGAIN, rel_port = -1;
3187 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3193 d = vpd_pg83->data + 4;
3194 while (d < vpd_pg83->data + vpd_pg83->len) {
3195 switch (d[1] & 0xf) {
3197 /* Relative target port */
3198 rel_port = get_unaligned_be16(&d[6]);
3201 /* Target port group */
3202 group_id = get_unaligned_be16(&d[6]);
3211 if (group_id >= 0 && rel_id && rel_port != -1)
3216 EXPORT_SYMBOL(scsi_vpd_tpg_id);
3219 * scsi_build_sense - build sense data for a command
3220 * @scmd: scsi command for which the sense should be formatted
3221 * @desc: Sense format (non-zero == descriptor format,
3222 * 0 == fixed format)
3224 * @asc: Additional sense code
3225 * @ascq: Additional sense code qualifier
3228 void scsi_build_sense(struct scsi_cmnd *scmd, int desc, u8 key, u8 asc, u8 ascq)
3230 scsi_build_sense_buffer(desc, scmd->sense_buffer, key, asc, ascq);
3231 scmd->result = SAM_STAT_CHECK_CONDITION;
3233 EXPORT_SYMBOL_GPL(scsi_build_sense);