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"
43 static struct kmem_cache *scsi_sdb_cache;
44 static struct kmem_cache *scsi_sense_cache;
45 static struct kmem_cache *scsi_sense_isadma_cache;
46 static DEFINE_MUTEX(scsi_sense_cache_mutex);
48 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd);
50 static inline struct kmem_cache *
51 scsi_select_sense_cache(bool unchecked_isa_dma)
53 return unchecked_isa_dma ? scsi_sense_isadma_cache : scsi_sense_cache;
56 static void scsi_free_sense_buffer(bool unchecked_isa_dma,
57 unsigned char *sense_buffer)
59 kmem_cache_free(scsi_select_sense_cache(unchecked_isa_dma),
63 static unsigned char *scsi_alloc_sense_buffer(bool unchecked_isa_dma,
64 gfp_t gfp_mask, int numa_node)
66 return kmem_cache_alloc_node(scsi_select_sense_cache(unchecked_isa_dma),
70 int scsi_init_sense_cache(struct Scsi_Host *shost)
72 struct kmem_cache *cache;
75 cache = scsi_select_sense_cache(shost->unchecked_isa_dma);
79 mutex_lock(&scsi_sense_cache_mutex);
80 if (shost->unchecked_isa_dma) {
81 scsi_sense_isadma_cache =
82 kmem_cache_create("scsi_sense_cache(DMA)",
83 SCSI_SENSE_BUFFERSIZE, 0,
84 SLAB_HWCACHE_ALIGN | SLAB_CACHE_DMA, NULL);
85 if (!scsi_sense_isadma_cache)
89 kmem_cache_create_usercopy("scsi_sense_cache",
90 SCSI_SENSE_BUFFERSIZE, 0, SLAB_HWCACHE_ALIGN,
91 0, SCSI_SENSE_BUFFERSIZE, NULL);
92 if (!scsi_sense_cache)
96 mutex_unlock(&scsi_sense_cache_mutex);
101 * When to reinvoke queueing after a resource shortage. It's 3 msecs to
102 * not change behaviour from the previous unplug mechanism, experimentation
103 * may prove this needs changing.
105 #define SCSI_QUEUE_DELAY 3
108 scsi_set_blocked(struct scsi_cmnd *cmd, int reason)
110 struct Scsi_Host *host = cmd->device->host;
111 struct scsi_device *device = cmd->device;
112 struct scsi_target *starget = scsi_target(device);
115 * Set the appropriate busy bit for the device/host.
117 * If the host/device isn't busy, assume that something actually
118 * completed, and that we should be able to queue a command now.
120 * Note that the prior mid-layer assumption that any host could
121 * always queue at least one command is now broken. The mid-layer
122 * will implement a user specifiable stall (see
123 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
124 * if a command is requeued with no other commands outstanding
125 * either for the device or for the host.
128 case SCSI_MLQUEUE_HOST_BUSY:
129 atomic_set(&host->host_blocked, host->max_host_blocked);
131 case SCSI_MLQUEUE_DEVICE_BUSY:
132 case SCSI_MLQUEUE_EH_RETRY:
133 atomic_set(&device->device_blocked,
134 device->max_device_blocked);
136 case SCSI_MLQUEUE_TARGET_BUSY:
137 atomic_set(&starget->target_blocked,
138 starget->max_target_blocked);
143 static void scsi_mq_requeue_cmd(struct scsi_cmnd *cmd)
145 if (cmd->request->rq_flags & RQF_DONTPREP) {
146 cmd->request->rq_flags &= ~RQF_DONTPREP;
147 scsi_mq_uninit_cmd(cmd);
151 blk_mq_requeue_request(cmd->request, true);
155 * __scsi_queue_insert - private queue insertion
156 * @cmd: The SCSI command being requeued
157 * @reason: The reason for the requeue
158 * @unbusy: Whether the queue should be unbusied
160 * This is a private queue insertion. The public interface
161 * scsi_queue_insert() always assumes the queue should be unbusied
162 * because it's always called before the completion. This function is
163 * for a requeue after completion, which should only occur in this
166 static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, bool unbusy)
168 struct scsi_device *device = cmd->device;
170 SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd,
171 "Inserting command %p into mlqueue\n", cmd));
173 scsi_set_blocked(cmd, reason);
176 * Decrement the counters, since these commands are no longer
177 * active on the host/device.
180 scsi_device_unbusy(device);
183 * Requeue this command. It will go before all other commands
184 * that are already in the queue. Schedule requeue work under
185 * lock such that the kblockd_schedule_work() call happens
186 * before blk_cleanup_queue() finishes.
190 blk_mq_requeue_request(cmd->request, true);
194 * Function: scsi_queue_insert()
196 * Purpose: Insert a command in the midlevel queue.
198 * Arguments: cmd - command that we are adding to queue.
199 * reason - why we are inserting command to queue.
201 * Lock status: Assumed that lock is not held upon entry.
205 * Notes: We do this for one of two cases. Either the host is busy
206 * and it cannot accept any more commands for the time being,
207 * or the device returned QUEUE_FULL and can accept no more
209 * Notes: This could be called either from an interrupt context or a
210 * normal process context.
212 void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
214 __scsi_queue_insert(cmd, reason, true);
219 * __scsi_execute - insert request and wait for the result
222 * @data_direction: data direction
223 * @buffer: data buffer
224 * @bufflen: len of buffer
225 * @sense: optional sense buffer
226 * @sshdr: optional decoded sense header
227 * @timeout: request timeout in seconds
228 * @retries: number of times to retry request
229 * @flags: flags for ->cmd_flags
230 * @rq_flags: flags for ->rq_flags
231 * @resid: optional residual length
233 * Returns the scsi_cmnd result field if a command was executed, or a negative
234 * Linux error code if we didn't get that far.
236 int __scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
237 int data_direction, void *buffer, unsigned bufflen,
238 unsigned char *sense, struct scsi_sense_hdr *sshdr,
239 int timeout, int retries, u64 flags, req_flags_t rq_flags,
243 struct scsi_request *rq;
244 int ret = DRIVER_ERROR << 24;
246 req = blk_get_request(sdev->request_queue,
247 data_direction == DMA_TO_DEVICE ?
248 REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN, BLK_MQ_REQ_PREEMPT);
253 if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
254 buffer, bufflen, GFP_NOIO))
257 rq->cmd_len = COMMAND_SIZE(cmd[0]);
258 memcpy(rq->cmd, cmd, rq->cmd_len);
259 rq->retries = retries;
260 req->timeout = timeout;
261 req->cmd_flags |= flags;
262 req->rq_flags |= rq_flags | RQF_QUIET;
265 * head injection *required* here otherwise quiesce won't work
267 blk_execute_rq(req->q, NULL, req, 1);
270 * Some devices (USB mass-storage in particular) may transfer
271 * garbage data together with a residue indicating that the data
272 * is invalid. Prevent the garbage from being misinterpreted
273 * and prevent security leaks by zeroing out the excess data.
275 if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen))
276 memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len);
279 *resid = rq->resid_len;
280 if (sense && rq->sense_len)
281 memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE);
283 scsi_normalize_sense(rq->sense, rq->sense_len, sshdr);
286 blk_put_request(req);
290 EXPORT_SYMBOL(__scsi_execute);
293 * Function: scsi_init_cmd_errh()
295 * Purpose: Initialize cmd fields related to error handling.
297 * Arguments: cmd - command that is ready to be queued.
299 * Notes: This function has the job of initializing a number of
300 * fields related to error handling. Typically this will
301 * be called once for each command, as required.
303 static void scsi_init_cmd_errh(struct scsi_cmnd *cmd)
305 scsi_set_resid(cmd, 0);
306 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
307 if (cmd->cmd_len == 0)
308 cmd->cmd_len = scsi_command_size(cmd->cmnd);
312 * Decrement the host_busy counter and wake up the error handler if necessary.
313 * Avoid as follows that the error handler is not woken up if shost->host_busy
314 * == shost->host_failed: use call_rcu() in scsi_eh_scmd_add() in combination
315 * with an RCU read lock in this function to ensure that this function in its
316 * entirety either finishes before scsi_eh_scmd_add() increases the
317 * host_failed counter or that it notices the shost state change made by
318 * scsi_eh_scmd_add().
320 static void scsi_dec_host_busy(struct Scsi_Host *shost)
325 atomic_dec(&shost->host_busy);
326 if (unlikely(scsi_host_in_recovery(shost))) {
327 spin_lock_irqsave(shost->host_lock, flags);
328 if (shost->host_failed || shost->host_eh_scheduled)
329 scsi_eh_wakeup(shost);
330 spin_unlock_irqrestore(shost->host_lock, flags);
335 void scsi_device_unbusy(struct scsi_device *sdev)
337 struct Scsi_Host *shost = sdev->host;
338 struct scsi_target *starget = scsi_target(sdev);
340 scsi_dec_host_busy(shost);
342 if (starget->can_queue > 0)
343 atomic_dec(&starget->target_busy);
345 atomic_dec(&sdev->device_busy);
348 static void scsi_kick_queue(struct request_queue *q)
350 blk_mq_run_hw_queues(q, false);
354 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
355 * and call blk_run_queue for all the scsi_devices on the target -
356 * including current_sdev first.
358 * Called with *no* scsi locks held.
360 static void scsi_single_lun_run(struct scsi_device *current_sdev)
362 struct Scsi_Host *shost = current_sdev->host;
363 struct scsi_device *sdev, *tmp;
364 struct scsi_target *starget = scsi_target(current_sdev);
367 spin_lock_irqsave(shost->host_lock, flags);
368 starget->starget_sdev_user = NULL;
369 spin_unlock_irqrestore(shost->host_lock, flags);
372 * Call blk_run_queue for all LUNs on the target, starting with
373 * current_sdev. We race with others (to set starget_sdev_user),
374 * but in most cases, we will be first. Ideally, each LU on the
375 * target would get some limited time or requests on the target.
377 scsi_kick_queue(current_sdev->request_queue);
379 spin_lock_irqsave(shost->host_lock, flags);
380 if (starget->starget_sdev_user)
382 list_for_each_entry_safe(sdev, tmp, &starget->devices,
383 same_target_siblings) {
384 if (sdev == current_sdev)
386 if (scsi_device_get(sdev))
389 spin_unlock_irqrestore(shost->host_lock, flags);
390 scsi_kick_queue(sdev->request_queue);
391 spin_lock_irqsave(shost->host_lock, flags);
393 scsi_device_put(sdev);
396 spin_unlock_irqrestore(shost->host_lock, flags);
399 static inline bool scsi_device_is_busy(struct scsi_device *sdev)
401 if (atomic_read(&sdev->device_busy) >= sdev->queue_depth)
403 if (atomic_read(&sdev->device_blocked) > 0)
408 static inline bool scsi_target_is_busy(struct scsi_target *starget)
410 if (starget->can_queue > 0) {
411 if (atomic_read(&starget->target_busy) >= starget->can_queue)
413 if (atomic_read(&starget->target_blocked) > 0)
419 static inline bool scsi_host_is_busy(struct Scsi_Host *shost)
421 if (shost->can_queue > 0 &&
422 atomic_read(&shost->host_busy) >= shost->can_queue)
424 if (atomic_read(&shost->host_blocked) > 0)
426 if (shost->host_self_blocked)
431 static void scsi_starved_list_run(struct Scsi_Host *shost)
433 LIST_HEAD(starved_list);
434 struct scsi_device *sdev;
437 spin_lock_irqsave(shost->host_lock, flags);
438 list_splice_init(&shost->starved_list, &starved_list);
440 while (!list_empty(&starved_list)) {
441 struct request_queue *slq;
444 * As long as shost is accepting commands and we have
445 * starved queues, call blk_run_queue. scsi_request_fn
446 * drops the queue_lock and can add us back to the
449 * host_lock protects the starved_list and starved_entry.
450 * scsi_request_fn must get the host_lock before checking
451 * or modifying starved_list or starved_entry.
453 if (scsi_host_is_busy(shost))
456 sdev = list_entry(starved_list.next,
457 struct scsi_device, starved_entry);
458 list_del_init(&sdev->starved_entry);
459 if (scsi_target_is_busy(scsi_target(sdev))) {
460 list_move_tail(&sdev->starved_entry,
461 &shost->starved_list);
466 * Once we drop the host lock, a racing scsi_remove_device()
467 * call may remove the sdev from the starved list and destroy
468 * it and the queue. Mitigate by taking a reference to the
469 * queue and never touching the sdev again after we drop the
470 * host lock. Note: if __scsi_remove_device() invokes
471 * blk_cleanup_queue() before the queue is run from this
472 * function then blk_run_queue() will return immediately since
473 * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
475 slq = sdev->request_queue;
476 if (!blk_get_queue(slq))
478 spin_unlock_irqrestore(shost->host_lock, flags);
480 scsi_kick_queue(slq);
483 spin_lock_irqsave(shost->host_lock, flags);
485 /* put any unprocessed entries back */
486 list_splice(&starved_list, &shost->starved_list);
487 spin_unlock_irqrestore(shost->host_lock, flags);
491 * Function: scsi_run_queue()
493 * Purpose: Select a proper request queue to serve next
495 * Arguments: q - last request's queue
499 * Notes: The previous command was completely finished, start
500 * a new one if possible.
502 static void scsi_run_queue(struct request_queue *q)
504 struct scsi_device *sdev = q->queuedata;
506 if (scsi_target(sdev)->single_lun)
507 scsi_single_lun_run(sdev);
508 if (!list_empty(&sdev->host->starved_list))
509 scsi_starved_list_run(sdev->host);
511 blk_mq_run_hw_queues(q, false);
514 void scsi_requeue_run_queue(struct work_struct *work)
516 struct scsi_device *sdev;
517 struct request_queue *q;
519 sdev = container_of(work, struct scsi_device, requeue_work);
520 q = sdev->request_queue;
524 void scsi_run_host_queues(struct Scsi_Host *shost)
526 struct scsi_device *sdev;
528 shost_for_each_device(sdev, shost)
529 scsi_run_queue(sdev->request_queue);
532 static void scsi_uninit_cmd(struct scsi_cmnd *cmd)
534 if (!blk_rq_is_passthrough(cmd->request)) {
535 struct scsi_driver *drv = scsi_cmd_to_driver(cmd);
537 if (drv->uninit_command)
538 drv->uninit_command(cmd);
542 static void scsi_mq_free_sgtables(struct scsi_cmnd *cmd)
544 if (cmd->sdb.table.nents)
545 sg_free_table_chained(&cmd->sdb.table, true);
546 if (scsi_prot_sg_count(cmd))
547 sg_free_table_chained(&cmd->prot_sdb->table, true);
550 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd)
552 scsi_mq_free_sgtables(cmd);
553 scsi_uninit_cmd(cmd);
554 scsi_del_cmd_from_list(cmd);
557 /* Returns false when no more bytes to process, true if there are more */
558 static bool scsi_end_request(struct request *req, blk_status_t error,
561 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
562 struct scsi_device *sdev = cmd->device;
563 struct request_queue *q = sdev->request_queue;
565 if (blk_update_request(req, error, bytes))
568 if (blk_queue_add_random(q))
569 add_disk_randomness(req->rq_disk);
571 if (!blk_rq_is_scsi(req)) {
572 WARN_ON_ONCE(!(cmd->flags & SCMD_INITIALIZED));
573 cmd->flags &= ~SCMD_INITIALIZED;
577 * Calling rcu_barrier() is not necessary here because the
578 * SCSI error handler guarantees that the function called by
579 * call_rcu() has been called before scsi_end_request() is
582 destroy_rcu_head(&cmd->rcu);
585 * In the MQ case the command gets freed by __blk_mq_end_request,
586 * so we have to do all cleanup that depends on it earlier.
588 * We also can't kick the queues from irq context, so we
589 * will have to defer it to a workqueue.
591 scsi_mq_uninit_cmd(cmd);
594 * queue is still alive, so grab the ref for preventing it
595 * from being cleaned up during running queue.
597 percpu_ref_get(&q->q_usage_counter);
599 __blk_mq_end_request(req, error);
601 if (scsi_target(sdev)->single_lun ||
602 !list_empty(&sdev->host->starved_list))
603 kblockd_schedule_work(&sdev->requeue_work);
605 blk_mq_run_hw_queues(q, true);
607 percpu_ref_put(&q->q_usage_counter);
612 * scsi_result_to_blk_status - translate a SCSI result code into blk_status_t
614 * @result: scsi error code
616 * Translate a SCSI result code into a blk_status_t value. May reset the host
617 * byte of @cmd->result.
619 static blk_status_t scsi_result_to_blk_status(struct scsi_cmnd *cmd, int result)
621 switch (host_byte(result)) {
624 * Also check the other bytes than the status byte in result
625 * to handle the case when a SCSI LLD sets result to
626 * DRIVER_SENSE << 24 without setting SAM_STAT_CHECK_CONDITION.
628 if (scsi_status_is_good(result) && (result & ~0xff) == 0)
630 return BLK_STS_IOERR;
631 case DID_TRANSPORT_FAILFAST:
632 return BLK_STS_TRANSPORT;
633 case DID_TARGET_FAILURE:
634 set_host_byte(cmd, DID_OK);
635 return BLK_STS_TARGET;
636 case DID_NEXUS_FAILURE:
637 set_host_byte(cmd, DID_OK);
638 return BLK_STS_NEXUS;
639 case DID_ALLOC_FAILURE:
640 set_host_byte(cmd, DID_OK);
641 return BLK_STS_NOSPC;
642 case DID_MEDIUM_ERROR:
643 set_host_byte(cmd, DID_OK);
644 return BLK_STS_MEDIUM;
646 return BLK_STS_IOERR;
650 /* Helper for scsi_io_completion() when "reprep" action required. */
651 static void scsi_io_completion_reprep(struct scsi_cmnd *cmd,
652 struct request_queue *q)
654 /* A new command will be prepared and issued. */
655 scsi_mq_requeue_cmd(cmd);
658 /* Helper for scsi_io_completion() when special action required. */
659 static void scsi_io_completion_action(struct scsi_cmnd *cmd, int result)
661 struct request_queue *q = cmd->device->request_queue;
662 struct request *req = cmd->request;
664 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
665 ACTION_DELAYED_RETRY} action;
666 unsigned long wait_for = (cmd->allowed + 1) * req->timeout;
667 struct scsi_sense_hdr sshdr;
669 bool sense_current = true; /* false implies "deferred sense" */
670 blk_status_t blk_stat;
672 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
674 sense_current = !scsi_sense_is_deferred(&sshdr);
676 blk_stat = scsi_result_to_blk_status(cmd, result);
678 if (host_byte(result) == DID_RESET) {
679 /* Third party bus reset or reset for error recovery
680 * reasons. Just retry the command and see what
683 action = ACTION_RETRY;
684 } else if (sense_valid && sense_current) {
685 switch (sshdr.sense_key) {
687 if (cmd->device->removable) {
688 /* Detected disc change. Set a bit
689 * and quietly refuse further access.
691 cmd->device->changed = 1;
692 action = ACTION_FAIL;
694 /* Must have been a power glitch, or a
695 * bus reset. Could not have been a
696 * media change, so we just retry the
697 * command and see what happens.
699 action = ACTION_RETRY;
702 case ILLEGAL_REQUEST:
703 /* If we had an ILLEGAL REQUEST returned, then
704 * we may have performed an unsupported
705 * command. The only thing this should be
706 * would be a ten byte read where only a six
707 * byte read was supported. Also, on a system
708 * where READ CAPACITY failed, we may have
709 * read past the end of the disk.
711 if ((cmd->device->use_10_for_rw &&
712 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
713 (cmd->cmnd[0] == READ_10 ||
714 cmd->cmnd[0] == WRITE_10)) {
715 /* This will issue a new 6-byte command. */
716 cmd->device->use_10_for_rw = 0;
717 action = ACTION_REPREP;
718 } else if (sshdr.asc == 0x10) /* DIX */ {
719 action = ACTION_FAIL;
720 blk_stat = BLK_STS_PROTECTION;
721 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
722 } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
723 action = ACTION_FAIL;
724 blk_stat = BLK_STS_TARGET;
726 action = ACTION_FAIL;
728 case ABORTED_COMMAND:
729 action = ACTION_FAIL;
730 if (sshdr.asc == 0x10) /* DIF */
731 blk_stat = BLK_STS_PROTECTION;
734 /* If the device is in the process of becoming
735 * ready, or has a temporary blockage, retry.
737 if (sshdr.asc == 0x04) {
738 switch (sshdr.ascq) {
739 case 0x01: /* becoming ready */
740 case 0x04: /* format in progress */
741 case 0x05: /* rebuild in progress */
742 case 0x06: /* recalculation in progress */
743 case 0x07: /* operation in progress */
744 case 0x08: /* Long write in progress */
745 case 0x09: /* self test in progress */
746 case 0x14: /* space allocation in progress */
747 case 0x1a: /* start stop unit in progress */
748 case 0x1b: /* sanitize in progress */
749 case 0x1d: /* configuration in progress */
750 case 0x24: /* depopulation in progress */
751 action = ACTION_DELAYED_RETRY;
754 action = ACTION_FAIL;
758 action = ACTION_FAIL;
760 case VOLUME_OVERFLOW:
761 /* See SSC3rXX or current. */
762 action = ACTION_FAIL;
765 action = ACTION_FAIL;
769 action = ACTION_FAIL;
771 if (action != ACTION_FAIL &&
772 time_before(cmd->jiffies_at_alloc + wait_for, jiffies))
773 action = ACTION_FAIL;
777 /* Give up and fail the remainder of the request */
778 if (!(req->rq_flags & RQF_QUIET)) {
779 static DEFINE_RATELIMIT_STATE(_rs,
780 DEFAULT_RATELIMIT_INTERVAL,
781 DEFAULT_RATELIMIT_BURST);
783 if (unlikely(scsi_logging_level))
785 SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
786 SCSI_LOG_MLCOMPLETE_BITS);
789 * if logging is enabled the failure will be printed
790 * in scsi_log_completion(), so avoid duplicate messages
792 if (!level && __ratelimit(&_rs)) {
793 scsi_print_result(cmd, NULL, FAILED);
794 if (driver_byte(result) == DRIVER_SENSE)
795 scsi_print_sense(cmd);
796 scsi_print_command(cmd);
799 if (!scsi_end_request(req, blk_stat, blk_rq_err_bytes(req)))
803 scsi_io_completion_reprep(cmd, q);
806 /* Retry the same command immediately */
807 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, false);
809 case ACTION_DELAYED_RETRY:
810 /* Retry the same command after a delay */
811 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, false);
817 * Helper for scsi_io_completion() when cmd->result is non-zero. Returns a
818 * new result that may suppress further error checking. Also modifies
819 * *blk_statp in some cases.
821 static int scsi_io_completion_nz_result(struct scsi_cmnd *cmd, int result,
822 blk_status_t *blk_statp)
825 bool sense_current = true; /* false implies "deferred sense" */
826 struct request *req = cmd->request;
827 struct scsi_sense_hdr sshdr;
829 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
831 sense_current = !scsi_sense_is_deferred(&sshdr);
833 if (blk_rq_is_passthrough(req)) {
836 * SG_IO wants current and deferred errors
838 scsi_req(req)->sense_len =
839 min(8 + cmd->sense_buffer[7],
840 SCSI_SENSE_BUFFERSIZE);
843 *blk_statp = scsi_result_to_blk_status(cmd, result);
844 } else if (blk_rq_bytes(req) == 0 && sense_current) {
846 * Flush commands do not transfers any data, and thus cannot use
847 * good_bytes != blk_rq_bytes(req) as the signal for an error.
848 * This sets *blk_statp explicitly for the problem case.
850 *blk_statp = scsi_result_to_blk_status(cmd, result);
853 * Recovered errors need reporting, but they're always treated as
854 * success, so fiddle the result code here. For passthrough requests
855 * we already took a copy of the original into sreq->result which
856 * is what gets returned to the user
858 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
859 bool do_print = true;
861 * if ATA PASS-THROUGH INFORMATION AVAILABLE [0x0, 0x1d]
862 * skip print since caller wants ATA registers. Only occurs
863 * on SCSI ATA PASS_THROUGH commands when CK_COND=1
865 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
867 else if (req->rq_flags & RQF_QUIET)
870 scsi_print_sense(cmd);
872 /* for passthrough, *blk_statp may be set */
873 *blk_statp = BLK_STS_OK;
876 * Another corner case: the SCSI status byte is non-zero but 'good'.
877 * Example: PRE-FETCH command returns SAM_STAT_CONDITION_MET when
878 * it is able to fit nominated LBs in its cache (and SAM_STAT_GOOD
879 * if it can't fit). Treat SAM_STAT_CONDITION_MET and the related
880 * intermediate statuses (both obsolete in SAM-4) as good.
882 if (status_byte(result) && scsi_status_is_good(result)) {
884 *blk_statp = BLK_STS_OK;
890 * Function: scsi_io_completion()
892 * Purpose: Completion processing for block device I/O requests.
894 * Arguments: cmd - command that is finished.
896 * Lock status: Assumed that no lock is held upon entry.
900 * Notes: We will finish off the specified number of sectors. If we
901 * are done, the command block will be released and the queue
902 * function will be goosed. If we are not done then we have to
903 * figure out what to do next:
905 * a) We can call scsi_requeue_command(). The request
906 * will be unprepared and put back on the queue. Then
907 * a new command will be created for it. This should
908 * be used if we made forward progress, or if we want
909 * to switch from READ(10) to READ(6) for example.
911 * b) We can call __scsi_queue_insert(). The request will
912 * be put back on the queue and retried using the same
913 * command as before, possibly after a delay.
915 * c) We can call scsi_end_request() with blk_stat other than
916 * BLK_STS_OK, to fail the remainder of the request.
918 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
920 int result = cmd->result;
921 struct request_queue *q = cmd->device->request_queue;
922 struct request *req = cmd->request;
923 blk_status_t blk_stat = BLK_STS_OK;
925 if (unlikely(result)) /* a nz result may or may not be an error */
926 result = scsi_io_completion_nz_result(cmd, result, &blk_stat);
928 if (unlikely(blk_rq_is_passthrough(req))) {
930 * scsi_result_to_blk_status may have reset the host_byte
932 scsi_req(req)->result = cmd->result;
936 * Next deal with any sectors which we were able to correctly
939 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd,
940 "%u sectors total, %d bytes done.\n",
941 blk_rq_sectors(req), good_bytes));
944 * Next deal with any sectors which we were able to correctly
945 * handle. Failed, zero length commands always need to drop down
946 * to retry code. Fast path should return in this block.
948 if (likely(blk_rq_bytes(req) > 0 || blk_stat == BLK_STS_OK)) {
949 if (likely(!scsi_end_request(req, blk_stat, good_bytes)))
950 return; /* no bytes remaining */
953 /* Kill remainder if no retries. */
954 if (unlikely(blk_stat && scsi_noretry_cmd(cmd))) {
955 if (scsi_end_request(req, blk_stat, blk_rq_bytes(req)))
957 "Bytes remaining after failed, no-retry command");
962 * If there had been no error, but we have leftover bytes in the
963 * requeues just queue the command up again.
965 if (likely(result == 0))
966 scsi_io_completion_reprep(cmd, q);
968 scsi_io_completion_action(cmd, result);
971 static blk_status_t scsi_init_sgtable(struct request *req,
972 struct scsi_data_buffer *sdb)
977 * If sg table allocation fails, requeue request later.
979 if (unlikely(sg_alloc_table_chained(&sdb->table,
980 blk_rq_nr_phys_segments(req), sdb->table.sgl)))
981 return BLK_STS_RESOURCE;
984 * Next, walk the list, and fill in the addresses and sizes of
987 count = blk_rq_map_sg(req->q, req, sdb->table.sgl);
988 BUG_ON(count > sdb->table.nents);
989 sdb->table.nents = count;
990 sdb->length = blk_rq_payload_bytes(req);
995 * Function: scsi_init_io()
997 * Purpose: SCSI I/O initialize function.
999 * Arguments: cmd - Command descriptor we wish to initialize
1001 * Returns: BLK_STS_OK on success
1002 * BLK_STS_RESOURCE if the failure is retryable
1003 * BLK_STS_IOERR if the failure is fatal
1005 blk_status_t scsi_init_io(struct scsi_cmnd *cmd)
1007 struct request *rq = cmd->request;
1010 if (WARN_ON_ONCE(!blk_rq_nr_phys_segments(rq)))
1011 return BLK_STS_IOERR;
1013 ret = scsi_init_sgtable(rq, &cmd->sdb);
1017 if (blk_integrity_rq(rq)) {
1018 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1021 if (WARN_ON_ONCE(!prot_sdb)) {
1023 * This can happen if someone (e.g. multipath)
1024 * queues a command to a device on an adapter
1025 * that does not support DIX.
1027 ret = BLK_STS_IOERR;
1028 goto out_free_sgtables;
1031 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
1033 if (sg_alloc_table_chained(&prot_sdb->table, ivecs,
1034 prot_sdb->table.sgl)) {
1035 ret = BLK_STS_RESOURCE;
1036 goto out_free_sgtables;
1039 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
1040 prot_sdb->table.sgl);
1041 BUG_ON(count > ivecs);
1042 BUG_ON(count > queue_max_integrity_segments(rq->q));
1044 cmd->prot_sdb = prot_sdb;
1045 cmd->prot_sdb->table.nents = count;
1050 scsi_mq_free_sgtables(cmd);
1053 EXPORT_SYMBOL(scsi_init_io);
1056 * scsi_initialize_rq - initialize struct scsi_cmnd partially
1057 * @rq: Request associated with the SCSI command to be initialized.
1059 * This function initializes the members of struct scsi_cmnd that must be
1060 * initialized before request processing starts and that won't be
1061 * reinitialized if a SCSI command is requeued.
1063 * Called from inside blk_get_request() for pass-through requests and from
1064 * inside scsi_init_command() for filesystem requests.
1066 static void scsi_initialize_rq(struct request *rq)
1068 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1070 scsi_req_init(&cmd->req);
1071 init_rcu_head(&cmd->rcu);
1072 cmd->jiffies_at_alloc = jiffies;
1076 /* Add a command to the list used by the aacraid and dpt_i2o drivers */
1077 void scsi_add_cmd_to_list(struct scsi_cmnd *cmd)
1079 struct scsi_device *sdev = cmd->device;
1080 struct Scsi_Host *shost = sdev->host;
1081 unsigned long flags;
1083 if (shost->use_cmd_list) {
1084 spin_lock_irqsave(&sdev->list_lock, flags);
1085 list_add_tail(&cmd->list, &sdev->cmd_list);
1086 spin_unlock_irqrestore(&sdev->list_lock, flags);
1090 /* Remove a command from the list used by the aacraid and dpt_i2o drivers */
1091 void scsi_del_cmd_from_list(struct scsi_cmnd *cmd)
1093 struct scsi_device *sdev = cmd->device;
1094 struct Scsi_Host *shost = sdev->host;
1095 unsigned long flags;
1097 if (shost->use_cmd_list) {
1098 spin_lock_irqsave(&sdev->list_lock, flags);
1099 BUG_ON(list_empty(&cmd->list));
1100 list_del_init(&cmd->list);
1101 spin_unlock_irqrestore(&sdev->list_lock, flags);
1105 /* Called after a request has been started. */
1106 void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd)
1108 void *buf = cmd->sense_buffer;
1109 void *prot = cmd->prot_sdb;
1110 struct request *rq = blk_mq_rq_from_pdu(cmd);
1111 unsigned int flags = cmd->flags & SCMD_PRESERVED_FLAGS;
1112 unsigned long jiffies_at_alloc;
1115 if (!blk_rq_is_scsi(rq) && !(flags & SCMD_INITIALIZED)) {
1116 flags |= SCMD_INITIALIZED;
1117 scsi_initialize_rq(rq);
1120 jiffies_at_alloc = cmd->jiffies_at_alloc;
1121 retries = cmd->retries;
1122 /* zero out the cmd, except for the embedded scsi_request */
1123 memset((char *)cmd + sizeof(cmd->req), 0,
1124 sizeof(*cmd) - sizeof(cmd->req) + dev->host->hostt->cmd_size);
1127 cmd->sense_buffer = buf;
1128 cmd->prot_sdb = prot;
1130 INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
1131 cmd->jiffies_at_alloc = jiffies_at_alloc;
1132 cmd->retries = retries;
1134 scsi_add_cmd_to_list(cmd);
1137 static blk_status_t scsi_setup_scsi_cmnd(struct scsi_device *sdev,
1138 struct request *req)
1140 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1143 * Passthrough requests may transfer data, in which case they must
1144 * a bio attached to them. Or they might contain a SCSI command
1145 * that does not transfer data, in which case they may optionally
1146 * submit a request without an attached bio.
1149 blk_status_t ret = scsi_init_io(cmd);
1150 if (unlikely(ret != BLK_STS_OK))
1153 BUG_ON(blk_rq_bytes(req));
1155 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1158 cmd->cmd_len = scsi_req(req)->cmd_len;
1159 cmd->cmnd = scsi_req(req)->cmd;
1160 cmd->transfersize = blk_rq_bytes(req);
1161 cmd->allowed = scsi_req(req)->retries;
1166 * Setup a normal block command. These are simple request from filesystems
1167 * that still need to be translated to SCSI CDBs from the ULD.
1169 static blk_status_t scsi_setup_fs_cmnd(struct scsi_device *sdev,
1170 struct request *req)
1172 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1174 if (unlikely(sdev->handler && sdev->handler->prep_fn)) {
1175 blk_status_t ret = sdev->handler->prep_fn(sdev, req);
1176 if (ret != BLK_STS_OK)
1180 cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd;
1181 memset(cmd->cmnd, 0, BLK_MAX_CDB);
1182 return scsi_cmd_to_driver(cmd)->init_command(cmd);
1185 static blk_status_t scsi_setup_cmnd(struct scsi_device *sdev,
1186 struct request *req)
1188 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1190 if (!blk_rq_bytes(req))
1191 cmd->sc_data_direction = DMA_NONE;
1192 else if (rq_data_dir(req) == WRITE)
1193 cmd->sc_data_direction = DMA_TO_DEVICE;
1195 cmd->sc_data_direction = DMA_FROM_DEVICE;
1197 if (blk_rq_is_scsi(req))
1198 return scsi_setup_scsi_cmnd(sdev, req);
1200 return scsi_setup_fs_cmnd(sdev, req);
1204 scsi_prep_state_check(struct scsi_device *sdev, struct request *req)
1206 switch (sdev->sdev_state) {
1208 case SDEV_TRANSPORT_OFFLINE:
1210 * If the device is offline we refuse to process any
1211 * commands. The device must be brought online
1212 * before trying any recovery commands.
1214 sdev_printk(KERN_ERR, sdev,
1215 "rejecting I/O to offline device\n");
1216 return BLK_STS_IOERR;
1219 * If the device is fully deleted, we refuse to
1220 * process any commands as well.
1222 sdev_printk(KERN_ERR, sdev,
1223 "rejecting I/O to dead device\n");
1224 return BLK_STS_IOERR;
1226 case SDEV_CREATED_BLOCK:
1227 return BLK_STS_RESOURCE;
1230 * If the devices is blocked we defer normal commands.
1232 if (req && !(req->rq_flags & RQF_PREEMPT))
1233 return BLK_STS_RESOURCE;
1237 * For any other not fully online state we only allow
1238 * special commands. In particular any user initiated
1239 * command is not allowed.
1241 if (req && !(req->rq_flags & RQF_PREEMPT))
1242 return BLK_STS_IOERR;
1248 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1251 * Called with the queue_lock held.
1253 static inline int scsi_dev_queue_ready(struct request_queue *q,
1254 struct scsi_device *sdev)
1258 busy = atomic_inc_return(&sdev->device_busy) - 1;
1259 if (atomic_read(&sdev->device_blocked)) {
1264 * unblock after device_blocked iterates to zero
1266 if (atomic_dec_return(&sdev->device_blocked) > 0)
1268 SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev,
1269 "unblocking device at zero depth\n"));
1272 if (busy >= sdev->queue_depth)
1277 atomic_dec(&sdev->device_busy);
1282 * scsi_target_queue_ready: checks if there we can send commands to target
1283 * @sdev: scsi device on starget to check.
1285 static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1286 struct scsi_device *sdev)
1288 struct scsi_target *starget = scsi_target(sdev);
1291 if (starget->single_lun) {
1292 spin_lock_irq(shost->host_lock);
1293 if (starget->starget_sdev_user &&
1294 starget->starget_sdev_user != sdev) {
1295 spin_unlock_irq(shost->host_lock);
1298 starget->starget_sdev_user = sdev;
1299 spin_unlock_irq(shost->host_lock);
1302 if (starget->can_queue <= 0)
1305 busy = atomic_inc_return(&starget->target_busy) - 1;
1306 if (atomic_read(&starget->target_blocked) > 0) {
1311 * unblock after target_blocked iterates to zero
1313 if (atomic_dec_return(&starget->target_blocked) > 0)
1316 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1317 "unblocking target at zero depth\n"));
1320 if (busy >= starget->can_queue)
1326 spin_lock_irq(shost->host_lock);
1327 list_move_tail(&sdev->starved_entry, &shost->starved_list);
1328 spin_unlock_irq(shost->host_lock);
1330 if (starget->can_queue > 0)
1331 atomic_dec(&starget->target_busy);
1336 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1337 * return 0. We must end up running the queue again whenever 0 is
1338 * returned, else IO can hang.
1340 static inline int scsi_host_queue_ready(struct request_queue *q,
1341 struct Scsi_Host *shost,
1342 struct scsi_device *sdev)
1346 if (scsi_host_in_recovery(shost))
1349 busy = atomic_inc_return(&shost->host_busy) - 1;
1350 if (atomic_read(&shost->host_blocked) > 0) {
1355 * unblock after host_blocked iterates to zero
1357 if (atomic_dec_return(&shost->host_blocked) > 0)
1361 shost_printk(KERN_INFO, shost,
1362 "unblocking host at zero depth\n"));
1365 if (shost->can_queue > 0 && busy >= shost->can_queue)
1367 if (shost->host_self_blocked)
1370 /* We're OK to process the command, so we can't be starved */
1371 if (!list_empty(&sdev->starved_entry)) {
1372 spin_lock_irq(shost->host_lock);
1373 if (!list_empty(&sdev->starved_entry))
1374 list_del_init(&sdev->starved_entry);
1375 spin_unlock_irq(shost->host_lock);
1381 spin_lock_irq(shost->host_lock);
1382 if (list_empty(&sdev->starved_entry))
1383 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1384 spin_unlock_irq(shost->host_lock);
1386 scsi_dec_host_busy(shost);
1391 * Busy state exporting function for request stacking drivers.
1393 * For efficiency, no lock is taken to check the busy state of
1394 * shost/starget/sdev, since the returned value is not guaranteed and
1395 * may be changed after request stacking drivers call the function,
1396 * regardless of taking lock or not.
1398 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1399 * needs to return 'not busy'. Otherwise, request stacking drivers
1400 * may hold requests forever.
1402 static bool scsi_mq_lld_busy(struct request_queue *q)
1404 struct scsi_device *sdev = q->queuedata;
1405 struct Scsi_Host *shost;
1407 if (blk_queue_dying(q))
1413 * Ignore host/starget busy state.
1414 * Since block layer does not have a concept of fairness across
1415 * multiple queues, congestion of host/starget needs to be handled
1418 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
1424 static void scsi_softirq_done(struct request *rq)
1426 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1427 unsigned long wait_for = (cmd->allowed + 1) * rq->timeout;
1430 INIT_LIST_HEAD(&cmd->eh_entry);
1432 atomic_inc(&cmd->device->iodone_cnt);
1434 atomic_inc(&cmd->device->ioerr_cnt);
1436 disposition = scsi_decide_disposition(cmd);
1437 if (disposition != SUCCESS &&
1438 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1439 sdev_printk(KERN_ERR, cmd->device,
1440 "timing out command, waited %lus\n",
1442 disposition = SUCCESS;
1445 scsi_log_completion(cmd, disposition);
1447 switch (disposition) {
1449 scsi_finish_command(cmd);
1452 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1454 case ADD_TO_MLQUEUE:
1455 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1458 scsi_eh_scmd_add(cmd);
1464 * scsi_dispatch_command - Dispatch a command to the low-level driver.
1465 * @cmd: command block we are dispatching.
1467 * Return: nonzero return request was rejected and device's queue needs to be
1470 static int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
1472 struct Scsi_Host *host = cmd->device->host;
1475 atomic_inc(&cmd->device->iorequest_cnt);
1477 /* check if the device is still usable */
1478 if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
1479 /* in SDEV_DEL we error all commands. DID_NO_CONNECT
1480 * returns an immediate error upwards, and signals
1481 * that the device is no longer present */
1482 cmd->result = DID_NO_CONNECT << 16;
1486 /* Check to see if the scsi lld made this device blocked. */
1487 if (unlikely(scsi_device_blocked(cmd->device))) {
1489 * in blocked state, the command is just put back on
1490 * the device queue. The suspend state has already
1491 * blocked the queue so future requests should not
1492 * occur until the device transitions out of the
1495 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1496 "queuecommand : device blocked\n"));
1497 return SCSI_MLQUEUE_DEVICE_BUSY;
1500 /* Store the LUN value in cmnd, if needed. */
1501 if (cmd->device->lun_in_cdb)
1502 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
1503 (cmd->device->lun << 5 & 0xe0);
1508 * Before we queue this command, check if the command
1509 * length exceeds what the host adapter can handle.
1511 if (cmd->cmd_len > cmd->device->host->max_cmd_len) {
1512 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1513 "queuecommand : command too long. "
1514 "cdb_size=%d host->max_cmd_len=%d\n",
1515 cmd->cmd_len, cmd->device->host->max_cmd_len));
1516 cmd->result = (DID_ABORT << 16);
1520 if (unlikely(host->shost_state == SHOST_DEL)) {
1521 cmd->result = (DID_NO_CONNECT << 16);
1526 trace_scsi_dispatch_cmd_start(cmd);
1527 rtn = host->hostt->queuecommand(host, cmd);
1529 trace_scsi_dispatch_cmd_error(cmd, rtn);
1530 if (rtn != SCSI_MLQUEUE_DEVICE_BUSY &&
1531 rtn != SCSI_MLQUEUE_TARGET_BUSY)
1532 rtn = SCSI_MLQUEUE_HOST_BUSY;
1534 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1535 "queuecommand : request rejected\n"));
1540 cmd->scsi_done(cmd);
1544 /* Size in bytes of the sg-list stored in the scsi-mq command-private data. */
1545 static unsigned int scsi_mq_sgl_size(struct Scsi_Host *shost)
1547 return min_t(unsigned int, shost->sg_tablesize, SG_CHUNK_SIZE) *
1548 sizeof(struct scatterlist);
1551 static blk_status_t scsi_mq_prep_fn(struct request *req)
1553 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1554 struct scsi_device *sdev = req->q->queuedata;
1555 struct Scsi_Host *shost = sdev->host;
1556 struct scatterlist *sg;
1558 scsi_init_command(sdev, cmd);
1561 cmd->tag = req->tag;
1562 cmd->prot_op = SCSI_PROT_NORMAL;
1564 sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
1565 cmd->sdb.table.sgl = sg;
1567 if (scsi_host_get_prot(shost)) {
1568 memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer));
1570 cmd->prot_sdb->table.sgl =
1571 (struct scatterlist *)(cmd->prot_sdb + 1);
1574 blk_mq_start_request(req);
1576 return scsi_setup_cmnd(sdev, req);
1579 static void scsi_mq_done(struct scsi_cmnd *cmd)
1581 if (unlikely(test_and_set_bit(SCMD_STATE_COMPLETE, &cmd->state)))
1583 trace_scsi_dispatch_cmd_done(cmd);
1586 * If the block layer didn't complete the request due to a timeout
1587 * injection, scsi must clear its internal completed state so that the
1588 * timeout handler will see it needs to escalate its own error
1591 if (unlikely(!blk_mq_complete_request(cmd->request)))
1592 clear_bit(SCMD_STATE_COMPLETE, &cmd->state);
1595 static void scsi_mq_put_budget(struct blk_mq_hw_ctx *hctx)
1597 struct request_queue *q = hctx->queue;
1598 struct scsi_device *sdev = q->queuedata;
1600 atomic_dec(&sdev->device_busy);
1603 static bool scsi_mq_get_budget(struct blk_mq_hw_ctx *hctx)
1605 struct request_queue *q = hctx->queue;
1606 struct scsi_device *sdev = q->queuedata;
1608 if (scsi_dev_queue_ready(q, sdev))
1611 if (atomic_read(&sdev->device_busy) == 0 && !scsi_device_blocked(sdev))
1612 blk_mq_delay_run_hw_queue(hctx, SCSI_QUEUE_DELAY);
1616 static blk_status_t scsi_queue_rq(struct blk_mq_hw_ctx *hctx,
1617 const struct blk_mq_queue_data *bd)
1619 struct request *req = bd->rq;
1620 struct request_queue *q = req->q;
1621 struct scsi_device *sdev = q->queuedata;
1622 struct Scsi_Host *shost = sdev->host;
1623 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1628 * If the device is not in running state we will reject some or all
1631 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1632 ret = scsi_prep_state_check(sdev, req);
1633 if (ret != BLK_STS_OK)
1634 goto out_put_budget;
1637 ret = BLK_STS_RESOURCE;
1638 if (!scsi_target_queue_ready(shost, sdev))
1639 goto out_put_budget;
1640 if (!scsi_host_queue_ready(q, shost, sdev))
1641 goto out_dec_target_busy;
1643 if (!(req->rq_flags & RQF_DONTPREP)) {
1644 ret = scsi_mq_prep_fn(req);
1645 if (ret != BLK_STS_OK)
1646 goto out_dec_host_busy;
1647 req->rq_flags |= RQF_DONTPREP;
1649 clear_bit(SCMD_STATE_COMPLETE, &cmd->state);
1650 blk_mq_start_request(req);
1653 if (sdev->simple_tags)
1654 cmd->flags |= SCMD_TAGGED;
1656 cmd->flags &= ~SCMD_TAGGED;
1658 scsi_init_cmd_errh(cmd);
1659 cmd->scsi_done = scsi_mq_done;
1661 reason = scsi_dispatch_cmd(cmd);
1663 scsi_set_blocked(cmd, reason);
1664 ret = BLK_STS_RESOURCE;
1665 goto out_dec_host_busy;
1671 scsi_dec_host_busy(shost);
1672 out_dec_target_busy:
1673 if (scsi_target(sdev)->can_queue > 0)
1674 atomic_dec(&scsi_target(sdev)->target_busy);
1676 scsi_mq_put_budget(hctx);
1680 case BLK_STS_RESOURCE:
1681 if (atomic_read(&sdev->device_busy) ||
1682 scsi_device_blocked(sdev))
1683 ret = BLK_STS_DEV_RESOURCE;
1686 if (unlikely(!scsi_device_online(sdev)))
1687 scsi_req(req)->result = DID_NO_CONNECT << 16;
1689 scsi_req(req)->result = DID_ERROR << 16;
1691 * Make sure to release all allocated resources when
1692 * we hit an error, as we will never see this command
1695 if (req->rq_flags & RQF_DONTPREP)
1696 scsi_mq_uninit_cmd(cmd);
1702 static enum blk_eh_timer_return scsi_timeout(struct request *req,
1706 return BLK_EH_RESET_TIMER;
1707 return scsi_times_out(req);
1710 static int scsi_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
1711 unsigned int hctx_idx, unsigned int numa_node)
1713 struct Scsi_Host *shost = set->driver_data;
1714 const bool unchecked_isa_dma = shost->unchecked_isa_dma;
1715 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1716 struct scatterlist *sg;
1718 if (unchecked_isa_dma)
1719 cmd->flags |= SCMD_UNCHECKED_ISA_DMA;
1720 cmd->sense_buffer = scsi_alloc_sense_buffer(unchecked_isa_dma,
1721 GFP_KERNEL, numa_node);
1722 if (!cmd->sense_buffer)
1724 cmd->req.sense = cmd->sense_buffer;
1726 if (scsi_host_get_prot(shost)) {
1727 sg = (void *)cmd + sizeof(struct scsi_cmnd) +
1728 shost->hostt->cmd_size;
1729 cmd->prot_sdb = (void *)sg + scsi_mq_sgl_size(shost);
1735 static void scsi_mq_exit_request(struct blk_mq_tag_set *set, struct request *rq,
1736 unsigned int hctx_idx)
1738 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1740 scsi_free_sense_buffer(cmd->flags & SCMD_UNCHECKED_ISA_DMA,
1744 static int scsi_map_queues(struct blk_mq_tag_set *set)
1746 struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set);
1748 if (shost->hostt->map_queues)
1749 return shost->hostt->map_queues(shost);
1750 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
1753 void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q)
1755 struct device *dev = shost->dma_dev;
1758 * this limit is imposed by hardware restrictions
1760 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
1763 if (scsi_host_prot_dma(shost)) {
1764 shost->sg_prot_tablesize =
1765 min_not_zero(shost->sg_prot_tablesize,
1766 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
1767 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
1768 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
1771 blk_queue_max_hw_sectors(q, shost->max_sectors);
1772 if (shost->unchecked_isa_dma)
1773 blk_queue_bounce_limit(q, BLK_BOUNCE_ISA);
1774 blk_queue_segment_boundary(q, shost->dma_boundary);
1775 dma_set_seg_boundary(dev, shost->dma_boundary);
1777 blk_queue_max_segment_size(q, shost->max_segment_size);
1778 dma_set_max_seg_size(dev, shost->max_segment_size);
1781 * Set a reasonable default alignment: The larger of 32-byte (dword),
1782 * which is a common minimum for HBAs, and the minimum DMA alignment,
1783 * which is set by the platform.
1785 * Devices that require a bigger alignment can increase it later.
1787 blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1);
1789 EXPORT_SYMBOL_GPL(__scsi_init_queue);
1791 static const struct blk_mq_ops scsi_mq_ops = {
1792 .get_budget = scsi_mq_get_budget,
1793 .put_budget = scsi_mq_put_budget,
1794 .queue_rq = scsi_queue_rq,
1795 .complete = scsi_softirq_done,
1796 .timeout = scsi_timeout,
1797 #ifdef CONFIG_BLK_DEBUG_FS
1798 .show_rq = scsi_show_rq,
1800 .init_request = scsi_mq_init_request,
1801 .exit_request = scsi_mq_exit_request,
1802 .initialize_rq_fn = scsi_initialize_rq,
1803 .busy = scsi_mq_lld_busy,
1804 .map_queues = scsi_map_queues,
1807 struct request_queue *scsi_mq_alloc_queue(struct scsi_device *sdev)
1809 sdev->request_queue = blk_mq_init_queue(&sdev->host->tag_set);
1810 if (IS_ERR(sdev->request_queue))
1813 sdev->request_queue->queuedata = sdev;
1814 __scsi_init_queue(sdev->host, sdev->request_queue);
1815 blk_queue_flag_set(QUEUE_FLAG_SCSI_PASSTHROUGH, sdev->request_queue);
1816 return sdev->request_queue;
1819 int scsi_mq_setup_tags(struct Scsi_Host *shost)
1821 unsigned int cmd_size, sgl_size;
1823 sgl_size = scsi_mq_sgl_size(shost);
1824 cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size;
1825 if (scsi_host_get_prot(shost))
1826 cmd_size += sizeof(struct scsi_data_buffer) + sgl_size;
1828 memset(&shost->tag_set, 0, sizeof(shost->tag_set));
1829 shost->tag_set.ops = &scsi_mq_ops;
1830 shost->tag_set.nr_hw_queues = shost->nr_hw_queues ? : 1;
1831 shost->tag_set.queue_depth = shost->can_queue;
1832 shost->tag_set.cmd_size = cmd_size;
1833 shost->tag_set.numa_node = NUMA_NO_NODE;
1834 shost->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
1835 shost->tag_set.flags |=
1836 BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy);
1837 shost->tag_set.driver_data = shost;
1839 return blk_mq_alloc_tag_set(&shost->tag_set);
1842 void scsi_mq_destroy_tags(struct Scsi_Host *shost)
1844 blk_mq_free_tag_set(&shost->tag_set);
1848 * scsi_device_from_queue - return sdev associated with a request_queue
1849 * @q: The request queue to return the sdev from
1851 * Return the sdev associated with a request queue or NULL if the
1852 * request_queue does not reference a SCSI device.
1854 struct scsi_device *scsi_device_from_queue(struct request_queue *q)
1856 struct scsi_device *sdev = NULL;
1858 if (q->mq_ops == &scsi_mq_ops)
1859 sdev = q->queuedata;
1860 if (!sdev || !get_device(&sdev->sdev_gendev))
1865 EXPORT_SYMBOL_GPL(scsi_device_from_queue);
1868 * Function: scsi_block_requests()
1870 * Purpose: Utility function used by low-level drivers to prevent further
1871 * commands from being queued to the device.
1873 * Arguments: shost - Host in question
1877 * Lock status: No locks are assumed held.
1879 * Notes: There is no timer nor any other means by which the requests
1880 * get unblocked other than the low-level driver calling
1881 * scsi_unblock_requests().
1883 void scsi_block_requests(struct Scsi_Host *shost)
1885 shost->host_self_blocked = 1;
1887 EXPORT_SYMBOL(scsi_block_requests);
1890 * Function: scsi_unblock_requests()
1892 * Purpose: Utility function used by low-level drivers to allow further
1893 * commands from being queued to the device.
1895 * Arguments: shost - Host in question
1899 * Lock status: No locks are assumed held.
1901 * Notes: There is no timer nor any other means by which the requests
1902 * get unblocked other than the low-level driver calling
1903 * scsi_unblock_requests().
1905 * This is done as an API function so that changes to the
1906 * internals of the scsi mid-layer won't require wholesale
1907 * changes to drivers that use this feature.
1909 void scsi_unblock_requests(struct Scsi_Host *shost)
1911 shost->host_self_blocked = 0;
1912 scsi_run_host_queues(shost);
1914 EXPORT_SYMBOL(scsi_unblock_requests);
1916 int __init scsi_init_queue(void)
1918 scsi_sdb_cache = kmem_cache_create("scsi_data_buffer",
1919 sizeof(struct scsi_data_buffer),
1921 if (!scsi_sdb_cache) {
1922 printk(KERN_ERR "SCSI: can't init scsi sdb cache\n");
1929 void scsi_exit_queue(void)
1931 kmem_cache_destroy(scsi_sense_cache);
1932 kmem_cache_destroy(scsi_sense_isadma_cache);
1933 kmem_cache_destroy(scsi_sdb_cache);
1937 * scsi_mode_select - issue a mode select
1938 * @sdev: SCSI device to be queried
1939 * @pf: Page format bit (1 == standard, 0 == vendor specific)
1940 * @sp: Save page bit (0 == don't save, 1 == save)
1941 * @modepage: mode page being requested
1942 * @buffer: request buffer (may not be smaller than eight bytes)
1943 * @len: length of request buffer.
1944 * @timeout: command timeout
1945 * @retries: number of retries before failing
1946 * @data: returns a structure abstracting the mode header data
1947 * @sshdr: place to put sense data (or NULL if no sense to be collected).
1948 * must be SCSI_SENSE_BUFFERSIZE big.
1950 * Returns zero if successful; negative error number or scsi
1955 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
1956 unsigned char *buffer, int len, int timeout, int retries,
1957 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1959 unsigned char cmd[10];
1960 unsigned char *real_buffer;
1963 memset(cmd, 0, sizeof(cmd));
1964 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
1966 if (sdev->use_10_for_ms) {
1969 real_buffer = kmalloc(8 + len, GFP_KERNEL);
1972 memcpy(real_buffer + 8, buffer, len);
1976 real_buffer[2] = data->medium_type;
1977 real_buffer[3] = data->device_specific;
1978 real_buffer[4] = data->longlba ? 0x01 : 0;
1980 real_buffer[6] = data->block_descriptor_length >> 8;
1981 real_buffer[7] = data->block_descriptor_length;
1983 cmd[0] = MODE_SELECT_10;
1987 if (len > 255 || data->block_descriptor_length > 255 ||
1991 real_buffer = kmalloc(4 + len, GFP_KERNEL);
1994 memcpy(real_buffer + 4, buffer, len);
1997 real_buffer[1] = data->medium_type;
1998 real_buffer[2] = data->device_specific;
1999 real_buffer[3] = data->block_descriptor_length;
2002 cmd[0] = MODE_SELECT;
2006 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
2007 sshdr, timeout, retries, NULL);
2011 EXPORT_SYMBOL_GPL(scsi_mode_select);
2014 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
2015 * @sdev: SCSI device to be queried
2016 * @dbd: set if mode sense will allow block descriptors to be returned
2017 * @modepage: mode page being requested
2018 * @buffer: request buffer (may not be smaller than eight bytes)
2019 * @len: length of request buffer.
2020 * @timeout: command timeout
2021 * @retries: number of retries before failing
2022 * @data: returns a structure abstracting the mode header data
2023 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2024 * must be SCSI_SENSE_BUFFERSIZE big.
2026 * Returns zero if unsuccessful, or the header offset (either 4
2027 * or 8 depending on whether a six or ten byte command was
2028 * issued) if successful.
2031 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
2032 unsigned char *buffer, int len, int timeout, int retries,
2033 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2035 unsigned char cmd[12];
2038 int result, retry_count = retries;
2039 struct scsi_sense_hdr my_sshdr;
2041 memset(data, 0, sizeof(*data));
2042 memset(&cmd[0], 0, 12);
2043 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
2046 /* caller might not be interested in sense, but we need it */
2051 use_10_for_ms = sdev->use_10_for_ms;
2053 if (use_10_for_ms) {
2057 cmd[0] = MODE_SENSE_10;
2064 cmd[0] = MODE_SENSE;
2069 memset(buffer, 0, len);
2071 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
2072 sshdr, timeout, retries, NULL);
2074 /* This code looks awful: what it's doing is making sure an
2075 * ILLEGAL REQUEST sense return identifies the actual command
2076 * byte as the problem. MODE_SENSE commands can return
2077 * ILLEGAL REQUEST if the code page isn't supported */
2079 if (use_10_for_ms && !scsi_status_is_good(result) &&
2080 driver_byte(result) == DRIVER_SENSE) {
2081 if (scsi_sense_valid(sshdr)) {
2082 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
2083 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
2085 * Invalid command operation code
2087 sdev->use_10_for_ms = 0;
2093 if(scsi_status_is_good(result)) {
2094 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
2095 (modepage == 6 || modepage == 8))) {
2096 /* Initio breakage? */
2099 data->medium_type = 0;
2100 data->device_specific = 0;
2102 data->block_descriptor_length = 0;
2103 } else if(use_10_for_ms) {
2104 data->length = buffer[0]*256 + buffer[1] + 2;
2105 data->medium_type = buffer[2];
2106 data->device_specific = buffer[3];
2107 data->longlba = buffer[4] & 0x01;
2108 data->block_descriptor_length = buffer[6]*256
2111 data->length = buffer[0] + 1;
2112 data->medium_type = buffer[1];
2113 data->device_specific = buffer[2];
2114 data->block_descriptor_length = buffer[3];
2116 data->header_length = header_length;
2117 } else if ((status_byte(result) == CHECK_CONDITION) &&
2118 scsi_sense_valid(sshdr) &&
2119 sshdr->sense_key == UNIT_ATTENTION && retry_count) {
2126 EXPORT_SYMBOL(scsi_mode_sense);
2129 * scsi_test_unit_ready - test if unit is ready
2130 * @sdev: scsi device to change the state of.
2131 * @timeout: command timeout
2132 * @retries: number of retries before failing
2133 * @sshdr: outpout pointer for decoded sense information.
2135 * Returns zero if unsuccessful or an error if TUR failed. For
2136 * removable media, UNIT_ATTENTION sets ->changed flag.
2139 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2140 struct scsi_sense_hdr *sshdr)
2143 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2147 /* try to eat the UNIT_ATTENTION if there are enough retries */
2149 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
2151 if (sdev->removable && scsi_sense_valid(sshdr) &&
2152 sshdr->sense_key == UNIT_ATTENTION)
2154 } while (scsi_sense_valid(sshdr) &&
2155 sshdr->sense_key == UNIT_ATTENTION && --retries);
2159 EXPORT_SYMBOL(scsi_test_unit_ready);
2162 * scsi_device_set_state - Take the given device through the device state model.
2163 * @sdev: scsi device to change the state of.
2164 * @state: state to change to.
2166 * Returns zero if successful or an error if the requested
2167 * transition is illegal.
2170 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2172 enum scsi_device_state oldstate = sdev->sdev_state;
2174 if (state == oldstate)
2180 case SDEV_CREATED_BLOCK:
2191 case SDEV_TRANSPORT_OFFLINE:
2204 case SDEV_TRANSPORT_OFFLINE:
2212 case SDEV_TRANSPORT_OFFLINE:
2227 case SDEV_CREATED_BLOCK:
2235 case SDEV_CREATED_BLOCK:
2250 case SDEV_TRANSPORT_OFFLINE:
2262 case SDEV_TRANSPORT_OFFLINE:
2265 case SDEV_CREATED_BLOCK:
2273 sdev->sdev_state = state;
2277 SCSI_LOG_ERROR_RECOVERY(1,
2278 sdev_printk(KERN_ERR, sdev,
2279 "Illegal state transition %s->%s",
2280 scsi_device_state_name(oldstate),
2281 scsi_device_state_name(state))
2285 EXPORT_SYMBOL(scsi_device_set_state);
2288 * sdev_evt_emit - emit a single SCSI device uevent
2289 * @sdev: associated SCSI device
2290 * @evt: event to emit
2292 * Send a single uevent (scsi_event) to the associated scsi_device.
2294 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2299 switch (evt->evt_type) {
2300 case SDEV_EVT_MEDIA_CHANGE:
2301 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2303 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2304 scsi_rescan_device(&sdev->sdev_gendev);
2305 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
2307 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2308 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
2310 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2311 envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
2313 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2314 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
2316 case SDEV_EVT_LUN_CHANGE_REPORTED:
2317 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
2319 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2320 envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED";
2322 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2323 envp[idx++] = "SDEV_UA=POWER_ON_RESET_OCCURRED";
2332 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2336 * sdev_evt_thread - send a uevent for each scsi event
2337 * @work: work struct for scsi_device
2339 * Dispatch queued events to their associated scsi_device kobjects
2342 void scsi_evt_thread(struct work_struct *work)
2344 struct scsi_device *sdev;
2345 enum scsi_device_event evt_type;
2346 LIST_HEAD(event_list);
2348 sdev = container_of(work, struct scsi_device, event_work);
2350 for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
2351 if (test_and_clear_bit(evt_type, sdev->pending_events))
2352 sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
2355 struct scsi_event *evt;
2356 struct list_head *this, *tmp;
2357 unsigned long flags;
2359 spin_lock_irqsave(&sdev->list_lock, flags);
2360 list_splice_init(&sdev->event_list, &event_list);
2361 spin_unlock_irqrestore(&sdev->list_lock, flags);
2363 if (list_empty(&event_list))
2366 list_for_each_safe(this, tmp, &event_list) {
2367 evt = list_entry(this, struct scsi_event, node);
2368 list_del(&evt->node);
2369 scsi_evt_emit(sdev, evt);
2376 * sdev_evt_send - send asserted event to uevent thread
2377 * @sdev: scsi_device event occurred on
2378 * @evt: event to send
2380 * Assert scsi device event asynchronously.
2382 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2384 unsigned long flags;
2387 /* FIXME: currently this check eliminates all media change events
2388 * for polled devices. Need to update to discriminate between AN
2389 * and polled events */
2390 if (!test_bit(evt->evt_type, sdev->supported_events)) {
2396 spin_lock_irqsave(&sdev->list_lock, flags);
2397 list_add_tail(&evt->node, &sdev->event_list);
2398 schedule_work(&sdev->event_work);
2399 spin_unlock_irqrestore(&sdev->list_lock, flags);
2401 EXPORT_SYMBOL_GPL(sdev_evt_send);
2404 * sdev_evt_alloc - allocate a new scsi event
2405 * @evt_type: type of event to allocate
2406 * @gfpflags: GFP flags for allocation
2408 * Allocates and returns a new scsi_event.
2410 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2413 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2417 evt->evt_type = evt_type;
2418 INIT_LIST_HEAD(&evt->node);
2420 /* evt_type-specific initialization, if any */
2422 case SDEV_EVT_MEDIA_CHANGE:
2423 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2424 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2425 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2426 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2427 case SDEV_EVT_LUN_CHANGE_REPORTED:
2428 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2429 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2437 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2440 * sdev_evt_send_simple - send asserted event to uevent thread
2441 * @sdev: scsi_device event occurred on
2442 * @evt_type: type of event to send
2443 * @gfpflags: GFP flags for allocation
2445 * Assert scsi device event asynchronously, given an event type.
2447 void sdev_evt_send_simple(struct scsi_device *sdev,
2448 enum scsi_device_event evt_type, gfp_t gfpflags)
2450 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2452 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2457 sdev_evt_send(sdev, evt);
2459 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2462 * scsi_device_quiesce - Block user issued commands.
2463 * @sdev: scsi device to quiesce.
2465 * This works by trying to transition to the SDEV_QUIESCE state
2466 * (which must be a legal transition). When the device is in this
2467 * state, only special requests will be accepted, all others will
2468 * be deferred. Since special requests may also be requeued requests,
2469 * a successful return doesn't guarantee the device will be
2470 * totally quiescent.
2472 * Must be called with user context, may sleep.
2474 * Returns zero if unsuccessful or an error if not.
2477 scsi_device_quiesce(struct scsi_device *sdev)
2479 struct request_queue *q = sdev->request_queue;
2483 * It is allowed to call scsi_device_quiesce() multiple times from
2484 * the same context but concurrent scsi_device_quiesce() calls are
2487 WARN_ON_ONCE(sdev->quiesced_by && sdev->quiesced_by != current);
2489 if (sdev->quiesced_by == current)
2494 blk_mq_freeze_queue(q);
2496 * Ensure that the effect of blk_set_pm_only() will be visible
2497 * for percpu_ref_tryget() callers that occur after the queue
2498 * unfreeze even if the queue was already frozen before this function
2499 * was called. See also https://lwn.net/Articles/573497/.
2502 blk_mq_unfreeze_queue(q);
2504 mutex_lock(&sdev->state_mutex);
2505 err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2507 sdev->quiesced_by = current;
2509 blk_clear_pm_only(q);
2510 mutex_unlock(&sdev->state_mutex);
2514 EXPORT_SYMBOL(scsi_device_quiesce);
2517 * scsi_device_resume - Restart user issued commands to a quiesced device.
2518 * @sdev: scsi device to resume.
2520 * Moves the device from quiesced back to running and restarts the
2523 * Must be called with user context, may sleep.
2525 void scsi_device_resume(struct scsi_device *sdev)
2527 /* check if the device state was mutated prior to resume, and if
2528 * so assume the state is being managed elsewhere (for example
2529 * device deleted during suspend)
2531 mutex_lock(&sdev->state_mutex);
2532 if (sdev->quiesced_by) {
2533 sdev->quiesced_by = NULL;
2534 blk_clear_pm_only(sdev->request_queue);
2536 if (sdev->sdev_state == SDEV_QUIESCE)
2537 scsi_device_set_state(sdev, SDEV_RUNNING);
2538 mutex_unlock(&sdev->state_mutex);
2540 EXPORT_SYMBOL(scsi_device_resume);
2543 device_quiesce_fn(struct scsi_device *sdev, void *data)
2545 scsi_device_quiesce(sdev);
2549 scsi_target_quiesce(struct scsi_target *starget)
2551 starget_for_each_device(starget, NULL, device_quiesce_fn);
2553 EXPORT_SYMBOL(scsi_target_quiesce);
2556 device_resume_fn(struct scsi_device *sdev, void *data)
2558 scsi_device_resume(sdev);
2562 scsi_target_resume(struct scsi_target *starget)
2564 starget_for_each_device(starget, NULL, device_resume_fn);
2566 EXPORT_SYMBOL(scsi_target_resume);
2569 * scsi_internal_device_block_nowait - try to transition to the SDEV_BLOCK state
2570 * @sdev: device to block
2572 * Pause SCSI command processing on the specified device. Does not sleep.
2574 * Returns zero if successful or a negative error code upon failure.
2577 * This routine transitions the device to the SDEV_BLOCK state (which must be
2578 * a legal transition). When the device is in this state, command processing
2579 * is paused until the device leaves the SDEV_BLOCK state. See also
2580 * scsi_internal_device_unblock_nowait().
2582 int scsi_internal_device_block_nowait(struct scsi_device *sdev)
2584 struct request_queue *q = sdev->request_queue;
2587 err = scsi_device_set_state(sdev, SDEV_BLOCK);
2589 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
2596 * The device has transitioned to SDEV_BLOCK. Stop the
2597 * block layer from calling the midlayer with this device's
2600 blk_mq_quiesce_queue_nowait(q);
2603 EXPORT_SYMBOL_GPL(scsi_internal_device_block_nowait);
2606 * scsi_internal_device_block - try to transition to the SDEV_BLOCK state
2607 * @sdev: device to block
2609 * Pause SCSI command processing on the specified device and wait until all
2610 * ongoing scsi_request_fn() / scsi_queue_rq() calls have finished. May sleep.
2612 * Returns zero if successful or a negative error code upon failure.
2615 * This routine transitions the device to the SDEV_BLOCK state (which must be
2616 * a legal transition). When the device is in this state, command processing
2617 * is paused until the device leaves the SDEV_BLOCK state. See also
2618 * scsi_internal_device_unblock().
2620 * To do: avoid that scsi_send_eh_cmnd() calls queuecommand() after
2621 * scsi_internal_device_block() has blocked a SCSI device and also
2622 * remove the rport mutex lock and unlock calls from srp_queuecommand().
2624 static int scsi_internal_device_block(struct scsi_device *sdev)
2626 struct request_queue *q = sdev->request_queue;
2629 mutex_lock(&sdev->state_mutex);
2630 err = scsi_internal_device_block_nowait(sdev);
2632 blk_mq_quiesce_queue(q);
2633 mutex_unlock(&sdev->state_mutex);
2638 void scsi_start_queue(struct scsi_device *sdev)
2640 struct request_queue *q = sdev->request_queue;
2642 blk_mq_unquiesce_queue(q);
2646 * scsi_internal_device_unblock_nowait - resume a device after a block request
2647 * @sdev: device to resume
2648 * @new_state: state to set the device to after unblocking
2650 * Restart the device queue for a previously suspended SCSI device. Does not
2653 * Returns zero if successful or a negative error code upon failure.
2656 * This routine transitions the device to the SDEV_RUNNING state or to one of
2657 * the offline states (which must be a legal transition) allowing the midlayer
2658 * to goose the queue for this device.
2660 int scsi_internal_device_unblock_nowait(struct scsi_device *sdev,
2661 enum scsi_device_state new_state)
2664 * Try to transition the scsi device to SDEV_RUNNING or one of the
2665 * offlined states and goose the device queue if successful.
2667 switch (sdev->sdev_state) {
2669 case SDEV_TRANSPORT_OFFLINE:
2670 sdev->sdev_state = new_state;
2672 case SDEV_CREATED_BLOCK:
2673 if (new_state == SDEV_TRANSPORT_OFFLINE ||
2674 new_state == SDEV_OFFLINE)
2675 sdev->sdev_state = new_state;
2677 sdev->sdev_state = SDEV_CREATED;
2685 scsi_start_queue(sdev);
2689 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock_nowait);
2692 * scsi_internal_device_unblock - resume a device after a block request
2693 * @sdev: device to resume
2694 * @new_state: state to set the device to after unblocking
2696 * Restart the device queue for a previously suspended SCSI device. May sleep.
2698 * Returns zero if successful or a negative error code upon failure.
2701 * This routine transitions the device to the SDEV_RUNNING state or to one of
2702 * the offline states (which must be a legal transition) allowing the midlayer
2703 * to goose the queue for this device.
2705 static int scsi_internal_device_unblock(struct scsi_device *sdev,
2706 enum scsi_device_state new_state)
2710 mutex_lock(&sdev->state_mutex);
2711 ret = scsi_internal_device_unblock_nowait(sdev, new_state);
2712 mutex_unlock(&sdev->state_mutex);
2718 device_block(struct scsi_device *sdev, void *data)
2720 scsi_internal_device_block(sdev);
2724 target_block(struct device *dev, void *data)
2726 if (scsi_is_target_device(dev))
2727 starget_for_each_device(to_scsi_target(dev), NULL,
2733 scsi_target_block(struct device *dev)
2735 if (scsi_is_target_device(dev))
2736 starget_for_each_device(to_scsi_target(dev), NULL,
2739 device_for_each_child(dev, NULL, target_block);
2741 EXPORT_SYMBOL_GPL(scsi_target_block);
2744 device_unblock(struct scsi_device *sdev, void *data)
2746 scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
2750 target_unblock(struct device *dev, void *data)
2752 if (scsi_is_target_device(dev))
2753 starget_for_each_device(to_scsi_target(dev), data,
2759 scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
2761 if (scsi_is_target_device(dev))
2762 starget_for_each_device(to_scsi_target(dev), &new_state,
2765 device_for_each_child(dev, &new_state, target_unblock);
2767 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2770 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
2771 * @sgl: scatter-gather list
2772 * @sg_count: number of segments in sg
2773 * @offset: offset in bytes into sg, on return offset into the mapped area
2774 * @len: bytes to map, on return number of bytes mapped
2776 * Returns virtual address of the start of the mapped page
2778 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
2779 size_t *offset, size_t *len)
2782 size_t sg_len = 0, len_complete = 0;
2783 struct scatterlist *sg;
2786 WARN_ON(!irqs_disabled());
2788 for_each_sg(sgl, sg, sg_count, i) {
2789 len_complete = sg_len; /* Complete sg-entries */
2790 sg_len += sg->length;
2791 if (sg_len > *offset)
2795 if (unlikely(i == sg_count)) {
2796 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2798 __func__, sg_len, *offset, sg_count);
2803 /* Offset starting from the beginning of first page in this sg-entry */
2804 *offset = *offset - len_complete + sg->offset;
2806 /* Assumption: contiguous pages can be accessed as "page + i" */
2807 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
2808 *offset &= ~PAGE_MASK;
2810 /* Bytes in this sg-entry from *offset to the end of the page */
2811 sg_len = PAGE_SIZE - *offset;
2815 return kmap_atomic(page);
2817 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2820 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
2821 * @virt: virtual address to be unmapped
2823 void scsi_kunmap_atomic_sg(void *virt)
2825 kunmap_atomic(virt);
2827 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
2829 void sdev_disable_disk_events(struct scsi_device *sdev)
2831 atomic_inc(&sdev->disk_events_disable_depth);
2833 EXPORT_SYMBOL(sdev_disable_disk_events);
2835 void sdev_enable_disk_events(struct scsi_device *sdev)
2837 if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
2839 atomic_dec(&sdev->disk_events_disable_depth);
2841 EXPORT_SYMBOL(sdev_enable_disk_events);
2844 * scsi_vpd_lun_id - return a unique device identification
2845 * @sdev: SCSI device
2846 * @id: buffer for the identification
2847 * @id_len: length of the buffer
2849 * Copies a unique device identification into @id based
2850 * on the information in the VPD page 0x83 of the device.
2851 * The string will be formatted as a SCSI name string.
2853 * Returns the length of the identification or error on failure.
2854 * If the identifier is longer than the supplied buffer the actual
2855 * identifier length is returned and the buffer is not zero-padded.
2857 int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
2859 u8 cur_id_type = 0xff;
2861 const unsigned char *d, *cur_id_str;
2862 const struct scsi_vpd *vpd_pg83;
2863 int id_size = -EINVAL;
2866 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
2873 * Look for the correct descriptor.
2874 * Order of preference for lun descriptor:
2875 * - SCSI name string
2876 * - NAA IEEE Registered Extended
2877 * - EUI-64 based 16-byte
2878 * - EUI-64 based 12-byte
2879 * - NAA IEEE Registered
2880 * - NAA IEEE Extended
2882 * as longer descriptors reduce the likelyhood
2883 * of identification clashes.
2886 /* The id string must be at least 20 bytes + terminating NULL byte */
2892 memset(id, 0, id_len);
2893 d = vpd_pg83->data + 4;
2894 while (d < vpd_pg83->data + vpd_pg83->len) {
2895 /* Skip designators not referring to the LUN */
2896 if ((d[1] & 0x30) != 0x00)
2899 switch (d[1] & 0xf) {
2902 if (cur_id_size > d[3])
2904 /* Prefer anything */
2905 if (cur_id_type > 0x01 && cur_id_type != 0xff)
2908 if (cur_id_size + 4 > id_len)
2909 cur_id_size = id_len - 4;
2911 cur_id_type = d[1] & 0xf;
2912 id_size = snprintf(id, id_len, "t10.%*pE",
2913 cur_id_size, cur_id_str);
2917 if (cur_id_size > d[3])
2919 /* Prefer NAA IEEE Registered Extended */
2920 if (cur_id_type == 0x3 &&
2921 cur_id_size == d[3])
2925 cur_id_type = d[1] & 0xf;
2926 switch (cur_id_size) {
2928 id_size = snprintf(id, id_len,
2933 id_size = snprintf(id, id_len,
2938 id_size = snprintf(id, id_len,
2949 if (cur_id_size > d[3])
2953 cur_id_type = d[1] & 0xf;
2954 switch (cur_id_size) {
2956 id_size = snprintf(id, id_len,
2961 id_size = snprintf(id, id_len,
2971 /* SCSI name string */
2972 if (cur_id_size + 4 > d[3])
2974 /* Prefer others for truncated descriptor */
2975 if (cur_id_size && d[3] > id_len)
2977 cur_id_size = id_size = d[3];
2979 cur_id_type = d[1] & 0xf;
2980 if (cur_id_size >= id_len)
2981 cur_id_size = id_len - 1;
2982 memcpy(id, cur_id_str, cur_id_size);
2983 /* Decrease priority for truncated descriptor */
2984 if (cur_id_size != id_size)
2997 EXPORT_SYMBOL(scsi_vpd_lun_id);
3000 * scsi_vpd_tpg_id - return a target port group identifier
3001 * @sdev: SCSI device
3003 * Returns the Target Port Group identifier from the information
3004 * froom VPD page 0x83 of the device.
3006 * Returns the identifier or error on failure.
3008 int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
3010 const unsigned char *d;
3011 const struct scsi_vpd *vpd_pg83;
3012 int group_id = -EAGAIN, rel_port = -1;
3015 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3021 d = vpd_pg83->data + 4;
3022 while (d < vpd_pg83->data + vpd_pg83->len) {
3023 switch (d[1] & 0xf) {
3025 /* Relative target port */
3026 rel_port = get_unaligned_be16(&d[6]);
3029 /* Target port group */
3030 group_id = get_unaligned_be16(&d[6]);
3039 if (group_id >= 0 && rel_id && rel_port != -1)
3044 EXPORT_SYMBOL(scsi_vpd_tpg_id);