2 * Copyright (C) 1999 Eric Youngdale
3 * Copyright (C) 2014 Christoph Hellwig
5 * SCSI queueing library.
7 * Based upon conversations with large numbers
8 * of people at Linux Expo.
11 #include <linux/bio.h>
12 #include <linux/bitops.h>
13 #include <linux/blkdev.h>
14 #include <linux/completion.h>
15 #include <linux/kernel.h>
16 #include <linux/export.h>
17 #include <linux/init.h>
18 #include <linux/pci.h>
19 #include <linux/delay.h>
20 #include <linux/hardirq.h>
21 #include <linux/scatterlist.h>
22 #include <linux/blk-mq.h>
23 #include <linux/ratelimit.h>
24 #include <asm/unaligned.h>
26 #include <scsi/scsi.h>
27 #include <scsi/scsi_cmnd.h>
28 #include <scsi/scsi_dbg.h>
29 #include <scsi/scsi_device.h>
30 #include <scsi/scsi_driver.h>
31 #include <scsi/scsi_eh.h>
32 #include <scsi/scsi_host.h>
33 #include <scsi/scsi_dh.h>
35 #include <trace/events/scsi.h>
37 #include "scsi_priv.h"
38 #include "scsi_logging.h"
40 static struct kmem_cache *scsi_sdb_cache;
41 static struct kmem_cache *scsi_sense_cache;
42 static struct kmem_cache *scsi_sense_isadma_cache;
43 static DEFINE_MUTEX(scsi_sense_cache_mutex);
45 static inline struct kmem_cache *
46 scsi_select_sense_cache(struct Scsi_Host *shost)
48 return shost->unchecked_isa_dma ?
49 scsi_sense_isadma_cache : scsi_sense_cache;
52 static void scsi_free_sense_buffer(struct Scsi_Host *shost,
53 unsigned char *sense_buffer)
55 kmem_cache_free(scsi_select_sense_cache(shost), sense_buffer);
58 static unsigned char *scsi_alloc_sense_buffer(struct Scsi_Host *shost,
59 gfp_t gfp_mask, int numa_node)
61 return kmem_cache_alloc_node(scsi_select_sense_cache(shost), gfp_mask,
65 int scsi_init_sense_cache(struct Scsi_Host *shost)
67 struct kmem_cache *cache;
70 cache = scsi_select_sense_cache(shost);
74 mutex_lock(&scsi_sense_cache_mutex);
75 if (shost->unchecked_isa_dma) {
76 scsi_sense_isadma_cache =
77 kmem_cache_create("scsi_sense_cache(DMA)",
78 SCSI_SENSE_BUFFERSIZE, 0,
79 SLAB_HWCACHE_ALIGN | SLAB_CACHE_DMA, NULL);
80 if (!scsi_sense_isadma_cache)
84 kmem_cache_create("scsi_sense_cache",
85 SCSI_SENSE_BUFFERSIZE, 0, SLAB_HWCACHE_ALIGN, NULL);
86 if (!scsi_sense_cache)
90 mutex_unlock(&scsi_sense_cache_mutex);
95 * When to reinvoke queueing after a resource shortage. It's 3 msecs to
96 * not change behaviour from the previous unplug mechanism, experimentation
97 * may prove this needs changing.
99 #define SCSI_QUEUE_DELAY 3
102 scsi_set_blocked(struct scsi_cmnd *cmd, int reason)
104 struct Scsi_Host *host = cmd->device->host;
105 struct scsi_device *device = cmd->device;
106 struct scsi_target *starget = scsi_target(device);
109 * Set the appropriate busy bit for the device/host.
111 * If the host/device isn't busy, assume that something actually
112 * completed, and that we should be able to queue a command now.
114 * Note that the prior mid-layer assumption that any host could
115 * always queue at least one command is now broken. The mid-layer
116 * will implement a user specifiable stall (see
117 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
118 * if a command is requeued with no other commands outstanding
119 * either for the device or for the host.
122 case SCSI_MLQUEUE_HOST_BUSY:
123 atomic_set(&host->host_blocked, host->max_host_blocked);
125 case SCSI_MLQUEUE_DEVICE_BUSY:
126 case SCSI_MLQUEUE_EH_RETRY:
127 atomic_set(&device->device_blocked,
128 device->max_device_blocked);
130 case SCSI_MLQUEUE_TARGET_BUSY:
131 atomic_set(&starget->target_blocked,
132 starget->max_target_blocked);
137 static void scsi_mq_requeue_cmd(struct scsi_cmnd *cmd)
139 struct scsi_device *sdev = cmd->device;
141 blk_mq_requeue_request(cmd->request, true);
142 put_device(&sdev->sdev_gendev);
146 * __scsi_queue_insert - private queue insertion
147 * @cmd: The SCSI command being requeued
148 * @reason: The reason for the requeue
149 * @unbusy: Whether the queue should be unbusied
151 * This is a private queue insertion. The public interface
152 * scsi_queue_insert() always assumes the queue should be unbusied
153 * because it's always called before the completion. This function is
154 * for a requeue after completion, which should only occur in this
157 static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, int unbusy)
159 struct scsi_device *device = cmd->device;
160 struct request_queue *q = device->request_queue;
163 SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd,
164 "Inserting command %p into mlqueue\n", cmd));
166 scsi_set_blocked(cmd, reason);
169 * Decrement the counters, since these commands are no longer
170 * active on the host/device.
173 scsi_device_unbusy(device);
176 * Requeue this command. It will go before all other commands
177 * that are already in the queue. Schedule requeue work under
178 * lock such that the kblockd_schedule_work() call happens
179 * before blk_cleanup_queue() finishes.
183 scsi_mq_requeue_cmd(cmd);
186 spin_lock_irqsave(q->queue_lock, flags);
187 blk_requeue_request(q, cmd->request);
188 kblockd_schedule_work(&device->requeue_work);
189 spin_unlock_irqrestore(q->queue_lock, flags);
193 * Function: scsi_queue_insert()
195 * Purpose: Insert a command in the midlevel queue.
197 * Arguments: cmd - command that we are adding to queue.
198 * reason - why we are inserting command to queue.
200 * Lock status: Assumed that lock is not held upon entry.
204 * Notes: We do this for one of two cases. Either the host is busy
205 * and it cannot accept any more commands for the time being,
206 * or the device returned QUEUE_FULL and can accept no more
208 * Notes: This could be called either from an interrupt context or a
209 * normal process context.
211 void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
213 __scsi_queue_insert(cmd, reason, 1);
216 static int __scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
217 int data_direction, void *buffer, unsigned bufflen,
218 unsigned char *sense, int timeout, int retries, u64 flags,
219 req_flags_t rq_flags, int *resid)
222 struct scsi_request *rq;
223 int ret = DRIVER_ERROR << 24;
225 req = blk_get_request(sdev->request_queue,
226 data_direction == DMA_TO_DEVICE ?
227 REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN, __GFP_RECLAIM);
233 if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
234 buffer, bufflen, __GFP_RECLAIM))
237 rq->cmd_len = COMMAND_SIZE(cmd[0]);
238 memcpy(rq->cmd, cmd, rq->cmd_len);
239 req->retries = retries;
240 req->timeout = timeout;
241 req->cmd_flags |= flags;
242 req->rq_flags |= rq_flags | RQF_QUIET | RQF_PREEMPT;
245 * head injection *required* here otherwise quiesce won't work
247 blk_execute_rq(req->q, NULL, req, 1);
250 * Some devices (USB mass-storage in particular) may transfer
251 * garbage data together with a residue indicating that the data
252 * is invalid. Prevent the garbage from being misinterpreted
253 * and prevent security leaks by zeroing out the excess data.
255 if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen))
256 memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len);
259 *resid = rq->resid_len;
260 if (sense && rq->sense_len)
261 memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE);
264 blk_put_request(req);
270 * scsi_execute - insert request and wait for the result
273 * @data_direction: data direction
274 * @buffer: data buffer
275 * @bufflen: len of buffer
276 * @sense: optional sense buffer
277 * @timeout: request timeout in seconds
278 * @retries: number of times to retry request
279 * @flags: or into request flags;
280 * @resid: optional residual length
282 * returns the req->errors value which is the scsi_cmnd result
285 int scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
286 int data_direction, void *buffer, unsigned bufflen,
287 unsigned char *sense, int timeout, int retries, u64 flags,
290 return __scsi_execute(sdev, cmd, data_direction, buffer, bufflen, sense,
291 timeout, retries, flags, 0, resid);
293 EXPORT_SYMBOL(scsi_execute);
295 int scsi_execute_req_flags(struct scsi_device *sdev, const unsigned char *cmd,
296 int data_direction, void *buffer, unsigned bufflen,
297 struct scsi_sense_hdr *sshdr, int timeout, int retries,
298 int *resid, u64 flags, req_flags_t rq_flags)
304 sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
306 return DRIVER_ERROR << 24;
308 result = __scsi_execute(sdev, cmd, data_direction, buffer, bufflen,
309 sense, timeout, retries, flags, rq_flags, resid);
311 scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, sshdr);
316 EXPORT_SYMBOL(scsi_execute_req_flags);
319 * Function: scsi_init_cmd_errh()
321 * Purpose: Initialize cmd fields related to error handling.
323 * Arguments: cmd - command that is ready to be queued.
325 * Notes: This function has the job of initializing a number of
326 * fields related to error handling. Typically this will
327 * be called once for each command, as required.
329 static void scsi_init_cmd_errh(struct scsi_cmnd *cmd)
331 cmd->serial_number = 0;
332 scsi_set_resid(cmd, 0);
333 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
334 if (cmd->cmd_len == 0)
335 cmd->cmd_len = scsi_command_size(cmd->cmnd);
338 void scsi_device_unbusy(struct scsi_device *sdev)
340 struct Scsi_Host *shost = sdev->host;
341 struct scsi_target *starget = scsi_target(sdev);
344 atomic_dec(&shost->host_busy);
345 if (starget->can_queue > 0)
346 atomic_dec(&starget->target_busy);
348 if (unlikely(scsi_host_in_recovery(shost) &&
349 (shost->host_failed || shost->host_eh_scheduled))) {
350 spin_lock_irqsave(shost->host_lock, flags);
351 scsi_eh_wakeup(shost);
352 spin_unlock_irqrestore(shost->host_lock, flags);
355 atomic_dec(&sdev->device_busy);
358 static void scsi_kick_queue(struct request_queue *q)
361 blk_mq_start_hw_queues(q);
367 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
368 * and call blk_run_queue for all the scsi_devices on the target -
369 * including current_sdev first.
371 * Called with *no* scsi locks held.
373 static void scsi_single_lun_run(struct scsi_device *current_sdev)
375 struct Scsi_Host *shost = current_sdev->host;
376 struct scsi_device *sdev, *tmp;
377 struct scsi_target *starget = scsi_target(current_sdev);
380 spin_lock_irqsave(shost->host_lock, flags);
381 starget->starget_sdev_user = NULL;
382 spin_unlock_irqrestore(shost->host_lock, flags);
385 * Call blk_run_queue for all LUNs on the target, starting with
386 * current_sdev. We race with others (to set starget_sdev_user),
387 * but in most cases, we will be first. Ideally, each LU on the
388 * target would get some limited time or requests on the target.
390 scsi_kick_queue(current_sdev->request_queue);
392 spin_lock_irqsave(shost->host_lock, flags);
393 if (starget->starget_sdev_user)
395 list_for_each_entry_safe(sdev, tmp, &starget->devices,
396 same_target_siblings) {
397 if (sdev == current_sdev)
399 if (scsi_device_get(sdev))
402 spin_unlock_irqrestore(shost->host_lock, flags);
403 scsi_kick_queue(sdev->request_queue);
404 spin_lock_irqsave(shost->host_lock, flags);
406 scsi_device_put(sdev);
409 spin_unlock_irqrestore(shost->host_lock, flags);
412 static inline bool scsi_device_is_busy(struct scsi_device *sdev)
414 if (atomic_read(&sdev->device_busy) >= sdev->queue_depth)
416 if (atomic_read(&sdev->device_blocked) > 0)
421 static inline bool scsi_target_is_busy(struct scsi_target *starget)
423 if (starget->can_queue > 0) {
424 if (atomic_read(&starget->target_busy) >= starget->can_queue)
426 if (atomic_read(&starget->target_blocked) > 0)
432 static inline bool scsi_host_is_busy(struct Scsi_Host *shost)
434 if (shost->can_queue > 0 &&
435 atomic_read(&shost->host_busy) >= shost->can_queue)
437 if (atomic_read(&shost->host_blocked) > 0)
439 if (shost->host_self_blocked)
444 static void scsi_starved_list_run(struct Scsi_Host *shost)
446 LIST_HEAD(starved_list);
447 struct scsi_device *sdev;
450 spin_lock_irqsave(shost->host_lock, flags);
451 list_splice_init(&shost->starved_list, &starved_list);
453 while (!list_empty(&starved_list)) {
454 struct request_queue *slq;
457 * As long as shost is accepting commands and we have
458 * starved queues, call blk_run_queue. scsi_request_fn
459 * drops the queue_lock and can add us back to the
462 * host_lock protects the starved_list and starved_entry.
463 * scsi_request_fn must get the host_lock before checking
464 * or modifying starved_list or starved_entry.
466 if (scsi_host_is_busy(shost))
469 sdev = list_entry(starved_list.next,
470 struct scsi_device, starved_entry);
471 list_del_init(&sdev->starved_entry);
472 if (scsi_target_is_busy(scsi_target(sdev))) {
473 list_move_tail(&sdev->starved_entry,
474 &shost->starved_list);
479 * Once we drop the host lock, a racing scsi_remove_device()
480 * call may remove the sdev from the starved list and destroy
481 * it and the queue. Mitigate by taking a reference to the
482 * queue and never touching the sdev again after we drop the
483 * host lock. Note: if __scsi_remove_device() invokes
484 * blk_cleanup_queue() before the queue is run from this
485 * function then blk_run_queue() will return immediately since
486 * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
488 slq = sdev->request_queue;
489 if (!blk_get_queue(slq))
491 spin_unlock_irqrestore(shost->host_lock, flags);
493 scsi_kick_queue(slq);
496 spin_lock_irqsave(shost->host_lock, flags);
498 /* put any unprocessed entries back */
499 list_splice(&starved_list, &shost->starved_list);
500 spin_unlock_irqrestore(shost->host_lock, flags);
504 * Function: scsi_run_queue()
506 * Purpose: Select a proper request queue to serve next
508 * Arguments: q - last request's queue
512 * Notes: The previous command was completely finished, start
513 * a new one if possible.
515 static void scsi_run_queue(struct request_queue *q)
517 struct scsi_device *sdev = q->queuedata;
519 if (scsi_target(sdev)->single_lun)
520 scsi_single_lun_run(sdev);
521 if (!list_empty(&sdev->host->starved_list))
522 scsi_starved_list_run(sdev->host);
525 blk_mq_start_stopped_hw_queues(q, false);
530 void scsi_requeue_run_queue(struct work_struct *work)
532 struct scsi_device *sdev;
533 struct request_queue *q;
535 sdev = container_of(work, struct scsi_device, requeue_work);
536 q = sdev->request_queue;
541 * Function: scsi_requeue_command()
543 * Purpose: Handle post-processing of completed commands.
545 * Arguments: q - queue to operate on
546 * cmd - command that may need to be requeued.
550 * Notes: After command completion, there may be blocks left
551 * over which weren't finished by the previous command
552 * this can be for a number of reasons - the main one is
553 * I/O errors in the middle of the request, in which case
554 * we need to request the blocks that come after the bad
556 * Notes: Upon return, cmd is a stale pointer.
558 static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
560 struct scsi_device *sdev = cmd->device;
561 struct request *req = cmd->request;
564 spin_lock_irqsave(q->queue_lock, flags);
565 blk_unprep_request(req);
567 scsi_put_command(cmd);
568 blk_requeue_request(q, req);
569 spin_unlock_irqrestore(q->queue_lock, flags);
573 put_device(&sdev->sdev_gendev);
576 void scsi_run_host_queues(struct Scsi_Host *shost)
578 struct scsi_device *sdev;
580 shost_for_each_device(sdev, shost)
581 scsi_run_queue(sdev->request_queue);
584 static void scsi_uninit_cmd(struct scsi_cmnd *cmd)
586 if (!blk_rq_is_passthrough(cmd->request)) {
587 struct scsi_driver *drv = scsi_cmd_to_driver(cmd);
589 if (drv->uninit_command)
590 drv->uninit_command(cmd);
594 static void scsi_mq_free_sgtables(struct scsi_cmnd *cmd)
596 struct scsi_data_buffer *sdb;
598 if (cmd->sdb.table.nents)
599 sg_free_table_chained(&cmd->sdb.table, true);
600 if (cmd->request->next_rq) {
601 sdb = cmd->request->next_rq->special;
603 sg_free_table_chained(&sdb->table, true);
605 if (scsi_prot_sg_count(cmd))
606 sg_free_table_chained(&cmd->prot_sdb->table, true);
609 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd)
611 struct scsi_device *sdev = cmd->device;
612 struct Scsi_Host *shost = sdev->host;
615 scsi_mq_free_sgtables(cmd);
616 scsi_uninit_cmd(cmd);
618 if (shost->use_cmd_list) {
619 BUG_ON(list_empty(&cmd->list));
620 spin_lock_irqsave(&sdev->list_lock, flags);
621 list_del_init(&cmd->list);
622 spin_unlock_irqrestore(&sdev->list_lock, flags);
627 * Function: scsi_release_buffers()
629 * Purpose: Free resources allocate for a scsi_command.
631 * Arguments: cmd - command that we are bailing.
633 * Lock status: Assumed that no lock is held upon entry.
637 * Notes: In the event that an upper level driver rejects a
638 * command, we must release resources allocated during
639 * the __init_io() function. Primarily this would involve
640 * the scatter-gather table.
642 static void scsi_release_buffers(struct scsi_cmnd *cmd)
644 if (cmd->sdb.table.nents)
645 sg_free_table_chained(&cmd->sdb.table, false);
647 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
649 if (scsi_prot_sg_count(cmd))
650 sg_free_table_chained(&cmd->prot_sdb->table, false);
653 static void scsi_release_bidi_buffers(struct scsi_cmnd *cmd)
655 struct scsi_data_buffer *bidi_sdb = cmd->request->next_rq->special;
657 sg_free_table_chained(&bidi_sdb->table, false);
658 kmem_cache_free(scsi_sdb_cache, bidi_sdb);
659 cmd->request->next_rq->special = NULL;
662 static bool scsi_end_request(struct request *req, int error,
663 unsigned int bytes, unsigned int bidi_bytes)
665 struct scsi_cmnd *cmd = req->special;
666 struct scsi_device *sdev = cmd->device;
667 struct request_queue *q = sdev->request_queue;
669 if (blk_update_request(req, error, bytes))
672 /* Bidi request must be completed as a whole */
673 if (unlikely(bidi_bytes) &&
674 blk_update_request(req->next_rq, error, bidi_bytes))
677 if (blk_queue_add_random(q))
678 add_disk_randomness(req->rq_disk);
682 * In the MQ case the command gets freed by __blk_mq_end_request,
683 * so we have to do all cleanup that depends on it earlier.
685 * We also can't kick the queues from irq context, so we
686 * will have to defer it to a workqueue.
688 scsi_mq_uninit_cmd(cmd);
690 __blk_mq_end_request(req, error);
692 if (scsi_target(sdev)->single_lun ||
693 !list_empty(&sdev->host->starved_list))
694 kblockd_schedule_work(&sdev->requeue_work);
696 blk_mq_start_stopped_hw_queues(q, true);
701 scsi_release_bidi_buffers(cmd);
702 scsi_release_buffers(cmd);
703 scsi_put_command(cmd);
705 spin_lock_irqsave(q->queue_lock, flags);
706 blk_finish_request(req, error);
707 spin_unlock_irqrestore(q->queue_lock, flags);
712 put_device(&sdev->sdev_gendev);
717 * __scsi_error_from_host_byte - translate SCSI error code into errno
718 * @cmd: SCSI command (unused)
719 * @result: scsi error code
721 * Translate SCSI error code into standard UNIX errno.
723 * -ENOLINK temporary transport failure
724 * -EREMOTEIO permanent target failure, do not retry
725 * -EBADE permanent nexus failure, retry on other path
726 * -ENOSPC No write space available
727 * -ENODATA Medium error
728 * -EIO unspecified I/O error
730 static int __scsi_error_from_host_byte(struct scsi_cmnd *cmd, int result)
734 switch(host_byte(result)) {
735 case DID_TRANSPORT_FAILFAST:
738 case DID_TARGET_FAILURE:
739 set_host_byte(cmd, DID_OK);
742 case DID_NEXUS_FAILURE:
743 set_host_byte(cmd, DID_OK);
746 case DID_ALLOC_FAILURE:
747 set_host_byte(cmd, DID_OK);
750 case DID_MEDIUM_ERROR:
751 set_host_byte(cmd, DID_OK);
763 * Function: scsi_io_completion()
765 * Purpose: Completion processing for block device I/O requests.
767 * Arguments: cmd - command that is finished.
769 * Lock status: Assumed that no lock is held upon entry.
773 * Notes: We will finish off the specified number of sectors. If we
774 * are done, the command block will be released and the queue
775 * function will be goosed. If we are not done then we have to
776 * figure out what to do next:
778 * a) We can call scsi_requeue_command(). The request
779 * will be unprepared and put back on the queue. Then
780 * a new command will be created for it. This should
781 * be used if we made forward progress, or if we want
782 * to switch from READ(10) to READ(6) for example.
784 * b) We can call __scsi_queue_insert(). The request will
785 * be put back on the queue and retried using the same
786 * command as before, possibly after a delay.
788 * c) We can call scsi_end_request() with -EIO to fail
789 * the remainder of the request.
791 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
793 int result = cmd->result;
794 struct request_queue *q = cmd->device->request_queue;
795 struct request *req = cmd->request;
797 struct scsi_sense_hdr sshdr;
798 bool sense_valid = false;
799 int sense_deferred = 0, level = 0;
800 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
801 ACTION_DELAYED_RETRY} action;
802 unsigned long wait_for = (cmd->allowed + 1) * req->timeout;
805 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
807 sense_deferred = scsi_sense_is_deferred(&sshdr);
810 if (blk_rq_is_passthrough(req)) {
814 * SG_IO wants current and deferred errors
816 scsi_req(req)->sense_len =
817 min(8 + cmd->sense_buffer[7],
818 SCSI_SENSE_BUFFERSIZE);
821 error = __scsi_error_from_host_byte(cmd, result);
824 * __scsi_error_from_host_byte may have reset the host_byte
826 req->errors = cmd->result;
828 scsi_req(req)->resid_len = scsi_get_resid(cmd);
830 if (scsi_bidi_cmnd(cmd)) {
832 * Bidi commands Must be complete as a whole,
833 * both sides at once.
835 scsi_req(req->next_rq)->resid_len = scsi_in(cmd)->resid;
836 if (scsi_end_request(req, 0, blk_rq_bytes(req),
837 blk_rq_bytes(req->next_rq)))
841 } else if (blk_rq_bytes(req) == 0 && result && !sense_deferred) {
843 * Flush commands do not transfers any data, and thus cannot use
844 * good_bytes != blk_rq_bytes(req) as the signal for an error.
845 * This sets the error explicitly for the problem case.
847 error = __scsi_error_from_host_byte(cmd, result);
850 /* no bidi support for !blk_rq_is_passthrough yet */
851 BUG_ON(blk_bidi_rq(req));
854 * Next deal with any sectors which we were able to correctly
857 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd,
858 "%u sectors total, %d bytes done.\n",
859 blk_rq_sectors(req), good_bytes));
862 * Recovered errors need reporting, but they're always treated as
863 * success, so fiddle the result code here. For passthrough requests
864 * we already took a copy of the original into rq->errors which
865 * is what gets returned to the user
867 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
868 /* if ATA PASS-THROUGH INFORMATION AVAILABLE skip
869 * print since caller wants ATA registers. Only occurs on
870 * SCSI ATA PASS_THROUGH commands when CK_COND=1
872 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
874 else if (!(req->rq_flags & RQF_QUIET))
875 scsi_print_sense(cmd);
877 /* for passthrough error may be set */
882 * special case: failed zero length commands always need to
883 * drop down into the retry code. Otherwise, if we finished
884 * all bytes in the request we are done now.
886 if (!(blk_rq_bytes(req) == 0 && error) &&
887 !scsi_end_request(req, error, good_bytes, 0))
891 * Kill remainder if no retrys.
893 if (error && scsi_noretry_cmd(cmd)) {
894 if (scsi_end_request(req, error, blk_rq_bytes(req), 0))
900 * If there had been no error, but we have leftover bytes in the
901 * requeues just queue the command up again.
906 error = __scsi_error_from_host_byte(cmd, result);
908 if (host_byte(result) == DID_RESET) {
909 /* Third party bus reset or reset for error recovery
910 * reasons. Just retry the command and see what
913 action = ACTION_RETRY;
914 } else if (sense_valid && !sense_deferred) {
915 switch (sshdr.sense_key) {
917 if (cmd->device->removable) {
918 /* Detected disc change. Set a bit
919 * and quietly refuse further access.
921 cmd->device->changed = 1;
922 action = ACTION_FAIL;
924 /* Must have been a power glitch, or a
925 * bus reset. Could not have been a
926 * media change, so we just retry the
927 * command and see what happens.
929 action = ACTION_RETRY;
932 case ILLEGAL_REQUEST:
933 /* If we had an ILLEGAL REQUEST returned, then
934 * we may have performed an unsupported
935 * command. The only thing this should be
936 * would be a ten byte read where only a six
937 * byte read was supported. Also, on a system
938 * where READ CAPACITY failed, we may have
939 * read past the end of the disk.
941 if ((cmd->device->use_10_for_rw &&
942 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
943 (cmd->cmnd[0] == READ_10 ||
944 cmd->cmnd[0] == WRITE_10)) {
945 /* This will issue a new 6-byte command. */
946 cmd->device->use_10_for_rw = 0;
947 action = ACTION_REPREP;
948 } else if (sshdr.asc == 0x10) /* DIX */ {
949 action = ACTION_FAIL;
951 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
952 } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
953 action = ACTION_FAIL;
956 action = ACTION_FAIL;
958 case ABORTED_COMMAND:
959 action = ACTION_FAIL;
960 if (sshdr.asc == 0x10) /* DIF */
964 /* If the device is in the process of becoming
965 * ready, or has a temporary blockage, retry.
967 if (sshdr.asc == 0x04) {
968 switch (sshdr.ascq) {
969 case 0x01: /* becoming ready */
970 case 0x04: /* format in progress */
971 case 0x05: /* rebuild in progress */
972 case 0x06: /* recalculation in progress */
973 case 0x07: /* operation in progress */
974 case 0x08: /* Long write in progress */
975 case 0x09: /* self test in progress */
976 case 0x14: /* space allocation in progress */
977 action = ACTION_DELAYED_RETRY;
980 action = ACTION_FAIL;
984 action = ACTION_FAIL;
986 case VOLUME_OVERFLOW:
987 /* See SSC3rXX or current. */
988 action = ACTION_FAIL;
991 action = ACTION_FAIL;
995 action = ACTION_FAIL;
997 if (action != ACTION_FAIL &&
998 time_before(cmd->jiffies_at_alloc + wait_for, jiffies))
999 action = ACTION_FAIL;
1003 /* Give up and fail the remainder of the request */
1004 if (!(req->rq_flags & RQF_QUIET)) {
1005 static DEFINE_RATELIMIT_STATE(_rs,
1006 DEFAULT_RATELIMIT_INTERVAL,
1007 DEFAULT_RATELIMIT_BURST);
1009 if (unlikely(scsi_logging_level))
1010 level = SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
1011 SCSI_LOG_MLCOMPLETE_BITS);
1014 * if logging is enabled the failure will be printed
1015 * in scsi_log_completion(), so avoid duplicate messages
1017 if (!level && __ratelimit(&_rs)) {
1018 scsi_print_result(cmd, NULL, FAILED);
1019 if (driver_byte(result) & DRIVER_SENSE)
1020 scsi_print_sense(cmd);
1021 scsi_print_command(cmd);
1024 if (!scsi_end_request(req, error, blk_rq_err_bytes(req), 0))
1029 /* Unprep the request and put it back at the head of the queue.
1030 * A new command will be prepared and issued.
1033 cmd->request->rq_flags &= ~RQF_DONTPREP;
1034 scsi_mq_uninit_cmd(cmd);
1035 scsi_mq_requeue_cmd(cmd);
1037 scsi_release_buffers(cmd);
1038 scsi_requeue_command(q, cmd);
1042 /* Retry the same command immediately */
1043 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, 0);
1045 case ACTION_DELAYED_RETRY:
1046 /* Retry the same command after a delay */
1047 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, 0);
1052 static int scsi_init_sgtable(struct request *req, struct scsi_data_buffer *sdb)
1057 * If sg table allocation fails, requeue request later.
1059 if (unlikely(sg_alloc_table_chained(&sdb->table,
1060 blk_rq_nr_phys_segments(req), sdb->table.sgl)))
1061 return BLKPREP_DEFER;
1064 * Next, walk the list, and fill in the addresses and sizes of
1067 count = blk_rq_map_sg(req->q, req, sdb->table.sgl);
1068 BUG_ON(count > sdb->table.nents);
1069 sdb->table.nents = count;
1070 sdb->length = blk_rq_payload_bytes(req);
1075 * Function: scsi_init_io()
1077 * Purpose: SCSI I/O initialize function.
1079 * Arguments: cmd - Command descriptor we wish to initialize
1081 * Returns: 0 on success
1082 * BLKPREP_DEFER if the failure is retryable
1083 * BLKPREP_KILL if the failure is fatal
1085 int scsi_init_io(struct scsi_cmnd *cmd)
1087 struct scsi_device *sdev = cmd->device;
1088 struct request *rq = cmd->request;
1089 bool is_mq = (rq->mq_ctx != NULL);
1092 if (WARN_ON_ONCE(!blk_rq_nr_phys_segments(rq)))
1095 error = scsi_init_sgtable(rq, &cmd->sdb);
1099 if (blk_bidi_rq(rq)) {
1100 if (!rq->q->mq_ops) {
1101 struct scsi_data_buffer *bidi_sdb =
1102 kmem_cache_zalloc(scsi_sdb_cache, GFP_ATOMIC);
1104 error = BLKPREP_DEFER;
1108 rq->next_rq->special = bidi_sdb;
1111 error = scsi_init_sgtable(rq->next_rq, rq->next_rq->special);
1116 if (blk_integrity_rq(rq)) {
1117 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1120 if (prot_sdb == NULL) {
1122 * This can happen if someone (e.g. multipath)
1123 * queues a command to a device on an adapter
1124 * that does not support DIX.
1127 error = BLKPREP_KILL;
1131 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
1133 if (sg_alloc_table_chained(&prot_sdb->table, ivecs,
1134 prot_sdb->table.sgl)) {
1135 error = BLKPREP_DEFER;
1139 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
1140 prot_sdb->table.sgl);
1141 BUG_ON(unlikely(count > ivecs));
1142 BUG_ON(unlikely(count > queue_max_integrity_segments(rq->q)));
1144 cmd->prot_sdb = prot_sdb;
1145 cmd->prot_sdb->table.nents = count;
1151 scsi_mq_free_sgtables(cmd);
1153 scsi_release_buffers(cmd);
1154 cmd->request->special = NULL;
1155 scsi_put_command(cmd);
1156 put_device(&sdev->sdev_gendev);
1160 EXPORT_SYMBOL(scsi_init_io);
1162 void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd)
1164 void *buf = cmd->sense_buffer;
1165 void *prot = cmd->prot_sdb;
1166 unsigned long flags;
1168 /* zero out the cmd, except for the embedded scsi_request */
1169 memset((char *)cmd + sizeof(cmd->req), 0,
1170 sizeof(*cmd) - sizeof(cmd->req));
1173 cmd->sense_buffer = buf;
1174 cmd->prot_sdb = prot;
1175 INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
1176 cmd->jiffies_at_alloc = jiffies;
1178 spin_lock_irqsave(&dev->list_lock, flags);
1179 list_add_tail(&cmd->list, &dev->cmd_list);
1180 spin_unlock_irqrestore(&dev->list_lock, flags);
1183 static int scsi_setup_scsi_cmnd(struct scsi_device *sdev, struct request *req)
1185 struct scsi_cmnd *cmd = req->special;
1188 * Passthrough requests may transfer data, in which case they must
1189 * a bio attached to them. Or they might contain a SCSI command
1190 * that does not transfer data, in which case they may optionally
1191 * submit a request without an attached bio.
1194 int ret = scsi_init_io(cmd);
1198 BUG_ON(blk_rq_bytes(req));
1200 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1203 cmd->cmd_len = scsi_req(req)->cmd_len;
1204 cmd->cmnd = scsi_req(req)->cmd;
1205 cmd->transfersize = blk_rq_bytes(req);
1206 cmd->allowed = req->retries;
1211 * Setup a normal block command. These are simple request from filesystems
1212 * that still need to be translated to SCSI CDBs from the ULD.
1214 static int scsi_setup_fs_cmnd(struct scsi_device *sdev, struct request *req)
1216 struct scsi_cmnd *cmd = req->special;
1218 if (unlikely(sdev->handler && sdev->handler->prep_fn)) {
1219 int ret = sdev->handler->prep_fn(sdev, req);
1220 if (ret != BLKPREP_OK)
1224 cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd;
1225 memset(cmd->cmnd, 0, BLK_MAX_CDB);
1226 return scsi_cmd_to_driver(cmd)->init_command(cmd);
1229 static int scsi_setup_cmnd(struct scsi_device *sdev, struct request *req)
1231 struct scsi_cmnd *cmd = req->special;
1233 if (!blk_rq_bytes(req))
1234 cmd->sc_data_direction = DMA_NONE;
1235 else if (rq_data_dir(req) == WRITE)
1236 cmd->sc_data_direction = DMA_TO_DEVICE;
1238 cmd->sc_data_direction = DMA_FROM_DEVICE;
1240 if (blk_rq_is_scsi(req))
1241 return scsi_setup_scsi_cmnd(sdev, req);
1243 return scsi_setup_fs_cmnd(sdev, req);
1247 scsi_prep_state_check(struct scsi_device *sdev, struct request *req)
1249 int ret = BLKPREP_OK;
1252 * If the device is not in running state we will reject some
1255 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1256 switch (sdev->sdev_state) {
1258 case SDEV_TRANSPORT_OFFLINE:
1260 * If the device is offline we refuse to process any
1261 * commands. The device must be brought online
1262 * before trying any recovery commands.
1264 sdev_printk(KERN_ERR, sdev,
1265 "rejecting I/O to offline device\n");
1270 * If the device is fully deleted, we refuse to
1271 * process any commands as well.
1273 sdev_printk(KERN_ERR, sdev,
1274 "rejecting I/O to dead device\n");
1278 case SDEV_CREATED_BLOCK:
1279 ret = BLKPREP_DEFER;
1283 * If the devices is blocked we defer normal commands.
1285 if (!(req->rq_flags & RQF_PREEMPT))
1286 ret = BLKPREP_DEFER;
1290 * For any other not fully online state we only allow
1291 * special commands. In particular any user initiated
1292 * command is not allowed.
1294 if (!(req->rq_flags & RQF_PREEMPT))
1303 scsi_prep_return(struct request_queue *q, struct request *req, int ret)
1305 struct scsi_device *sdev = q->queuedata;
1309 case BLKPREP_INVALID:
1310 req->errors = DID_NO_CONNECT << 16;
1311 /* release the command and kill it */
1313 struct scsi_cmnd *cmd = req->special;
1314 scsi_release_buffers(cmd);
1315 scsi_put_command(cmd);
1316 put_device(&sdev->sdev_gendev);
1317 req->special = NULL;
1322 * If we defer, the blk_peek_request() returns NULL, but the
1323 * queue must be restarted, so we schedule a callback to happen
1326 if (atomic_read(&sdev->device_busy) == 0)
1327 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1330 req->rq_flags |= RQF_DONTPREP;
1336 static int scsi_prep_fn(struct request_queue *q, struct request *req)
1338 struct scsi_device *sdev = q->queuedata;
1339 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1342 ret = scsi_prep_state_check(sdev, req);
1343 if (ret != BLKPREP_OK)
1346 if (!req->special) {
1347 /* Bail if we can't get a reference to the device */
1348 if (unlikely(!get_device(&sdev->sdev_gendev))) {
1349 ret = BLKPREP_DEFER;
1353 scsi_init_command(sdev, cmd);
1357 cmd->tag = req->tag;
1359 cmd->prot_op = SCSI_PROT_NORMAL;
1361 ret = scsi_setup_cmnd(sdev, req);
1363 return scsi_prep_return(q, req, ret);
1366 static void scsi_unprep_fn(struct request_queue *q, struct request *req)
1368 scsi_uninit_cmd(req->special);
1372 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1375 * Called with the queue_lock held.
1377 static inline int scsi_dev_queue_ready(struct request_queue *q,
1378 struct scsi_device *sdev)
1382 busy = atomic_inc_return(&sdev->device_busy) - 1;
1383 if (atomic_read(&sdev->device_blocked)) {
1388 * unblock after device_blocked iterates to zero
1390 if (atomic_dec_return(&sdev->device_blocked) > 0) {
1392 * For the MQ case we take care of this in the caller.
1395 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1398 SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev,
1399 "unblocking device at zero depth\n"));
1402 if (busy >= sdev->queue_depth)
1407 atomic_dec(&sdev->device_busy);
1412 * scsi_target_queue_ready: checks if there we can send commands to target
1413 * @sdev: scsi device on starget to check.
1415 static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1416 struct scsi_device *sdev)
1418 struct scsi_target *starget = scsi_target(sdev);
1421 if (starget->single_lun) {
1422 spin_lock_irq(shost->host_lock);
1423 if (starget->starget_sdev_user &&
1424 starget->starget_sdev_user != sdev) {
1425 spin_unlock_irq(shost->host_lock);
1428 starget->starget_sdev_user = sdev;
1429 spin_unlock_irq(shost->host_lock);
1432 if (starget->can_queue <= 0)
1435 busy = atomic_inc_return(&starget->target_busy) - 1;
1436 if (atomic_read(&starget->target_blocked) > 0) {
1441 * unblock after target_blocked iterates to zero
1443 if (atomic_dec_return(&starget->target_blocked) > 0)
1446 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1447 "unblocking target at zero depth\n"));
1450 if (busy >= starget->can_queue)
1456 spin_lock_irq(shost->host_lock);
1457 list_move_tail(&sdev->starved_entry, &shost->starved_list);
1458 spin_unlock_irq(shost->host_lock);
1460 if (starget->can_queue > 0)
1461 atomic_dec(&starget->target_busy);
1466 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1467 * return 0. We must end up running the queue again whenever 0 is
1468 * returned, else IO can hang.
1470 static inline int scsi_host_queue_ready(struct request_queue *q,
1471 struct Scsi_Host *shost,
1472 struct scsi_device *sdev)
1476 if (scsi_host_in_recovery(shost))
1479 busy = atomic_inc_return(&shost->host_busy) - 1;
1480 if (atomic_read(&shost->host_blocked) > 0) {
1485 * unblock after host_blocked iterates to zero
1487 if (atomic_dec_return(&shost->host_blocked) > 0)
1491 shost_printk(KERN_INFO, shost,
1492 "unblocking host at zero depth\n"));
1495 if (shost->can_queue > 0 && busy >= shost->can_queue)
1497 if (shost->host_self_blocked)
1500 /* We're OK to process the command, so we can't be starved */
1501 if (!list_empty(&sdev->starved_entry)) {
1502 spin_lock_irq(shost->host_lock);
1503 if (!list_empty(&sdev->starved_entry))
1504 list_del_init(&sdev->starved_entry);
1505 spin_unlock_irq(shost->host_lock);
1511 spin_lock_irq(shost->host_lock);
1512 if (list_empty(&sdev->starved_entry))
1513 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1514 spin_unlock_irq(shost->host_lock);
1516 atomic_dec(&shost->host_busy);
1521 * Busy state exporting function for request stacking drivers.
1523 * For efficiency, no lock is taken to check the busy state of
1524 * shost/starget/sdev, since the returned value is not guaranteed and
1525 * may be changed after request stacking drivers call the function,
1526 * regardless of taking lock or not.
1528 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1529 * needs to return 'not busy'. Otherwise, request stacking drivers
1530 * may hold requests forever.
1532 static int scsi_lld_busy(struct request_queue *q)
1534 struct scsi_device *sdev = q->queuedata;
1535 struct Scsi_Host *shost;
1537 if (blk_queue_dying(q))
1543 * Ignore host/starget busy state.
1544 * Since block layer does not have a concept of fairness across
1545 * multiple queues, congestion of host/starget needs to be handled
1548 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
1555 * Kill a request for a dead device
1557 static void scsi_kill_request(struct request *req, struct request_queue *q)
1559 struct scsi_cmnd *cmd = req->special;
1560 struct scsi_device *sdev;
1561 struct scsi_target *starget;
1562 struct Scsi_Host *shost;
1564 blk_start_request(req);
1566 scmd_printk(KERN_INFO, cmd, "killing request\n");
1569 starget = scsi_target(sdev);
1571 scsi_init_cmd_errh(cmd);
1572 cmd->result = DID_NO_CONNECT << 16;
1573 atomic_inc(&cmd->device->iorequest_cnt);
1576 * SCSI request completion path will do scsi_device_unbusy(),
1577 * bump busy counts. To bump the counters, we need to dance
1578 * with the locks as normal issue path does.
1580 atomic_inc(&sdev->device_busy);
1581 atomic_inc(&shost->host_busy);
1582 if (starget->can_queue > 0)
1583 atomic_inc(&starget->target_busy);
1585 blk_complete_request(req);
1588 static void scsi_softirq_done(struct request *rq)
1590 struct scsi_cmnd *cmd = rq->special;
1591 unsigned long wait_for = (cmd->allowed + 1) * rq->timeout;
1594 INIT_LIST_HEAD(&cmd->eh_entry);
1596 atomic_inc(&cmd->device->iodone_cnt);
1598 atomic_inc(&cmd->device->ioerr_cnt);
1600 disposition = scsi_decide_disposition(cmd);
1601 if (disposition != SUCCESS &&
1602 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1603 sdev_printk(KERN_ERR, cmd->device,
1604 "timing out command, waited %lus\n",
1606 disposition = SUCCESS;
1609 scsi_log_completion(cmd, disposition);
1611 switch (disposition) {
1613 scsi_finish_command(cmd);
1616 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1618 case ADD_TO_MLQUEUE:
1619 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1622 if (!scsi_eh_scmd_add(cmd, 0))
1623 scsi_finish_command(cmd);
1628 * scsi_dispatch_command - Dispatch a command to the low-level driver.
1629 * @cmd: command block we are dispatching.
1631 * Return: nonzero return request was rejected and device's queue needs to be
1634 static int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
1636 struct Scsi_Host *host = cmd->device->host;
1639 atomic_inc(&cmd->device->iorequest_cnt);
1641 /* check if the device is still usable */
1642 if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
1643 /* in SDEV_DEL we error all commands. DID_NO_CONNECT
1644 * returns an immediate error upwards, and signals
1645 * that the device is no longer present */
1646 cmd->result = DID_NO_CONNECT << 16;
1650 /* Check to see if the scsi lld made this device blocked. */
1651 if (unlikely(scsi_device_blocked(cmd->device))) {
1653 * in blocked state, the command is just put back on
1654 * the device queue. The suspend state has already
1655 * blocked the queue so future requests should not
1656 * occur until the device transitions out of the
1659 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1660 "queuecommand : device blocked\n"));
1661 return SCSI_MLQUEUE_DEVICE_BUSY;
1664 /* Store the LUN value in cmnd, if needed. */
1665 if (cmd->device->lun_in_cdb)
1666 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
1667 (cmd->device->lun << 5 & 0xe0);
1672 * Before we queue this command, check if the command
1673 * length exceeds what the host adapter can handle.
1675 if (cmd->cmd_len > cmd->device->host->max_cmd_len) {
1676 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1677 "queuecommand : command too long. "
1678 "cdb_size=%d host->max_cmd_len=%d\n",
1679 cmd->cmd_len, cmd->device->host->max_cmd_len));
1680 cmd->result = (DID_ABORT << 16);
1684 if (unlikely(host->shost_state == SHOST_DEL)) {
1685 cmd->result = (DID_NO_CONNECT << 16);
1690 trace_scsi_dispatch_cmd_start(cmd);
1691 rtn = host->hostt->queuecommand(host, cmd);
1693 trace_scsi_dispatch_cmd_error(cmd, rtn);
1694 if (rtn != SCSI_MLQUEUE_DEVICE_BUSY &&
1695 rtn != SCSI_MLQUEUE_TARGET_BUSY)
1696 rtn = SCSI_MLQUEUE_HOST_BUSY;
1698 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1699 "queuecommand : request rejected\n"));
1704 cmd->scsi_done(cmd);
1709 * scsi_done - Invoke completion on finished SCSI command.
1710 * @cmd: The SCSI Command for which a low-level device driver (LLDD) gives
1711 * ownership back to SCSI Core -- i.e. the LLDD has finished with it.
1713 * Description: This function is the mid-level's (SCSI Core) interrupt routine,
1714 * which regains ownership of the SCSI command (de facto) from a LLDD, and
1715 * calls blk_complete_request() for further processing.
1717 * This function is interrupt context safe.
1719 static void scsi_done(struct scsi_cmnd *cmd)
1721 trace_scsi_dispatch_cmd_done(cmd);
1722 blk_complete_request(cmd->request);
1726 * Function: scsi_request_fn()
1728 * Purpose: Main strategy routine for SCSI.
1730 * Arguments: q - Pointer to actual queue.
1734 * Lock status: IO request lock assumed to be held when called.
1736 static void scsi_request_fn(struct request_queue *q)
1737 __releases(q->queue_lock)
1738 __acquires(q->queue_lock)
1740 struct scsi_device *sdev = q->queuedata;
1741 struct Scsi_Host *shost;
1742 struct scsi_cmnd *cmd;
1743 struct request *req;
1746 * To start with, we keep looping until the queue is empty, or until
1747 * the host is no longer able to accept any more requests.
1753 * get next queueable request. We do this early to make sure
1754 * that the request is fully prepared even if we cannot
1757 req = blk_peek_request(q);
1761 if (unlikely(!scsi_device_online(sdev))) {
1762 sdev_printk(KERN_ERR, sdev,
1763 "rejecting I/O to offline device\n");
1764 scsi_kill_request(req, q);
1768 if (!scsi_dev_queue_ready(q, sdev))
1772 * Remove the request from the request list.
1774 if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
1775 blk_start_request(req);
1777 spin_unlock_irq(q->queue_lock);
1779 if (unlikely(cmd == NULL)) {
1780 printk(KERN_CRIT "impossible request in %s.\n"
1781 "please mail a stack trace to "
1784 blk_dump_rq_flags(req, "foo");
1789 * We hit this when the driver is using a host wide
1790 * tag map. For device level tag maps the queue_depth check
1791 * in the device ready fn would prevent us from trying
1792 * to allocate a tag. Since the map is a shared host resource
1793 * we add the dev to the starved list so it eventually gets
1794 * a run when a tag is freed.
1796 if (blk_queue_tagged(q) && !(req->rq_flags & RQF_QUEUED)) {
1797 spin_lock_irq(shost->host_lock);
1798 if (list_empty(&sdev->starved_entry))
1799 list_add_tail(&sdev->starved_entry,
1800 &shost->starved_list);
1801 spin_unlock_irq(shost->host_lock);
1805 if (!scsi_target_queue_ready(shost, sdev))
1808 if (!scsi_host_queue_ready(q, shost, sdev))
1809 goto host_not_ready;
1811 if (sdev->simple_tags)
1812 cmd->flags |= SCMD_TAGGED;
1814 cmd->flags &= ~SCMD_TAGGED;
1817 * Finally, initialize any error handling parameters, and set up
1818 * the timers for timeouts.
1820 scsi_init_cmd_errh(cmd);
1823 * Dispatch the command to the low-level driver.
1825 cmd->scsi_done = scsi_done;
1826 rtn = scsi_dispatch_cmd(cmd);
1828 scsi_queue_insert(cmd, rtn);
1829 spin_lock_irq(q->queue_lock);
1832 spin_lock_irq(q->queue_lock);
1838 if (scsi_target(sdev)->can_queue > 0)
1839 atomic_dec(&scsi_target(sdev)->target_busy);
1842 * lock q, handle tag, requeue req, and decrement device_busy. We
1843 * must return with queue_lock held.
1845 * Decrementing device_busy without checking it is OK, as all such
1846 * cases (host limits or settings) should run the queue at some
1849 spin_lock_irq(q->queue_lock);
1850 blk_requeue_request(q, req);
1851 atomic_dec(&sdev->device_busy);
1853 if (!atomic_read(&sdev->device_busy) && !scsi_device_blocked(sdev))
1854 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1857 static inline int prep_to_mq(int ret)
1861 return BLK_MQ_RQ_QUEUE_OK;
1863 return BLK_MQ_RQ_QUEUE_BUSY;
1865 return BLK_MQ_RQ_QUEUE_ERROR;
1869 static int scsi_mq_prep_fn(struct request *req)
1871 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1872 struct scsi_device *sdev = req->q->queuedata;
1873 struct Scsi_Host *shost = sdev->host;
1874 unsigned char *sense_buf = cmd->sense_buffer;
1875 struct scatterlist *sg;
1877 /* zero out the cmd, except for the embedded scsi_request */
1878 memset((char *)cmd + sizeof(cmd->req), 0,
1879 sizeof(*cmd) - sizeof(cmd->req));
1885 cmd->sense_buffer = sense_buf;
1887 cmd->tag = req->tag;
1889 cmd->prot_op = SCSI_PROT_NORMAL;
1891 INIT_LIST_HEAD(&cmd->list);
1892 INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
1893 cmd->jiffies_at_alloc = jiffies;
1895 if (shost->use_cmd_list) {
1896 spin_lock_irq(&sdev->list_lock);
1897 list_add_tail(&cmd->list, &sdev->cmd_list);
1898 spin_unlock_irq(&sdev->list_lock);
1901 sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
1902 cmd->sdb.table.sgl = sg;
1904 if (scsi_host_get_prot(shost)) {
1905 cmd->prot_sdb = (void *)sg +
1907 shost->sg_tablesize, SG_CHUNK_SIZE) *
1908 sizeof(struct scatterlist);
1909 memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer));
1911 cmd->prot_sdb->table.sgl =
1912 (struct scatterlist *)(cmd->prot_sdb + 1);
1915 if (blk_bidi_rq(req)) {
1916 struct request *next_rq = req->next_rq;
1917 struct scsi_data_buffer *bidi_sdb = blk_mq_rq_to_pdu(next_rq);
1919 memset(bidi_sdb, 0, sizeof(struct scsi_data_buffer));
1920 bidi_sdb->table.sgl =
1921 (struct scatterlist *)(bidi_sdb + 1);
1923 next_rq->special = bidi_sdb;
1926 blk_mq_start_request(req);
1928 return scsi_setup_cmnd(sdev, req);
1931 static void scsi_mq_done(struct scsi_cmnd *cmd)
1933 trace_scsi_dispatch_cmd_done(cmd);
1934 blk_mq_complete_request(cmd->request, cmd->request->errors);
1937 static int scsi_queue_rq(struct blk_mq_hw_ctx *hctx,
1938 const struct blk_mq_queue_data *bd)
1940 struct request *req = bd->rq;
1941 struct request_queue *q = req->q;
1942 struct scsi_device *sdev = q->queuedata;
1943 struct Scsi_Host *shost = sdev->host;
1944 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1948 ret = prep_to_mq(scsi_prep_state_check(sdev, req));
1949 if (ret != BLK_MQ_RQ_QUEUE_OK)
1952 ret = BLK_MQ_RQ_QUEUE_BUSY;
1953 if (!get_device(&sdev->sdev_gendev))
1956 if (!scsi_dev_queue_ready(q, sdev))
1957 goto out_put_device;
1958 if (!scsi_target_queue_ready(shost, sdev))
1959 goto out_dec_device_busy;
1960 if (!scsi_host_queue_ready(q, shost, sdev))
1961 goto out_dec_target_busy;
1963 if (!(req->rq_flags & RQF_DONTPREP)) {
1964 ret = prep_to_mq(scsi_mq_prep_fn(req));
1965 if (ret != BLK_MQ_RQ_QUEUE_OK)
1966 goto out_dec_host_busy;
1967 req->rq_flags |= RQF_DONTPREP;
1969 blk_mq_start_request(req);
1972 if (sdev->simple_tags)
1973 cmd->flags |= SCMD_TAGGED;
1975 cmd->flags &= ~SCMD_TAGGED;
1977 scsi_init_cmd_errh(cmd);
1978 cmd->scsi_done = scsi_mq_done;
1980 reason = scsi_dispatch_cmd(cmd);
1982 scsi_set_blocked(cmd, reason);
1983 ret = BLK_MQ_RQ_QUEUE_BUSY;
1984 goto out_dec_host_busy;
1987 return BLK_MQ_RQ_QUEUE_OK;
1990 atomic_dec(&shost->host_busy);
1991 out_dec_target_busy:
1992 if (scsi_target(sdev)->can_queue > 0)
1993 atomic_dec(&scsi_target(sdev)->target_busy);
1994 out_dec_device_busy:
1995 atomic_dec(&sdev->device_busy);
1997 put_device(&sdev->sdev_gendev);
2000 case BLK_MQ_RQ_QUEUE_BUSY:
2001 if (atomic_read(&sdev->device_busy) == 0 &&
2002 !scsi_device_blocked(sdev))
2003 blk_mq_delay_queue(hctx, SCSI_QUEUE_DELAY);
2005 case BLK_MQ_RQ_QUEUE_ERROR:
2007 * Make sure to release all allocated ressources when
2008 * we hit an error, as we will never see this command
2011 if (req->rq_flags & RQF_DONTPREP)
2012 scsi_mq_uninit_cmd(cmd);
2020 static enum blk_eh_timer_return scsi_timeout(struct request *req,
2024 return BLK_EH_RESET_TIMER;
2025 return scsi_times_out(req);
2028 static int scsi_init_request(void *data, struct request *rq,
2029 unsigned int hctx_idx, unsigned int request_idx,
2030 unsigned int numa_node)
2032 struct Scsi_Host *shost = data;
2033 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2036 scsi_alloc_sense_buffer(shost, GFP_KERNEL, numa_node);
2037 if (!cmd->sense_buffer)
2039 cmd->req.sense = cmd->sense_buffer;
2043 static void scsi_exit_request(void *data, struct request *rq,
2044 unsigned int hctx_idx, unsigned int request_idx)
2046 struct Scsi_Host *shost = data;
2047 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2049 scsi_free_sense_buffer(shost, cmd->sense_buffer);
2052 static int scsi_map_queues(struct blk_mq_tag_set *set)
2054 struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set);
2056 if (shost->hostt->map_queues)
2057 return shost->hostt->map_queues(shost);
2058 return blk_mq_map_queues(set);
2061 static u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
2063 struct device *host_dev;
2064 u64 bounce_limit = 0xffffffff;
2066 if (shost->unchecked_isa_dma)
2067 return BLK_BOUNCE_ISA;
2069 * Platforms with virtual-DMA translation
2070 * hardware have no practical limit.
2072 if (!PCI_DMA_BUS_IS_PHYS)
2073 return BLK_BOUNCE_ANY;
2075 host_dev = scsi_get_device(shost);
2076 if (host_dev && host_dev->dma_mask)
2077 bounce_limit = (u64)dma_max_pfn(host_dev) << PAGE_SHIFT;
2079 return bounce_limit;
2082 void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q)
2084 struct device *dev = shost->dma_dev;
2087 * this limit is imposed by hardware restrictions
2089 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
2092 if (scsi_host_prot_dma(shost)) {
2093 shost->sg_prot_tablesize =
2094 min_not_zero(shost->sg_prot_tablesize,
2095 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
2096 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
2097 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
2100 blk_queue_max_hw_sectors(q, shost->max_sectors);
2101 blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
2102 blk_queue_segment_boundary(q, shost->dma_boundary);
2103 dma_set_seg_boundary(dev, shost->dma_boundary);
2105 blk_queue_max_segment_size(q, dma_get_max_seg_size(dev));
2107 if (!shost->use_clustering)
2108 q->limits.cluster = 0;
2111 * set a reasonable default alignment on word boundaries: the
2112 * host and device may alter it using
2113 * blk_queue_update_dma_alignment() later.
2115 blk_queue_dma_alignment(q, 0x03);
2117 EXPORT_SYMBOL_GPL(__scsi_init_queue);
2119 static int scsi_init_rq(struct request_queue *q, struct request *rq, gfp_t gfp)
2121 struct Scsi_Host *shost = q->rq_alloc_data;
2122 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2124 memset(cmd, 0, sizeof(*cmd));
2126 cmd->sense_buffer = scsi_alloc_sense_buffer(shost, gfp, NUMA_NO_NODE);
2127 if (!cmd->sense_buffer)
2129 cmd->req.sense = cmd->sense_buffer;
2131 if (scsi_host_get_prot(shost) >= SHOST_DIX_TYPE0_PROTECTION) {
2132 cmd->prot_sdb = kmem_cache_zalloc(scsi_sdb_cache, gfp);
2134 goto fail_free_sense;
2140 scsi_free_sense_buffer(shost, cmd->sense_buffer);
2145 static void scsi_exit_rq(struct request_queue *q, struct request *rq)
2147 struct Scsi_Host *shost = q->rq_alloc_data;
2148 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2151 kmem_cache_free(scsi_sdb_cache, cmd->prot_sdb);
2152 scsi_free_sense_buffer(shost, cmd->sense_buffer);
2155 struct request_queue *scsi_alloc_queue(struct scsi_device *sdev)
2157 struct Scsi_Host *shost = sdev->host;
2158 struct request_queue *q;
2160 q = blk_alloc_queue_node(GFP_KERNEL, NUMA_NO_NODE);
2163 q->cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
2164 q->rq_alloc_data = shost;
2165 q->request_fn = scsi_request_fn;
2166 q->init_rq_fn = scsi_init_rq;
2167 q->exit_rq_fn = scsi_exit_rq;
2169 if (blk_init_allocated_queue(q) < 0) {
2170 blk_cleanup_queue(q);
2174 __scsi_init_queue(shost, q);
2175 blk_queue_prep_rq(q, scsi_prep_fn);
2176 blk_queue_unprep_rq(q, scsi_unprep_fn);
2177 blk_queue_softirq_done(q, scsi_softirq_done);
2178 blk_queue_rq_timed_out(q, scsi_times_out);
2179 blk_queue_lld_busy(q, scsi_lld_busy);
2183 static struct blk_mq_ops scsi_mq_ops = {
2184 .queue_rq = scsi_queue_rq,
2185 .complete = scsi_softirq_done,
2186 .timeout = scsi_timeout,
2187 .init_request = scsi_init_request,
2188 .exit_request = scsi_exit_request,
2189 .map_queues = scsi_map_queues,
2192 struct request_queue *scsi_mq_alloc_queue(struct scsi_device *sdev)
2194 sdev->request_queue = blk_mq_init_queue(&sdev->host->tag_set);
2195 if (IS_ERR(sdev->request_queue))
2198 sdev->request_queue->queuedata = sdev;
2199 __scsi_init_queue(sdev->host, sdev->request_queue);
2200 return sdev->request_queue;
2203 int scsi_mq_setup_tags(struct Scsi_Host *shost)
2205 unsigned int cmd_size, sgl_size, tbl_size;
2207 tbl_size = shost->sg_tablesize;
2208 if (tbl_size > SG_CHUNK_SIZE)
2209 tbl_size = SG_CHUNK_SIZE;
2210 sgl_size = tbl_size * sizeof(struct scatterlist);
2211 cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size;
2212 if (scsi_host_get_prot(shost))
2213 cmd_size += sizeof(struct scsi_data_buffer) + sgl_size;
2215 memset(&shost->tag_set, 0, sizeof(shost->tag_set));
2216 shost->tag_set.ops = &scsi_mq_ops;
2217 shost->tag_set.nr_hw_queues = shost->nr_hw_queues ? : 1;
2218 shost->tag_set.queue_depth = shost->can_queue;
2219 shost->tag_set.cmd_size = cmd_size;
2220 shost->tag_set.numa_node = NUMA_NO_NODE;
2221 shost->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2222 shost->tag_set.flags |=
2223 BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy);
2224 shost->tag_set.driver_data = shost;
2226 return blk_mq_alloc_tag_set(&shost->tag_set);
2229 void scsi_mq_destroy_tags(struct Scsi_Host *shost)
2231 blk_mq_free_tag_set(&shost->tag_set);
2235 * Function: scsi_block_requests()
2237 * Purpose: Utility function used by low-level drivers to prevent further
2238 * commands from being queued to the device.
2240 * Arguments: shost - Host in question
2244 * Lock status: No locks are assumed held.
2246 * Notes: There is no timer nor any other means by which the requests
2247 * get unblocked other than the low-level driver calling
2248 * scsi_unblock_requests().
2250 void scsi_block_requests(struct Scsi_Host *shost)
2252 shost->host_self_blocked = 1;
2254 EXPORT_SYMBOL(scsi_block_requests);
2257 * Function: scsi_unblock_requests()
2259 * Purpose: Utility function used by low-level drivers to allow further
2260 * commands from being queued to the device.
2262 * Arguments: shost - Host in question
2266 * Lock status: No locks are assumed held.
2268 * Notes: There is no timer nor any other means by which the requests
2269 * get unblocked other than the low-level driver calling
2270 * scsi_unblock_requests().
2272 * This is done as an API function so that changes to the
2273 * internals of the scsi mid-layer won't require wholesale
2274 * changes to drivers that use this feature.
2276 void scsi_unblock_requests(struct Scsi_Host *shost)
2278 shost->host_self_blocked = 0;
2279 scsi_run_host_queues(shost);
2281 EXPORT_SYMBOL(scsi_unblock_requests);
2283 int __init scsi_init_queue(void)
2285 scsi_sdb_cache = kmem_cache_create("scsi_data_buffer",
2286 sizeof(struct scsi_data_buffer),
2288 if (!scsi_sdb_cache) {
2289 printk(KERN_ERR "SCSI: can't init scsi sdb cache\n");
2296 void scsi_exit_queue(void)
2298 kmem_cache_destroy(scsi_sense_cache);
2299 kmem_cache_destroy(scsi_sense_isadma_cache);
2300 kmem_cache_destroy(scsi_sdb_cache);
2304 * scsi_mode_select - issue a mode select
2305 * @sdev: SCSI device to be queried
2306 * @pf: Page format bit (1 == standard, 0 == vendor specific)
2307 * @sp: Save page bit (0 == don't save, 1 == save)
2308 * @modepage: mode page being requested
2309 * @buffer: request buffer (may not be smaller than eight bytes)
2310 * @len: length of request buffer.
2311 * @timeout: command timeout
2312 * @retries: number of retries before failing
2313 * @data: returns a structure abstracting the mode header data
2314 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2315 * must be SCSI_SENSE_BUFFERSIZE big.
2317 * Returns zero if successful; negative error number or scsi
2322 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
2323 unsigned char *buffer, int len, int timeout, int retries,
2324 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2326 unsigned char cmd[10];
2327 unsigned char *real_buffer;
2330 memset(cmd, 0, sizeof(cmd));
2331 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
2333 if (sdev->use_10_for_ms) {
2336 real_buffer = kmalloc(8 + len, GFP_KERNEL);
2339 memcpy(real_buffer + 8, buffer, len);
2343 real_buffer[2] = data->medium_type;
2344 real_buffer[3] = data->device_specific;
2345 real_buffer[4] = data->longlba ? 0x01 : 0;
2347 real_buffer[6] = data->block_descriptor_length >> 8;
2348 real_buffer[7] = data->block_descriptor_length;
2350 cmd[0] = MODE_SELECT_10;
2354 if (len > 255 || data->block_descriptor_length > 255 ||
2358 real_buffer = kmalloc(4 + len, GFP_KERNEL);
2361 memcpy(real_buffer + 4, buffer, len);
2364 real_buffer[1] = data->medium_type;
2365 real_buffer[2] = data->device_specific;
2366 real_buffer[3] = data->block_descriptor_length;
2369 cmd[0] = MODE_SELECT;
2373 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
2374 sshdr, timeout, retries, NULL);
2378 EXPORT_SYMBOL_GPL(scsi_mode_select);
2381 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
2382 * @sdev: SCSI device to be queried
2383 * @dbd: set if mode sense will allow block descriptors to be returned
2384 * @modepage: mode page being requested
2385 * @buffer: request buffer (may not be smaller than eight bytes)
2386 * @len: length of request buffer.
2387 * @timeout: command timeout
2388 * @retries: number of retries before failing
2389 * @data: returns a structure abstracting the mode header data
2390 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2391 * must be SCSI_SENSE_BUFFERSIZE big.
2393 * Returns zero if unsuccessful, or the header offset (either 4
2394 * or 8 depending on whether a six or ten byte command was
2395 * issued) if successful.
2398 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
2399 unsigned char *buffer, int len, int timeout, int retries,
2400 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2402 unsigned char cmd[12];
2405 int result, retry_count = retries;
2406 struct scsi_sense_hdr my_sshdr;
2408 memset(data, 0, sizeof(*data));
2409 memset(&cmd[0], 0, 12);
2410 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
2413 /* caller might not be interested in sense, but we need it */
2418 use_10_for_ms = sdev->use_10_for_ms;
2420 if (use_10_for_ms) {
2424 cmd[0] = MODE_SENSE_10;
2431 cmd[0] = MODE_SENSE;
2436 memset(buffer, 0, len);
2438 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
2439 sshdr, timeout, retries, NULL);
2441 /* This code looks awful: what it's doing is making sure an
2442 * ILLEGAL REQUEST sense return identifies the actual command
2443 * byte as the problem. MODE_SENSE commands can return
2444 * ILLEGAL REQUEST if the code page isn't supported */
2446 if (use_10_for_ms && !scsi_status_is_good(result) &&
2447 (driver_byte(result) & DRIVER_SENSE)) {
2448 if (scsi_sense_valid(sshdr)) {
2449 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
2450 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
2452 * Invalid command operation code
2454 sdev->use_10_for_ms = 0;
2460 if(scsi_status_is_good(result)) {
2461 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
2462 (modepage == 6 || modepage == 8))) {
2463 /* Initio breakage? */
2466 data->medium_type = 0;
2467 data->device_specific = 0;
2469 data->block_descriptor_length = 0;
2470 } else if(use_10_for_ms) {
2471 data->length = buffer[0]*256 + buffer[1] + 2;
2472 data->medium_type = buffer[2];
2473 data->device_specific = buffer[3];
2474 data->longlba = buffer[4] & 0x01;
2475 data->block_descriptor_length = buffer[6]*256
2478 data->length = buffer[0] + 1;
2479 data->medium_type = buffer[1];
2480 data->device_specific = buffer[2];
2481 data->block_descriptor_length = buffer[3];
2483 data->header_length = header_length;
2484 } else if ((status_byte(result) == CHECK_CONDITION) &&
2485 scsi_sense_valid(sshdr) &&
2486 sshdr->sense_key == UNIT_ATTENTION && retry_count) {
2493 EXPORT_SYMBOL(scsi_mode_sense);
2496 * scsi_test_unit_ready - test if unit is ready
2497 * @sdev: scsi device to change the state of.
2498 * @timeout: command timeout
2499 * @retries: number of retries before failing
2500 * @sshdr_external: Optional pointer to struct scsi_sense_hdr for
2501 * returning sense. Make sure that this is cleared before passing
2504 * Returns zero if unsuccessful or an error if TUR failed. For
2505 * removable media, UNIT_ATTENTION sets ->changed flag.
2508 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2509 struct scsi_sense_hdr *sshdr_external)
2512 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2514 struct scsi_sense_hdr *sshdr;
2517 if (!sshdr_external)
2518 sshdr = kzalloc(sizeof(*sshdr), GFP_KERNEL);
2520 sshdr = sshdr_external;
2522 /* try to eat the UNIT_ATTENTION if there are enough retries */
2524 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
2525 timeout, retries, NULL);
2526 if (sdev->removable && scsi_sense_valid(sshdr) &&
2527 sshdr->sense_key == UNIT_ATTENTION)
2529 } while (scsi_sense_valid(sshdr) &&
2530 sshdr->sense_key == UNIT_ATTENTION && --retries);
2532 if (!sshdr_external)
2536 EXPORT_SYMBOL(scsi_test_unit_ready);
2539 * scsi_device_set_state - Take the given device through the device state model.
2540 * @sdev: scsi device to change the state of.
2541 * @state: state to change to.
2543 * Returns zero if unsuccessful or an error if the requested
2544 * transition is illegal.
2547 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2549 enum scsi_device_state oldstate = sdev->sdev_state;
2551 if (state == oldstate)
2557 case SDEV_CREATED_BLOCK:
2568 case SDEV_TRANSPORT_OFFLINE:
2581 case SDEV_TRANSPORT_OFFLINE:
2589 case SDEV_TRANSPORT_OFFLINE:
2604 case SDEV_CREATED_BLOCK:
2611 case SDEV_CREATED_BLOCK:
2626 case SDEV_TRANSPORT_OFFLINE:
2639 case SDEV_TRANSPORT_OFFLINE:
2641 case SDEV_CREATED_BLOCK:
2649 sdev->sdev_state = state;
2653 SCSI_LOG_ERROR_RECOVERY(1,
2654 sdev_printk(KERN_ERR, sdev,
2655 "Illegal state transition %s->%s",
2656 scsi_device_state_name(oldstate),
2657 scsi_device_state_name(state))
2661 EXPORT_SYMBOL(scsi_device_set_state);
2664 * sdev_evt_emit - emit a single SCSI device uevent
2665 * @sdev: associated SCSI device
2666 * @evt: event to emit
2668 * Send a single uevent (scsi_event) to the associated scsi_device.
2670 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2675 switch (evt->evt_type) {
2676 case SDEV_EVT_MEDIA_CHANGE:
2677 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2679 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2680 scsi_rescan_device(&sdev->sdev_gendev);
2681 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
2683 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2684 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
2686 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2687 envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
2689 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2690 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
2692 case SDEV_EVT_LUN_CHANGE_REPORTED:
2693 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
2695 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2696 envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED";
2705 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2709 * sdev_evt_thread - send a uevent for each scsi event
2710 * @work: work struct for scsi_device
2712 * Dispatch queued events to their associated scsi_device kobjects
2715 void scsi_evt_thread(struct work_struct *work)
2717 struct scsi_device *sdev;
2718 enum scsi_device_event evt_type;
2719 LIST_HEAD(event_list);
2721 sdev = container_of(work, struct scsi_device, event_work);
2723 for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
2724 if (test_and_clear_bit(evt_type, sdev->pending_events))
2725 sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
2728 struct scsi_event *evt;
2729 struct list_head *this, *tmp;
2730 unsigned long flags;
2732 spin_lock_irqsave(&sdev->list_lock, flags);
2733 list_splice_init(&sdev->event_list, &event_list);
2734 spin_unlock_irqrestore(&sdev->list_lock, flags);
2736 if (list_empty(&event_list))
2739 list_for_each_safe(this, tmp, &event_list) {
2740 evt = list_entry(this, struct scsi_event, node);
2741 list_del(&evt->node);
2742 scsi_evt_emit(sdev, evt);
2749 * sdev_evt_send - send asserted event to uevent thread
2750 * @sdev: scsi_device event occurred on
2751 * @evt: event to send
2753 * Assert scsi device event asynchronously.
2755 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2757 unsigned long flags;
2760 /* FIXME: currently this check eliminates all media change events
2761 * for polled devices. Need to update to discriminate between AN
2762 * and polled events */
2763 if (!test_bit(evt->evt_type, sdev->supported_events)) {
2769 spin_lock_irqsave(&sdev->list_lock, flags);
2770 list_add_tail(&evt->node, &sdev->event_list);
2771 schedule_work(&sdev->event_work);
2772 spin_unlock_irqrestore(&sdev->list_lock, flags);
2774 EXPORT_SYMBOL_GPL(sdev_evt_send);
2777 * sdev_evt_alloc - allocate a new scsi event
2778 * @evt_type: type of event to allocate
2779 * @gfpflags: GFP flags for allocation
2781 * Allocates and returns a new scsi_event.
2783 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2786 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2790 evt->evt_type = evt_type;
2791 INIT_LIST_HEAD(&evt->node);
2793 /* evt_type-specific initialization, if any */
2795 case SDEV_EVT_MEDIA_CHANGE:
2796 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2797 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2798 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2799 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2800 case SDEV_EVT_LUN_CHANGE_REPORTED:
2801 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2809 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2812 * sdev_evt_send_simple - send asserted event to uevent thread
2813 * @sdev: scsi_device event occurred on
2814 * @evt_type: type of event to send
2815 * @gfpflags: GFP flags for allocation
2817 * Assert scsi device event asynchronously, given an event type.
2819 void sdev_evt_send_simple(struct scsi_device *sdev,
2820 enum scsi_device_event evt_type, gfp_t gfpflags)
2822 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2824 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2829 sdev_evt_send(sdev, evt);
2831 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2834 * scsi_request_fn_active() - number of kernel threads inside scsi_request_fn()
2835 * @sdev: SCSI device to count the number of scsi_request_fn() callers for.
2837 static int scsi_request_fn_active(struct scsi_device *sdev)
2839 struct request_queue *q = sdev->request_queue;
2840 int request_fn_active;
2842 WARN_ON_ONCE(sdev->host->use_blk_mq);
2844 spin_lock_irq(q->queue_lock);
2845 request_fn_active = q->request_fn_active;
2846 spin_unlock_irq(q->queue_lock);
2848 return request_fn_active;
2852 * scsi_wait_for_queuecommand() - wait for ongoing queuecommand() calls
2853 * @sdev: SCSI device pointer.
2855 * Wait until the ongoing shost->hostt->queuecommand() calls that are
2856 * invoked from scsi_request_fn() have finished.
2858 static void scsi_wait_for_queuecommand(struct scsi_device *sdev)
2860 WARN_ON_ONCE(sdev->host->use_blk_mq);
2862 while (scsi_request_fn_active(sdev))
2867 * scsi_device_quiesce - Block user issued commands.
2868 * @sdev: scsi device to quiesce.
2870 * This works by trying to transition to the SDEV_QUIESCE state
2871 * (which must be a legal transition). When the device is in this
2872 * state, only special requests will be accepted, all others will
2873 * be deferred. Since special requests may also be requeued requests,
2874 * a successful return doesn't guarantee the device will be
2875 * totally quiescent.
2877 * Must be called with user context, may sleep.
2879 * Returns zero if unsuccessful or an error if not.
2882 scsi_device_quiesce(struct scsi_device *sdev)
2884 int err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2888 scsi_run_queue(sdev->request_queue);
2889 while (atomic_read(&sdev->device_busy)) {
2890 msleep_interruptible(200);
2891 scsi_run_queue(sdev->request_queue);
2895 EXPORT_SYMBOL(scsi_device_quiesce);
2898 * scsi_device_resume - Restart user issued commands to a quiesced device.
2899 * @sdev: scsi device to resume.
2901 * Moves the device from quiesced back to running and restarts the
2904 * Must be called with user context, may sleep.
2906 void scsi_device_resume(struct scsi_device *sdev)
2908 /* check if the device state was mutated prior to resume, and if
2909 * so assume the state is being managed elsewhere (for example
2910 * device deleted during suspend)
2912 if (sdev->sdev_state != SDEV_QUIESCE ||
2913 scsi_device_set_state(sdev, SDEV_RUNNING))
2915 scsi_run_queue(sdev->request_queue);
2917 EXPORT_SYMBOL(scsi_device_resume);
2920 device_quiesce_fn(struct scsi_device *sdev, void *data)
2922 scsi_device_quiesce(sdev);
2926 scsi_target_quiesce(struct scsi_target *starget)
2928 starget_for_each_device(starget, NULL, device_quiesce_fn);
2930 EXPORT_SYMBOL(scsi_target_quiesce);
2933 device_resume_fn(struct scsi_device *sdev, void *data)
2935 scsi_device_resume(sdev);
2939 scsi_target_resume(struct scsi_target *starget)
2941 starget_for_each_device(starget, NULL, device_resume_fn);
2943 EXPORT_SYMBOL(scsi_target_resume);
2946 * scsi_internal_device_block - internal function to put a device temporarily into the SDEV_BLOCK state
2947 * @sdev: device to block
2949 * Block request made by scsi lld's to temporarily stop all
2950 * scsi commands on the specified device. May sleep.
2952 * Returns zero if successful or error if not
2955 * This routine transitions the device to the SDEV_BLOCK state
2956 * (which must be a legal transition). When the device is in this
2957 * state, all commands are deferred until the scsi lld reenables
2958 * the device with scsi_device_unblock or device_block_tmo fires.
2960 * To do: avoid that scsi_send_eh_cmnd() calls queuecommand() after
2961 * scsi_internal_device_block() has blocked a SCSI device and also
2962 * remove the rport mutex lock and unlock calls from srp_queuecommand().
2965 scsi_internal_device_block(struct scsi_device *sdev)
2967 struct request_queue *q = sdev->request_queue;
2968 unsigned long flags;
2971 err = scsi_device_set_state(sdev, SDEV_BLOCK);
2973 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
2980 * The device has transitioned to SDEV_BLOCK. Stop the
2981 * block layer from calling the midlayer with this device's
2985 blk_mq_quiesce_queue(q);
2987 spin_lock_irqsave(q->queue_lock, flags);
2989 spin_unlock_irqrestore(q->queue_lock, flags);
2990 scsi_wait_for_queuecommand(sdev);
2995 EXPORT_SYMBOL_GPL(scsi_internal_device_block);
2998 * scsi_internal_device_unblock - resume a device after a block request
2999 * @sdev: device to resume
3000 * @new_state: state to set devices to after unblocking
3002 * Called by scsi lld's or the midlayer to restart the device queue
3003 * for the previously suspended scsi device. Called from interrupt or
3004 * normal process context.
3006 * Returns zero if successful or error if not.
3009 * This routine transitions the device to the SDEV_RUNNING state
3010 * or to one of the offline states (which must be a legal transition)
3011 * allowing the midlayer to goose the queue for this device.
3014 scsi_internal_device_unblock(struct scsi_device *sdev,
3015 enum scsi_device_state new_state)
3017 struct request_queue *q = sdev->request_queue;
3018 unsigned long flags;
3021 * Try to transition the scsi device to SDEV_RUNNING or one of the
3022 * offlined states and goose the device queue if successful.
3024 if ((sdev->sdev_state == SDEV_BLOCK) ||
3025 (sdev->sdev_state == SDEV_TRANSPORT_OFFLINE))
3026 sdev->sdev_state = new_state;
3027 else if (sdev->sdev_state == SDEV_CREATED_BLOCK) {
3028 if (new_state == SDEV_TRANSPORT_OFFLINE ||
3029 new_state == SDEV_OFFLINE)
3030 sdev->sdev_state = new_state;
3032 sdev->sdev_state = SDEV_CREATED;
3033 } else if (sdev->sdev_state != SDEV_CANCEL &&
3034 sdev->sdev_state != SDEV_OFFLINE)
3038 blk_mq_start_stopped_hw_queues(q, false);
3040 spin_lock_irqsave(q->queue_lock, flags);
3042 spin_unlock_irqrestore(q->queue_lock, flags);
3047 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock);
3050 device_block(struct scsi_device *sdev, void *data)
3052 scsi_internal_device_block(sdev);
3056 target_block(struct device *dev, void *data)
3058 if (scsi_is_target_device(dev))
3059 starget_for_each_device(to_scsi_target(dev), NULL,
3065 scsi_target_block(struct device *dev)
3067 if (scsi_is_target_device(dev))
3068 starget_for_each_device(to_scsi_target(dev), NULL,
3071 device_for_each_child(dev, NULL, target_block);
3073 EXPORT_SYMBOL_GPL(scsi_target_block);
3076 device_unblock(struct scsi_device *sdev, void *data)
3078 scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
3082 target_unblock(struct device *dev, void *data)
3084 if (scsi_is_target_device(dev))
3085 starget_for_each_device(to_scsi_target(dev), data,
3091 scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
3093 if (scsi_is_target_device(dev))
3094 starget_for_each_device(to_scsi_target(dev), &new_state,
3097 device_for_each_child(dev, &new_state, target_unblock);
3099 EXPORT_SYMBOL_GPL(scsi_target_unblock);
3102 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
3103 * @sgl: scatter-gather list
3104 * @sg_count: number of segments in sg
3105 * @offset: offset in bytes into sg, on return offset into the mapped area
3106 * @len: bytes to map, on return number of bytes mapped
3108 * Returns virtual address of the start of the mapped page
3110 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
3111 size_t *offset, size_t *len)
3114 size_t sg_len = 0, len_complete = 0;
3115 struct scatterlist *sg;
3118 WARN_ON(!irqs_disabled());
3120 for_each_sg(sgl, sg, sg_count, i) {
3121 len_complete = sg_len; /* Complete sg-entries */
3122 sg_len += sg->length;
3123 if (sg_len > *offset)
3127 if (unlikely(i == sg_count)) {
3128 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
3130 __func__, sg_len, *offset, sg_count);
3135 /* Offset starting from the beginning of first page in this sg-entry */
3136 *offset = *offset - len_complete + sg->offset;
3138 /* Assumption: contiguous pages can be accessed as "page + i" */
3139 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
3140 *offset &= ~PAGE_MASK;
3142 /* Bytes in this sg-entry from *offset to the end of the page */
3143 sg_len = PAGE_SIZE - *offset;
3147 return kmap_atomic(page);
3149 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
3152 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
3153 * @virt: virtual address to be unmapped
3155 void scsi_kunmap_atomic_sg(void *virt)
3157 kunmap_atomic(virt);
3159 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
3161 void sdev_disable_disk_events(struct scsi_device *sdev)
3163 atomic_inc(&sdev->disk_events_disable_depth);
3165 EXPORT_SYMBOL(sdev_disable_disk_events);
3167 void sdev_enable_disk_events(struct scsi_device *sdev)
3169 if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
3171 atomic_dec(&sdev->disk_events_disable_depth);
3173 EXPORT_SYMBOL(sdev_enable_disk_events);
3176 * scsi_vpd_lun_id - return a unique device identification
3177 * @sdev: SCSI device
3178 * @id: buffer for the identification
3179 * @id_len: length of the buffer
3181 * Copies a unique device identification into @id based
3182 * on the information in the VPD page 0x83 of the device.
3183 * The string will be formatted as a SCSI name string.
3185 * Returns the length of the identification or error on failure.
3186 * If the identifier is longer than the supplied buffer the actual
3187 * identifier length is returned and the buffer is not zero-padded.
3189 int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
3191 u8 cur_id_type = 0xff;
3193 unsigned char *d, *cur_id_str;
3194 unsigned char __rcu *vpd_pg83;
3195 int id_size = -EINVAL;
3198 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3205 * Look for the correct descriptor.
3206 * Order of preference for lun descriptor:
3207 * - SCSI name string
3208 * - NAA IEEE Registered Extended
3209 * - EUI-64 based 16-byte
3210 * - EUI-64 based 12-byte
3211 * - NAA IEEE Registered
3212 * - NAA IEEE Extended
3214 * as longer descriptors reduce the likelyhood
3215 * of identification clashes.
3218 /* The id string must be at least 20 bytes + terminating NULL byte */
3224 memset(id, 0, id_len);
3226 while (d < vpd_pg83 + sdev->vpd_pg83_len) {
3227 /* Skip designators not referring to the LUN */
3228 if ((d[1] & 0x30) != 0x00)
3231 switch (d[1] & 0xf) {
3234 if (cur_id_size > d[3])
3236 /* Prefer anything */
3237 if (cur_id_type > 0x01 && cur_id_type != 0xff)
3240 if (cur_id_size + 4 > id_len)
3241 cur_id_size = id_len - 4;
3243 cur_id_type = d[1] & 0xf;
3244 id_size = snprintf(id, id_len, "t10.%*pE",
3245 cur_id_size, cur_id_str);
3249 if (cur_id_size > d[3])
3251 /* Prefer NAA IEEE Registered Extended */
3252 if (cur_id_type == 0x3 &&
3253 cur_id_size == d[3])
3257 cur_id_type = d[1] & 0xf;
3258 switch (cur_id_size) {
3260 id_size = snprintf(id, id_len,
3265 id_size = snprintf(id, id_len,
3270 id_size = snprintf(id, id_len,
3281 if (cur_id_size > d[3])
3285 cur_id_type = d[1] & 0xf;
3286 switch (cur_id_size) {
3288 id_size = snprintf(id, id_len,
3293 id_size = snprintf(id, id_len,
3303 /* SCSI name string */
3304 if (cur_id_size + 4 > d[3])
3306 /* Prefer others for truncated descriptor */
3307 if (cur_id_size && d[3] > id_len)
3309 cur_id_size = id_size = d[3];
3311 cur_id_type = d[1] & 0xf;
3312 if (cur_id_size >= id_len)
3313 cur_id_size = id_len - 1;
3314 memcpy(id, cur_id_str, cur_id_size);
3315 /* Decrease priority for truncated descriptor */
3316 if (cur_id_size != id_size)
3329 EXPORT_SYMBOL(scsi_vpd_lun_id);
3332 * scsi_vpd_tpg_id - return a target port group identifier
3333 * @sdev: SCSI device
3335 * Returns the Target Port Group identifier from the information
3336 * froom VPD page 0x83 of the device.
3338 * Returns the identifier or error on failure.
3340 int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
3343 unsigned char __rcu *vpd_pg83;
3344 int group_id = -EAGAIN, rel_port = -1;
3347 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3353 d = sdev->vpd_pg83 + 4;
3354 while (d < sdev->vpd_pg83 + sdev->vpd_pg83_len) {
3355 switch (d[1] & 0xf) {
3357 /* Relative target port */
3358 rel_port = get_unaligned_be16(&d[6]);
3361 /* Target port group */
3362 group_id = get_unaligned_be16(&d[6]);
3371 if (group_id >= 0 && rel_id && rel_port != -1)
3376 EXPORT_SYMBOL(scsi_vpd_tpg_id);