vfio/pci: Pull BAR mapping setup from read-write path
[linux/fpc-iii.git] / drivers / scsi / scsi_lib.c
blobc84f931388f226cdab2071245f7308d2c0b035b3
1 /*
2 * Copyright (C) 1999 Eric Youngdale
3 * Copyright (C) 2014 Christoph Hellwig
5 * SCSI queueing library.
6 * Initial versions: Eric Youngdale (eric@andante.org).
7 * Based upon conversations with large numbers
8 * of people at Linux Expo.
9 */
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_transport.h> /* __scsi_init_queue() */
34 #include <scsi/scsi_dh.h>
36 #include <trace/events/scsi.h>
38 #include "scsi_debugfs.h"
39 #include "scsi_priv.h"
40 #include "scsi_logging.h"
42 static struct kmem_cache *scsi_sdb_cache;
43 static struct kmem_cache *scsi_sense_cache;
44 static struct kmem_cache *scsi_sense_isadma_cache;
45 static DEFINE_MUTEX(scsi_sense_cache_mutex);
47 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd);
49 static inline struct kmem_cache *
50 scsi_select_sense_cache(bool unchecked_isa_dma)
52 return unchecked_isa_dma ? scsi_sense_isadma_cache : scsi_sense_cache;
55 static void scsi_free_sense_buffer(bool unchecked_isa_dma,
56 unsigned char *sense_buffer)
58 kmem_cache_free(scsi_select_sense_cache(unchecked_isa_dma),
59 sense_buffer);
62 static unsigned char *scsi_alloc_sense_buffer(bool unchecked_isa_dma,
63 gfp_t gfp_mask, int numa_node)
65 return kmem_cache_alloc_node(scsi_select_sense_cache(unchecked_isa_dma),
66 gfp_mask, numa_node);
69 int scsi_init_sense_cache(struct Scsi_Host *shost)
71 struct kmem_cache *cache;
72 int ret = 0;
74 cache = scsi_select_sense_cache(shost->unchecked_isa_dma);
75 if (cache)
76 return 0;
78 mutex_lock(&scsi_sense_cache_mutex);
79 if (shost->unchecked_isa_dma) {
80 scsi_sense_isadma_cache =
81 kmem_cache_create("scsi_sense_cache(DMA)",
82 SCSI_SENSE_BUFFERSIZE, 0,
83 SLAB_HWCACHE_ALIGN | SLAB_CACHE_DMA, NULL);
84 if (!scsi_sense_isadma_cache)
85 ret = -ENOMEM;
86 } else {
87 scsi_sense_cache =
88 kmem_cache_create_usercopy("scsi_sense_cache",
89 SCSI_SENSE_BUFFERSIZE, 0, SLAB_HWCACHE_ALIGN,
90 0, SCSI_SENSE_BUFFERSIZE, NULL);
91 if (!scsi_sense_cache)
92 ret = -ENOMEM;
95 mutex_unlock(&scsi_sense_cache_mutex);
96 return ret;
100 * When to reinvoke queueing after a resource shortage. It's 3 msecs to
101 * not change behaviour from the previous unplug mechanism, experimentation
102 * may prove this needs changing.
104 #define SCSI_QUEUE_DELAY 3
106 static void
107 scsi_set_blocked(struct scsi_cmnd *cmd, int reason)
109 struct Scsi_Host *host = cmd->device->host;
110 struct scsi_device *device = cmd->device;
111 struct scsi_target *starget = scsi_target(device);
114 * Set the appropriate busy bit for the device/host.
116 * If the host/device isn't busy, assume that something actually
117 * completed, and that we should be able to queue a command now.
119 * Note that the prior mid-layer assumption that any host could
120 * always queue at least one command is now broken. The mid-layer
121 * will implement a user specifiable stall (see
122 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
123 * if a command is requeued with no other commands outstanding
124 * either for the device or for the host.
126 switch (reason) {
127 case SCSI_MLQUEUE_HOST_BUSY:
128 atomic_set(&host->host_blocked, host->max_host_blocked);
129 break;
130 case SCSI_MLQUEUE_DEVICE_BUSY:
131 case SCSI_MLQUEUE_EH_RETRY:
132 atomic_set(&device->device_blocked,
133 device->max_device_blocked);
134 break;
135 case SCSI_MLQUEUE_TARGET_BUSY:
136 atomic_set(&starget->target_blocked,
137 starget->max_target_blocked);
138 break;
142 static void scsi_mq_requeue_cmd(struct scsi_cmnd *cmd)
144 struct scsi_device *sdev = cmd->device;
146 if (cmd->request->rq_flags & RQF_DONTPREP) {
147 cmd->request->rq_flags &= ~RQF_DONTPREP;
148 scsi_mq_uninit_cmd(cmd);
149 } else {
150 WARN_ON_ONCE(true);
152 blk_mq_requeue_request(cmd->request, true);
153 put_device(&sdev->sdev_gendev);
157 * __scsi_queue_insert - private queue insertion
158 * @cmd: The SCSI command being requeued
159 * @reason: The reason for the requeue
160 * @unbusy: Whether the queue should be unbusied
162 * This is a private queue insertion. The public interface
163 * scsi_queue_insert() always assumes the queue should be unbusied
164 * because it's always called before the completion. This function is
165 * for a requeue after completion, which should only occur in this
166 * file.
168 static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, bool unbusy)
170 struct scsi_device *device = cmd->device;
171 struct request_queue *q = device->request_queue;
172 unsigned long flags;
174 SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd,
175 "Inserting command %p into mlqueue\n", cmd));
177 scsi_set_blocked(cmd, reason);
180 * Decrement the counters, since these commands are no longer
181 * active on the host/device.
183 if (unbusy)
184 scsi_device_unbusy(device);
187 * Requeue this command. It will go before all other commands
188 * that are already in the queue. Schedule requeue work under
189 * lock such that the kblockd_schedule_work() call happens
190 * before blk_cleanup_queue() finishes.
192 cmd->result = 0;
193 if (q->mq_ops) {
194 scsi_mq_requeue_cmd(cmd);
195 return;
197 spin_lock_irqsave(q->queue_lock, flags);
198 blk_requeue_request(q, cmd->request);
199 kblockd_schedule_work(&device->requeue_work);
200 spin_unlock_irqrestore(q->queue_lock, flags);
204 * Function: scsi_queue_insert()
206 * Purpose: Insert a command in the midlevel queue.
208 * Arguments: cmd - command that we are adding to queue.
209 * reason - why we are inserting command to queue.
211 * Lock status: Assumed that lock is not held upon entry.
213 * Returns: Nothing.
215 * Notes: We do this for one of two cases. Either the host is busy
216 * and it cannot accept any more commands for the time being,
217 * or the device returned QUEUE_FULL and can accept no more
218 * commands.
219 * Notes: This could be called either from an interrupt context or a
220 * normal process context.
222 void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
224 __scsi_queue_insert(cmd, reason, true);
229 * scsi_execute - insert request and wait for the result
230 * @sdev: scsi device
231 * @cmd: scsi command
232 * @data_direction: data direction
233 * @buffer: data buffer
234 * @bufflen: len of buffer
235 * @sense: optional sense buffer
236 * @sshdr: optional decoded sense header
237 * @timeout: request timeout in seconds
238 * @retries: number of times to retry request
239 * @flags: flags for ->cmd_flags
240 * @rq_flags: flags for ->rq_flags
241 * @resid: optional residual length
243 * Returns the scsi_cmnd result field if a command was executed, or a negative
244 * Linux error code if we didn't get that far.
246 int scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
247 int data_direction, void *buffer, unsigned bufflen,
248 unsigned char *sense, struct scsi_sense_hdr *sshdr,
249 int timeout, int retries, u64 flags, req_flags_t rq_flags,
250 int *resid)
252 struct request *req;
253 struct scsi_request *rq;
254 int ret = DRIVER_ERROR << 24;
256 req = blk_get_request_flags(sdev->request_queue,
257 data_direction == DMA_TO_DEVICE ?
258 REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN, BLK_MQ_REQ_PREEMPT);
259 if (IS_ERR(req))
260 return ret;
261 rq = scsi_req(req);
263 if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
264 buffer, bufflen, __GFP_RECLAIM))
265 goto out;
267 rq->cmd_len = COMMAND_SIZE(cmd[0]);
268 memcpy(rq->cmd, cmd, rq->cmd_len);
269 rq->retries = retries;
270 req->timeout = timeout;
271 req->cmd_flags |= flags;
272 req->rq_flags |= rq_flags | RQF_QUIET;
275 * head injection *required* here otherwise quiesce won't work
277 blk_execute_rq(req->q, NULL, req, 1);
280 * Some devices (USB mass-storage in particular) may transfer
281 * garbage data together with a residue indicating that the data
282 * is invalid. Prevent the garbage from being misinterpreted
283 * and prevent security leaks by zeroing out the excess data.
285 if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen))
286 memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len);
288 if (resid)
289 *resid = rq->resid_len;
290 if (sense && rq->sense_len)
291 memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE);
292 if (sshdr)
293 scsi_normalize_sense(rq->sense, rq->sense_len, sshdr);
294 ret = rq->result;
295 out:
296 blk_put_request(req);
298 return ret;
300 EXPORT_SYMBOL(scsi_execute);
303 * Function: scsi_init_cmd_errh()
305 * Purpose: Initialize cmd fields related to error handling.
307 * Arguments: cmd - command that is ready to be queued.
309 * Notes: This function has the job of initializing a number of
310 * fields related to error handling. Typically this will
311 * be called once for each command, as required.
313 static void scsi_init_cmd_errh(struct scsi_cmnd *cmd)
315 cmd->serial_number = 0;
316 scsi_set_resid(cmd, 0);
317 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
318 if (cmd->cmd_len == 0)
319 cmd->cmd_len = scsi_command_size(cmd->cmnd);
323 * Decrement the host_busy counter and wake up the error handler if necessary.
324 * Avoid as follows that the error handler is not woken up if shost->host_busy
325 * == shost->host_failed: use call_rcu() in scsi_eh_scmd_add() in combination
326 * with an RCU read lock in this function to ensure that this function in its
327 * entirety either finishes before scsi_eh_scmd_add() increases the
328 * host_failed counter or that it notices the shost state change made by
329 * scsi_eh_scmd_add().
331 static void scsi_dec_host_busy(struct Scsi_Host *shost)
333 unsigned long flags;
335 rcu_read_lock();
336 atomic_dec(&shost->host_busy);
337 if (unlikely(scsi_host_in_recovery(shost))) {
338 spin_lock_irqsave(shost->host_lock, flags);
339 if (shost->host_failed || shost->host_eh_scheduled)
340 scsi_eh_wakeup(shost);
341 spin_unlock_irqrestore(shost->host_lock, flags);
343 rcu_read_unlock();
346 void scsi_device_unbusy(struct scsi_device *sdev)
348 struct Scsi_Host *shost = sdev->host;
349 struct scsi_target *starget = scsi_target(sdev);
351 scsi_dec_host_busy(shost);
353 if (starget->can_queue > 0)
354 atomic_dec(&starget->target_busy);
356 atomic_dec(&sdev->device_busy);
359 static void scsi_kick_queue(struct request_queue *q)
361 if (q->mq_ops)
362 blk_mq_start_hw_queues(q);
363 else
364 blk_run_queue(q);
368 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
369 * and call blk_run_queue for all the scsi_devices on the target -
370 * including current_sdev first.
372 * Called with *no* scsi locks held.
374 static void scsi_single_lun_run(struct scsi_device *current_sdev)
376 struct Scsi_Host *shost = current_sdev->host;
377 struct scsi_device *sdev, *tmp;
378 struct scsi_target *starget = scsi_target(current_sdev);
379 unsigned long flags;
381 spin_lock_irqsave(shost->host_lock, flags);
382 starget->starget_sdev_user = NULL;
383 spin_unlock_irqrestore(shost->host_lock, flags);
386 * Call blk_run_queue for all LUNs on the target, starting with
387 * current_sdev. We race with others (to set starget_sdev_user),
388 * but in most cases, we will be first. Ideally, each LU on the
389 * target would get some limited time or requests on the target.
391 scsi_kick_queue(current_sdev->request_queue);
393 spin_lock_irqsave(shost->host_lock, flags);
394 if (starget->starget_sdev_user)
395 goto out;
396 list_for_each_entry_safe(sdev, tmp, &starget->devices,
397 same_target_siblings) {
398 if (sdev == current_sdev)
399 continue;
400 if (scsi_device_get(sdev))
401 continue;
403 spin_unlock_irqrestore(shost->host_lock, flags);
404 scsi_kick_queue(sdev->request_queue);
405 spin_lock_irqsave(shost->host_lock, flags);
407 scsi_device_put(sdev);
409 out:
410 spin_unlock_irqrestore(shost->host_lock, flags);
413 static inline bool scsi_device_is_busy(struct scsi_device *sdev)
415 if (atomic_read(&sdev->device_busy) >= sdev->queue_depth)
416 return true;
417 if (atomic_read(&sdev->device_blocked) > 0)
418 return true;
419 return false;
422 static inline bool scsi_target_is_busy(struct scsi_target *starget)
424 if (starget->can_queue > 0) {
425 if (atomic_read(&starget->target_busy) >= starget->can_queue)
426 return true;
427 if (atomic_read(&starget->target_blocked) > 0)
428 return true;
430 return false;
433 static inline bool scsi_host_is_busy(struct Scsi_Host *shost)
435 if (shost->can_queue > 0 &&
436 atomic_read(&shost->host_busy) >= shost->can_queue)
437 return true;
438 if (atomic_read(&shost->host_blocked) > 0)
439 return true;
440 if (shost->host_self_blocked)
441 return true;
442 return false;
445 static void scsi_starved_list_run(struct Scsi_Host *shost)
447 LIST_HEAD(starved_list);
448 struct scsi_device *sdev;
449 unsigned long flags;
451 spin_lock_irqsave(shost->host_lock, flags);
452 list_splice_init(&shost->starved_list, &starved_list);
454 while (!list_empty(&starved_list)) {
455 struct request_queue *slq;
458 * As long as shost is accepting commands and we have
459 * starved queues, call blk_run_queue. scsi_request_fn
460 * drops the queue_lock and can add us back to the
461 * starved_list.
463 * host_lock protects the starved_list and starved_entry.
464 * scsi_request_fn must get the host_lock before checking
465 * or modifying starved_list or starved_entry.
467 if (scsi_host_is_busy(shost))
468 break;
470 sdev = list_entry(starved_list.next,
471 struct scsi_device, starved_entry);
472 list_del_init(&sdev->starved_entry);
473 if (scsi_target_is_busy(scsi_target(sdev))) {
474 list_move_tail(&sdev->starved_entry,
475 &shost->starved_list);
476 continue;
480 * Once we drop the host lock, a racing scsi_remove_device()
481 * call may remove the sdev from the starved list and destroy
482 * it and the queue. Mitigate by taking a reference to the
483 * queue and never touching the sdev again after we drop the
484 * host lock. Note: if __scsi_remove_device() invokes
485 * blk_cleanup_queue() before the queue is run from this
486 * function then blk_run_queue() will return immediately since
487 * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
489 slq = sdev->request_queue;
490 if (!blk_get_queue(slq))
491 continue;
492 spin_unlock_irqrestore(shost->host_lock, flags);
494 scsi_kick_queue(slq);
495 blk_put_queue(slq);
497 spin_lock_irqsave(shost->host_lock, flags);
499 /* put any unprocessed entries back */
500 list_splice(&starved_list, &shost->starved_list);
501 spin_unlock_irqrestore(shost->host_lock, flags);
505 * Function: scsi_run_queue()
507 * Purpose: Select a proper request queue to serve next
509 * Arguments: q - last request's queue
511 * Returns: Nothing
513 * Notes: The previous command was completely finished, start
514 * a new one if possible.
516 static void scsi_run_queue(struct request_queue *q)
518 struct scsi_device *sdev = q->queuedata;
520 if (scsi_target(sdev)->single_lun)
521 scsi_single_lun_run(sdev);
522 if (!list_empty(&sdev->host->starved_list))
523 scsi_starved_list_run(sdev->host);
525 if (q->mq_ops)
526 blk_mq_run_hw_queues(q, false);
527 else
528 blk_run_queue(q);
531 void scsi_requeue_run_queue(struct work_struct *work)
533 struct scsi_device *sdev;
534 struct request_queue *q;
536 sdev = container_of(work, struct scsi_device, requeue_work);
537 q = sdev->request_queue;
538 scsi_run_queue(q);
542 * Function: scsi_requeue_command()
544 * Purpose: Handle post-processing of completed commands.
546 * Arguments: q - queue to operate on
547 * cmd - command that may need to be requeued.
549 * Returns: Nothing
551 * Notes: After command completion, there may be blocks left
552 * over which weren't finished by the previous command
553 * this can be for a number of reasons - the main one is
554 * I/O errors in the middle of the request, in which case
555 * we need to request the blocks that come after the bad
556 * sector.
557 * Notes: Upon return, cmd is a stale pointer.
559 static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
561 struct scsi_device *sdev = cmd->device;
562 struct request *req = cmd->request;
563 unsigned long flags;
565 spin_lock_irqsave(q->queue_lock, flags);
566 blk_unprep_request(req);
567 req->special = NULL;
568 scsi_put_command(cmd);
569 blk_requeue_request(q, req);
570 spin_unlock_irqrestore(q->queue_lock, flags);
572 scsi_run_queue(q);
574 put_device(&sdev->sdev_gendev);
577 void scsi_run_host_queues(struct Scsi_Host *shost)
579 struct scsi_device *sdev;
581 shost_for_each_device(sdev, shost)
582 scsi_run_queue(sdev->request_queue);
585 static void scsi_uninit_cmd(struct scsi_cmnd *cmd)
587 if (!blk_rq_is_passthrough(cmd->request)) {
588 struct scsi_driver *drv = scsi_cmd_to_driver(cmd);
590 if (drv->uninit_command)
591 drv->uninit_command(cmd);
595 static void scsi_mq_free_sgtables(struct scsi_cmnd *cmd)
597 struct scsi_data_buffer *sdb;
599 if (cmd->sdb.table.nents)
600 sg_free_table_chained(&cmd->sdb.table, true);
601 if (cmd->request->next_rq) {
602 sdb = cmd->request->next_rq->special;
603 if (sdb)
604 sg_free_table_chained(&sdb->table, true);
606 if (scsi_prot_sg_count(cmd))
607 sg_free_table_chained(&cmd->prot_sdb->table, true);
610 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd)
612 scsi_mq_free_sgtables(cmd);
613 scsi_uninit_cmd(cmd);
614 scsi_del_cmd_from_list(cmd);
618 * Function: scsi_release_buffers()
620 * Purpose: Free resources allocate for a scsi_command.
622 * Arguments: cmd - command that we are bailing.
624 * Lock status: Assumed that no lock is held upon entry.
626 * Returns: Nothing
628 * Notes: In the event that an upper level driver rejects a
629 * command, we must release resources allocated during
630 * the __init_io() function. Primarily this would involve
631 * the scatter-gather table.
633 static void scsi_release_buffers(struct scsi_cmnd *cmd)
635 if (cmd->sdb.table.nents)
636 sg_free_table_chained(&cmd->sdb.table, false);
638 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
640 if (scsi_prot_sg_count(cmd))
641 sg_free_table_chained(&cmd->prot_sdb->table, false);
644 static void scsi_release_bidi_buffers(struct scsi_cmnd *cmd)
646 struct scsi_data_buffer *bidi_sdb = cmd->request->next_rq->special;
648 sg_free_table_chained(&bidi_sdb->table, false);
649 kmem_cache_free(scsi_sdb_cache, bidi_sdb);
650 cmd->request->next_rq->special = NULL;
653 static bool scsi_end_request(struct request *req, blk_status_t error,
654 unsigned int bytes, unsigned int bidi_bytes)
656 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
657 struct scsi_device *sdev = cmd->device;
658 struct request_queue *q = sdev->request_queue;
660 if (blk_update_request(req, error, bytes))
661 return true;
663 /* Bidi request must be completed as a whole */
664 if (unlikely(bidi_bytes) &&
665 blk_update_request(req->next_rq, error, bidi_bytes))
666 return true;
668 if (blk_queue_add_random(q))
669 add_disk_randomness(req->rq_disk);
671 if (!blk_rq_is_scsi(req)) {
672 WARN_ON_ONCE(!(cmd->flags & SCMD_INITIALIZED));
673 cmd->flags &= ~SCMD_INITIALIZED;
674 destroy_rcu_head(&cmd->rcu);
677 if (req->mq_ctx) {
679 * In the MQ case the command gets freed by __blk_mq_end_request,
680 * so we have to do all cleanup that depends on it earlier.
682 * We also can't kick the queues from irq context, so we
683 * will have to defer it to a workqueue.
685 scsi_mq_uninit_cmd(cmd);
687 __blk_mq_end_request(req, error);
689 if (scsi_target(sdev)->single_lun ||
690 !list_empty(&sdev->host->starved_list))
691 kblockd_schedule_work(&sdev->requeue_work);
692 else
693 blk_mq_run_hw_queues(q, true);
694 } else {
695 unsigned long flags;
697 if (bidi_bytes)
698 scsi_release_bidi_buffers(cmd);
699 scsi_release_buffers(cmd);
700 scsi_put_command(cmd);
702 spin_lock_irqsave(q->queue_lock, flags);
703 blk_finish_request(req, error);
704 spin_unlock_irqrestore(q->queue_lock, flags);
706 scsi_run_queue(q);
709 put_device(&sdev->sdev_gendev);
710 return false;
714 * __scsi_error_from_host_byte - translate SCSI error code into errno
715 * @cmd: SCSI command (unused)
716 * @result: scsi error code
718 * Translate SCSI error code into block errors.
720 static blk_status_t __scsi_error_from_host_byte(struct scsi_cmnd *cmd,
721 int result)
723 switch (host_byte(result)) {
724 case DID_OK:
725 return BLK_STS_OK;
726 case DID_TRANSPORT_FAILFAST:
727 return BLK_STS_TRANSPORT;
728 case DID_TARGET_FAILURE:
729 set_host_byte(cmd, DID_OK);
730 return BLK_STS_TARGET;
731 case DID_NEXUS_FAILURE:
732 return BLK_STS_NEXUS;
733 case DID_ALLOC_FAILURE:
734 set_host_byte(cmd, DID_OK);
735 return BLK_STS_NOSPC;
736 case DID_MEDIUM_ERROR:
737 set_host_byte(cmd, DID_OK);
738 return BLK_STS_MEDIUM;
739 default:
740 return BLK_STS_IOERR;
745 * Function: scsi_io_completion()
747 * Purpose: Completion processing for block device I/O requests.
749 * Arguments: cmd - command that is finished.
751 * Lock status: Assumed that no lock is held upon entry.
753 * Returns: Nothing
755 * Notes: We will finish off the specified number of sectors. If we
756 * are done, the command block will be released and the queue
757 * function will be goosed. If we are not done then we have to
758 * figure out what to do next:
760 * a) We can call scsi_requeue_command(). The request
761 * will be unprepared and put back on the queue. Then
762 * a new command will be created for it. This should
763 * be used if we made forward progress, or if we want
764 * to switch from READ(10) to READ(6) for example.
766 * b) We can call __scsi_queue_insert(). The request will
767 * be put back on the queue and retried using the same
768 * command as before, possibly after a delay.
770 * c) We can call scsi_end_request() with -EIO to fail
771 * the remainder of the request.
773 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
775 int result = cmd->result;
776 struct request_queue *q = cmd->device->request_queue;
777 struct request *req = cmd->request;
778 blk_status_t error = BLK_STS_OK;
779 struct scsi_sense_hdr sshdr;
780 bool sense_valid = false;
781 int sense_deferred = 0, level = 0;
782 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
783 ACTION_DELAYED_RETRY} action;
784 unsigned long wait_for = (cmd->allowed + 1) * req->timeout;
786 if (result) {
787 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
788 if (sense_valid)
789 sense_deferred = scsi_sense_is_deferred(&sshdr);
792 if (blk_rq_is_passthrough(req)) {
793 if (result) {
794 if (sense_valid) {
796 * SG_IO wants current and deferred errors
798 scsi_req(req)->sense_len =
799 min(8 + cmd->sense_buffer[7],
800 SCSI_SENSE_BUFFERSIZE);
802 if (!sense_deferred)
803 error = __scsi_error_from_host_byte(cmd, result);
806 * __scsi_error_from_host_byte may have reset the host_byte
808 scsi_req(req)->result = cmd->result;
809 scsi_req(req)->resid_len = scsi_get_resid(cmd);
811 if (scsi_bidi_cmnd(cmd)) {
813 * Bidi commands Must be complete as a whole,
814 * both sides at once.
816 scsi_req(req->next_rq)->resid_len = scsi_in(cmd)->resid;
817 if (scsi_end_request(req, BLK_STS_OK, blk_rq_bytes(req),
818 blk_rq_bytes(req->next_rq)))
819 BUG();
820 return;
822 } else if (blk_rq_bytes(req) == 0 && result && !sense_deferred) {
824 * Flush commands do not transfers any data, and thus cannot use
825 * good_bytes != blk_rq_bytes(req) as the signal for an error.
826 * This sets the error explicitly for the problem case.
828 error = __scsi_error_from_host_byte(cmd, result);
831 /* no bidi support for !blk_rq_is_passthrough yet */
832 BUG_ON(blk_bidi_rq(req));
835 * Next deal with any sectors which we were able to correctly
836 * handle.
838 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd,
839 "%u sectors total, %d bytes done.\n",
840 blk_rq_sectors(req), good_bytes));
843 * Recovered errors need reporting, but they're always treated as
844 * success, so fiddle the result code here. For passthrough requests
845 * we already took a copy of the original into sreq->result which
846 * is what gets returned to the user
848 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
849 /* if ATA PASS-THROUGH INFORMATION AVAILABLE skip
850 * print since caller wants ATA registers. Only occurs on
851 * SCSI ATA PASS_THROUGH commands when CK_COND=1
853 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
855 else if (!(req->rq_flags & RQF_QUIET))
856 scsi_print_sense(cmd);
857 result = 0;
858 /* for passthrough error may be set */
859 error = BLK_STS_OK;
863 * special case: failed zero length commands always need to
864 * drop down into the retry code. Otherwise, if we finished
865 * all bytes in the request we are done now.
867 if (!(blk_rq_bytes(req) == 0 && error) &&
868 !scsi_end_request(req, error, good_bytes, 0))
869 return;
872 * Kill remainder if no retrys.
874 if (error && scsi_noretry_cmd(cmd)) {
875 if (scsi_end_request(req, error, blk_rq_bytes(req), 0))
876 BUG();
877 return;
881 * If there had been no error, but we have leftover bytes in the
882 * requeues just queue the command up again.
884 if (result == 0)
885 goto requeue;
887 error = __scsi_error_from_host_byte(cmd, result);
889 if (host_byte(result) == DID_RESET) {
890 /* Third party bus reset or reset for error recovery
891 * reasons. Just retry the command and see what
892 * happens.
894 action = ACTION_RETRY;
895 } else if (sense_valid && !sense_deferred) {
896 switch (sshdr.sense_key) {
897 case UNIT_ATTENTION:
898 if (cmd->device->removable) {
899 /* Detected disc change. Set a bit
900 * and quietly refuse further access.
902 cmd->device->changed = 1;
903 action = ACTION_FAIL;
904 } else {
905 /* Must have been a power glitch, or a
906 * bus reset. Could not have been a
907 * media change, so we just retry the
908 * command and see what happens.
910 action = ACTION_RETRY;
912 break;
913 case ILLEGAL_REQUEST:
914 /* If we had an ILLEGAL REQUEST returned, then
915 * we may have performed an unsupported
916 * command. The only thing this should be
917 * would be a ten byte read where only a six
918 * byte read was supported. Also, on a system
919 * where READ CAPACITY failed, we may have
920 * read past the end of the disk.
922 if ((cmd->device->use_10_for_rw &&
923 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
924 (cmd->cmnd[0] == READ_10 ||
925 cmd->cmnd[0] == WRITE_10)) {
926 /* This will issue a new 6-byte command. */
927 cmd->device->use_10_for_rw = 0;
928 action = ACTION_REPREP;
929 } else if (sshdr.asc == 0x10) /* DIX */ {
930 action = ACTION_FAIL;
931 error = BLK_STS_PROTECTION;
932 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
933 } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
934 action = ACTION_FAIL;
935 error = BLK_STS_TARGET;
936 } else
937 action = ACTION_FAIL;
938 break;
939 case ABORTED_COMMAND:
940 action = ACTION_FAIL;
941 if (sshdr.asc == 0x10) /* DIF */
942 error = BLK_STS_PROTECTION;
943 break;
944 case NOT_READY:
945 /* If the device is in the process of becoming
946 * ready, or has a temporary blockage, retry.
948 if (sshdr.asc == 0x04) {
949 switch (sshdr.ascq) {
950 case 0x01: /* becoming ready */
951 case 0x04: /* format in progress */
952 case 0x05: /* rebuild in progress */
953 case 0x06: /* recalculation in progress */
954 case 0x07: /* operation in progress */
955 case 0x08: /* Long write in progress */
956 case 0x09: /* self test in progress */
957 case 0x14: /* space allocation in progress */
958 action = ACTION_DELAYED_RETRY;
959 break;
960 default:
961 action = ACTION_FAIL;
962 break;
964 } else
965 action = ACTION_FAIL;
966 break;
967 case VOLUME_OVERFLOW:
968 /* See SSC3rXX or current. */
969 action = ACTION_FAIL;
970 break;
971 default:
972 action = ACTION_FAIL;
973 break;
975 } else
976 action = ACTION_FAIL;
978 if (action != ACTION_FAIL &&
979 time_before(cmd->jiffies_at_alloc + wait_for, jiffies))
980 action = ACTION_FAIL;
982 switch (action) {
983 case ACTION_FAIL:
984 /* Give up and fail the remainder of the request */
985 if (!(req->rq_flags & RQF_QUIET)) {
986 static DEFINE_RATELIMIT_STATE(_rs,
987 DEFAULT_RATELIMIT_INTERVAL,
988 DEFAULT_RATELIMIT_BURST);
990 if (unlikely(scsi_logging_level))
991 level = SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
992 SCSI_LOG_MLCOMPLETE_BITS);
995 * if logging is enabled the failure will be printed
996 * in scsi_log_completion(), so avoid duplicate messages
998 if (!level && __ratelimit(&_rs)) {
999 scsi_print_result(cmd, NULL, FAILED);
1000 if (driver_byte(result) & DRIVER_SENSE)
1001 scsi_print_sense(cmd);
1002 scsi_print_command(cmd);
1005 if (!scsi_end_request(req, error, blk_rq_err_bytes(req), 0))
1006 return;
1007 /*FALLTHRU*/
1008 case ACTION_REPREP:
1009 requeue:
1010 /* Unprep the request and put it back at the head of the queue.
1011 * A new command will be prepared and issued.
1013 if (q->mq_ops) {
1014 scsi_mq_requeue_cmd(cmd);
1015 } else {
1016 scsi_release_buffers(cmd);
1017 scsi_requeue_command(q, cmd);
1019 break;
1020 case ACTION_RETRY:
1021 /* Retry the same command immediately */
1022 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, false);
1023 break;
1024 case ACTION_DELAYED_RETRY:
1025 /* Retry the same command after a delay */
1026 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, false);
1027 break;
1031 static int scsi_init_sgtable(struct request *req, struct scsi_data_buffer *sdb)
1033 int count;
1036 * If sg table allocation fails, requeue request later.
1038 if (unlikely(sg_alloc_table_chained(&sdb->table,
1039 blk_rq_nr_phys_segments(req), sdb->table.sgl)))
1040 return BLKPREP_DEFER;
1043 * Next, walk the list, and fill in the addresses and sizes of
1044 * each segment.
1046 count = blk_rq_map_sg(req->q, req, sdb->table.sgl);
1047 BUG_ON(count > sdb->table.nents);
1048 sdb->table.nents = count;
1049 sdb->length = blk_rq_payload_bytes(req);
1050 return BLKPREP_OK;
1054 * Function: scsi_init_io()
1056 * Purpose: SCSI I/O initialize function.
1058 * Arguments: cmd - Command descriptor we wish to initialize
1060 * Returns: 0 on success
1061 * BLKPREP_DEFER if the failure is retryable
1062 * BLKPREP_KILL if the failure is fatal
1064 int scsi_init_io(struct scsi_cmnd *cmd)
1066 struct scsi_device *sdev = cmd->device;
1067 struct request *rq = cmd->request;
1068 bool is_mq = (rq->mq_ctx != NULL);
1069 int error = BLKPREP_KILL;
1071 if (WARN_ON_ONCE(!blk_rq_nr_phys_segments(rq)))
1072 goto err_exit;
1074 error = scsi_init_sgtable(rq, &cmd->sdb);
1075 if (error)
1076 goto err_exit;
1078 if (blk_bidi_rq(rq)) {
1079 if (!rq->q->mq_ops) {
1080 struct scsi_data_buffer *bidi_sdb =
1081 kmem_cache_zalloc(scsi_sdb_cache, GFP_ATOMIC);
1082 if (!bidi_sdb) {
1083 error = BLKPREP_DEFER;
1084 goto err_exit;
1087 rq->next_rq->special = bidi_sdb;
1090 error = scsi_init_sgtable(rq->next_rq, rq->next_rq->special);
1091 if (error)
1092 goto err_exit;
1095 if (blk_integrity_rq(rq)) {
1096 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1097 int ivecs, count;
1099 if (prot_sdb == NULL) {
1101 * This can happen if someone (e.g. multipath)
1102 * queues a command to a device on an adapter
1103 * that does not support DIX.
1105 WARN_ON_ONCE(1);
1106 error = BLKPREP_KILL;
1107 goto err_exit;
1110 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
1112 if (sg_alloc_table_chained(&prot_sdb->table, ivecs,
1113 prot_sdb->table.sgl)) {
1114 error = BLKPREP_DEFER;
1115 goto err_exit;
1118 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
1119 prot_sdb->table.sgl);
1120 BUG_ON(unlikely(count > ivecs));
1121 BUG_ON(unlikely(count > queue_max_integrity_segments(rq->q)));
1123 cmd->prot_sdb = prot_sdb;
1124 cmd->prot_sdb->table.nents = count;
1127 return BLKPREP_OK;
1128 err_exit:
1129 if (is_mq) {
1130 scsi_mq_free_sgtables(cmd);
1131 } else {
1132 scsi_release_buffers(cmd);
1133 cmd->request->special = NULL;
1134 scsi_put_command(cmd);
1135 put_device(&sdev->sdev_gendev);
1137 return error;
1139 EXPORT_SYMBOL(scsi_init_io);
1142 * scsi_initialize_rq - initialize struct scsi_cmnd partially
1143 * @rq: Request associated with the SCSI command to be initialized.
1145 * This function initializes the members of struct scsi_cmnd that must be
1146 * initialized before request processing starts and that won't be
1147 * reinitialized if a SCSI command is requeued.
1149 * Called from inside blk_get_request() for pass-through requests and from
1150 * inside scsi_init_command() for filesystem requests.
1152 static void scsi_initialize_rq(struct request *rq)
1154 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1156 scsi_req_init(&cmd->req);
1157 init_rcu_head(&cmd->rcu);
1158 cmd->jiffies_at_alloc = jiffies;
1159 cmd->retries = 0;
1162 /* Add a command to the list used by the aacraid and dpt_i2o drivers */
1163 void scsi_add_cmd_to_list(struct scsi_cmnd *cmd)
1165 struct scsi_device *sdev = cmd->device;
1166 struct Scsi_Host *shost = sdev->host;
1167 unsigned long flags;
1169 if (shost->use_cmd_list) {
1170 spin_lock_irqsave(&sdev->list_lock, flags);
1171 list_add_tail(&cmd->list, &sdev->cmd_list);
1172 spin_unlock_irqrestore(&sdev->list_lock, flags);
1176 /* Remove a command from the list used by the aacraid and dpt_i2o drivers */
1177 void scsi_del_cmd_from_list(struct scsi_cmnd *cmd)
1179 struct scsi_device *sdev = cmd->device;
1180 struct Scsi_Host *shost = sdev->host;
1181 unsigned long flags;
1183 if (shost->use_cmd_list) {
1184 spin_lock_irqsave(&sdev->list_lock, flags);
1185 BUG_ON(list_empty(&cmd->list));
1186 list_del_init(&cmd->list);
1187 spin_unlock_irqrestore(&sdev->list_lock, flags);
1191 /* Called after a request has been started. */
1192 void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd)
1194 void *buf = cmd->sense_buffer;
1195 void *prot = cmd->prot_sdb;
1196 struct request *rq = blk_mq_rq_from_pdu(cmd);
1197 unsigned int flags = cmd->flags & SCMD_PRESERVED_FLAGS;
1198 unsigned long jiffies_at_alloc;
1199 int retries;
1201 if (!blk_rq_is_scsi(rq) && !(flags & SCMD_INITIALIZED)) {
1202 flags |= SCMD_INITIALIZED;
1203 scsi_initialize_rq(rq);
1206 jiffies_at_alloc = cmd->jiffies_at_alloc;
1207 retries = cmd->retries;
1208 /* zero out the cmd, except for the embedded scsi_request */
1209 memset((char *)cmd + sizeof(cmd->req), 0,
1210 sizeof(*cmd) - sizeof(cmd->req) + dev->host->hostt->cmd_size);
1212 cmd->device = dev;
1213 cmd->sense_buffer = buf;
1214 cmd->prot_sdb = prot;
1215 cmd->flags = flags;
1216 INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
1217 cmd->jiffies_at_alloc = jiffies_at_alloc;
1218 cmd->retries = retries;
1220 scsi_add_cmd_to_list(cmd);
1223 static int scsi_setup_scsi_cmnd(struct scsi_device *sdev, struct request *req)
1225 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1228 * Passthrough requests may transfer data, in which case they must
1229 * a bio attached to them. Or they might contain a SCSI command
1230 * that does not transfer data, in which case they may optionally
1231 * submit a request without an attached bio.
1233 if (req->bio) {
1234 int ret = scsi_init_io(cmd);
1235 if (unlikely(ret))
1236 return ret;
1237 } else {
1238 BUG_ON(blk_rq_bytes(req));
1240 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1243 cmd->cmd_len = scsi_req(req)->cmd_len;
1244 cmd->cmnd = scsi_req(req)->cmd;
1245 cmd->transfersize = blk_rq_bytes(req);
1246 cmd->allowed = scsi_req(req)->retries;
1247 return BLKPREP_OK;
1251 * Setup a normal block command. These are simple request from filesystems
1252 * that still need to be translated to SCSI CDBs from the ULD.
1254 static int scsi_setup_fs_cmnd(struct scsi_device *sdev, struct request *req)
1256 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1258 if (unlikely(sdev->handler && sdev->handler->prep_fn)) {
1259 int ret = sdev->handler->prep_fn(sdev, req);
1260 if (ret != BLKPREP_OK)
1261 return ret;
1264 cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd;
1265 memset(cmd->cmnd, 0, BLK_MAX_CDB);
1266 return scsi_cmd_to_driver(cmd)->init_command(cmd);
1269 static int scsi_setup_cmnd(struct scsi_device *sdev, struct request *req)
1271 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1273 if (!blk_rq_bytes(req))
1274 cmd->sc_data_direction = DMA_NONE;
1275 else if (rq_data_dir(req) == WRITE)
1276 cmd->sc_data_direction = DMA_TO_DEVICE;
1277 else
1278 cmd->sc_data_direction = DMA_FROM_DEVICE;
1280 if (blk_rq_is_scsi(req))
1281 return scsi_setup_scsi_cmnd(sdev, req);
1282 else
1283 return scsi_setup_fs_cmnd(sdev, req);
1286 static int
1287 scsi_prep_state_check(struct scsi_device *sdev, struct request *req)
1289 int ret = BLKPREP_OK;
1292 * If the device is not in running state we will reject some
1293 * or all commands.
1295 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1296 switch (sdev->sdev_state) {
1297 case SDEV_OFFLINE:
1298 case SDEV_TRANSPORT_OFFLINE:
1300 * If the device is offline we refuse to process any
1301 * commands. The device must be brought online
1302 * before trying any recovery commands.
1304 sdev_printk(KERN_ERR, sdev,
1305 "rejecting I/O to offline device\n");
1306 ret = BLKPREP_KILL;
1307 break;
1308 case SDEV_DEL:
1310 * If the device is fully deleted, we refuse to
1311 * process any commands as well.
1313 sdev_printk(KERN_ERR, sdev,
1314 "rejecting I/O to dead device\n");
1315 ret = BLKPREP_KILL;
1316 break;
1317 case SDEV_BLOCK:
1318 case SDEV_CREATED_BLOCK:
1319 ret = BLKPREP_DEFER;
1320 break;
1321 case SDEV_QUIESCE:
1323 * If the devices is blocked we defer normal commands.
1325 if (req && !(req->rq_flags & RQF_PREEMPT))
1326 ret = BLKPREP_DEFER;
1327 break;
1328 default:
1330 * For any other not fully online state we only allow
1331 * special commands. In particular any user initiated
1332 * command is not allowed.
1334 if (req && !(req->rq_flags & RQF_PREEMPT))
1335 ret = BLKPREP_KILL;
1336 break;
1339 return ret;
1342 static int
1343 scsi_prep_return(struct request_queue *q, struct request *req, int ret)
1345 struct scsi_device *sdev = q->queuedata;
1347 switch (ret) {
1348 case BLKPREP_KILL:
1349 case BLKPREP_INVALID:
1350 scsi_req(req)->result = DID_NO_CONNECT << 16;
1351 /* release the command and kill it */
1352 if (req->special) {
1353 struct scsi_cmnd *cmd = req->special;
1354 scsi_release_buffers(cmd);
1355 scsi_put_command(cmd);
1356 put_device(&sdev->sdev_gendev);
1357 req->special = NULL;
1359 break;
1360 case BLKPREP_DEFER:
1362 * If we defer, the blk_peek_request() returns NULL, but the
1363 * queue must be restarted, so we schedule a callback to happen
1364 * shortly.
1366 if (atomic_read(&sdev->device_busy) == 0)
1367 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1368 break;
1369 default:
1370 req->rq_flags |= RQF_DONTPREP;
1373 return ret;
1376 static int scsi_prep_fn(struct request_queue *q, struct request *req)
1378 struct scsi_device *sdev = q->queuedata;
1379 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1380 int ret;
1382 ret = scsi_prep_state_check(sdev, req);
1383 if (ret != BLKPREP_OK)
1384 goto out;
1386 if (!req->special) {
1387 /* Bail if we can't get a reference to the device */
1388 if (unlikely(!get_device(&sdev->sdev_gendev))) {
1389 ret = BLKPREP_DEFER;
1390 goto out;
1393 scsi_init_command(sdev, cmd);
1394 req->special = cmd;
1397 cmd->tag = req->tag;
1398 cmd->request = req;
1399 cmd->prot_op = SCSI_PROT_NORMAL;
1401 ret = scsi_setup_cmnd(sdev, req);
1402 out:
1403 return scsi_prep_return(q, req, ret);
1406 static void scsi_unprep_fn(struct request_queue *q, struct request *req)
1408 scsi_uninit_cmd(blk_mq_rq_to_pdu(req));
1412 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1413 * return 0.
1415 * Called with the queue_lock held.
1417 static inline int scsi_dev_queue_ready(struct request_queue *q,
1418 struct scsi_device *sdev)
1420 unsigned int busy;
1422 busy = atomic_inc_return(&sdev->device_busy) - 1;
1423 if (atomic_read(&sdev->device_blocked)) {
1424 if (busy)
1425 goto out_dec;
1428 * unblock after device_blocked iterates to zero
1430 if (atomic_dec_return(&sdev->device_blocked) > 0) {
1432 * For the MQ case we take care of this in the caller.
1434 if (!q->mq_ops)
1435 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1436 goto out_dec;
1438 SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev,
1439 "unblocking device at zero depth\n"));
1442 if (busy >= sdev->queue_depth)
1443 goto out_dec;
1445 return 1;
1446 out_dec:
1447 atomic_dec(&sdev->device_busy);
1448 return 0;
1452 * scsi_target_queue_ready: checks if there we can send commands to target
1453 * @sdev: scsi device on starget to check.
1455 static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1456 struct scsi_device *sdev)
1458 struct scsi_target *starget = scsi_target(sdev);
1459 unsigned int busy;
1461 if (starget->single_lun) {
1462 spin_lock_irq(shost->host_lock);
1463 if (starget->starget_sdev_user &&
1464 starget->starget_sdev_user != sdev) {
1465 spin_unlock_irq(shost->host_lock);
1466 return 0;
1468 starget->starget_sdev_user = sdev;
1469 spin_unlock_irq(shost->host_lock);
1472 if (starget->can_queue <= 0)
1473 return 1;
1475 busy = atomic_inc_return(&starget->target_busy) - 1;
1476 if (atomic_read(&starget->target_blocked) > 0) {
1477 if (busy)
1478 goto starved;
1481 * unblock after target_blocked iterates to zero
1483 if (atomic_dec_return(&starget->target_blocked) > 0)
1484 goto out_dec;
1486 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1487 "unblocking target at zero depth\n"));
1490 if (busy >= starget->can_queue)
1491 goto starved;
1493 return 1;
1495 starved:
1496 spin_lock_irq(shost->host_lock);
1497 list_move_tail(&sdev->starved_entry, &shost->starved_list);
1498 spin_unlock_irq(shost->host_lock);
1499 out_dec:
1500 if (starget->can_queue > 0)
1501 atomic_dec(&starget->target_busy);
1502 return 0;
1506 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1507 * return 0. We must end up running the queue again whenever 0 is
1508 * returned, else IO can hang.
1510 static inline int scsi_host_queue_ready(struct request_queue *q,
1511 struct Scsi_Host *shost,
1512 struct scsi_device *sdev)
1514 unsigned int busy;
1516 if (scsi_host_in_recovery(shost))
1517 return 0;
1519 busy = atomic_inc_return(&shost->host_busy) - 1;
1520 if (atomic_read(&shost->host_blocked) > 0) {
1521 if (busy)
1522 goto starved;
1525 * unblock after host_blocked iterates to zero
1527 if (atomic_dec_return(&shost->host_blocked) > 0)
1528 goto out_dec;
1530 SCSI_LOG_MLQUEUE(3,
1531 shost_printk(KERN_INFO, shost,
1532 "unblocking host at zero depth\n"));
1535 if (shost->can_queue > 0 && busy >= shost->can_queue)
1536 goto starved;
1537 if (shost->host_self_blocked)
1538 goto starved;
1540 /* We're OK to process the command, so we can't be starved */
1541 if (!list_empty(&sdev->starved_entry)) {
1542 spin_lock_irq(shost->host_lock);
1543 if (!list_empty(&sdev->starved_entry))
1544 list_del_init(&sdev->starved_entry);
1545 spin_unlock_irq(shost->host_lock);
1548 return 1;
1550 starved:
1551 spin_lock_irq(shost->host_lock);
1552 if (list_empty(&sdev->starved_entry))
1553 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1554 spin_unlock_irq(shost->host_lock);
1555 out_dec:
1556 scsi_dec_host_busy(shost);
1557 return 0;
1561 * Busy state exporting function for request stacking drivers.
1563 * For efficiency, no lock is taken to check the busy state of
1564 * shost/starget/sdev, since the returned value is not guaranteed and
1565 * may be changed after request stacking drivers call the function,
1566 * regardless of taking lock or not.
1568 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1569 * needs to return 'not busy'. Otherwise, request stacking drivers
1570 * may hold requests forever.
1572 static int scsi_lld_busy(struct request_queue *q)
1574 struct scsi_device *sdev = q->queuedata;
1575 struct Scsi_Host *shost;
1577 if (blk_queue_dying(q))
1578 return 0;
1580 shost = sdev->host;
1583 * Ignore host/starget busy state.
1584 * Since block layer does not have a concept of fairness across
1585 * multiple queues, congestion of host/starget needs to be handled
1586 * in SCSI layer.
1588 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
1589 return 1;
1591 return 0;
1595 * Kill a request for a dead device
1597 static void scsi_kill_request(struct request *req, struct request_queue *q)
1599 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1600 struct scsi_device *sdev;
1601 struct scsi_target *starget;
1602 struct Scsi_Host *shost;
1604 blk_start_request(req);
1606 scmd_printk(KERN_INFO, cmd, "killing request\n");
1608 sdev = cmd->device;
1609 starget = scsi_target(sdev);
1610 shost = sdev->host;
1611 scsi_init_cmd_errh(cmd);
1612 cmd->result = DID_NO_CONNECT << 16;
1613 atomic_inc(&cmd->device->iorequest_cnt);
1616 * SCSI request completion path will do scsi_device_unbusy(),
1617 * bump busy counts. To bump the counters, we need to dance
1618 * with the locks as normal issue path does.
1620 atomic_inc(&sdev->device_busy);
1621 atomic_inc(&shost->host_busy);
1622 if (starget->can_queue > 0)
1623 atomic_inc(&starget->target_busy);
1625 blk_complete_request(req);
1628 static void scsi_softirq_done(struct request *rq)
1630 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1631 unsigned long wait_for = (cmd->allowed + 1) * rq->timeout;
1632 int disposition;
1634 INIT_LIST_HEAD(&cmd->eh_entry);
1636 atomic_inc(&cmd->device->iodone_cnt);
1637 if (cmd->result)
1638 atomic_inc(&cmd->device->ioerr_cnt);
1640 disposition = scsi_decide_disposition(cmd);
1641 if (disposition != SUCCESS &&
1642 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1643 sdev_printk(KERN_ERR, cmd->device,
1644 "timing out command, waited %lus\n",
1645 wait_for/HZ);
1646 disposition = SUCCESS;
1649 scsi_log_completion(cmd, disposition);
1651 switch (disposition) {
1652 case SUCCESS:
1653 scsi_finish_command(cmd);
1654 break;
1655 case NEEDS_RETRY:
1656 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1657 break;
1658 case ADD_TO_MLQUEUE:
1659 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1660 break;
1661 default:
1662 scsi_eh_scmd_add(cmd);
1663 break;
1668 * scsi_dispatch_command - Dispatch a command to the low-level driver.
1669 * @cmd: command block we are dispatching.
1671 * Return: nonzero return request was rejected and device's queue needs to be
1672 * plugged.
1674 static int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
1676 struct Scsi_Host *host = cmd->device->host;
1677 int rtn = 0;
1679 atomic_inc(&cmd->device->iorequest_cnt);
1681 /* check if the device is still usable */
1682 if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
1683 /* in SDEV_DEL we error all commands. DID_NO_CONNECT
1684 * returns an immediate error upwards, and signals
1685 * that the device is no longer present */
1686 cmd->result = DID_NO_CONNECT << 16;
1687 goto done;
1690 /* Check to see if the scsi lld made this device blocked. */
1691 if (unlikely(scsi_device_blocked(cmd->device))) {
1693 * in blocked state, the command is just put back on
1694 * the device queue. The suspend state has already
1695 * blocked the queue so future requests should not
1696 * occur until the device transitions out of the
1697 * suspend state.
1699 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1700 "queuecommand : device blocked\n"));
1701 return SCSI_MLQUEUE_DEVICE_BUSY;
1704 /* Store the LUN value in cmnd, if needed. */
1705 if (cmd->device->lun_in_cdb)
1706 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
1707 (cmd->device->lun << 5 & 0xe0);
1709 scsi_log_send(cmd);
1712 * Before we queue this command, check if the command
1713 * length exceeds what the host adapter can handle.
1715 if (cmd->cmd_len > cmd->device->host->max_cmd_len) {
1716 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1717 "queuecommand : command too long. "
1718 "cdb_size=%d host->max_cmd_len=%d\n",
1719 cmd->cmd_len, cmd->device->host->max_cmd_len));
1720 cmd->result = (DID_ABORT << 16);
1721 goto done;
1724 if (unlikely(host->shost_state == SHOST_DEL)) {
1725 cmd->result = (DID_NO_CONNECT << 16);
1726 goto done;
1730 trace_scsi_dispatch_cmd_start(cmd);
1731 rtn = host->hostt->queuecommand(host, cmd);
1732 if (rtn) {
1733 trace_scsi_dispatch_cmd_error(cmd, rtn);
1734 if (rtn != SCSI_MLQUEUE_DEVICE_BUSY &&
1735 rtn != SCSI_MLQUEUE_TARGET_BUSY)
1736 rtn = SCSI_MLQUEUE_HOST_BUSY;
1738 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1739 "queuecommand : request rejected\n"));
1742 return rtn;
1743 done:
1744 cmd->scsi_done(cmd);
1745 return 0;
1749 * scsi_done - Invoke completion on finished SCSI command.
1750 * @cmd: The SCSI Command for which a low-level device driver (LLDD) gives
1751 * ownership back to SCSI Core -- i.e. the LLDD has finished with it.
1753 * Description: This function is the mid-level's (SCSI Core) interrupt routine,
1754 * which regains ownership of the SCSI command (de facto) from a LLDD, and
1755 * calls blk_complete_request() for further processing.
1757 * This function is interrupt context safe.
1759 static void scsi_done(struct scsi_cmnd *cmd)
1761 trace_scsi_dispatch_cmd_done(cmd);
1762 blk_complete_request(cmd->request);
1766 * Function: scsi_request_fn()
1768 * Purpose: Main strategy routine for SCSI.
1770 * Arguments: q - Pointer to actual queue.
1772 * Returns: Nothing
1774 * Lock status: request queue lock assumed to be held when called.
1776 * Note: See sd_zbc.c sd_zbc_write_lock_zone() for write order
1777 * protection for ZBC disks.
1779 static void scsi_request_fn(struct request_queue *q)
1780 __releases(q->queue_lock)
1781 __acquires(q->queue_lock)
1783 struct scsi_device *sdev = q->queuedata;
1784 struct Scsi_Host *shost;
1785 struct scsi_cmnd *cmd;
1786 struct request *req;
1789 * To start with, we keep looping until the queue is empty, or until
1790 * the host is no longer able to accept any more requests.
1792 shost = sdev->host;
1793 for (;;) {
1794 int rtn;
1796 * get next queueable request. We do this early to make sure
1797 * that the request is fully prepared even if we cannot
1798 * accept it.
1800 req = blk_peek_request(q);
1801 if (!req)
1802 break;
1804 if (unlikely(!scsi_device_online(sdev))) {
1805 sdev_printk(KERN_ERR, sdev,
1806 "rejecting I/O to offline device\n");
1807 scsi_kill_request(req, q);
1808 continue;
1811 if (!scsi_dev_queue_ready(q, sdev))
1812 break;
1815 * Remove the request from the request list.
1817 if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
1818 blk_start_request(req);
1820 spin_unlock_irq(q->queue_lock);
1821 cmd = blk_mq_rq_to_pdu(req);
1822 if (cmd != req->special) {
1823 printk(KERN_CRIT "impossible request in %s.\n"
1824 "please mail a stack trace to "
1825 "linux-scsi@vger.kernel.org\n",
1826 __func__);
1827 blk_dump_rq_flags(req, "foo");
1828 BUG();
1832 * We hit this when the driver is using a host wide
1833 * tag map. For device level tag maps the queue_depth check
1834 * in the device ready fn would prevent us from trying
1835 * to allocate a tag. Since the map is a shared host resource
1836 * we add the dev to the starved list so it eventually gets
1837 * a run when a tag is freed.
1839 if (blk_queue_tagged(q) && !(req->rq_flags & RQF_QUEUED)) {
1840 spin_lock_irq(shost->host_lock);
1841 if (list_empty(&sdev->starved_entry))
1842 list_add_tail(&sdev->starved_entry,
1843 &shost->starved_list);
1844 spin_unlock_irq(shost->host_lock);
1845 goto not_ready;
1848 if (!scsi_target_queue_ready(shost, sdev))
1849 goto not_ready;
1851 if (!scsi_host_queue_ready(q, shost, sdev))
1852 goto host_not_ready;
1854 if (sdev->simple_tags)
1855 cmd->flags |= SCMD_TAGGED;
1856 else
1857 cmd->flags &= ~SCMD_TAGGED;
1860 * Finally, initialize any error handling parameters, and set up
1861 * the timers for timeouts.
1863 scsi_init_cmd_errh(cmd);
1866 * Dispatch the command to the low-level driver.
1868 cmd->scsi_done = scsi_done;
1869 rtn = scsi_dispatch_cmd(cmd);
1870 if (rtn) {
1871 scsi_queue_insert(cmd, rtn);
1872 spin_lock_irq(q->queue_lock);
1873 goto out_delay;
1875 spin_lock_irq(q->queue_lock);
1878 return;
1880 host_not_ready:
1881 if (scsi_target(sdev)->can_queue > 0)
1882 atomic_dec(&scsi_target(sdev)->target_busy);
1883 not_ready:
1885 * lock q, handle tag, requeue req, and decrement device_busy. We
1886 * must return with queue_lock held.
1888 * Decrementing device_busy without checking it is OK, as all such
1889 * cases (host limits or settings) should run the queue at some
1890 * later time.
1892 spin_lock_irq(q->queue_lock);
1893 blk_requeue_request(q, req);
1894 atomic_dec(&sdev->device_busy);
1895 out_delay:
1896 if (!atomic_read(&sdev->device_busy) && !scsi_device_blocked(sdev))
1897 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1900 static inline blk_status_t prep_to_mq(int ret)
1902 switch (ret) {
1903 case BLKPREP_OK:
1904 return BLK_STS_OK;
1905 case BLKPREP_DEFER:
1906 return BLK_STS_RESOURCE;
1907 default:
1908 return BLK_STS_IOERR;
1912 /* Size in bytes of the sg-list stored in the scsi-mq command-private data. */
1913 static unsigned int scsi_mq_sgl_size(struct Scsi_Host *shost)
1915 return min_t(unsigned int, shost->sg_tablesize, SG_CHUNK_SIZE) *
1916 sizeof(struct scatterlist);
1919 static int scsi_mq_prep_fn(struct request *req)
1921 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1922 struct scsi_device *sdev = req->q->queuedata;
1923 struct Scsi_Host *shost = sdev->host;
1924 struct scatterlist *sg;
1926 scsi_init_command(sdev, cmd);
1928 req->special = cmd;
1930 cmd->request = req;
1932 cmd->tag = req->tag;
1933 cmd->prot_op = SCSI_PROT_NORMAL;
1935 sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
1936 cmd->sdb.table.sgl = sg;
1938 if (scsi_host_get_prot(shost)) {
1939 memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer));
1941 cmd->prot_sdb->table.sgl =
1942 (struct scatterlist *)(cmd->prot_sdb + 1);
1945 if (blk_bidi_rq(req)) {
1946 struct request *next_rq = req->next_rq;
1947 struct scsi_data_buffer *bidi_sdb = blk_mq_rq_to_pdu(next_rq);
1949 memset(bidi_sdb, 0, sizeof(struct scsi_data_buffer));
1950 bidi_sdb->table.sgl =
1951 (struct scatterlist *)(bidi_sdb + 1);
1953 next_rq->special = bidi_sdb;
1956 blk_mq_start_request(req);
1958 return scsi_setup_cmnd(sdev, req);
1961 static void scsi_mq_done(struct scsi_cmnd *cmd)
1963 trace_scsi_dispatch_cmd_done(cmd);
1964 blk_mq_complete_request(cmd->request);
1967 static void scsi_mq_put_budget(struct blk_mq_hw_ctx *hctx)
1969 struct request_queue *q = hctx->queue;
1970 struct scsi_device *sdev = q->queuedata;
1972 atomic_dec(&sdev->device_busy);
1973 put_device(&sdev->sdev_gendev);
1976 static bool scsi_mq_get_budget(struct blk_mq_hw_ctx *hctx)
1978 struct request_queue *q = hctx->queue;
1979 struct scsi_device *sdev = q->queuedata;
1981 if (!get_device(&sdev->sdev_gendev))
1982 goto out;
1983 if (!scsi_dev_queue_ready(q, sdev))
1984 goto out_put_device;
1986 return true;
1988 out_put_device:
1989 put_device(&sdev->sdev_gendev);
1990 out:
1991 if (atomic_read(&sdev->device_busy) == 0 && !scsi_device_blocked(sdev))
1992 blk_mq_delay_run_hw_queue(hctx, SCSI_QUEUE_DELAY);
1993 return false;
1996 static blk_status_t scsi_queue_rq(struct blk_mq_hw_ctx *hctx,
1997 const struct blk_mq_queue_data *bd)
1999 struct request *req = bd->rq;
2000 struct request_queue *q = req->q;
2001 struct scsi_device *sdev = q->queuedata;
2002 struct Scsi_Host *shost = sdev->host;
2003 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
2004 blk_status_t ret;
2005 int reason;
2007 ret = prep_to_mq(scsi_prep_state_check(sdev, req));
2008 if (ret != BLK_STS_OK)
2009 goto out_put_budget;
2011 ret = BLK_STS_RESOURCE;
2012 if (!scsi_target_queue_ready(shost, sdev))
2013 goto out_put_budget;
2014 if (!scsi_host_queue_ready(q, shost, sdev))
2015 goto out_dec_target_busy;
2017 if (!(req->rq_flags & RQF_DONTPREP)) {
2018 ret = prep_to_mq(scsi_mq_prep_fn(req));
2019 if (ret != BLK_STS_OK)
2020 goto out_dec_host_busy;
2021 req->rq_flags |= RQF_DONTPREP;
2022 } else {
2023 blk_mq_start_request(req);
2026 if (sdev->simple_tags)
2027 cmd->flags |= SCMD_TAGGED;
2028 else
2029 cmd->flags &= ~SCMD_TAGGED;
2031 scsi_init_cmd_errh(cmd);
2032 cmd->scsi_done = scsi_mq_done;
2034 reason = scsi_dispatch_cmd(cmd);
2035 if (reason) {
2036 scsi_set_blocked(cmd, reason);
2037 ret = BLK_STS_RESOURCE;
2038 goto out_dec_host_busy;
2041 return BLK_STS_OK;
2043 out_dec_host_busy:
2044 scsi_dec_host_busy(shost);
2045 out_dec_target_busy:
2046 if (scsi_target(sdev)->can_queue > 0)
2047 atomic_dec(&scsi_target(sdev)->target_busy);
2048 out_put_budget:
2049 scsi_mq_put_budget(hctx);
2050 switch (ret) {
2051 case BLK_STS_OK:
2052 break;
2053 case BLK_STS_RESOURCE:
2054 if (atomic_read(&sdev->device_busy) ||
2055 scsi_device_blocked(sdev))
2056 ret = BLK_STS_DEV_RESOURCE;
2057 break;
2058 default:
2060 * Make sure to release all allocated ressources when
2061 * we hit an error, as we will never see this command
2062 * again.
2064 if (req->rq_flags & RQF_DONTPREP)
2065 scsi_mq_uninit_cmd(cmd);
2066 break;
2068 return ret;
2071 static enum blk_eh_timer_return scsi_timeout(struct request *req,
2072 bool reserved)
2074 if (reserved)
2075 return BLK_EH_RESET_TIMER;
2076 return scsi_times_out(req);
2079 static int scsi_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
2080 unsigned int hctx_idx, unsigned int numa_node)
2082 struct Scsi_Host *shost = set->driver_data;
2083 const bool unchecked_isa_dma = shost->unchecked_isa_dma;
2084 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2085 struct scatterlist *sg;
2087 if (unchecked_isa_dma)
2088 cmd->flags |= SCMD_UNCHECKED_ISA_DMA;
2089 cmd->sense_buffer = scsi_alloc_sense_buffer(unchecked_isa_dma,
2090 GFP_KERNEL, numa_node);
2091 if (!cmd->sense_buffer)
2092 return -ENOMEM;
2093 cmd->req.sense = cmd->sense_buffer;
2095 if (scsi_host_get_prot(shost)) {
2096 sg = (void *)cmd + sizeof(struct scsi_cmnd) +
2097 shost->hostt->cmd_size;
2098 cmd->prot_sdb = (void *)sg + scsi_mq_sgl_size(shost);
2101 return 0;
2104 static void scsi_mq_exit_request(struct blk_mq_tag_set *set, struct request *rq,
2105 unsigned int hctx_idx)
2107 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2109 scsi_free_sense_buffer(cmd->flags & SCMD_UNCHECKED_ISA_DMA,
2110 cmd->sense_buffer);
2113 static int scsi_map_queues(struct blk_mq_tag_set *set)
2115 struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set);
2117 if (shost->hostt->map_queues)
2118 return shost->hostt->map_queues(shost);
2119 return blk_mq_map_queues(set);
2122 static u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
2124 struct device *host_dev;
2125 u64 bounce_limit = 0xffffffff;
2127 if (shost->unchecked_isa_dma)
2128 return BLK_BOUNCE_ISA;
2130 * Platforms with virtual-DMA translation
2131 * hardware have no practical limit.
2133 if (!PCI_DMA_BUS_IS_PHYS)
2134 return BLK_BOUNCE_ANY;
2136 host_dev = scsi_get_device(shost);
2137 if (host_dev && host_dev->dma_mask)
2138 bounce_limit = (u64)dma_max_pfn(host_dev) << PAGE_SHIFT;
2140 return bounce_limit;
2143 void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q)
2145 struct device *dev = shost->dma_dev;
2147 queue_flag_set_unlocked(QUEUE_FLAG_SCSI_PASSTHROUGH, q);
2150 * this limit is imposed by hardware restrictions
2152 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
2153 SG_MAX_SEGMENTS));
2155 if (scsi_host_prot_dma(shost)) {
2156 shost->sg_prot_tablesize =
2157 min_not_zero(shost->sg_prot_tablesize,
2158 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
2159 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
2160 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
2163 blk_queue_max_hw_sectors(q, shost->max_sectors);
2164 blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
2165 blk_queue_segment_boundary(q, shost->dma_boundary);
2166 dma_set_seg_boundary(dev, shost->dma_boundary);
2168 blk_queue_max_segment_size(q, dma_get_max_seg_size(dev));
2170 if (!shost->use_clustering)
2171 q->limits.cluster = 0;
2174 * Set a reasonable default alignment: The larger of 32-byte (dword),
2175 * which is a common minimum for HBAs, and the minimum DMA alignment,
2176 * which is set by the platform.
2178 * Devices that require a bigger alignment can increase it later.
2180 blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1);
2182 EXPORT_SYMBOL_GPL(__scsi_init_queue);
2184 static int scsi_old_init_rq(struct request_queue *q, struct request *rq,
2185 gfp_t gfp)
2187 struct Scsi_Host *shost = q->rq_alloc_data;
2188 const bool unchecked_isa_dma = shost->unchecked_isa_dma;
2189 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2191 memset(cmd, 0, sizeof(*cmd));
2193 if (unchecked_isa_dma)
2194 cmd->flags |= SCMD_UNCHECKED_ISA_DMA;
2195 cmd->sense_buffer = scsi_alloc_sense_buffer(unchecked_isa_dma, gfp,
2196 NUMA_NO_NODE);
2197 if (!cmd->sense_buffer)
2198 goto fail;
2199 cmd->req.sense = cmd->sense_buffer;
2201 if (scsi_host_get_prot(shost) >= SHOST_DIX_TYPE0_PROTECTION) {
2202 cmd->prot_sdb = kmem_cache_zalloc(scsi_sdb_cache, gfp);
2203 if (!cmd->prot_sdb)
2204 goto fail_free_sense;
2207 return 0;
2209 fail_free_sense:
2210 scsi_free_sense_buffer(unchecked_isa_dma, cmd->sense_buffer);
2211 fail:
2212 return -ENOMEM;
2215 static void scsi_old_exit_rq(struct request_queue *q, struct request *rq)
2217 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
2219 if (cmd->prot_sdb)
2220 kmem_cache_free(scsi_sdb_cache, cmd->prot_sdb);
2221 scsi_free_sense_buffer(cmd->flags & SCMD_UNCHECKED_ISA_DMA,
2222 cmd->sense_buffer);
2225 struct request_queue *scsi_old_alloc_queue(struct scsi_device *sdev)
2227 struct Scsi_Host *shost = sdev->host;
2228 struct request_queue *q;
2230 q = blk_alloc_queue_node(GFP_KERNEL, NUMA_NO_NODE);
2231 if (!q)
2232 return NULL;
2233 q->cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
2234 q->rq_alloc_data = shost;
2235 q->request_fn = scsi_request_fn;
2236 q->init_rq_fn = scsi_old_init_rq;
2237 q->exit_rq_fn = scsi_old_exit_rq;
2238 q->initialize_rq_fn = scsi_initialize_rq;
2240 if (blk_init_allocated_queue(q) < 0) {
2241 blk_cleanup_queue(q);
2242 return NULL;
2245 __scsi_init_queue(shost, q);
2246 blk_queue_prep_rq(q, scsi_prep_fn);
2247 blk_queue_unprep_rq(q, scsi_unprep_fn);
2248 blk_queue_softirq_done(q, scsi_softirq_done);
2249 blk_queue_rq_timed_out(q, scsi_times_out);
2250 blk_queue_lld_busy(q, scsi_lld_busy);
2251 return q;
2254 static const struct blk_mq_ops scsi_mq_ops = {
2255 .get_budget = scsi_mq_get_budget,
2256 .put_budget = scsi_mq_put_budget,
2257 .queue_rq = scsi_queue_rq,
2258 .complete = scsi_softirq_done,
2259 .timeout = scsi_timeout,
2260 #ifdef CONFIG_BLK_DEBUG_FS
2261 .show_rq = scsi_show_rq,
2262 #endif
2263 .init_request = scsi_mq_init_request,
2264 .exit_request = scsi_mq_exit_request,
2265 .initialize_rq_fn = scsi_initialize_rq,
2266 .map_queues = scsi_map_queues,
2269 struct request_queue *scsi_mq_alloc_queue(struct scsi_device *sdev)
2271 sdev->request_queue = blk_mq_init_queue(&sdev->host->tag_set);
2272 if (IS_ERR(sdev->request_queue))
2273 return NULL;
2275 sdev->request_queue->queuedata = sdev;
2276 __scsi_init_queue(sdev->host, sdev->request_queue);
2277 return sdev->request_queue;
2280 int scsi_mq_setup_tags(struct Scsi_Host *shost)
2282 unsigned int cmd_size, sgl_size;
2284 sgl_size = scsi_mq_sgl_size(shost);
2285 cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size;
2286 if (scsi_host_get_prot(shost))
2287 cmd_size += sizeof(struct scsi_data_buffer) + sgl_size;
2289 memset(&shost->tag_set, 0, sizeof(shost->tag_set));
2290 shost->tag_set.ops = &scsi_mq_ops;
2291 shost->tag_set.nr_hw_queues = shost->nr_hw_queues ? : 1;
2292 shost->tag_set.queue_depth = shost->can_queue;
2293 shost->tag_set.cmd_size = cmd_size;
2294 shost->tag_set.numa_node = NUMA_NO_NODE;
2295 shost->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2296 shost->tag_set.flags |=
2297 BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy);
2298 shost->tag_set.driver_data = shost;
2300 return blk_mq_alloc_tag_set(&shost->tag_set);
2303 void scsi_mq_destroy_tags(struct Scsi_Host *shost)
2305 blk_mq_free_tag_set(&shost->tag_set);
2309 * scsi_device_from_queue - return sdev associated with a request_queue
2310 * @q: The request queue to return the sdev from
2312 * Return the sdev associated with a request queue or NULL if the
2313 * request_queue does not reference a SCSI device.
2315 struct scsi_device *scsi_device_from_queue(struct request_queue *q)
2317 struct scsi_device *sdev = NULL;
2319 if (q->mq_ops) {
2320 if (q->mq_ops == &scsi_mq_ops)
2321 sdev = q->queuedata;
2322 } else if (q->request_fn == scsi_request_fn)
2323 sdev = q->queuedata;
2324 if (!sdev || !get_device(&sdev->sdev_gendev))
2325 sdev = NULL;
2327 return sdev;
2329 EXPORT_SYMBOL_GPL(scsi_device_from_queue);
2332 * Function: scsi_block_requests()
2334 * Purpose: Utility function used by low-level drivers to prevent further
2335 * commands from being queued to the device.
2337 * Arguments: shost - Host in question
2339 * Returns: Nothing
2341 * Lock status: No locks are assumed held.
2343 * Notes: There is no timer nor any other means by which the requests
2344 * get unblocked other than the low-level driver calling
2345 * scsi_unblock_requests().
2347 void scsi_block_requests(struct Scsi_Host *shost)
2349 shost->host_self_blocked = 1;
2351 EXPORT_SYMBOL(scsi_block_requests);
2354 * Function: scsi_unblock_requests()
2356 * Purpose: Utility function used by low-level drivers to allow further
2357 * commands from being queued to the device.
2359 * Arguments: shost - Host in question
2361 * Returns: Nothing
2363 * Lock status: No locks are assumed held.
2365 * Notes: There is no timer nor any other means by which the requests
2366 * get unblocked other than the low-level driver calling
2367 * scsi_unblock_requests().
2369 * This is done as an API function so that changes to the
2370 * internals of the scsi mid-layer won't require wholesale
2371 * changes to drivers that use this feature.
2373 void scsi_unblock_requests(struct Scsi_Host *shost)
2375 shost->host_self_blocked = 0;
2376 scsi_run_host_queues(shost);
2378 EXPORT_SYMBOL(scsi_unblock_requests);
2380 int __init scsi_init_queue(void)
2382 scsi_sdb_cache = kmem_cache_create("scsi_data_buffer",
2383 sizeof(struct scsi_data_buffer),
2384 0, 0, NULL);
2385 if (!scsi_sdb_cache) {
2386 printk(KERN_ERR "SCSI: can't init scsi sdb cache\n");
2387 return -ENOMEM;
2390 return 0;
2393 void scsi_exit_queue(void)
2395 kmem_cache_destroy(scsi_sense_cache);
2396 kmem_cache_destroy(scsi_sense_isadma_cache);
2397 kmem_cache_destroy(scsi_sdb_cache);
2401 * scsi_mode_select - issue a mode select
2402 * @sdev: SCSI device to be queried
2403 * @pf: Page format bit (1 == standard, 0 == vendor specific)
2404 * @sp: Save page bit (0 == don't save, 1 == save)
2405 * @modepage: mode page being requested
2406 * @buffer: request buffer (may not be smaller than eight bytes)
2407 * @len: length of request buffer.
2408 * @timeout: command timeout
2409 * @retries: number of retries before failing
2410 * @data: returns a structure abstracting the mode header data
2411 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2412 * must be SCSI_SENSE_BUFFERSIZE big.
2414 * Returns zero if successful; negative error number or scsi
2415 * status on error
2419 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
2420 unsigned char *buffer, int len, int timeout, int retries,
2421 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2423 unsigned char cmd[10];
2424 unsigned char *real_buffer;
2425 int ret;
2427 memset(cmd, 0, sizeof(cmd));
2428 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
2430 if (sdev->use_10_for_ms) {
2431 if (len > 65535)
2432 return -EINVAL;
2433 real_buffer = kmalloc(8 + len, GFP_KERNEL);
2434 if (!real_buffer)
2435 return -ENOMEM;
2436 memcpy(real_buffer + 8, buffer, len);
2437 len += 8;
2438 real_buffer[0] = 0;
2439 real_buffer[1] = 0;
2440 real_buffer[2] = data->medium_type;
2441 real_buffer[3] = data->device_specific;
2442 real_buffer[4] = data->longlba ? 0x01 : 0;
2443 real_buffer[5] = 0;
2444 real_buffer[6] = data->block_descriptor_length >> 8;
2445 real_buffer[7] = data->block_descriptor_length;
2447 cmd[0] = MODE_SELECT_10;
2448 cmd[7] = len >> 8;
2449 cmd[8] = len;
2450 } else {
2451 if (len > 255 || data->block_descriptor_length > 255 ||
2452 data->longlba)
2453 return -EINVAL;
2455 real_buffer = kmalloc(4 + len, GFP_KERNEL);
2456 if (!real_buffer)
2457 return -ENOMEM;
2458 memcpy(real_buffer + 4, buffer, len);
2459 len += 4;
2460 real_buffer[0] = 0;
2461 real_buffer[1] = data->medium_type;
2462 real_buffer[2] = data->device_specific;
2463 real_buffer[3] = data->block_descriptor_length;
2466 cmd[0] = MODE_SELECT;
2467 cmd[4] = len;
2470 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
2471 sshdr, timeout, retries, NULL);
2472 kfree(real_buffer);
2473 return ret;
2475 EXPORT_SYMBOL_GPL(scsi_mode_select);
2478 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
2479 * @sdev: SCSI device to be queried
2480 * @dbd: set if mode sense will allow block descriptors to be returned
2481 * @modepage: mode page being requested
2482 * @buffer: request buffer (may not be smaller than eight bytes)
2483 * @len: length of request buffer.
2484 * @timeout: command timeout
2485 * @retries: number of retries before failing
2486 * @data: returns a structure abstracting the mode header data
2487 * @sshdr: place to put sense data (or NULL if no sense to be collected).
2488 * must be SCSI_SENSE_BUFFERSIZE big.
2490 * Returns zero if unsuccessful, or the header offset (either 4
2491 * or 8 depending on whether a six or ten byte command was
2492 * issued) if successful.
2495 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
2496 unsigned char *buffer, int len, int timeout, int retries,
2497 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2499 unsigned char cmd[12];
2500 int use_10_for_ms;
2501 int header_length;
2502 int result, retry_count = retries;
2503 struct scsi_sense_hdr my_sshdr;
2505 memset(data, 0, sizeof(*data));
2506 memset(&cmd[0], 0, 12);
2507 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
2508 cmd[2] = modepage;
2510 /* caller might not be interested in sense, but we need it */
2511 if (!sshdr)
2512 sshdr = &my_sshdr;
2514 retry:
2515 use_10_for_ms = sdev->use_10_for_ms;
2517 if (use_10_for_ms) {
2518 if (len < 8)
2519 len = 8;
2521 cmd[0] = MODE_SENSE_10;
2522 cmd[8] = len;
2523 header_length = 8;
2524 } else {
2525 if (len < 4)
2526 len = 4;
2528 cmd[0] = MODE_SENSE;
2529 cmd[4] = len;
2530 header_length = 4;
2533 memset(buffer, 0, len);
2535 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
2536 sshdr, timeout, retries, NULL);
2538 /* This code looks awful: what it's doing is making sure an
2539 * ILLEGAL REQUEST sense return identifies the actual command
2540 * byte as the problem. MODE_SENSE commands can return
2541 * ILLEGAL REQUEST if the code page isn't supported */
2543 if (use_10_for_ms && !scsi_status_is_good(result) &&
2544 (driver_byte(result) & DRIVER_SENSE)) {
2545 if (scsi_sense_valid(sshdr)) {
2546 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
2547 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
2549 * Invalid command operation code
2551 sdev->use_10_for_ms = 0;
2552 goto retry;
2557 if(scsi_status_is_good(result)) {
2558 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
2559 (modepage == 6 || modepage == 8))) {
2560 /* Initio breakage? */
2561 header_length = 0;
2562 data->length = 13;
2563 data->medium_type = 0;
2564 data->device_specific = 0;
2565 data->longlba = 0;
2566 data->block_descriptor_length = 0;
2567 } else if(use_10_for_ms) {
2568 data->length = buffer[0]*256 + buffer[1] + 2;
2569 data->medium_type = buffer[2];
2570 data->device_specific = buffer[3];
2571 data->longlba = buffer[4] & 0x01;
2572 data->block_descriptor_length = buffer[6]*256
2573 + buffer[7];
2574 } else {
2575 data->length = buffer[0] + 1;
2576 data->medium_type = buffer[1];
2577 data->device_specific = buffer[2];
2578 data->block_descriptor_length = buffer[3];
2580 data->header_length = header_length;
2581 } else if ((status_byte(result) == CHECK_CONDITION) &&
2582 scsi_sense_valid(sshdr) &&
2583 sshdr->sense_key == UNIT_ATTENTION && retry_count) {
2584 retry_count--;
2585 goto retry;
2588 return result;
2590 EXPORT_SYMBOL(scsi_mode_sense);
2593 * scsi_test_unit_ready - test if unit is ready
2594 * @sdev: scsi device to change the state of.
2595 * @timeout: command timeout
2596 * @retries: number of retries before failing
2597 * @sshdr: outpout pointer for decoded sense information.
2599 * Returns zero if unsuccessful or an error if TUR failed. For
2600 * removable media, UNIT_ATTENTION sets ->changed flag.
2603 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2604 struct scsi_sense_hdr *sshdr)
2606 char cmd[] = {
2607 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2609 int result;
2611 /* try to eat the UNIT_ATTENTION if there are enough retries */
2612 do {
2613 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
2614 timeout, retries, NULL);
2615 if (sdev->removable && scsi_sense_valid(sshdr) &&
2616 sshdr->sense_key == UNIT_ATTENTION)
2617 sdev->changed = 1;
2618 } while (scsi_sense_valid(sshdr) &&
2619 sshdr->sense_key == UNIT_ATTENTION && --retries);
2621 return result;
2623 EXPORT_SYMBOL(scsi_test_unit_ready);
2626 * scsi_device_set_state - Take the given device through the device state model.
2627 * @sdev: scsi device to change the state of.
2628 * @state: state to change to.
2630 * Returns zero if successful or an error if the requested
2631 * transition is illegal.
2634 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2636 enum scsi_device_state oldstate = sdev->sdev_state;
2638 if (state == oldstate)
2639 return 0;
2641 switch (state) {
2642 case SDEV_CREATED:
2643 switch (oldstate) {
2644 case SDEV_CREATED_BLOCK:
2645 break;
2646 default:
2647 goto illegal;
2649 break;
2651 case SDEV_RUNNING:
2652 switch (oldstate) {
2653 case SDEV_CREATED:
2654 case SDEV_OFFLINE:
2655 case SDEV_TRANSPORT_OFFLINE:
2656 case SDEV_QUIESCE:
2657 case SDEV_BLOCK:
2658 break;
2659 default:
2660 goto illegal;
2662 break;
2664 case SDEV_QUIESCE:
2665 switch (oldstate) {
2666 case SDEV_RUNNING:
2667 case SDEV_OFFLINE:
2668 case SDEV_TRANSPORT_OFFLINE:
2669 break;
2670 default:
2671 goto illegal;
2673 break;
2675 case SDEV_OFFLINE:
2676 case SDEV_TRANSPORT_OFFLINE:
2677 switch (oldstate) {
2678 case SDEV_CREATED:
2679 case SDEV_RUNNING:
2680 case SDEV_QUIESCE:
2681 case SDEV_BLOCK:
2682 break;
2683 default:
2684 goto illegal;
2686 break;
2688 case SDEV_BLOCK:
2689 switch (oldstate) {
2690 case SDEV_RUNNING:
2691 case SDEV_CREATED_BLOCK:
2692 break;
2693 default:
2694 goto illegal;
2696 break;
2698 case SDEV_CREATED_BLOCK:
2699 switch (oldstate) {
2700 case SDEV_CREATED:
2701 break;
2702 default:
2703 goto illegal;
2705 break;
2707 case SDEV_CANCEL:
2708 switch (oldstate) {
2709 case SDEV_CREATED:
2710 case SDEV_RUNNING:
2711 case SDEV_QUIESCE:
2712 case SDEV_OFFLINE:
2713 case SDEV_TRANSPORT_OFFLINE:
2714 break;
2715 default:
2716 goto illegal;
2718 break;
2720 case SDEV_DEL:
2721 switch (oldstate) {
2722 case SDEV_CREATED:
2723 case SDEV_RUNNING:
2724 case SDEV_OFFLINE:
2725 case SDEV_TRANSPORT_OFFLINE:
2726 case SDEV_CANCEL:
2727 case SDEV_BLOCK:
2728 case SDEV_CREATED_BLOCK:
2729 break;
2730 default:
2731 goto illegal;
2733 break;
2736 sdev->sdev_state = state;
2737 return 0;
2739 illegal:
2740 SCSI_LOG_ERROR_RECOVERY(1,
2741 sdev_printk(KERN_ERR, sdev,
2742 "Illegal state transition %s->%s",
2743 scsi_device_state_name(oldstate),
2744 scsi_device_state_name(state))
2746 return -EINVAL;
2748 EXPORT_SYMBOL(scsi_device_set_state);
2751 * sdev_evt_emit - emit a single SCSI device uevent
2752 * @sdev: associated SCSI device
2753 * @evt: event to emit
2755 * Send a single uevent (scsi_event) to the associated scsi_device.
2757 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2759 int idx = 0;
2760 char *envp[3];
2762 switch (evt->evt_type) {
2763 case SDEV_EVT_MEDIA_CHANGE:
2764 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2765 break;
2766 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2767 scsi_rescan_device(&sdev->sdev_gendev);
2768 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
2769 break;
2770 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2771 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
2772 break;
2773 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2774 envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
2775 break;
2776 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2777 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
2778 break;
2779 case SDEV_EVT_LUN_CHANGE_REPORTED:
2780 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
2781 break;
2782 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2783 envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED";
2784 break;
2785 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2786 envp[idx++] = "SDEV_UA=POWER_ON_RESET_OCCURRED";
2787 break;
2788 default:
2789 /* do nothing */
2790 break;
2793 envp[idx++] = NULL;
2795 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2799 * sdev_evt_thread - send a uevent for each scsi event
2800 * @work: work struct for scsi_device
2802 * Dispatch queued events to their associated scsi_device kobjects
2803 * as uevents.
2805 void scsi_evt_thread(struct work_struct *work)
2807 struct scsi_device *sdev;
2808 enum scsi_device_event evt_type;
2809 LIST_HEAD(event_list);
2811 sdev = container_of(work, struct scsi_device, event_work);
2813 for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
2814 if (test_and_clear_bit(evt_type, sdev->pending_events))
2815 sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
2817 while (1) {
2818 struct scsi_event *evt;
2819 struct list_head *this, *tmp;
2820 unsigned long flags;
2822 spin_lock_irqsave(&sdev->list_lock, flags);
2823 list_splice_init(&sdev->event_list, &event_list);
2824 spin_unlock_irqrestore(&sdev->list_lock, flags);
2826 if (list_empty(&event_list))
2827 break;
2829 list_for_each_safe(this, tmp, &event_list) {
2830 evt = list_entry(this, struct scsi_event, node);
2831 list_del(&evt->node);
2832 scsi_evt_emit(sdev, evt);
2833 kfree(evt);
2839 * sdev_evt_send - send asserted event to uevent thread
2840 * @sdev: scsi_device event occurred on
2841 * @evt: event to send
2843 * Assert scsi device event asynchronously.
2845 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2847 unsigned long flags;
2849 #if 0
2850 /* FIXME: currently this check eliminates all media change events
2851 * for polled devices. Need to update to discriminate between AN
2852 * and polled events */
2853 if (!test_bit(evt->evt_type, sdev->supported_events)) {
2854 kfree(evt);
2855 return;
2857 #endif
2859 spin_lock_irqsave(&sdev->list_lock, flags);
2860 list_add_tail(&evt->node, &sdev->event_list);
2861 schedule_work(&sdev->event_work);
2862 spin_unlock_irqrestore(&sdev->list_lock, flags);
2864 EXPORT_SYMBOL_GPL(sdev_evt_send);
2867 * sdev_evt_alloc - allocate a new scsi event
2868 * @evt_type: type of event to allocate
2869 * @gfpflags: GFP flags for allocation
2871 * Allocates and returns a new scsi_event.
2873 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2874 gfp_t gfpflags)
2876 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2877 if (!evt)
2878 return NULL;
2880 evt->evt_type = evt_type;
2881 INIT_LIST_HEAD(&evt->node);
2883 /* evt_type-specific initialization, if any */
2884 switch (evt_type) {
2885 case SDEV_EVT_MEDIA_CHANGE:
2886 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2887 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2888 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2889 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2890 case SDEV_EVT_LUN_CHANGE_REPORTED:
2891 case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2892 case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2893 default:
2894 /* do nothing */
2895 break;
2898 return evt;
2900 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2903 * sdev_evt_send_simple - send asserted event to uevent thread
2904 * @sdev: scsi_device event occurred on
2905 * @evt_type: type of event to send
2906 * @gfpflags: GFP flags for allocation
2908 * Assert scsi device event asynchronously, given an event type.
2910 void sdev_evt_send_simple(struct scsi_device *sdev,
2911 enum scsi_device_event evt_type, gfp_t gfpflags)
2913 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2914 if (!evt) {
2915 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2916 evt_type);
2917 return;
2920 sdev_evt_send(sdev, evt);
2922 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2925 * scsi_request_fn_active() - number of kernel threads inside scsi_request_fn()
2926 * @sdev: SCSI device to count the number of scsi_request_fn() callers for.
2928 static int scsi_request_fn_active(struct scsi_device *sdev)
2930 struct request_queue *q = sdev->request_queue;
2931 int request_fn_active;
2933 WARN_ON_ONCE(sdev->host->use_blk_mq);
2935 spin_lock_irq(q->queue_lock);
2936 request_fn_active = q->request_fn_active;
2937 spin_unlock_irq(q->queue_lock);
2939 return request_fn_active;
2943 * scsi_wait_for_queuecommand() - wait for ongoing queuecommand() calls
2944 * @sdev: SCSI device pointer.
2946 * Wait until the ongoing shost->hostt->queuecommand() calls that are
2947 * invoked from scsi_request_fn() have finished.
2949 static void scsi_wait_for_queuecommand(struct scsi_device *sdev)
2951 WARN_ON_ONCE(sdev->host->use_blk_mq);
2953 while (scsi_request_fn_active(sdev))
2954 msleep(20);
2958 * scsi_device_quiesce - Block user issued commands.
2959 * @sdev: scsi device to quiesce.
2961 * This works by trying to transition to the SDEV_QUIESCE state
2962 * (which must be a legal transition). When the device is in this
2963 * state, only special requests will be accepted, all others will
2964 * be deferred. Since special requests may also be requeued requests,
2965 * a successful return doesn't guarantee the device will be
2966 * totally quiescent.
2968 * Must be called with user context, may sleep.
2970 * Returns zero if unsuccessful or an error if not.
2973 scsi_device_quiesce(struct scsi_device *sdev)
2975 struct request_queue *q = sdev->request_queue;
2976 int err;
2979 * It is allowed to call scsi_device_quiesce() multiple times from
2980 * the same context but concurrent scsi_device_quiesce() calls are
2981 * not allowed.
2983 WARN_ON_ONCE(sdev->quiesced_by && sdev->quiesced_by != current);
2985 blk_set_preempt_only(q);
2987 blk_mq_freeze_queue(q);
2989 * Ensure that the effect of blk_set_preempt_only() will be visible
2990 * for percpu_ref_tryget() callers that occur after the queue
2991 * unfreeze even if the queue was already frozen before this function
2992 * was called. See also https://lwn.net/Articles/573497/.
2994 synchronize_rcu();
2995 blk_mq_unfreeze_queue(q);
2997 mutex_lock(&sdev->state_mutex);
2998 err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2999 if (err == 0)
3000 sdev->quiesced_by = current;
3001 else
3002 blk_clear_preempt_only(q);
3003 mutex_unlock(&sdev->state_mutex);
3005 return err;
3007 EXPORT_SYMBOL(scsi_device_quiesce);
3010 * scsi_device_resume - Restart user issued commands to a quiesced device.
3011 * @sdev: scsi device to resume.
3013 * Moves the device from quiesced back to running and restarts the
3014 * queues.
3016 * Must be called with user context, may sleep.
3018 void scsi_device_resume(struct scsi_device *sdev)
3020 /* check if the device state was mutated prior to resume, and if
3021 * so assume the state is being managed elsewhere (for example
3022 * device deleted during suspend)
3024 mutex_lock(&sdev->state_mutex);
3025 WARN_ON_ONCE(!sdev->quiesced_by);
3026 sdev->quiesced_by = NULL;
3027 blk_clear_preempt_only(sdev->request_queue);
3028 if (sdev->sdev_state == SDEV_QUIESCE)
3029 scsi_device_set_state(sdev, SDEV_RUNNING);
3030 mutex_unlock(&sdev->state_mutex);
3032 EXPORT_SYMBOL(scsi_device_resume);
3034 static void
3035 device_quiesce_fn(struct scsi_device *sdev, void *data)
3037 scsi_device_quiesce(sdev);
3040 void
3041 scsi_target_quiesce(struct scsi_target *starget)
3043 starget_for_each_device(starget, NULL, device_quiesce_fn);
3045 EXPORT_SYMBOL(scsi_target_quiesce);
3047 static void
3048 device_resume_fn(struct scsi_device *sdev, void *data)
3050 scsi_device_resume(sdev);
3053 void
3054 scsi_target_resume(struct scsi_target *starget)
3056 starget_for_each_device(starget, NULL, device_resume_fn);
3058 EXPORT_SYMBOL(scsi_target_resume);
3061 * scsi_internal_device_block_nowait - try to transition to the SDEV_BLOCK state
3062 * @sdev: device to block
3064 * Pause SCSI command processing on the specified device. Does not sleep.
3066 * Returns zero if successful or a negative error code upon failure.
3068 * Notes:
3069 * This routine transitions the device to the SDEV_BLOCK state (which must be
3070 * a legal transition). When the device is in this state, command processing
3071 * is paused until the device leaves the SDEV_BLOCK state. See also
3072 * scsi_internal_device_unblock_nowait().
3074 int scsi_internal_device_block_nowait(struct scsi_device *sdev)
3076 struct request_queue *q = sdev->request_queue;
3077 unsigned long flags;
3078 int err = 0;
3080 err = scsi_device_set_state(sdev, SDEV_BLOCK);
3081 if (err) {
3082 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
3084 if (err)
3085 return err;
3089 * The device has transitioned to SDEV_BLOCK. Stop the
3090 * block layer from calling the midlayer with this device's
3091 * request queue.
3093 if (q->mq_ops) {
3094 blk_mq_quiesce_queue_nowait(q);
3095 } else {
3096 spin_lock_irqsave(q->queue_lock, flags);
3097 blk_stop_queue(q);
3098 spin_unlock_irqrestore(q->queue_lock, flags);
3101 return 0;
3103 EXPORT_SYMBOL_GPL(scsi_internal_device_block_nowait);
3106 * scsi_internal_device_block - try to transition to the SDEV_BLOCK state
3107 * @sdev: device to block
3109 * Pause SCSI command processing on the specified device and wait until all
3110 * ongoing scsi_request_fn() / scsi_queue_rq() calls have finished. May sleep.
3112 * Returns zero if successful or a negative error code upon failure.
3114 * Note:
3115 * This routine transitions the device to the SDEV_BLOCK state (which must be
3116 * a legal transition). When the device is in this state, command processing
3117 * is paused until the device leaves the SDEV_BLOCK state. See also
3118 * scsi_internal_device_unblock().
3120 * To do: avoid that scsi_send_eh_cmnd() calls queuecommand() after
3121 * scsi_internal_device_block() has blocked a SCSI device and also
3122 * remove the rport mutex lock and unlock calls from srp_queuecommand().
3124 static int scsi_internal_device_block(struct scsi_device *sdev)
3126 struct request_queue *q = sdev->request_queue;
3127 int err;
3129 mutex_lock(&sdev->state_mutex);
3130 err = scsi_internal_device_block_nowait(sdev);
3131 if (err == 0) {
3132 if (q->mq_ops)
3133 blk_mq_quiesce_queue(q);
3134 else
3135 scsi_wait_for_queuecommand(sdev);
3137 mutex_unlock(&sdev->state_mutex);
3139 return err;
3142 void scsi_start_queue(struct scsi_device *sdev)
3144 struct request_queue *q = sdev->request_queue;
3145 unsigned long flags;
3147 if (q->mq_ops) {
3148 blk_mq_unquiesce_queue(q);
3149 } else {
3150 spin_lock_irqsave(q->queue_lock, flags);
3151 blk_start_queue(q);
3152 spin_unlock_irqrestore(q->queue_lock, flags);
3157 * scsi_internal_device_unblock_nowait - resume a device after a block request
3158 * @sdev: device to resume
3159 * @new_state: state to set the device to after unblocking
3161 * Restart the device queue for a previously suspended SCSI device. Does not
3162 * sleep.
3164 * Returns zero if successful or a negative error code upon failure.
3166 * Notes:
3167 * This routine transitions the device to the SDEV_RUNNING state or to one of
3168 * the offline states (which must be a legal transition) allowing the midlayer
3169 * to goose the queue for this device.
3171 int scsi_internal_device_unblock_nowait(struct scsi_device *sdev,
3172 enum scsi_device_state new_state)
3175 * Try to transition the scsi device to SDEV_RUNNING or one of the
3176 * offlined states and goose the device queue if successful.
3178 switch (sdev->sdev_state) {
3179 case SDEV_BLOCK:
3180 case SDEV_TRANSPORT_OFFLINE:
3181 sdev->sdev_state = new_state;
3182 break;
3183 case SDEV_CREATED_BLOCK:
3184 if (new_state == SDEV_TRANSPORT_OFFLINE ||
3185 new_state == SDEV_OFFLINE)
3186 sdev->sdev_state = new_state;
3187 else
3188 sdev->sdev_state = SDEV_CREATED;
3189 break;
3190 case SDEV_CANCEL:
3191 case SDEV_OFFLINE:
3192 break;
3193 default:
3194 return -EINVAL;
3196 scsi_start_queue(sdev);
3198 return 0;
3200 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock_nowait);
3203 * scsi_internal_device_unblock - resume a device after a block request
3204 * @sdev: device to resume
3205 * @new_state: state to set the device to after unblocking
3207 * Restart the device queue for a previously suspended SCSI device. May sleep.
3209 * Returns zero if successful or a negative error code upon failure.
3211 * Notes:
3212 * This routine transitions the device to the SDEV_RUNNING state or to one of
3213 * the offline states (which must be a legal transition) allowing the midlayer
3214 * to goose the queue for this device.
3216 static int scsi_internal_device_unblock(struct scsi_device *sdev,
3217 enum scsi_device_state new_state)
3219 int ret;
3221 mutex_lock(&sdev->state_mutex);
3222 ret = scsi_internal_device_unblock_nowait(sdev, new_state);
3223 mutex_unlock(&sdev->state_mutex);
3225 return ret;
3228 static void
3229 device_block(struct scsi_device *sdev, void *data)
3231 scsi_internal_device_block(sdev);
3234 static int
3235 target_block(struct device *dev, void *data)
3237 if (scsi_is_target_device(dev))
3238 starget_for_each_device(to_scsi_target(dev), NULL,
3239 device_block);
3240 return 0;
3243 void
3244 scsi_target_block(struct device *dev)
3246 if (scsi_is_target_device(dev))
3247 starget_for_each_device(to_scsi_target(dev), NULL,
3248 device_block);
3249 else
3250 device_for_each_child(dev, NULL, target_block);
3252 EXPORT_SYMBOL_GPL(scsi_target_block);
3254 static void
3255 device_unblock(struct scsi_device *sdev, void *data)
3257 scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
3260 static int
3261 target_unblock(struct device *dev, void *data)
3263 if (scsi_is_target_device(dev))
3264 starget_for_each_device(to_scsi_target(dev), data,
3265 device_unblock);
3266 return 0;
3269 void
3270 scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
3272 if (scsi_is_target_device(dev))
3273 starget_for_each_device(to_scsi_target(dev), &new_state,
3274 device_unblock);
3275 else
3276 device_for_each_child(dev, &new_state, target_unblock);
3278 EXPORT_SYMBOL_GPL(scsi_target_unblock);
3281 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
3282 * @sgl: scatter-gather list
3283 * @sg_count: number of segments in sg
3284 * @offset: offset in bytes into sg, on return offset into the mapped area
3285 * @len: bytes to map, on return number of bytes mapped
3287 * Returns virtual address of the start of the mapped page
3289 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
3290 size_t *offset, size_t *len)
3292 int i;
3293 size_t sg_len = 0, len_complete = 0;
3294 struct scatterlist *sg;
3295 struct page *page;
3297 WARN_ON(!irqs_disabled());
3299 for_each_sg(sgl, sg, sg_count, i) {
3300 len_complete = sg_len; /* Complete sg-entries */
3301 sg_len += sg->length;
3302 if (sg_len > *offset)
3303 break;
3306 if (unlikely(i == sg_count)) {
3307 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
3308 "elements %d\n",
3309 __func__, sg_len, *offset, sg_count);
3310 WARN_ON(1);
3311 return NULL;
3314 /* Offset starting from the beginning of first page in this sg-entry */
3315 *offset = *offset - len_complete + sg->offset;
3317 /* Assumption: contiguous pages can be accessed as "page + i" */
3318 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
3319 *offset &= ~PAGE_MASK;
3321 /* Bytes in this sg-entry from *offset to the end of the page */
3322 sg_len = PAGE_SIZE - *offset;
3323 if (*len > sg_len)
3324 *len = sg_len;
3326 return kmap_atomic(page);
3328 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
3331 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
3332 * @virt: virtual address to be unmapped
3334 void scsi_kunmap_atomic_sg(void *virt)
3336 kunmap_atomic(virt);
3338 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
3340 void sdev_disable_disk_events(struct scsi_device *sdev)
3342 atomic_inc(&sdev->disk_events_disable_depth);
3344 EXPORT_SYMBOL(sdev_disable_disk_events);
3346 void sdev_enable_disk_events(struct scsi_device *sdev)
3348 if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
3349 return;
3350 atomic_dec(&sdev->disk_events_disable_depth);
3352 EXPORT_SYMBOL(sdev_enable_disk_events);
3355 * scsi_vpd_lun_id - return a unique device identification
3356 * @sdev: SCSI device
3357 * @id: buffer for the identification
3358 * @id_len: length of the buffer
3360 * Copies a unique device identification into @id based
3361 * on the information in the VPD page 0x83 of the device.
3362 * The string will be formatted as a SCSI name string.
3364 * Returns the length of the identification or error on failure.
3365 * If the identifier is longer than the supplied buffer the actual
3366 * identifier length is returned and the buffer is not zero-padded.
3368 int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
3370 u8 cur_id_type = 0xff;
3371 u8 cur_id_size = 0;
3372 const unsigned char *d, *cur_id_str;
3373 const struct scsi_vpd *vpd_pg83;
3374 int id_size = -EINVAL;
3376 rcu_read_lock();
3377 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3378 if (!vpd_pg83) {
3379 rcu_read_unlock();
3380 return -ENXIO;
3384 * Look for the correct descriptor.
3385 * Order of preference for lun descriptor:
3386 * - SCSI name string
3387 * - NAA IEEE Registered Extended
3388 * - EUI-64 based 16-byte
3389 * - EUI-64 based 12-byte
3390 * - NAA IEEE Registered
3391 * - NAA IEEE Extended
3392 * - T10 Vendor ID
3393 * as longer descriptors reduce the likelyhood
3394 * of identification clashes.
3397 /* The id string must be at least 20 bytes + terminating NULL byte */
3398 if (id_len < 21) {
3399 rcu_read_unlock();
3400 return -EINVAL;
3403 memset(id, 0, id_len);
3404 d = vpd_pg83->data + 4;
3405 while (d < vpd_pg83->data + vpd_pg83->len) {
3406 /* Skip designators not referring to the LUN */
3407 if ((d[1] & 0x30) != 0x00)
3408 goto next_desig;
3410 switch (d[1] & 0xf) {
3411 case 0x1:
3412 /* T10 Vendor ID */
3413 if (cur_id_size > d[3])
3414 break;
3415 /* Prefer anything */
3416 if (cur_id_type > 0x01 && cur_id_type != 0xff)
3417 break;
3418 cur_id_size = d[3];
3419 if (cur_id_size + 4 > id_len)
3420 cur_id_size = id_len - 4;
3421 cur_id_str = d + 4;
3422 cur_id_type = d[1] & 0xf;
3423 id_size = snprintf(id, id_len, "t10.%*pE",
3424 cur_id_size, cur_id_str);
3425 break;
3426 case 0x2:
3427 /* EUI-64 */
3428 if (cur_id_size > d[3])
3429 break;
3430 /* Prefer NAA IEEE Registered Extended */
3431 if (cur_id_type == 0x3 &&
3432 cur_id_size == d[3])
3433 break;
3434 cur_id_size = d[3];
3435 cur_id_str = d + 4;
3436 cur_id_type = d[1] & 0xf;
3437 switch (cur_id_size) {
3438 case 8:
3439 id_size = snprintf(id, id_len,
3440 "eui.%8phN",
3441 cur_id_str);
3442 break;
3443 case 12:
3444 id_size = snprintf(id, id_len,
3445 "eui.%12phN",
3446 cur_id_str);
3447 break;
3448 case 16:
3449 id_size = snprintf(id, id_len,
3450 "eui.%16phN",
3451 cur_id_str);
3452 break;
3453 default:
3454 cur_id_size = 0;
3455 break;
3457 break;
3458 case 0x3:
3459 /* NAA */
3460 if (cur_id_size > d[3])
3461 break;
3462 cur_id_size = d[3];
3463 cur_id_str = d + 4;
3464 cur_id_type = d[1] & 0xf;
3465 switch (cur_id_size) {
3466 case 8:
3467 id_size = snprintf(id, id_len,
3468 "naa.%8phN",
3469 cur_id_str);
3470 break;
3471 case 16:
3472 id_size = snprintf(id, id_len,
3473 "naa.%16phN",
3474 cur_id_str);
3475 break;
3476 default:
3477 cur_id_size = 0;
3478 break;
3480 break;
3481 case 0x8:
3482 /* SCSI name string */
3483 if (cur_id_size + 4 > d[3])
3484 break;
3485 /* Prefer others for truncated descriptor */
3486 if (cur_id_size && d[3] > id_len)
3487 break;
3488 cur_id_size = id_size = d[3];
3489 cur_id_str = d + 4;
3490 cur_id_type = d[1] & 0xf;
3491 if (cur_id_size >= id_len)
3492 cur_id_size = id_len - 1;
3493 memcpy(id, cur_id_str, cur_id_size);
3494 /* Decrease priority for truncated descriptor */
3495 if (cur_id_size != id_size)
3496 cur_id_size = 6;
3497 break;
3498 default:
3499 break;
3501 next_desig:
3502 d += d[3] + 4;
3504 rcu_read_unlock();
3506 return id_size;
3508 EXPORT_SYMBOL(scsi_vpd_lun_id);
3511 * scsi_vpd_tpg_id - return a target port group identifier
3512 * @sdev: SCSI device
3514 * Returns the Target Port Group identifier from the information
3515 * froom VPD page 0x83 of the device.
3517 * Returns the identifier or error on failure.
3519 int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
3521 const unsigned char *d;
3522 const struct scsi_vpd *vpd_pg83;
3523 int group_id = -EAGAIN, rel_port = -1;
3525 rcu_read_lock();
3526 vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3527 if (!vpd_pg83) {
3528 rcu_read_unlock();
3529 return -ENXIO;
3532 d = vpd_pg83->data + 4;
3533 while (d < vpd_pg83->data + vpd_pg83->len) {
3534 switch (d[1] & 0xf) {
3535 case 0x4:
3536 /* Relative target port */
3537 rel_port = get_unaligned_be16(&d[6]);
3538 break;
3539 case 0x5:
3540 /* Target port group */
3541 group_id = get_unaligned_be16(&d[6]);
3542 break;
3543 default:
3544 break;
3546 d += d[3] + 4;
3548 rcu_read_unlock();
3550 if (group_id >= 0 && rel_id && rel_port != -1)
3551 *rel_id = rel_port;
3553 return group_id;
3555 EXPORT_SYMBOL(scsi_vpd_tpg_id);