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 if (cmd->request->rq_flags & RQF_DONTPREP) {
123 cmd->request->rq_flags &= ~RQF_DONTPREP;
124 scsi_mq_uninit_cmd(cmd);
128 blk_mq_requeue_request(cmd->request, true);
132 * __scsi_queue_insert - private queue insertion
133 * @cmd: The SCSI command being requeued
134 * @reason: The reason for the requeue
135 * @unbusy: Whether the queue should be unbusied
137 * This is a private queue insertion. The public interface
138 * scsi_queue_insert() always assumes the queue should be unbusied
139 * because it's always called before the completion. This function is
140 * for a requeue after completion, which should only occur in this
143 static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, bool unbusy)
145 struct scsi_device *device = cmd->device;
147 SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd,
148 "Inserting command %p into mlqueue\n", cmd));
150 scsi_set_blocked(cmd, reason);
153 * Decrement the counters, since these commands are no longer
154 * active on the host/device.
157 scsi_device_unbusy(device, cmd);
160 * Requeue this command. It will go before all other commands
161 * that are already in the queue. Schedule requeue work under
162 * lock such that the kblockd_schedule_work() call happens
163 * before blk_cleanup_queue() finishes.
167 blk_mq_requeue_request(cmd->request, true);
171 * scsi_queue_insert - Reinsert a command in the queue.
172 * @cmd: command that we are adding to queue.
173 * @reason: why we are inserting command to queue.
175 * We do this for one of two cases. Either the host is busy and it cannot accept
176 * any more commands for the time being, or the device returned QUEUE_FULL and
177 * can accept no more commands.
179 * Context: This could be called either from an interrupt context or a normal
182 void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
184 __scsi_queue_insert(cmd, reason, true);
189 * __scsi_execute - insert request and wait for the result
192 * @data_direction: data direction
193 * @buffer: data buffer
194 * @bufflen: len of buffer
195 * @sense: optional sense buffer
196 * @sshdr: optional decoded sense header
197 * @timeout: request timeout in seconds
198 * @retries: number of times to retry request
199 * @flags: flags for ->cmd_flags
200 * @rq_flags: flags for ->rq_flags
201 * @resid: optional residual length
203 * Returns the scsi_cmnd result field if a command was executed, or a negative
204 * Linux error code if we didn't get that far.
206 int __scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
207 int data_direction, void *buffer, unsigned bufflen,
208 unsigned char *sense, struct scsi_sense_hdr *sshdr,
209 int timeout, int retries, u64 flags, req_flags_t rq_flags,
213 struct scsi_request *rq;
214 int ret = DRIVER_ERROR << 24;
216 req = blk_get_request(sdev->request_queue,
217 data_direction == DMA_TO_DEVICE ?
218 REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN,
219 rq_flags & RQF_PM ? BLK_MQ_REQ_PM : 0);
224 if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
225 buffer, bufflen, GFP_NOIO))
228 rq->cmd_len = COMMAND_SIZE(cmd[0]);
229 memcpy(rq->cmd, cmd, rq->cmd_len);
230 rq->retries = retries;
231 req->timeout = timeout;
232 req->cmd_flags |= flags;
233 req->rq_flags |= rq_flags | RQF_QUIET;
236 * head injection *required* here otherwise quiesce won't work
238 blk_execute_rq(NULL, req, 1);
241 * Some devices (USB mass-storage in particular) may transfer
242 * garbage data together with a residue indicating that the data
243 * is invalid. Prevent the garbage from being misinterpreted
244 * and prevent security leaks by zeroing out the excess data.
246 if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen))
247 memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len);
250 *resid = rq->resid_len;
251 if (sense && rq->sense_len)
252 memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE);
254 scsi_normalize_sense(rq->sense, rq->sense_len, sshdr);
257 blk_put_request(req);
261 EXPORT_SYMBOL(__scsi_execute);
264 * Wake up the error handler if necessary. Avoid as follows that the error
265 * handler is not woken up if host in-flight requests number ==
266 * shost->host_failed: use call_rcu() in scsi_eh_scmd_add() in combination
267 * with an RCU read lock in this function to ensure that this function in
268 * its entirety either finishes before scsi_eh_scmd_add() increases the
269 * host_failed counter or that it notices the shost state change made by
270 * scsi_eh_scmd_add().
272 static void scsi_dec_host_busy(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
277 __clear_bit(SCMD_STATE_INFLIGHT, &cmd->state);
278 if (unlikely(scsi_host_in_recovery(shost))) {
279 spin_lock_irqsave(shost->host_lock, flags);
280 if (shost->host_failed || shost->host_eh_scheduled)
281 scsi_eh_wakeup(shost);
282 spin_unlock_irqrestore(shost->host_lock, flags);
287 void scsi_device_unbusy(struct scsi_device *sdev, struct scsi_cmnd *cmd)
289 struct Scsi_Host *shost = sdev->host;
290 struct scsi_target *starget = scsi_target(sdev);
292 scsi_dec_host_busy(shost, cmd);
294 if (starget->can_queue > 0)
295 atomic_dec(&starget->target_busy);
297 atomic_dec(&sdev->device_busy);
300 static void scsi_kick_queue(struct request_queue *q)
302 blk_mq_run_hw_queues(q, false);
306 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
307 * and call blk_run_queue for all the scsi_devices on the target -
308 * including current_sdev first.
310 * Called with *no* scsi locks held.
312 static void scsi_single_lun_run(struct scsi_device *current_sdev)
314 struct Scsi_Host *shost = current_sdev->host;
315 struct scsi_device *sdev, *tmp;
316 struct scsi_target *starget = scsi_target(current_sdev);
319 spin_lock_irqsave(shost->host_lock, flags);
320 starget->starget_sdev_user = NULL;
321 spin_unlock_irqrestore(shost->host_lock, flags);
324 * Call blk_run_queue for all LUNs on the target, starting with
325 * current_sdev. We race with others (to set starget_sdev_user),
326 * but in most cases, we will be first. Ideally, each LU on the
327 * target would get some limited time or requests on the target.
329 scsi_kick_queue(current_sdev->request_queue);
331 spin_lock_irqsave(shost->host_lock, flags);
332 if (starget->starget_sdev_user)
334 list_for_each_entry_safe(sdev, tmp, &starget->devices,
335 same_target_siblings) {
336 if (sdev == current_sdev)
338 if (scsi_device_get(sdev))
341 spin_unlock_irqrestore(shost->host_lock, flags);
342 scsi_kick_queue(sdev->request_queue);
343 spin_lock_irqsave(shost->host_lock, flags);
345 scsi_device_put(sdev);
348 spin_unlock_irqrestore(shost->host_lock, flags);
351 static inline bool scsi_device_is_busy(struct scsi_device *sdev)
353 if (atomic_read(&sdev->device_busy) >= sdev->queue_depth)
355 if (atomic_read(&sdev->device_blocked) > 0)
360 static inline bool scsi_target_is_busy(struct scsi_target *starget)
362 if (starget->can_queue > 0) {
363 if (atomic_read(&starget->target_busy) >= starget->can_queue)
365 if (atomic_read(&starget->target_blocked) > 0)
371 static inline bool scsi_host_is_busy(struct Scsi_Host *shost)
373 if (atomic_read(&shost->host_blocked) > 0)
375 if (shost->host_self_blocked)
380 static void scsi_starved_list_run(struct Scsi_Host *shost)
382 LIST_HEAD(starved_list);
383 struct scsi_device *sdev;
386 spin_lock_irqsave(shost->host_lock, flags);
387 list_splice_init(&shost->starved_list, &starved_list);
389 while (!list_empty(&starved_list)) {
390 struct request_queue *slq;
393 * As long as shost is accepting commands and we have
394 * starved queues, call blk_run_queue. scsi_request_fn
395 * drops the queue_lock and can add us back to the
398 * host_lock protects the starved_list and starved_entry.
399 * scsi_request_fn must get the host_lock before checking
400 * or modifying starved_list or starved_entry.
402 if (scsi_host_is_busy(shost))
405 sdev = list_entry(starved_list.next,
406 struct scsi_device, starved_entry);
407 list_del_init(&sdev->starved_entry);
408 if (scsi_target_is_busy(scsi_target(sdev))) {
409 list_move_tail(&sdev->starved_entry,
410 &shost->starved_list);
415 * Once we drop the host lock, a racing scsi_remove_device()
416 * call may remove the sdev from the starved list and destroy
417 * it and the queue. Mitigate by taking a reference to the
418 * queue and never touching the sdev again after we drop the
419 * host lock. Note: if __scsi_remove_device() invokes
420 * blk_cleanup_queue() before the queue is run from this
421 * function then blk_run_queue() will return immediately since
422 * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
424 slq = sdev->request_queue;
425 if (!blk_get_queue(slq))
427 spin_unlock_irqrestore(shost->host_lock, flags);
429 scsi_kick_queue(slq);
432 spin_lock_irqsave(shost->host_lock, flags);
434 /* put any unprocessed entries back */
435 list_splice(&starved_list, &shost->starved_list);
436 spin_unlock_irqrestore(shost->host_lock, flags);
440 * scsi_run_queue - Select a proper request queue to serve next.
441 * @q: last request's queue
443 * The previous command was completely finished, start a new one if possible.
445 static void scsi_run_queue(struct request_queue *q)
447 struct scsi_device *sdev = q->queuedata;
449 if (scsi_target(sdev)->single_lun)
450 scsi_single_lun_run(sdev);
451 if (!list_empty(&sdev->host->starved_list))
452 scsi_starved_list_run(sdev->host);
454 blk_mq_run_hw_queues(q, false);
457 void scsi_requeue_run_queue(struct work_struct *work)
459 struct scsi_device *sdev;
460 struct request_queue *q;
462 sdev = container_of(work, struct scsi_device, requeue_work);
463 q = sdev->request_queue;
467 void scsi_run_host_queues(struct Scsi_Host *shost)
469 struct scsi_device *sdev;
471 shost_for_each_device(sdev, shost)
472 scsi_run_queue(sdev->request_queue);
475 static void scsi_uninit_cmd(struct scsi_cmnd *cmd)
477 if (!blk_rq_is_passthrough(cmd->request)) {
478 struct scsi_driver *drv = scsi_cmd_to_driver(cmd);
480 if (drv->uninit_command)
481 drv->uninit_command(cmd);
485 void scsi_free_sgtables(struct scsi_cmnd *cmd)
487 if (cmd->sdb.table.nents)
488 sg_free_table_chained(&cmd->sdb.table,
490 if (scsi_prot_sg_count(cmd))
491 sg_free_table_chained(&cmd->prot_sdb->table,
492 SCSI_INLINE_PROT_SG_CNT);
494 EXPORT_SYMBOL_GPL(scsi_free_sgtables);
496 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd)
498 scsi_free_sgtables(cmd);
499 scsi_uninit_cmd(cmd);
502 static void scsi_run_queue_async(struct scsi_device *sdev)
504 if (scsi_target(sdev)->single_lun ||
505 !list_empty(&sdev->host->starved_list)) {
506 kblockd_schedule_work(&sdev->requeue_work);
509 * smp_mb() present in sbitmap_queue_clear() or implied in
510 * .end_io is for ordering writing .device_busy in
511 * scsi_device_unbusy() and reading sdev->restarts.
513 int old = atomic_read(&sdev->restarts);
516 * ->restarts has to be kept as non-zero if new budget
519 * No need to run queue when either another re-run
520 * queue wins in updating ->restarts or a new budget
523 if (old && atomic_cmpxchg(&sdev->restarts, old, 0) == old)
524 blk_mq_run_hw_queues(sdev->request_queue, true);
528 /* Returns false when no more bytes to process, true if there are more */
529 static bool scsi_end_request(struct request *req, blk_status_t error,
532 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
533 struct scsi_device *sdev = cmd->device;
534 struct request_queue *q = sdev->request_queue;
536 if (blk_update_request(req, error, bytes))
539 if (blk_queue_add_random(q))
540 add_disk_randomness(req->rq_disk);
542 if (!blk_rq_is_scsi(req)) {
543 WARN_ON_ONCE(!(cmd->flags & SCMD_INITIALIZED));
544 cmd->flags &= ~SCMD_INITIALIZED;
548 * Calling rcu_barrier() is not necessary here because the
549 * SCSI error handler guarantees that the function called by
550 * call_rcu() has been called before scsi_end_request() is
553 destroy_rcu_head(&cmd->rcu);
556 * In the MQ case the command gets freed by __blk_mq_end_request,
557 * so we have to do all cleanup that depends on it earlier.
559 * We also can't kick the queues from irq context, so we
560 * will have to defer it to a workqueue.
562 scsi_mq_uninit_cmd(cmd);
565 * queue is still alive, so grab the ref for preventing it
566 * from being cleaned up during running queue.
568 percpu_ref_get(&q->q_usage_counter);
570 __blk_mq_end_request(req, error);
572 scsi_run_queue_async(sdev);
574 percpu_ref_put(&q->q_usage_counter);
579 * scsi_result_to_blk_status - translate a SCSI result code into blk_status_t
581 * @result: scsi error code
583 * Translate a SCSI result code into a blk_status_t value. May reset the host
584 * byte of @cmd->result.
586 static blk_status_t scsi_result_to_blk_status(struct scsi_cmnd *cmd, int result)
588 switch (host_byte(result)) {
591 * Also check the other bytes than the status byte in result
592 * to handle the case when a SCSI LLD sets result to
593 * DRIVER_SENSE << 24 without setting SAM_STAT_CHECK_CONDITION.
595 if (scsi_status_is_good(result) && (result & ~0xff) == 0)
597 return BLK_STS_IOERR;
598 case DID_TRANSPORT_FAILFAST:
599 case DID_TRANSPORT_MARGINAL:
600 return BLK_STS_TRANSPORT;
601 case DID_TARGET_FAILURE:
602 set_host_byte(cmd, DID_OK);
603 return BLK_STS_TARGET;
604 case DID_NEXUS_FAILURE:
605 set_host_byte(cmd, DID_OK);
606 return BLK_STS_NEXUS;
607 case DID_ALLOC_FAILURE:
608 set_host_byte(cmd, DID_OK);
609 return BLK_STS_NOSPC;
610 case DID_MEDIUM_ERROR:
611 set_host_byte(cmd, DID_OK);
612 return BLK_STS_MEDIUM;
614 return BLK_STS_IOERR;
618 /* Helper for scsi_io_completion() when "reprep" action required. */
619 static void scsi_io_completion_reprep(struct scsi_cmnd *cmd,
620 struct request_queue *q)
622 /* A new command will be prepared and issued. */
623 scsi_mq_requeue_cmd(cmd);
626 static bool scsi_cmd_runtime_exceeced(struct scsi_cmnd *cmd)
628 struct request *req = cmd->request;
629 unsigned long wait_for;
631 if (cmd->allowed == SCSI_CMD_RETRIES_NO_LIMIT)
634 wait_for = (cmd->allowed + 1) * req->timeout;
635 if (time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
636 scmd_printk(KERN_ERR, cmd, "timing out command, waited %lus\n",
643 /* Helper for scsi_io_completion() when special action required. */
644 static void scsi_io_completion_action(struct scsi_cmnd *cmd, int result)
646 struct request_queue *q = cmd->device->request_queue;
647 struct request *req = cmd->request;
649 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
650 ACTION_DELAYED_RETRY} action;
651 struct scsi_sense_hdr sshdr;
653 bool sense_current = true; /* false implies "deferred sense" */
654 blk_status_t blk_stat;
656 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
658 sense_current = !scsi_sense_is_deferred(&sshdr);
660 blk_stat = scsi_result_to_blk_status(cmd, result);
662 if (host_byte(result) == DID_RESET) {
663 /* Third party bus reset or reset for error recovery
664 * reasons. Just retry the command and see what
667 action = ACTION_RETRY;
668 } else if (sense_valid && sense_current) {
669 switch (sshdr.sense_key) {
671 if (cmd->device->removable) {
672 /* Detected disc change. Set a bit
673 * and quietly refuse further access.
675 cmd->device->changed = 1;
676 action = ACTION_FAIL;
678 /* Must have been a power glitch, or a
679 * bus reset. Could not have been a
680 * media change, so we just retry the
681 * command and see what happens.
683 action = ACTION_RETRY;
686 case ILLEGAL_REQUEST:
687 /* If we had an ILLEGAL REQUEST returned, then
688 * we may have performed an unsupported
689 * command. The only thing this should be
690 * would be a ten byte read where only a six
691 * byte read was supported. Also, on a system
692 * where READ CAPACITY failed, we may have
693 * read past the end of the disk.
695 if ((cmd->device->use_10_for_rw &&
696 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
697 (cmd->cmnd[0] == READ_10 ||
698 cmd->cmnd[0] == WRITE_10)) {
699 /* This will issue a new 6-byte command. */
700 cmd->device->use_10_for_rw = 0;
701 action = ACTION_REPREP;
702 } else if (sshdr.asc == 0x10) /* DIX */ {
703 action = ACTION_FAIL;
704 blk_stat = BLK_STS_PROTECTION;
705 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
706 } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
707 action = ACTION_FAIL;
708 blk_stat = BLK_STS_TARGET;
710 action = ACTION_FAIL;
712 case ABORTED_COMMAND:
713 action = ACTION_FAIL;
714 if (sshdr.asc == 0x10) /* DIF */
715 blk_stat = BLK_STS_PROTECTION;
718 /* If the device is in the process of becoming
719 * ready, or has a temporary blockage, retry.
721 if (sshdr.asc == 0x04) {
722 switch (sshdr.ascq) {
723 case 0x01: /* becoming ready */
724 case 0x04: /* format in progress */
725 case 0x05: /* rebuild in progress */
726 case 0x06: /* recalculation in progress */
727 case 0x07: /* operation in progress */
728 case 0x08: /* Long write in progress */
729 case 0x09: /* self test in progress */
730 case 0x14: /* space allocation in progress */
731 case 0x1a: /* start stop unit in progress */
732 case 0x1b: /* sanitize in progress */
733 case 0x1d: /* configuration in progress */
734 case 0x24: /* depopulation in progress */
735 action = ACTION_DELAYED_RETRY;
737 case 0x0a: /* ALUA state transition */
738 blk_stat = BLK_STS_AGAIN;
741 action = ACTION_FAIL;
745 action = ACTION_FAIL;
747 case VOLUME_OVERFLOW:
748 /* See SSC3rXX or current. */
749 action = ACTION_FAIL;
752 action = ACTION_FAIL;
753 if ((sshdr.asc == 0x0C && sshdr.ascq == 0x12) ||
754 (sshdr.asc == 0x55 &&
755 (sshdr.ascq == 0x0E || sshdr.ascq == 0x0F))) {
756 /* Insufficient zone resources */
757 blk_stat = BLK_STS_ZONE_OPEN_RESOURCE;
761 action = ACTION_FAIL;
765 action = ACTION_FAIL;
767 if (action != ACTION_FAIL && scsi_cmd_runtime_exceeced(cmd))
768 action = ACTION_FAIL;
772 /* Give up and fail the remainder of the request */
773 if (!(req->rq_flags & RQF_QUIET)) {
774 static DEFINE_RATELIMIT_STATE(_rs,
775 DEFAULT_RATELIMIT_INTERVAL,
776 DEFAULT_RATELIMIT_BURST);
778 if (unlikely(scsi_logging_level))
780 SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
781 SCSI_LOG_MLCOMPLETE_BITS);
784 * if logging is enabled the failure will be printed
785 * in scsi_log_completion(), so avoid duplicate messages
787 if (!level && __ratelimit(&_rs)) {
788 scsi_print_result(cmd, NULL, FAILED);
789 if (driver_byte(result) == DRIVER_SENSE)
790 scsi_print_sense(cmd);
791 scsi_print_command(cmd);
794 if (!scsi_end_request(req, blk_stat, blk_rq_err_bytes(req)))
798 scsi_io_completion_reprep(cmd, q);
801 /* Retry the same command immediately */
802 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, false);
804 case ACTION_DELAYED_RETRY:
805 /* Retry the same command after a delay */
806 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, false);
812 * Helper for scsi_io_completion() when cmd->result is non-zero. Returns a
813 * new result that may suppress further error checking. Also modifies
814 * *blk_statp in some cases.
816 static int scsi_io_completion_nz_result(struct scsi_cmnd *cmd, int result,
817 blk_status_t *blk_statp)
820 bool sense_current = true; /* false implies "deferred sense" */
821 struct request *req = cmd->request;
822 struct scsi_sense_hdr sshdr;
824 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
826 sense_current = !scsi_sense_is_deferred(&sshdr);
828 if (blk_rq_is_passthrough(req)) {
831 * SG_IO wants current and deferred errors
833 scsi_req(req)->sense_len =
834 min(8 + cmd->sense_buffer[7],
835 SCSI_SENSE_BUFFERSIZE);
838 *blk_statp = scsi_result_to_blk_status(cmd, result);
839 } else if (blk_rq_bytes(req) == 0 && sense_current) {
841 * Flush commands do not transfers any data, and thus cannot use
842 * good_bytes != blk_rq_bytes(req) as the signal for an error.
843 * This sets *blk_statp explicitly for the problem case.
845 *blk_statp = scsi_result_to_blk_status(cmd, result);
848 * Recovered errors need reporting, but they're always treated as
849 * success, so fiddle the result code here. For passthrough requests
850 * we already took a copy of the original into sreq->result which
851 * is what gets returned to the user
853 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
854 bool do_print = true;
856 * if ATA PASS-THROUGH INFORMATION AVAILABLE [0x0, 0x1d]
857 * skip print since caller wants ATA registers. Only occurs
858 * on SCSI ATA PASS_THROUGH commands when CK_COND=1
860 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
862 else if (req->rq_flags & RQF_QUIET)
865 scsi_print_sense(cmd);
867 /* for passthrough, *blk_statp may be set */
868 *blk_statp = BLK_STS_OK;
871 * Another corner case: the SCSI status byte is non-zero but 'good'.
872 * Example: PRE-FETCH command returns SAM_STAT_CONDITION_MET when
873 * it is able to fit nominated LBs in its cache (and SAM_STAT_GOOD
874 * if it can't fit). Treat SAM_STAT_CONDITION_MET and the related
875 * intermediate statuses (both obsolete in SAM-4) as good.
877 if (status_byte(result) && scsi_status_is_good(result)) {
879 *blk_statp = BLK_STS_OK;
885 * scsi_io_completion - Completion processing for SCSI commands.
886 * @cmd: command that is finished.
887 * @good_bytes: number of processed bytes.
889 * We will finish off the specified number of sectors. If we are done, the
890 * command block will be released and the queue function will be goosed. If we
891 * are not done then we have to figure out what to do next:
893 * a) We can call scsi_io_completion_reprep(). The request will be
894 * unprepared and put back on the queue. Then a new command will
895 * be created for it. This should be used if we made forward
896 * progress, or if we want to switch from READ(10) to READ(6) for
899 * b) We can call scsi_io_completion_action(). The request will be
900 * put back on the queue and retried using the same command as
901 * before, possibly after a delay.
903 * c) We can call scsi_end_request() with blk_stat other than
904 * BLK_STS_OK, to fail the remainder of the request.
906 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
908 int result = cmd->result;
909 struct request_queue *q = cmd->device->request_queue;
910 struct request *req = cmd->request;
911 blk_status_t blk_stat = BLK_STS_OK;
913 if (unlikely(result)) /* a nz result may or may not be an error */
914 result = scsi_io_completion_nz_result(cmd, result, &blk_stat);
916 if (unlikely(blk_rq_is_passthrough(req))) {
918 * scsi_result_to_blk_status may have reset the host_byte
920 scsi_req(req)->result = cmd->result;
924 * Next deal with any sectors which we were able to correctly
927 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd,
928 "%u sectors total, %d bytes done.\n",
929 blk_rq_sectors(req), good_bytes));
932 * Failed, zero length commands always need to drop down
933 * to retry code. Fast path should return in this block.
935 if (likely(blk_rq_bytes(req) > 0 || blk_stat == BLK_STS_OK)) {
936 if (likely(!scsi_end_request(req, blk_stat, good_bytes)))
937 return; /* no bytes remaining */
940 /* Kill remainder if no retries. */
941 if (unlikely(blk_stat && scsi_noretry_cmd(cmd))) {
942 if (scsi_end_request(req, blk_stat, blk_rq_bytes(req)))
944 "Bytes remaining after failed, no-retry command");
949 * If there had been no error, but we have leftover bytes in the
950 * requeues just queue the command up again.
952 if (likely(result == 0))
953 scsi_io_completion_reprep(cmd, q);
955 scsi_io_completion_action(cmd, result);
958 static inline bool scsi_cmd_needs_dma_drain(struct scsi_device *sdev,
961 return sdev->dma_drain_len && blk_rq_is_passthrough(rq) &&
962 !op_is_write(req_op(rq)) &&
963 sdev->host->hostt->dma_need_drain(rq);
967 * scsi_alloc_sgtables - allocate S/G tables for a command
968 * @cmd: command descriptor we wish to initialize
971 * * BLK_STS_OK - on success
972 * * BLK_STS_RESOURCE - if the failure is retryable
973 * * BLK_STS_IOERR - if the failure is fatal
975 blk_status_t scsi_alloc_sgtables(struct scsi_cmnd *cmd)
977 struct scsi_device *sdev = cmd->device;
978 struct request *rq = cmd->request;
979 unsigned short nr_segs = blk_rq_nr_phys_segments(rq);
980 struct scatterlist *last_sg = NULL;
982 bool need_drain = scsi_cmd_needs_dma_drain(sdev, rq);
985 if (WARN_ON_ONCE(!nr_segs))
986 return BLK_STS_IOERR;
989 * Make sure there is space for the drain. The driver must adjust
990 * max_hw_segments to be prepared for this.
996 * If sg table allocation fails, requeue request later.
998 if (unlikely(sg_alloc_table_chained(&cmd->sdb.table, nr_segs,
999 cmd->sdb.table.sgl, SCSI_INLINE_SG_CNT)))
1000 return BLK_STS_RESOURCE;
1003 * Next, walk the list, and fill in the addresses and sizes of
1006 count = __blk_rq_map_sg(rq->q, rq, cmd->sdb.table.sgl, &last_sg);
1008 if (blk_rq_bytes(rq) & rq->q->dma_pad_mask) {
1009 unsigned int pad_len =
1010 (rq->q->dma_pad_mask & ~blk_rq_bytes(rq)) + 1;
1012 last_sg->length += pad_len;
1013 cmd->extra_len += pad_len;
1017 sg_unmark_end(last_sg);
1018 last_sg = sg_next(last_sg);
1019 sg_set_buf(last_sg, sdev->dma_drain_buf, sdev->dma_drain_len);
1020 sg_mark_end(last_sg);
1022 cmd->extra_len += sdev->dma_drain_len;
1026 BUG_ON(count > cmd->sdb.table.nents);
1027 cmd->sdb.table.nents = count;
1028 cmd->sdb.length = blk_rq_payload_bytes(rq);
1030 if (blk_integrity_rq(rq)) {
1031 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1034 if (WARN_ON_ONCE(!prot_sdb)) {
1036 * This can happen if someone (e.g. multipath)
1037 * queues a command to a device on an adapter
1038 * that does not support DIX.
1040 ret = BLK_STS_IOERR;
1041 goto out_free_sgtables;
1044 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
1046 if (sg_alloc_table_chained(&prot_sdb->table, ivecs,
1047 prot_sdb->table.sgl,
1048 SCSI_INLINE_PROT_SG_CNT)) {
1049 ret = BLK_STS_RESOURCE;
1050 goto out_free_sgtables;
1053 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
1054 prot_sdb->table.sgl);
1055 BUG_ON(count > ivecs);
1056 BUG_ON(count > queue_max_integrity_segments(rq->q));
1058 cmd->prot_sdb = prot_sdb;
1059 cmd->prot_sdb->table.nents = count;
1064 scsi_free_sgtables(cmd);
1067 EXPORT_SYMBOL(scsi_alloc_sgtables);
1070 * scsi_initialize_rq - initialize struct scsi_cmnd partially
1071 * @rq: Request associated with the SCSI command to be initialized.
1073 * This function initializes the members of struct scsi_cmnd that must be
1074 * initialized before request processing starts and that won't be
1075 * reinitialized if a SCSI command is requeued.
1077 * Called from inside blk_get_request() for pass-through requests and from
1078 * inside scsi_init_command() for filesystem requests.
1080 static void scsi_initialize_rq(struct request *rq)
1082 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1084 scsi_req_init(&cmd->req);
1085 init_rcu_head(&cmd->rcu);
1086 cmd->jiffies_at_alloc = jiffies;
1091 * Only called when the request isn't completed by SCSI, and not freed by
1094 static void scsi_cleanup_rq(struct request *rq)
1096 if (rq->rq_flags & RQF_DONTPREP) {
1097 scsi_mq_uninit_cmd(blk_mq_rq_to_pdu(rq));
1098 rq->rq_flags &= ~RQF_DONTPREP;
1102 /* Called before a request is prepared. See also scsi_mq_prep_fn(). */
1103 void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd)
1105 void *buf = cmd->sense_buffer;
1106 void *prot = cmd->prot_sdb;
1107 struct request *rq = blk_mq_rq_from_pdu(cmd);
1108 unsigned int flags = cmd->flags & SCMD_PRESERVED_FLAGS;
1109 unsigned long jiffies_at_alloc;
1110 int retries, to_clear;
1113 if (!blk_rq_is_scsi(rq) && !(flags & SCMD_INITIALIZED)) {
1114 flags |= SCMD_INITIALIZED;
1115 scsi_initialize_rq(rq);
1118 jiffies_at_alloc = cmd->jiffies_at_alloc;
1119 retries = cmd->retries;
1120 in_flight = test_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1122 * Zero out the cmd, except for the embedded scsi_request. Only clear
1123 * the driver-private command data if the LLD does not supply a
1124 * function to initialize that data.
1126 to_clear = sizeof(*cmd) - sizeof(cmd->req);
1127 if (!dev->host->hostt->init_cmd_priv)
1128 to_clear += dev->host->hostt->cmd_size;
1129 memset((char *)cmd + sizeof(cmd->req), 0, to_clear);
1132 cmd->sense_buffer = buf;
1133 cmd->prot_sdb = prot;
1135 INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
1136 cmd->jiffies_at_alloc = jiffies_at_alloc;
1137 cmd->retries = retries;
1139 __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1143 static blk_status_t scsi_setup_scsi_cmnd(struct scsi_device *sdev,
1144 struct request *req)
1146 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1149 * Passthrough requests may transfer data, in which case they must
1150 * a bio attached to them. Or they might contain a SCSI command
1151 * that does not transfer data, in which case they may optionally
1152 * submit a request without an attached bio.
1155 blk_status_t ret = scsi_alloc_sgtables(cmd);
1156 if (unlikely(ret != BLK_STS_OK))
1159 BUG_ON(blk_rq_bytes(req));
1161 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1164 cmd->cmd_len = scsi_req(req)->cmd_len;
1165 if (cmd->cmd_len == 0)
1166 cmd->cmd_len = scsi_command_size(cmd->cmnd);
1167 cmd->cmnd = scsi_req(req)->cmd;
1168 cmd->transfersize = blk_rq_bytes(req);
1169 cmd->allowed = scsi_req(req)->retries;
1174 scsi_device_state_check(struct scsi_device *sdev, struct request *req)
1176 switch (sdev->sdev_state) {
1180 case SDEV_TRANSPORT_OFFLINE:
1182 * If the device is offline we refuse to process any
1183 * commands. The device must be brought online
1184 * before trying any recovery commands.
1186 if (!sdev->offline_already) {
1187 sdev->offline_already = true;
1188 sdev_printk(KERN_ERR, sdev,
1189 "rejecting I/O to offline device\n");
1191 return BLK_STS_IOERR;
1194 * If the device is fully deleted, we refuse to
1195 * process any commands as well.
1197 sdev_printk(KERN_ERR, sdev,
1198 "rejecting I/O to dead device\n");
1199 return BLK_STS_IOERR;
1201 case SDEV_CREATED_BLOCK:
1202 return BLK_STS_RESOURCE;
1205 * If the device is blocked we only accept power management
1208 if (req && WARN_ON_ONCE(!(req->rq_flags & RQF_PM)))
1209 return BLK_STS_RESOURCE;
1213 * For any other not fully online state we only allow
1214 * power management commands.
1216 if (req && !(req->rq_flags & RQF_PM))
1217 return BLK_STS_IOERR;
1223 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1226 * Called with the queue_lock held.
1228 static inline int scsi_dev_queue_ready(struct request_queue *q,
1229 struct scsi_device *sdev)
1233 busy = atomic_inc_return(&sdev->device_busy) - 1;
1234 if (atomic_read(&sdev->device_blocked)) {
1239 * unblock after device_blocked iterates to zero
1241 if (atomic_dec_return(&sdev->device_blocked) > 0)
1243 SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev,
1244 "unblocking device at zero depth\n"));
1247 if (busy >= sdev->queue_depth)
1252 atomic_dec(&sdev->device_busy);
1257 * scsi_target_queue_ready: checks if there we can send commands to target
1258 * @sdev: scsi device on starget to check.
1260 static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1261 struct scsi_device *sdev)
1263 struct scsi_target *starget = scsi_target(sdev);
1266 if (starget->single_lun) {
1267 spin_lock_irq(shost->host_lock);
1268 if (starget->starget_sdev_user &&
1269 starget->starget_sdev_user != sdev) {
1270 spin_unlock_irq(shost->host_lock);
1273 starget->starget_sdev_user = sdev;
1274 spin_unlock_irq(shost->host_lock);
1277 if (starget->can_queue <= 0)
1280 busy = atomic_inc_return(&starget->target_busy) - 1;
1281 if (atomic_read(&starget->target_blocked) > 0) {
1286 * unblock after target_blocked iterates to zero
1288 if (atomic_dec_return(&starget->target_blocked) > 0)
1291 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1292 "unblocking target at zero depth\n"));
1295 if (busy >= starget->can_queue)
1301 spin_lock_irq(shost->host_lock);
1302 list_move_tail(&sdev->starved_entry, &shost->starved_list);
1303 spin_unlock_irq(shost->host_lock);
1305 if (starget->can_queue > 0)
1306 atomic_dec(&starget->target_busy);
1311 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1312 * return 0. We must end up running the queue again whenever 0 is
1313 * returned, else IO can hang.
1315 static inline int scsi_host_queue_ready(struct request_queue *q,
1316 struct Scsi_Host *shost,
1317 struct scsi_device *sdev,
1318 struct scsi_cmnd *cmd)
1320 if (scsi_host_in_recovery(shost))
1323 if (atomic_read(&shost->host_blocked) > 0) {
1324 if (scsi_host_busy(shost) > 0)
1328 * unblock after host_blocked iterates to zero
1330 if (atomic_dec_return(&shost->host_blocked) > 0)
1334 shost_printk(KERN_INFO, shost,
1335 "unblocking host at zero depth\n"));
1338 if (shost->host_self_blocked)
1341 /* We're OK to process the command, so we can't be starved */
1342 if (!list_empty(&sdev->starved_entry)) {
1343 spin_lock_irq(shost->host_lock);
1344 if (!list_empty(&sdev->starved_entry))
1345 list_del_init(&sdev->starved_entry);
1346 spin_unlock_irq(shost->host_lock);
1349 __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1354 spin_lock_irq(shost->host_lock);
1355 if (list_empty(&sdev->starved_entry))
1356 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1357 spin_unlock_irq(shost->host_lock);
1359 scsi_dec_host_busy(shost, cmd);
1364 * Busy state exporting function for request stacking drivers.
1366 * For efficiency, no lock is taken to check the busy state of
1367 * shost/starget/sdev, since the returned value is not guaranteed and
1368 * may be changed after request stacking drivers call the function,
1369 * regardless of taking lock or not.
1371 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1372 * needs to return 'not busy'. Otherwise, request stacking drivers
1373 * may hold requests forever.
1375 static bool scsi_mq_lld_busy(struct request_queue *q)
1377 struct scsi_device *sdev = q->queuedata;
1378 struct Scsi_Host *shost;
1380 if (blk_queue_dying(q))
1386 * Ignore host/starget busy state.
1387 * Since block layer does not have a concept of fairness across
1388 * multiple queues, congestion of host/starget needs to be handled
1391 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
1397 static void scsi_softirq_done(struct request *rq)
1399 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1402 INIT_LIST_HEAD(&cmd->eh_entry);
1404 atomic_inc(&cmd->device->iodone_cnt);
1406 atomic_inc(&cmd->device->ioerr_cnt);
1408 disposition = scsi_decide_disposition(cmd);
1409 if (disposition != SUCCESS && scsi_cmd_runtime_exceeced(cmd))
1410 disposition = SUCCESS;
1412 scsi_log_completion(cmd, disposition);
1414 switch (disposition) {
1416 scsi_finish_command(cmd);
1419 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1421 case ADD_TO_MLQUEUE:
1422 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1425 scsi_eh_scmd_add(cmd);
1431 * scsi_dispatch_cmd - Dispatch a command to the low-level driver.
1432 * @cmd: command block we are dispatching.
1434 * Return: nonzero return request was rejected and device's queue needs to be
1437 static int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
1439 struct Scsi_Host *host = cmd->device->host;
1442 atomic_inc(&cmd->device->iorequest_cnt);
1444 /* check if the device is still usable */
1445 if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
1446 /* in SDEV_DEL we error all commands. DID_NO_CONNECT
1447 * returns an immediate error upwards, and signals
1448 * that the device is no longer present */
1449 cmd->result = DID_NO_CONNECT << 16;
1453 /* Check to see if the scsi lld made this device blocked. */
1454 if (unlikely(scsi_device_blocked(cmd->device))) {
1456 * in blocked state, the command is just put back on
1457 * the device queue. The suspend state has already
1458 * blocked the queue so future requests should not
1459 * occur until the device transitions out of the
1462 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1463 "queuecommand : device blocked\n"));
1464 return SCSI_MLQUEUE_DEVICE_BUSY;
1467 /* Store the LUN value in cmnd, if needed. */
1468 if (cmd->device->lun_in_cdb)
1469 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
1470 (cmd->device->lun << 5 & 0xe0);
1475 * Before we queue this command, check if the command
1476 * length exceeds what the host adapter can handle.
1478 if (cmd->cmd_len > cmd->device->host->max_cmd_len) {
1479 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1480 "queuecommand : command too long. "
1481 "cdb_size=%d host->max_cmd_len=%d\n",
1482 cmd->cmd_len, cmd->device->host->max_cmd_len));
1483 cmd->result = (DID_ABORT << 16);
1487 if (unlikely(host->shost_state == SHOST_DEL)) {
1488 cmd->result = (DID_NO_CONNECT << 16);
1493 trace_scsi_dispatch_cmd_start(cmd);
1494 rtn = host->hostt->queuecommand(host, cmd);
1496 trace_scsi_dispatch_cmd_error(cmd, rtn);
1497 if (rtn != SCSI_MLQUEUE_DEVICE_BUSY &&
1498 rtn != SCSI_MLQUEUE_TARGET_BUSY)
1499 rtn = SCSI_MLQUEUE_HOST_BUSY;
1501 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1502 "queuecommand : request rejected\n"));
1507 cmd->scsi_done(cmd);
1511 /* Size in bytes of the sg-list stored in the scsi-mq command-private data. */
1512 static unsigned int scsi_mq_inline_sgl_size(struct Scsi_Host *shost)
1514 return min_t(unsigned int, shost->sg_tablesize, SCSI_INLINE_SG_CNT) *
1515 sizeof(struct scatterlist);
1518 static blk_status_t scsi_prepare_cmd(struct request *req)
1520 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1521 struct scsi_device *sdev = req->q->queuedata;
1522 struct Scsi_Host *shost = sdev->host;
1523 struct scatterlist *sg;
1525 scsi_init_command(sdev, cmd);
1528 cmd->tag = req->tag;
1529 cmd->prot_op = SCSI_PROT_NORMAL;
1530 if (blk_rq_bytes(req))
1531 cmd->sc_data_direction = rq_dma_dir(req);
1533 cmd->sc_data_direction = DMA_NONE;
1535 sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
1536 cmd->sdb.table.sgl = sg;
1538 if (scsi_host_get_prot(shost)) {
1539 memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer));
1541 cmd->prot_sdb->table.sgl =
1542 (struct scatterlist *)(cmd->prot_sdb + 1);
1546 * Special handling for passthrough commands, which don't go to the ULP
1549 if (blk_rq_is_scsi(req))
1550 return scsi_setup_scsi_cmnd(sdev, req);
1552 if (sdev->handler && sdev->handler->prep_fn) {
1553 blk_status_t ret = sdev->handler->prep_fn(sdev, req);
1555 if (ret != BLK_STS_OK)
1559 cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd;
1560 memset(cmd->cmnd, 0, BLK_MAX_CDB);
1561 return scsi_cmd_to_driver(cmd)->init_command(cmd);
1564 static void scsi_mq_done(struct scsi_cmnd *cmd)
1566 if (unlikely(blk_should_fake_timeout(cmd->request->q)))
1568 if (unlikely(test_and_set_bit(SCMD_STATE_COMPLETE, &cmd->state)))
1570 trace_scsi_dispatch_cmd_done(cmd);
1571 blk_mq_complete_request(cmd->request);
1574 static void scsi_mq_put_budget(struct request_queue *q)
1576 struct scsi_device *sdev = q->queuedata;
1578 atomic_dec(&sdev->device_busy);
1581 static bool scsi_mq_get_budget(struct request_queue *q)
1583 struct scsi_device *sdev = q->queuedata;
1585 if (scsi_dev_queue_ready(q, sdev))
1588 atomic_inc(&sdev->restarts);
1591 * Orders atomic_inc(&sdev->restarts) and atomic_read(&sdev->device_busy).
1592 * .restarts must be incremented before .device_busy is read because the
1593 * code in scsi_run_queue_async() depends on the order of these operations.
1595 smp_mb__after_atomic();
1598 * If all in-flight requests originated from this LUN are completed
1599 * before reading .device_busy, sdev->device_busy will be observed as
1600 * zero, then blk_mq_delay_run_hw_queues() will dispatch this request
1601 * soon. Otherwise, completion of one of these requests will observe
1602 * the .restarts flag, and the request queue will be run for handling
1603 * this request, see scsi_end_request().
1605 if (unlikely(atomic_read(&sdev->device_busy) == 0 &&
1606 !scsi_device_blocked(sdev)))
1607 blk_mq_delay_run_hw_queues(sdev->request_queue, SCSI_QUEUE_DELAY);
1611 static blk_status_t scsi_queue_rq(struct blk_mq_hw_ctx *hctx,
1612 const struct blk_mq_queue_data *bd)
1614 struct request *req = bd->rq;
1615 struct request_queue *q = req->q;
1616 struct scsi_device *sdev = q->queuedata;
1617 struct Scsi_Host *shost = sdev->host;
1618 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1623 * If the device is not in running state we will reject some or all
1626 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1627 ret = scsi_device_state_check(sdev, req);
1628 if (ret != BLK_STS_OK)
1629 goto out_put_budget;
1632 ret = BLK_STS_RESOURCE;
1633 if (!scsi_target_queue_ready(shost, sdev))
1634 goto out_put_budget;
1635 if (!scsi_host_queue_ready(q, shost, sdev, cmd))
1636 goto out_dec_target_busy;
1638 if (!(req->rq_flags & RQF_DONTPREP)) {
1639 ret = scsi_prepare_cmd(req);
1640 if (ret != BLK_STS_OK)
1641 goto out_dec_host_busy;
1642 req->rq_flags |= RQF_DONTPREP;
1644 clear_bit(SCMD_STATE_COMPLETE, &cmd->state);
1647 cmd->flags &= SCMD_PRESERVED_FLAGS;
1648 if (sdev->simple_tags)
1649 cmd->flags |= SCMD_TAGGED;
1651 cmd->flags |= SCMD_LAST;
1653 scsi_set_resid(cmd, 0);
1654 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1655 cmd->scsi_done = scsi_mq_done;
1657 blk_mq_start_request(req);
1658 reason = scsi_dispatch_cmd(cmd);
1660 scsi_set_blocked(cmd, reason);
1661 ret = BLK_STS_RESOURCE;
1662 goto out_dec_host_busy;
1668 scsi_dec_host_busy(shost, cmd);
1669 out_dec_target_busy:
1670 if (scsi_target(sdev)->can_queue > 0)
1671 atomic_dec(&scsi_target(sdev)->target_busy);
1673 scsi_mq_put_budget(q);
1677 case BLK_STS_RESOURCE:
1678 case BLK_STS_ZONE_RESOURCE:
1679 if (scsi_device_blocked(sdev))
1680 ret = BLK_STS_DEV_RESOURCE;
1683 scsi_req(req)->result = DID_BUS_BUSY << 16;
1684 if (req->rq_flags & RQF_DONTPREP)
1685 scsi_mq_uninit_cmd(cmd);
1688 if (unlikely(!scsi_device_online(sdev)))
1689 scsi_req(req)->result = DID_NO_CONNECT << 16;
1691 scsi_req(req)->result = DID_ERROR << 16;
1693 * Make sure to release all allocated resources when
1694 * we hit an error, as we will never see this command
1697 if (req->rq_flags & RQF_DONTPREP)
1698 scsi_mq_uninit_cmd(cmd);
1699 scsi_run_queue_async(sdev);
1705 static enum blk_eh_timer_return scsi_timeout(struct request *req,
1709 return BLK_EH_RESET_TIMER;
1710 return scsi_times_out(req);
1713 static int scsi_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
1714 unsigned int hctx_idx, unsigned int numa_node)
1716 struct Scsi_Host *shost = set->driver_data;
1717 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1718 struct scatterlist *sg;
1722 kmem_cache_alloc_node(scsi_sense_cache, GFP_KERNEL, numa_node);
1723 if (!cmd->sense_buffer)
1725 cmd->req.sense = cmd->sense_buffer;
1727 if (scsi_host_get_prot(shost)) {
1728 sg = (void *)cmd + sizeof(struct scsi_cmnd) +
1729 shost->hostt->cmd_size;
1730 cmd->prot_sdb = (void *)sg + scsi_mq_inline_sgl_size(shost);
1733 if (shost->hostt->init_cmd_priv) {
1734 ret = shost->hostt->init_cmd_priv(shost, cmd);
1736 kmem_cache_free(scsi_sense_cache, cmd->sense_buffer);
1742 static void scsi_mq_exit_request(struct blk_mq_tag_set *set, struct request *rq,
1743 unsigned int hctx_idx)
1745 struct Scsi_Host *shost = set->driver_data;
1746 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1748 if (shost->hostt->exit_cmd_priv)
1749 shost->hostt->exit_cmd_priv(shost, cmd);
1750 kmem_cache_free(scsi_sense_cache, cmd->sense_buffer);
1753 static int scsi_map_queues(struct blk_mq_tag_set *set)
1755 struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set);
1757 if (shost->hostt->map_queues)
1758 return shost->hostt->map_queues(shost);
1759 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
1762 void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q)
1764 struct device *dev = shost->dma_dev;
1767 * this limit is imposed by hardware restrictions
1769 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
1772 if (scsi_host_prot_dma(shost)) {
1773 shost->sg_prot_tablesize =
1774 min_not_zero(shost->sg_prot_tablesize,
1775 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
1776 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
1777 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
1780 if (dev->dma_mask) {
1781 shost->max_sectors = min_t(unsigned int, shost->max_sectors,
1782 dma_max_mapping_size(dev) >> SECTOR_SHIFT);
1784 blk_queue_max_hw_sectors(q, shost->max_sectors);
1785 blk_queue_segment_boundary(q, shost->dma_boundary);
1786 dma_set_seg_boundary(dev, shost->dma_boundary);
1788 blk_queue_max_segment_size(q, shost->max_segment_size);
1789 blk_queue_virt_boundary(q, shost->virt_boundary_mask);
1790 dma_set_max_seg_size(dev, queue_max_segment_size(q));
1793 * Set a reasonable default alignment: The larger of 32-byte (dword),
1794 * which is a common minimum for HBAs, and the minimum DMA alignment,
1795 * which is set by the platform.
1797 * Devices that require a bigger alignment can increase it later.
1799 blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1);
1801 EXPORT_SYMBOL_GPL(__scsi_init_queue);
1803 static const struct blk_mq_ops scsi_mq_ops_no_commit = {
1804 .get_budget = scsi_mq_get_budget,
1805 .put_budget = scsi_mq_put_budget,
1806 .queue_rq = scsi_queue_rq,
1807 .complete = scsi_softirq_done,
1808 .timeout = scsi_timeout,
1809 #ifdef CONFIG_BLK_DEBUG_FS
1810 .show_rq = scsi_show_rq,
1812 .init_request = scsi_mq_init_request,
1813 .exit_request = scsi_mq_exit_request,
1814 .initialize_rq_fn = scsi_initialize_rq,
1815 .cleanup_rq = scsi_cleanup_rq,
1816 .busy = scsi_mq_lld_busy,
1817 .map_queues = scsi_map_queues,
1821 static void scsi_commit_rqs(struct blk_mq_hw_ctx *hctx)
1823 struct request_queue *q = hctx->queue;
1824 struct scsi_device *sdev = q->queuedata;
1825 struct Scsi_Host *shost = sdev->host;
1827 shost->hostt->commit_rqs(shost, hctx->queue_num);
1830 static const struct blk_mq_ops scsi_mq_ops = {
1831 .get_budget = scsi_mq_get_budget,
1832 .put_budget = scsi_mq_put_budget,
1833 .queue_rq = scsi_queue_rq,
1834 .commit_rqs = scsi_commit_rqs,
1835 .complete = scsi_softirq_done,
1836 .timeout = scsi_timeout,
1837 #ifdef CONFIG_BLK_DEBUG_FS
1838 .show_rq = scsi_show_rq,
1840 .init_request = scsi_mq_init_request,
1841 .exit_request = scsi_mq_exit_request,
1842 .initialize_rq_fn = scsi_initialize_rq,
1843 .cleanup_rq = scsi_cleanup_rq,
1844 .busy = scsi_mq_lld_busy,
1845 .map_queues = scsi_map_queues,
1848 struct request_queue *scsi_mq_alloc_queue(struct scsi_device *sdev)
1850 sdev->request_queue = blk_mq_init_queue(&sdev->host->tag_set);
1851 if (IS_ERR(sdev->request_queue))
1854 sdev->request_queue->queuedata = sdev;
1855 __scsi_init_queue(sdev->host, sdev->request_queue);
1856 blk_queue_flag_set(QUEUE_FLAG_SCSI_PASSTHROUGH, sdev->request_queue);
1857 return sdev->request_queue;
1860 int scsi_mq_setup_tags(struct Scsi_Host *shost)
1862 unsigned int cmd_size, sgl_size;
1863 struct blk_mq_tag_set *tag_set = &shost->tag_set;
1865 sgl_size = max_t(unsigned int, sizeof(struct scatterlist),
1866 scsi_mq_inline_sgl_size(shost));
1867 cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size;
1868 if (scsi_host_get_prot(shost))
1869 cmd_size += sizeof(struct scsi_data_buffer) +
1870 sizeof(struct scatterlist) * SCSI_INLINE_PROT_SG_CNT;
1872 memset(tag_set, 0, sizeof(*tag_set));
1873 if (shost->hostt->commit_rqs)
1874 tag_set->ops = &scsi_mq_ops;
1876 tag_set->ops = &scsi_mq_ops_no_commit;
1877 tag_set->nr_hw_queues = shost->nr_hw_queues ? : 1;
1878 tag_set->queue_depth = shost->can_queue;
1879 tag_set->cmd_size = cmd_size;
1880 tag_set->numa_node = NUMA_NO_NODE;
1881 tag_set->flags = BLK_MQ_F_SHOULD_MERGE;
1883 BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy);
1884 tag_set->driver_data = shost;
1885 if (shost->host_tagset)
1886 tag_set->flags |= BLK_MQ_F_TAG_HCTX_SHARED;
1888 return blk_mq_alloc_tag_set(tag_set);
1891 void scsi_mq_destroy_tags(struct Scsi_Host *shost)
1893 blk_mq_free_tag_set(&shost->tag_set);
1897 * scsi_device_from_queue - return sdev associated with a request_queue
1898 * @q: The request queue to return the sdev from
1900 * Return the sdev associated with a request queue or NULL if the
1901 * request_queue does not reference a SCSI device.
1903 struct scsi_device *scsi_device_from_queue(struct request_queue *q)
1905 struct scsi_device *sdev = NULL;
1907 if (q->mq_ops == &scsi_mq_ops_no_commit ||
1908 q->mq_ops == &scsi_mq_ops)
1909 sdev = q->queuedata;
1910 if (!sdev || !get_device(&sdev->sdev_gendev))
1917 * scsi_block_requests - Utility function used by low-level drivers to prevent
1918 * further commands from being queued to the device.
1919 * @shost: host in question
1921 * There is no timer nor any other means by which the requests get unblocked
1922 * other than the low-level driver calling scsi_unblock_requests().
1924 void scsi_block_requests(struct Scsi_Host *shost)
1926 shost->host_self_blocked = 1;
1928 EXPORT_SYMBOL(scsi_block_requests);
1931 * scsi_unblock_requests - Utility function used by low-level drivers to allow
1932 * further commands to be queued to the device.
1933 * @shost: host in question
1935 * There is no timer nor any other means by which the requests get unblocked
1936 * other than the low-level driver calling scsi_unblock_requests(). This is done
1937 * as an API function so that changes to the internals of the scsi mid-layer
1938 * won't require wholesale changes to drivers that use this feature.
1940 void scsi_unblock_requests(struct Scsi_Host *shost)
1942 shost->host_self_blocked = 0;
1943 scsi_run_host_queues(shost);
1945 EXPORT_SYMBOL(scsi_unblock_requests);
1947 void scsi_exit_queue(void)
1949 kmem_cache_destroy(scsi_sense_cache);
1953 * scsi_mode_select - issue a mode select
1954 * @sdev: SCSI device to be queried
1955 * @pf: Page format bit (1 == standard, 0 == vendor specific)
1956 * @sp: Save page bit (0 == don't save, 1 == save)
1957 * @modepage: mode page being requested
1958 * @buffer: request buffer (may not be smaller than eight bytes)
1959 * @len: length of request buffer.
1960 * @timeout: command timeout
1961 * @retries: number of retries before failing
1962 * @data: returns a structure abstracting the mode header data
1963 * @sshdr: place to put sense data (or NULL if no sense to be collected).
1964 * must be SCSI_SENSE_BUFFERSIZE big.
1966 * Returns zero if successful; negative error number or scsi
1971 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
1972 unsigned char *buffer, int len, int timeout, int retries,
1973 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1975 unsigned char cmd[10];
1976 unsigned char *real_buffer;
1979 memset(cmd, 0, sizeof(cmd));
1980 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
1982 if (sdev->use_10_for_ms) {
1985 real_buffer = kmalloc(8 + len, GFP_KERNEL);
1988 memcpy(real_buffer + 8, buffer, len);
1992 real_buffer[2] = data->medium_type;
1993 real_buffer[3] = data->device_specific;
1994 real_buffer[4] = data->longlba ? 0x01 : 0;
1996 real_buffer[6] = data->block_descriptor_length >> 8;
1997 real_buffer[7] = data->block_descriptor_length;
1999 cmd[0] = MODE_SELECT_10;
2003 if (len > 255 || data->block_descriptor_length > 255 ||
2007 real_buffer = kmalloc(4 + len, GFP_KERNEL);
2010 memcpy(real_buffer + 4, buffer, len);
2013 real_buffer[1] = data->medium_type;
2014 real_buffer[2] = data->device_specific;
2015 real_buffer[3] = data->block_descriptor_length;
2017 cmd[0] = MODE_SELECT;
2021 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
2022 sshdr, timeout, retries, NULL);
2026 EXPORT_SYMBOL_GPL(scsi_mode_select);
2029 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
2030 * @sdev: SCSI device to be queried
2031 * @dbd: set if mode sense will allow block descriptors to be returned
2032 * @modepage: mode page being requested
2033 * @buffer: request buffer (may not be smaller than eight bytes)
2034 * @len: length of request buffer.
2035 * @timeout: command timeout
2036 * @retries: number of retries before failing
2037 * @data: returns a structure abstracting the mode header data
2038 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2039 * must be SCSI_SENSE_BUFFERSIZE big.
2041 * Returns zero if unsuccessful, or the header offset (either 4
2042 * or 8 depending on whether a six or ten byte command was
2043 * issued) if successful.
2046 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
2047 unsigned char *buffer, int len, int timeout, int retries,
2048 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2050 unsigned char cmd[12];
2053 int result, retry_count = retries;
2054 struct scsi_sense_hdr my_sshdr;
2056 memset(data, 0, sizeof(*data));
2057 memset(&cmd[0], 0, 12);
2059 dbd = sdev->set_dbd_for_ms ? 8 : dbd;
2060 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
2063 /* caller might not be interested in sense, but we need it */
2068 use_10_for_ms = sdev->use_10_for_ms;
2070 if (use_10_for_ms) {
2074 cmd[0] = MODE_SENSE_10;
2081 cmd[0] = MODE_SENSE;
2086 memset(buffer, 0, len);
2088 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
2089 sshdr, timeout, retries, NULL);
2091 /* This code looks awful: what it's doing is making sure an
2092 * ILLEGAL REQUEST sense return identifies the actual command
2093 * byte as the problem. MODE_SENSE commands can return
2094 * ILLEGAL REQUEST if the code page isn't supported */
2096 if (use_10_for_ms && !scsi_status_is_good(result) &&
2097 driver_byte(result) == DRIVER_SENSE) {
2098 if (scsi_sense_valid(sshdr)) {
2099 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
2100 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
2102 * Invalid command operation code
2104 sdev->use_10_for_ms = 0;
2110 if (scsi_status_is_good(result)) {
2111 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
2112 (modepage == 6 || modepage == 8))) {
2113 /* Initio breakage? */
2116 data->medium_type = 0;
2117 data->device_specific = 0;
2119 data->block_descriptor_length = 0;
2120 } else if (use_10_for_ms) {
2121 data->length = buffer[0]*256 + buffer[1] + 2;
2122 data->medium_type = buffer[2];
2123 data->device_specific = buffer[3];
2124 data->longlba = buffer[4] & 0x01;
2125 data->block_descriptor_length = buffer[6]*256
2128 data->length = buffer[0] + 1;
2129 data->medium_type = buffer[1];
2130 data->device_specific = buffer[2];
2131 data->block_descriptor_length = buffer[3];
2133 data->header_length = header_length;
2134 } else if ((status_byte(result) == CHECK_CONDITION) &&
2135 scsi_sense_valid(sshdr) &&
2136 sshdr->sense_key == UNIT_ATTENTION && retry_count) {
2143 EXPORT_SYMBOL(scsi_mode_sense);
2146 * scsi_test_unit_ready - test if unit is ready
2147 * @sdev: scsi device to change the state of.
2148 * @timeout: command timeout
2149 * @retries: number of retries before failing
2150 * @sshdr: outpout pointer for decoded sense information.
2152 * Returns zero if unsuccessful or an error if TUR failed. For
2153 * removable media, UNIT_ATTENTION sets ->changed flag.
2156 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2157 struct scsi_sense_hdr *sshdr)
2160 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2164 /* try to eat the UNIT_ATTENTION if there are enough retries */
2166 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
2168 if (sdev->removable && scsi_sense_valid(sshdr) &&
2169 sshdr->sense_key == UNIT_ATTENTION)
2171 } while (scsi_sense_valid(sshdr) &&
2172 sshdr->sense_key == UNIT_ATTENTION && --retries);
2176 EXPORT_SYMBOL(scsi_test_unit_ready);
2179 * scsi_device_set_state - Take the given device through the device state model.
2180 * @sdev: scsi device to change the state of.
2181 * @state: state to change to.
2183 * Returns zero if successful or an error if the requested
2184 * transition is illegal.
2187 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2189 enum scsi_device_state oldstate = sdev->sdev_state;
2191 if (state == oldstate)
2197 case SDEV_CREATED_BLOCK:
2208 case SDEV_TRANSPORT_OFFLINE:
2221 case SDEV_TRANSPORT_OFFLINE:
2229 case SDEV_TRANSPORT_OFFLINE:
2244 case SDEV_CREATED_BLOCK:
2253 case SDEV_CREATED_BLOCK:
2268 case SDEV_TRANSPORT_OFFLINE:
2280 case SDEV_TRANSPORT_OFFLINE:
2283 case SDEV_CREATED_BLOCK:
2291 sdev->offline_already = false;
2292 sdev->sdev_state = state;
2296 SCSI_LOG_ERROR_RECOVERY(1,
2297 sdev_printk(KERN_ERR, sdev,
2298 "Illegal state transition %s->%s",
2299 scsi_device_state_name(oldstate),
2300 scsi_device_state_name(state))
2304 EXPORT_SYMBOL(scsi_device_set_state);
2307 * scsi_evt_emit - emit a single SCSI device uevent
2308 * @sdev: associated SCSI device
2309 * @evt: event to emit
2311 * Send a single uevent (scsi_event) to the associated scsi_device.
2313 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2318 switch (evt->evt_type) {
2319 case SDEV_EVT_MEDIA_CHANGE:
2320 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2322 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2323 scsi_rescan_device(&sdev->sdev_gendev);
2324 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
2326 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2327 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
2329 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2330 envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
2332 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2333 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
2335 case SDEV_EVT_LUN_CHANGE_REPORTED:
2336 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
2338 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2339 envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED";
2341 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2342 envp[idx++] = "SDEV_UA=POWER_ON_RESET_OCCURRED";
2351 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2355 * scsi_evt_thread - send a uevent for each scsi event
2356 * @work: work struct for scsi_device
2358 * Dispatch queued events to their associated scsi_device kobjects
2361 void scsi_evt_thread(struct work_struct *work)
2363 struct scsi_device *sdev;
2364 enum scsi_device_event evt_type;
2365 LIST_HEAD(event_list);
2367 sdev = container_of(work, struct scsi_device, event_work);
2369 for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
2370 if (test_and_clear_bit(evt_type, sdev->pending_events))
2371 sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
2374 struct scsi_event *evt;
2375 struct list_head *this, *tmp;
2376 unsigned long flags;
2378 spin_lock_irqsave(&sdev->list_lock, flags);
2379 list_splice_init(&sdev->event_list, &event_list);
2380 spin_unlock_irqrestore(&sdev->list_lock, flags);
2382 if (list_empty(&event_list))
2385 list_for_each_safe(this, tmp, &event_list) {
2386 evt = list_entry(this, struct scsi_event, node);
2387 list_del(&evt->node);
2388 scsi_evt_emit(sdev, evt);
2395 * sdev_evt_send - send asserted event to uevent thread
2396 * @sdev: scsi_device event occurred on
2397 * @evt: event to send
2399 * Assert scsi device event asynchronously.
2401 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2403 unsigned long flags;
2406 /* FIXME: currently this check eliminates all media change events
2407 * for polled devices. Need to update to discriminate between AN
2408 * and polled events */
2409 if (!test_bit(evt->evt_type, sdev->supported_events)) {
2415 spin_lock_irqsave(&sdev->list_lock, flags);
2416 list_add_tail(&evt->node, &sdev->event_list);
2417 schedule_work(&sdev->event_work);
2418 spin_unlock_irqrestore(&sdev->list_lock, flags);
2420 EXPORT_SYMBOL_GPL(sdev_evt_send);
2423 * sdev_evt_alloc - allocate a new scsi event
2424 * @evt_type: type of event to allocate
2425 * @gfpflags: GFP flags for allocation
2427 * Allocates and returns a new scsi_event.
2429 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2432 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2436 evt->evt_type = evt_type;
2437 INIT_LIST_HEAD(&evt->node);
2439 /* evt_type-specific initialization, if any */
2441 case SDEV_EVT_MEDIA_CHANGE:
2442 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2443 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2444 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2445 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2446 case SDEV_EVT_LUN_CHANGE_REPORTED:
2447 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2448 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2456 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2459 * sdev_evt_send_simple - send asserted event to uevent thread
2460 * @sdev: scsi_device event occurred on
2461 * @evt_type: type of event to send
2462 * @gfpflags: GFP flags for allocation
2464 * Assert scsi device event asynchronously, given an event type.
2466 void sdev_evt_send_simple(struct scsi_device *sdev,
2467 enum scsi_device_event evt_type, gfp_t gfpflags)
2469 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2471 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2476 sdev_evt_send(sdev, evt);
2478 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2481 * scsi_device_quiesce - Block all commands except power management.
2482 * @sdev: scsi device to quiesce.
2484 * This works by trying to transition to the SDEV_QUIESCE state
2485 * (which must be a legal transition). When the device is in this
2486 * state, only power management requests will be accepted, all others will
2489 * Must be called with user context, may sleep.
2491 * Returns zero if unsuccessful or an error if not.
2494 scsi_device_quiesce(struct scsi_device *sdev)
2496 struct request_queue *q = sdev->request_queue;
2500 * It is allowed to call scsi_device_quiesce() multiple times from
2501 * the same context but concurrent scsi_device_quiesce() calls are
2504 WARN_ON_ONCE(sdev->quiesced_by && sdev->quiesced_by != current);
2506 if (sdev->quiesced_by == current)
2511 blk_mq_freeze_queue(q);
2513 * Ensure that the effect of blk_set_pm_only() will be visible
2514 * for percpu_ref_tryget() callers that occur after the queue
2515 * unfreeze even if the queue was already frozen before this function
2516 * was called. See also https://lwn.net/Articles/573497/.
2519 blk_mq_unfreeze_queue(q);
2521 mutex_lock(&sdev->state_mutex);
2522 err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2524 sdev->quiesced_by = current;
2526 blk_clear_pm_only(q);
2527 mutex_unlock(&sdev->state_mutex);
2531 EXPORT_SYMBOL(scsi_device_quiesce);
2534 * scsi_device_resume - Restart user issued commands to a quiesced device.
2535 * @sdev: scsi device to resume.
2537 * Moves the device from quiesced back to running and restarts the
2540 * Must be called with user context, may sleep.
2542 void scsi_device_resume(struct scsi_device *sdev)
2544 /* check if the device state was mutated prior to resume, and if
2545 * so assume the state is being managed elsewhere (for example
2546 * device deleted during suspend)
2548 mutex_lock(&sdev->state_mutex);
2549 if (sdev->sdev_state == SDEV_QUIESCE)
2550 scsi_device_set_state(sdev, SDEV_RUNNING);
2551 if (sdev->quiesced_by) {
2552 sdev->quiesced_by = NULL;
2553 blk_clear_pm_only(sdev->request_queue);
2555 mutex_unlock(&sdev->state_mutex);
2557 EXPORT_SYMBOL(scsi_device_resume);
2560 device_quiesce_fn(struct scsi_device *sdev, void *data)
2562 scsi_device_quiesce(sdev);
2566 scsi_target_quiesce(struct scsi_target *starget)
2568 starget_for_each_device(starget, NULL, device_quiesce_fn);
2570 EXPORT_SYMBOL(scsi_target_quiesce);
2573 device_resume_fn(struct scsi_device *sdev, void *data)
2575 scsi_device_resume(sdev);
2579 scsi_target_resume(struct scsi_target *starget)
2581 starget_for_each_device(starget, NULL, device_resume_fn);
2583 EXPORT_SYMBOL(scsi_target_resume);
2586 * scsi_internal_device_block_nowait - try to transition to the SDEV_BLOCK state
2587 * @sdev: device to block
2589 * Pause SCSI command processing on the specified device. Does not sleep.
2591 * Returns zero if successful or a negative error code upon failure.
2594 * This routine transitions the device to the SDEV_BLOCK state (which must be
2595 * a legal transition). When the device is in this state, command processing
2596 * is paused until the device leaves the SDEV_BLOCK state. See also
2597 * scsi_internal_device_unblock_nowait().
2599 int scsi_internal_device_block_nowait(struct scsi_device *sdev)
2601 struct request_queue *q = sdev->request_queue;
2604 err = scsi_device_set_state(sdev, SDEV_BLOCK);
2606 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
2613 * The device has transitioned to SDEV_BLOCK. Stop the
2614 * block layer from calling the midlayer with this device's
2617 blk_mq_quiesce_queue_nowait(q);
2620 EXPORT_SYMBOL_GPL(scsi_internal_device_block_nowait);
2623 * scsi_internal_device_block - try to transition to the SDEV_BLOCK state
2624 * @sdev: device to block
2626 * Pause SCSI command processing on the specified device and wait until all
2627 * ongoing scsi_request_fn() / scsi_queue_rq() calls have finished. May sleep.
2629 * Returns zero if successful or a negative error code upon failure.
2632 * This routine transitions the device to the SDEV_BLOCK state (which must be
2633 * a legal transition). When the device is in this state, command processing
2634 * is paused until the device leaves the SDEV_BLOCK state. See also
2635 * scsi_internal_device_unblock().
2637 static int scsi_internal_device_block(struct scsi_device *sdev)
2639 struct request_queue *q = sdev->request_queue;
2642 mutex_lock(&sdev->state_mutex);
2643 err = scsi_internal_device_block_nowait(sdev);
2645 blk_mq_quiesce_queue(q);
2646 mutex_unlock(&sdev->state_mutex);
2651 void scsi_start_queue(struct scsi_device *sdev)
2653 struct request_queue *q = sdev->request_queue;
2655 blk_mq_unquiesce_queue(q);
2659 * scsi_internal_device_unblock_nowait - resume a device after a block request
2660 * @sdev: device to resume
2661 * @new_state: state to set the device to after unblocking
2663 * Restart the device queue for a previously suspended SCSI device. Does not
2666 * Returns zero if successful or a negative error code upon failure.
2669 * This routine transitions the device to the SDEV_RUNNING state or to one of
2670 * the offline states (which must be a legal transition) allowing the midlayer
2671 * to goose the queue for this device.
2673 int scsi_internal_device_unblock_nowait(struct scsi_device *sdev,
2674 enum scsi_device_state new_state)
2676 switch (new_state) {
2678 case SDEV_TRANSPORT_OFFLINE:
2685 * Try to transition the scsi device to SDEV_RUNNING or one of the
2686 * offlined states and goose the device queue if successful.
2688 switch (sdev->sdev_state) {
2690 case SDEV_TRANSPORT_OFFLINE:
2691 sdev->sdev_state = new_state;
2693 case SDEV_CREATED_BLOCK:
2694 if (new_state == SDEV_TRANSPORT_OFFLINE ||
2695 new_state == SDEV_OFFLINE)
2696 sdev->sdev_state = new_state;
2698 sdev->sdev_state = SDEV_CREATED;
2706 scsi_start_queue(sdev);
2710 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock_nowait);
2713 * scsi_internal_device_unblock - resume a device after a block request
2714 * @sdev: device to resume
2715 * @new_state: state to set the device to after unblocking
2717 * Restart the device queue for a previously suspended SCSI device. May sleep.
2719 * Returns zero if successful or a negative error code upon failure.
2722 * This routine transitions the device to the SDEV_RUNNING state or to one of
2723 * the offline states (which must be a legal transition) allowing the midlayer
2724 * to goose the queue for this device.
2726 static int scsi_internal_device_unblock(struct scsi_device *sdev,
2727 enum scsi_device_state new_state)
2731 mutex_lock(&sdev->state_mutex);
2732 ret = scsi_internal_device_unblock_nowait(sdev, new_state);
2733 mutex_unlock(&sdev->state_mutex);
2739 device_block(struct scsi_device *sdev, void *data)
2743 ret = scsi_internal_device_block(sdev);
2745 WARN_ONCE(ret, "scsi_internal_device_block(%s) failed: ret = %d\n",
2746 dev_name(&sdev->sdev_gendev), ret);
2750 target_block(struct device *dev, void *data)
2752 if (scsi_is_target_device(dev))
2753 starget_for_each_device(to_scsi_target(dev), NULL,
2759 scsi_target_block(struct device *dev)
2761 if (scsi_is_target_device(dev))
2762 starget_for_each_device(to_scsi_target(dev), NULL,
2765 device_for_each_child(dev, NULL, target_block);
2767 EXPORT_SYMBOL_GPL(scsi_target_block);
2770 device_unblock(struct scsi_device *sdev, void *data)
2772 scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
2776 target_unblock(struct device *dev, void *data)
2778 if (scsi_is_target_device(dev))
2779 starget_for_each_device(to_scsi_target(dev), data,
2785 scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
2787 if (scsi_is_target_device(dev))
2788 starget_for_each_device(to_scsi_target(dev), &new_state,
2791 device_for_each_child(dev, &new_state, target_unblock);
2793 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2796 scsi_host_block(struct Scsi_Host *shost)
2798 struct scsi_device *sdev;
2802 * Call scsi_internal_device_block_nowait so we can avoid
2803 * calling synchronize_rcu() for each LUN.
2805 shost_for_each_device(sdev, shost) {
2806 mutex_lock(&sdev->state_mutex);
2807 ret = scsi_internal_device_block_nowait(sdev);
2808 mutex_unlock(&sdev->state_mutex);
2810 scsi_device_put(sdev);
2816 * SCSI never enables blk-mq's BLK_MQ_F_BLOCKING flag so
2817 * calling synchronize_rcu() once is enough.
2819 WARN_ON_ONCE(shost->tag_set.flags & BLK_MQ_F_BLOCKING);
2826 EXPORT_SYMBOL_GPL(scsi_host_block);
2829 scsi_host_unblock(struct Scsi_Host *shost, int new_state)
2831 struct scsi_device *sdev;
2834 shost_for_each_device(sdev, shost) {
2835 ret = scsi_internal_device_unblock(sdev, new_state);
2837 scsi_device_put(sdev);
2843 EXPORT_SYMBOL_GPL(scsi_host_unblock);
2846 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
2847 * @sgl: scatter-gather list
2848 * @sg_count: number of segments in sg
2849 * @offset: offset in bytes into sg, on return offset into the mapped area
2850 * @len: bytes to map, on return number of bytes mapped
2852 * Returns virtual address of the start of the mapped page
2854 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
2855 size_t *offset, size_t *len)
2858 size_t sg_len = 0, len_complete = 0;
2859 struct scatterlist *sg;
2862 WARN_ON(!irqs_disabled());
2864 for_each_sg(sgl, sg, sg_count, i) {
2865 len_complete = sg_len; /* Complete sg-entries */
2866 sg_len += sg->length;
2867 if (sg_len > *offset)
2871 if (unlikely(i == sg_count)) {
2872 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2874 __func__, sg_len, *offset, sg_count);
2879 /* Offset starting from the beginning of first page in this sg-entry */
2880 *offset = *offset - len_complete + sg->offset;
2882 /* Assumption: contiguous pages can be accessed as "page + i" */
2883 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
2884 *offset &= ~PAGE_MASK;
2886 /* Bytes in this sg-entry from *offset to the end of the page */
2887 sg_len = PAGE_SIZE - *offset;
2891 return kmap_atomic(page);
2893 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2896 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
2897 * @virt: virtual address to be unmapped
2899 void scsi_kunmap_atomic_sg(void *virt)
2901 kunmap_atomic(virt);
2903 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
2905 void sdev_disable_disk_events(struct scsi_device *sdev)
2907 atomic_inc(&sdev->disk_events_disable_depth);
2909 EXPORT_SYMBOL(sdev_disable_disk_events);
2911 void sdev_enable_disk_events(struct scsi_device *sdev)
2913 if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
2915 atomic_dec(&sdev->disk_events_disable_depth);
2917 EXPORT_SYMBOL(sdev_enable_disk_events);
2919 static unsigned char designator_prio(const unsigned char *d)
2922 /* not associated with LUN */
2926 /* invalid length */
2930 * Order of preference for lun descriptor:
2931 * - SCSI name string
2932 * - NAA IEEE Registered Extended
2933 * - EUI-64 based 16-byte
2934 * - EUI-64 based 12-byte
2935 * - NAA IEEE Registered
2936 * - NAA IEEE Extended
2937 * - EUI-64 based 8-byte
2938 * - SCSI name string (truncated)
2940 * as longer descriptors reduce the likelyhood
2941 * of identification clashes.
2944 switch (d[1] & 0xf) {
2946 /* SCSI name string, variable-length UTF-8 */
2949 switch (d[4] >> 4) {
2951 /* NAA registered extended */
2954 /* NAA registered */
2960 /* NAA locally assigned */
2969 /* EUI64-based, 16 byte */
2972 /* EUI64-based, 12 byte */
2975 /* EUI64-based, 8 byte */
2992 * scsi_vpd_lun_id - return a unique device identification
2993 * @sdev: SCSI device
2994 * @id: buffer for the identification
2995 * @id_len: length of the buffer
2997 * Copies a unique device identification into @id based
2998 * on the information in the VPD page 0x83 of the device.
2999 * The string will be formatted as a SCSI name string.
3001 * Returns the length of the identification or error on failure.
3002 * If the identifier is longer than the supplied buffer the actual
3003 * identifier length is returned and the buffer is not zero-padded.
3005 int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
3009 const unsigned char *d, *cur_id_str;
3010 const struct scsi_vpd *vpd_pg83;
3011 int id_size = -EINVAL;
3014 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3020 /* The id string must be at least 20 bytes + terminating NULL byte */
3026 memset(id, 0, id_len);
3027 for (d = vpd_pg83->data + 4;
3028 d < vpd_pg83->data + vpd_pg83->len;
3030 u8 prio = designator_prio(d);
3032 if (prio == 0 || cur_id_prio > prio)
3035 switch (d[1] & 0xf) {
3038 if (cur_id_size > d[3])
3042 if (cur_id_size + 4 > id_len)
3043 cur_id_size = id_len - 4;
3045 id_size = snprintf(id, id_len, "t10.%*pE",
3046 cur_id_size, cur_id_str);
3053 switch (cur_id_size) {
3055 id_size = snprintf(id, id_len,
3060 id_size = snprintf(id, id_len,
3065 id_size = snprintf(id, id_len,
3078 switch (cur_id_size) {
3080 id_size = snprintf(id, id_len,
3085 id_size = snprintf(id, id_len,
3094 /* SCSI name string */
3095 if (cur_id_size > d[3])
3097 /* Prefer others for truncated descriptor */
3098 if (d[3] > id_len) {
3100 if (cur_id_prio > prio)
3104 cur_id_size = id_size = d[3];
3106 if (cur_id_size >= id_len)
3107 cur_id_size = id_len - 1;
3108 memcpy(id, cur_id_str, cur_id_size);
3118 EXPORT_SYMBOL(scsi_vpd_lun_id);
3121 * scsi_vpd_tpg_id - return a target port group identifier
3122 * @sdev: SCSI device
3124 * Returns the Target Port Group identifier from the information
3125 * froom VPD page 0x83 of the device.
3127 * Returns the identifier or error on failure.
3129 int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
3131 const unsigned char *d;
3132 const struct scsi_vpd *vpd_pg83;
3133 int group_id = -EAGAIN, rel_port = -1;
3136 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3142 d = vpd_pg83->data + 4;
3143 while (d < vpd_pg83->data + vpd_pg83->len) {
3144 switch (d[1] & 0xf) {
3146 /* Relative target port */
3147 rel_port = get_unaligned_be16(&d[6]);
3150 /* Target port group */
3151 group_id = get_unaligned_be16(&d[6]);
3160 if (group_id >= 0 && rel_id && rel_port != -1)
3165 EXPORT_SYMBOL(scsi_vpd_tpg_id);