2 * scsi_lib.c Copyright (C) 1999 Eric Youngdale
4 * SCSI queueing library.
5 * Initial versions: Eric Youngdale (eric@andante.org).
6 * Based upon conversations with large numbers
7 * of people at Linux Expo.
10 #include <linux/bio.h>
11 #include <linux/bitops.h>
12 #include <linux/blkdev.h>
13 #include <linux/completion.h>
14 #include <linux/kernel.h>
15 #include <linux/export.h>
16 #include <linux/mempool.h>
17 #include <linux/slab.h>
18 #include <linux/init.h>
19 #include <linux/pci.h>
20 #include <linux/delay.h>
21 #include <linux/hardirq.h>
22 #include <linux/scatterlist.h>
24 #include <scsi/scsi.h>
25 #include <scsi/scsi_cmnd.h>
26 #include <scsi/scsi_dbg.h>
27 #include <scsi/scsi_device.h>
28 #include <scsi/scsi_driver.h>
29 #include <scsi/scsi_eh.h>
30 #include <scsi/scsi_host.h>
32 #include "scsi_priv.h"
33 #include "scsi_logging.h"
36 #define SG_MEMPOOL_NR ARRAY_SIZE(scsi_sg_pools)
37 #define SG_MEMPOOL_SIZE 2
39 struct scsi_host_sg_pool {
42 struct kmem_cache *slab;
46 #define SP(x) { x, "sgpool-" __stringify(x) }
47 #if (SCSI_MAX_SG_SEGMENTS < 32)
48 #error SCSI_MAX_SG_SEGMENTS is too small (must be 32 or greater)
50 static struct scsi_host_sg_pool scsi_sg_pools[] = {
53 #if (SCSI_MAX_SG_SEGMENTS > 32)
55 #if (SCSI_MAX_SG_SEGMENTS > 64)
57 #if (SCSI_MAX_SG_SEGMENTS > 128)
59 #if (SCSI_MAX_SG_SEGMENTS > 256)
60 #error SCSI_MAX_SG_SEGMENTS is too large (256 MAX)
65 SP(SCSI_MAX_SG_SEGMENTS)
69 struct kmem_cache *scsi_sdb_cache;
72 * When to reinvoke queueing after a resource shortage. It's 3 msecs to
73 * not change behaviour from the previous unplug mechanism, experimentation
74 * may prove this needs changing.
76 #define SCSI_QUEUE_DELAY 3
79 * Function: scsi_unprep_request()
81 * Purpose: Remove all preparation done for a request, including its
82 * associated scsi_cmnd, so that it can be requeued.
84 * Arguments: req - request to unprepare
86 * Lock status: Assumed that no locks are held upon entry.
90 static void scsi_unprep_request(struct request *req)
92 struct scsi_cmnd *cmd = req->special;
94 blk_unprep_request(req);
97 scsi_put_command(cmd);
101 * __scsi_queue_insert - private queue insertion
102 * @cmd: The SCSI command being requeued
103 * @reason: The reason for the requeue
104 * @unbusy: Whether the queue should be unbusied
106 * This is a private queue insertion. The public interface
107 * scsi_queue_insert() always assumes the queue should be unbusied
108 * because it's always called before the completion. This function is
109 * for a requeue after completion, which should only occur in this
112 static int __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, int unbusy)
114 struct Scsi_Host *host = cmd->device->host;
115 struct scsi_device *device = cmd->device;
116 struct scsi_target *starget = scsi_target(device);
117 struct request_queue *q = device->request_queue;
121 printk("Inserting command %p into mlqueue\n", cmd));
124 * Set the appropriate busy bit for the device/host.
126 * If the host/device isn't busy, assume that something actually
127 * completed, and that we should be able to queue a command now.
129 * Note that the prior mid-layer assumption that any host could
130 * always queue at least one command is now broken. The mid-layer
131 * will implement a user specifiable stall (see
132 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
133 * if a command is requeued with no other commands outstanding
134 * either for the device or for the host.
137 case SCSI_MLQUEUE_HOST_BUSY:
138 host->host_blocked = host->max_host_blocked;
140 case SCSI_MLQUEUE_DEVICE_BUSY:
141 case SCSI_MLQUEUE_EH_RETRY:
142 device->device_blocked = device->max_device_blocked;
144 case SCSI_MLQUEUE_TARGET_BUSY:
145 starget->target_blocked = starget->max_target_blocked;
150 * Decrement the counters, since these commands are no longer
151 * active on the host/device.
154 scsi_device_unbusy(device);
157 * Requeue this command. It will go before all other commands
158 * that are already in the queue. Schedule requeue work under
159 * lock such that the kblockd_schedule_work() call happens
160 * before blk_cleanup_queue() finishes.
162 spin_lock_irqsave(q->queue_lock, flags);
163 blk_requeue_request(q, cmd->request);
164 kblockd_schedule_work(q, &device->requeue_work);
165 spin_unlock_irqrestore(q->queue_lock, flags);
171 * Function: scsi_queue_insert()
173 * Purpose: Insert a command in the midlevel queue.
175 * Arguments: cmd - command that we are adding to queue.
176 * reason - why we are inserting command to queue.
178 * Lock status: Assumed that lock is not held upon entry.
182 * Notes: We do this for one of two cases. Either the host is busy
183 * and it cannot accept any more commands for the time being,
184 * or the device returned QUEUE_FULL and can accept no more
186 * Notes: This could be called either from an interrupt context or a
187 * normal process context.
189 int scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
191 return __scsi_queue_insert(cmd, reason, 1);
194 * scsi_execute - insert request and wait for the result
197 * @data_direction: data direction
198 * @buffer: data buffer
199 * @bufflen: len of buffer
200 * @sense: optional sense buffer
201 * @timeout: request timeout in seconds
202 * @retries: number of times to retry request
203 * @flags: or into request flags;
204 * @resid: optional residual length
206 * returns the req->errors value which is the scsi_cmnd result
209 int scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
210 int data_direction, void *buffer, unsigned bufflen,
211 unsigned char *sense, int timeout, int retries, int flags,
215 int write = (data_direction == DMA_TO_DEVICE);
216 int ret = DRIVER_ERROR << 24;
218 req = blk_get_request(sdev->request_queue, write, __GFP_WAIT);
222 if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
223 buffer, bufflen, __GFP_WAIT))
226 req->cmd_len = COMMAND_SIZE(cmd[0]);
227 memcpy(req->cmd, cmd, req->cmd_len);
230 req->retries = retries;
231 req->timeout = timeout;
232 req->cmd_type = REQ_TYPE_BLOCK_PC;
233 req->cmd_flags |= flags | REQ_QUIET | REQ_PREEMPT;
236 * head injection *required* here otherwise quiesce won't work
238 blk_execute_rq(req->q, NULL, req, 1);
241 * Some devices (USB mass-storage in particular) may transfer
242 * garbage data together with a residue indicating that the data
243 * is invalid. Prevent the garbage from being misinterpreted
244 * and prevent security leaks by zeroing out the excess data.
246 if (unlikely(req->resid_len > 0 && req->resid_len <= bufflen))
247 memset(buffer + (bufflen - req->resid_len), 0, req->resid_len);
250 *resid = req->resid_len;
253 blk_put_request(req);
257 EXPORT_SYMBOL(scsi_execute);
260 int scsi_execute_req(struct scsi_device *sdev, const unsigned char *cmd,
261 int data_direction, void *buffer, unsigned bufflen,
262 struct scsi_sense_hdr *sshdr, int timeout, int retries,
269 sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
271 return DRIVER_ERROR << 24;
273 result = scsi_execute(sdev, cmd, data_direction, buffer, bufflen,
274 sense, timeout, retries, 0, resid);
276 scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, sshdr);
281 EXPORT_SYMBOL(scsi_execute_req);
284 * Function: scsi_init_cmd_errh()
286 * Purpose: Initialize cmd fields related to error handling.
288 * Arguments: cmd - command that is ready to be queued.
290 * Notes: This function has the job of initializing a number of
291 * fields related to error handling. Typically this will
292 * be called once for each command, as required.
294 static void scsi_init_cmd_errh(struct scsi_cmnd *cmd)
296 cmd->serial_number = 0;
297 scsi_set_resid(cmd, 0);
298 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
299 if (cmd->cmd_len == 0)
300 cmd->cmd_len = scsi_command_size(cmd->cmnd);
303 void scsi_device_unbusy(struct scsi_device *sdev)
305 struct Scsi_Host *shost = sdev->host;
306 struct scsi_target *starget = scsi_target(sdev);
309 spin_lock_irqsave(shost->host_lock, flags);
311 starget->target_busy--;
312 if (unlikely(scsi_host_in_recovery(shost) &&
313 (shost->host_failed || shost->host_eh_scheduled)))
314 scsi_eh_wakeup(shost);
315 spin_unlock(shost->host_lock);
316 spin_lock(sdev->request_queue->queue_lock);
318 spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
322 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
323 * and call blk_run_queue for all the scsi_devices on the target -
324 * including current_sdev first.
326 * Called with *no* scsi locks held.
328 static void scsi_single_lun_run(struct scsi_device *current_sdev)
330 struct Scsi_Host *shost = current_sdev->host;
331 struct scsi_device *sdev, *tmp;
332 struct scsi_target *starget = scsi_target(current_sdev);
335 spin_lock_irqsave(shost->host_lock, flags);
336 starget->starget_sdev_user = NULL;
337 spin_unlock_irqrestore(shost->host_lock, flags);
340 * Call blk_run_queue for all LUNs on the target, starting with
341 * current_sdev. We race with others (to set starget_sdev_user),
342 * but in most cases, we will be first. Ideally, each LU on the
343 * target would get some limited time or requests on the target.
345 blk_run_queue(current_sdev->request_queue);
347 spin_lock_irqsave(shost->host_lock, flags);
348 if (starget->starget_sdev_user)
350 list_for_each_entry_safe(sdev, tmp, &starget->devices,
351 same_target_siblings) {
352 if (sdev == current_sdev)
354 if (scsi_device_get(sdev))
357 spin_unlock_irqrestore(shost->host_lock, flags);
358 blk_run_queue(sdev->request_queue);
359 spin_lock_irqsave(shost->host_lock, flags);
361 scsi_device_put(sdev);
364 spin_unlock_irqrestore(shost->host_lock, flags);
367 static inline int scsi_device_is_busy(struct scsi_device *sdev)
369 if (sdev->device_busy >= sdev->queue_depth || sdev->device_blocked)
375 static inline int scsi_target_is_busy(struct scsi_target *starget)
377 return ((starget->can_queue > 0 &&
378 starget->target_busy >= starget->can_queue) ||
379 starget->target_blocked);
382 static inline int scsi_host_is_busy(struct Scsi_Host *shost)
384 if ((shost->can_queue > 0 && shost->host_busy >= shost->can_queue) ||
385 shost->host_blocked || shost->host_self_blocked)
392 * Function: scsi_run_queue()
394 * Purpose: Select a proper request queue to serve next
396 * Arguments: q - last request's queue
400 * Notes: The previous command was completely finished, start
401 * a new one if possible.
403 static void scsi_run_queue(struct request_queue *q)
405 struct scsi_device *sdev = q->queuedata;
406 struct Scsi_Host *shost;
407 LIST_HEAD(starved_list);
411 if (scsi_target(sdev)->single_lun)
412 scsi_single_lun_run(sdev);
414 spin_lock_irqsave(shost->host_lock, flags);
415 list_splice_init(&shost->starved_list, &starved_list);
417 while (!list_empty(&starved_list)) {
419 * As long as shost is accepting commands and we have
420 * starved queues, call blk_run_queue. scsi_request_fn
421 * drops the queue_lock and can add us back to the
424 * host_lock protects the starved_list and starved_entry.
425 * scsi_request_fn must get the host_lock before checking
426 * or modifying starved_list or starved_entry.
428 if (scsi_host_is_busy(shost))
431 sdev = list_entry(starved_list.next,
432 struct scsi_device, starved_entry);
433 list_del_init(&sdev->starved_entry);
434 if (scsi_target_is_busy(scsi_target(sdev))) {
435 list_move_tail(&sdev->starved_entry,
436 &shost->starved_list);
440 spin_unlock(shost->host_lock);
441 spin_lock(sdev->request_queue->queue_lock);
442 __blk_run_queue(sdev->request_queue);
443 spin_unlock(sdev->request_queue->queue_lock);
444 spin_lock(shost->host_lock);
446 /* put any unprocessed entries back */
447 list_splice(&starved_list, &shost->starved_list);
448 spin_unlock_irqrestore(shost->host_lock, flags);
453 void scsi_requeue_run_queue(struct work_struct *work)
455 struct scsi_device *sdev;
456 struct request_queue *q;
458 sdev = container_of(work, struct scsi_device, requeue_work);
459 q = sdev->request_queue;
464 * Function: scsi_requeue_command()
466 * Purpose: Handle post-processing of completed commands.
468 * Arguments: q - queue to operate on
469 * cmd - command that may need to be requeued.
473 * Notes: After command completion, there may be blocks left
474 * over which weren't finished by the previous command
475 * this can be for a number of reasons - the main one is
476 * I/O errors in the middle of the request, in which case
477 * we need to request the blocks that come after the bad
479 * Notes: Upon return, cmd is a stale pointer.
481 static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
483 struct scsi_device *sdev = cmd->device;
484 struct request *req = cmd->request;
488 * We need to hold a reference on the device to avoid the queue being
489 * killed after the unlock and before scsi_run_queue is invoked which
490 * may happen because scsi_unprep_request() puts the command which
491 * releases its reference on the device.
493 get_device(&sdev->sdev_gendev);
495 spin_lock_irqsave(q->queue_lock, flags);
496 scsi_unprep_request(req);
497 blk_requeue_request(q, req);
498 spin_unlock_irqrestore(q->queue_lock, flags);
502 put_device(&sdev->sdev_gendev);
505 void scsi_next_command(struct scsi_cmnd *cmd)
507 struct scsi_device *sdev = cmd->device;
508 struct request_queue *q = sdev->request_queue;
510 /* need to hold a reference on the device before we let go of the cmd */
511 get_device(&sdev->sdev_gendev);
513 scsi_put_command(cmd);
516 /* ok to remove device now */
517 put_device(&sdev->sdev_gendev);
520 void scsi_run_host_queues(struct Scsi_Host *shost)
522 struct scsi_device *sdev;
524 shost_for_each_device(sdev, shost)
525 scsi_run_queue(sdev->request_queue);
528 static void __scsi_release_buffers(struct scsi_cmnd *, int);
531 * Function: scsi_end_request()
533 * Purpose: Post-processing of completed commands (usually invoked at end
534 * of upper level post-processing and scsi_io_completion).
536 * Arguments: cmd - command that is complete.
537 * error - 0 if I/O indicates success, < 0 for I/O error.
538 * bytes - number of bytes of completed I/O
539 * requeue - indicates whether we should requeue leftovers.
541 * Lock status: Assumed that lock is not held upon entry.
543 * Returns: cmd if requeue required, NULL otherwise.
545 * Notes: This is called for block device requests in order to
546 * mark some number of sectors as complete.
548 * We are guaranteeing that the request queue will be goosed
549 * at some point during this call.
550 * Notes: If cmd was requeued, upon return it will be a stale pointer.
552 static struct scsi_cmnd *scsi_end_request(struct scsi_cmnd *cmd, int error,
553 int bytes, int requeue)
555 struct request_queue *q = cmd->device->request_queue;
556 struct request *req = cmd->request;
559 * If there are blocks left over at the end, set up the command
560 * to queue the remainder of them.
562 if (blk_end_request(req, error, bytes)) {
563 /* kill remainder if no retrys */
564 if (error && scsi_noretry_cmd(cmd))
565 blk_end_request_all(req, error);
569 * Bleah. Leftovers again. Stick the
570 * leftovers in the front of the
571 * queue, and goose the queue again.
573 scsi_release_buffers(cmd);
574 scsi_requeue_command(q, cmd);
582 * This will goose the queue request function at the end, so we don't
583 * need to worry about launching another command.
585 __scsi_release_buffers(cmd, 0);
586 scsi_next_command(cmd);
590 static inline unsigned int scsi_sgtable_index(unsigned short nents)
594 BUG_ON(nents > SCSI_MAX_SG_SEGMENTS);
599 index = get_count_order(nents) - 3;
604 static void scsi_sg_free(struct scatterlist *sgl, unsigned int nents)
606 struct scsi_host_sg_pool *sgp;
608 sgp = scsi_sg_pools + scsi_sgtable_index(nents);
609 mempool_free(sgl, sgp->pool);
612 static struct scatterlist *scsi_sg_alloc(unsigned int nents, gfp_t gfp_mask)
614 struct scsi_host_sg_pool *sgp;
616 sgp = scsi_sg_pools + scsi_sgtable_index(nents);
617 return mempool_alloc(sgp->pool, gfp_mask);
620 static int scsi_alloc_sgtable(struct scsi_data_buffer *sdb, int nents,
627 ret = __sg_alloc_table(&sdb->table, nents, SCSI_MAX_SG_SEGMENTS,
628 gfp_mask, scsi_sg_alloc);
630 __sg_free_table(&sdb->table, SCSI_MAX_SG_SEGMENTS,
636 static void scsi_free_sgtable(struct scsi_data_buffer *sdb)
638 __sg_free_table(&sdb->table, SCSI_MAX_SG_SEGMENTS, scsi_sg_free);
641 static void __scsi_release_buffers(struct scsi_cmnd *cmd, int do_bidi_check)
644 if (cmd->sdb.table.nents)
645 scsi_free_sgtable(&cmd->sdb);
647 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
649 if (do_bidi_check && scsi_bidi_cmnd(cmd)) {
650 struct scsi_data_buffer *bidi_sdb =
651 cmd->request->next_rq->special;
652 scsi_free_sgtable(bidi_sdb);
653 kmem_cache_free(scsi_sdb_cache, bidi_sdb);
654 cmd->request->next_rq->special = NULL;
657 if (scsi_prot_sg_count(cmd))
658 scsi_free_sgtable(cmd->prot_sdb);
662 * Function: scsi_release_buffers()
664 * Purpose: Completion processing for block device I/O requests.
666 * Arguments: cmd - command that we are bailing.
668 * Lock status: Assumed that no lock is held upon entry.
672 * Notes: In the event that an upper level driver rejects a
673 * command, we must release resources allocated during
674 * the __init_io() function. Primarily this would involve
675 * the scatter-gather table, and potentially any bounce
678 void scsi_release_buffers(struct scsi_cmnd *cmd)
680 __scsi_release_buffers(cmd, 1);
682 EXPORT_SYMBOL(scsi_release_buffers);
684 static int __scsi_error_from_host_byte(struct scsi_cmnd *cmd, int result)
688 switch(host_byte(result)) {
689 case DID_TRANSPORT_FAILFAST:
692 case DID_TARGET_FAILURE:
693 cmd->result |= (DID_OK << 16);
696 case DID_NEXUS_FAILURE:
697 cmd->result |= (DID_OK << 16);
709 * Function: scsi_io_completion()
711 * Purpose: Completion processing for block device I/O requests.
713 * Arguments: cmd - command that is finished.
715 * Lock status: Assumed that no lock is held upon entry.
719 * Notes: This function is matched in terms of capabilities to
720 * the function that created the scatter-gather list.
721 * In other words, if there are no bounce buffers
722 * (the normal case for most drivers), we don't need
723 * the logic to deal with cleaning up afterwards.
725 * We must call scsi_end_request(). This will finish off
726 * the specified number of sectors. If we are done, the
727 * command block will be released and the queue function
728 * will be goosed. If we are not done then we have to
729 * figure out what to do next:
731 * a) We can call scsi_requeue_command(). The request
732 * will be unprepared and put back on the queue. Then
733 * a new command will be created for it. This should
734 * be used if we made forward progress, or if we want
735 * to switch from READ(10) to READ(6) for example.
737 * b) We can call scsi_queue_insert(). The request will
738 * be put back on the queue and retried using the same
739 * command as before, possibly after a delay.
741 * c) We can call blk_end_request() with -EIO to fail
742 * the remainder of the request.
744 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
746 int result = cmd->result;
747 struct request_queue *q = cmd->device->request_queue;
748 struct request *req = cmd->request;
750 struct scsi_sense_hdr sshdr;
752 int sense_deferred = 0;
753 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
754 ACTION_DELAYED_RETRY} action;
755 char *description = NULL;
758 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
760 sense_deferred = scsi_sense_is_deferred(&sshdr);
763 if (req->cmd_type == REQ_TYPE_BLOCK_PC) { /* SG_IO ioctl from block level */
764 req->errors = result;
766 if (sense_valid && req->sense) {
768 * SG_IO wants current and deferred errors
770 int len = 8 + cmd->sense_buffer[7];
772 if (len > SCSI_SENSE_BUFFERSIZE)
773 len = SCSI_SENSE_BUFFERSIZE;
774 memcpy(req->sense, cmd->sense_buffer, len);
775 req->sense_len = len;
778 error = __scsi_error_from_host_byte(cmd, result);
781 req->resid_len = scsi_get_resid(cmd);
783 if (scsi_bidi_cmnd(cmd)) {
785 * Bidi commands Must be complete as a whole,
786 * both sides at once.
788 req->next_rq->resid_len = scsi_in(cmd)->resid;
790 scsi_release_buffers(cmd);
791 blk_end_request_all(req, 0);
793 scsi_next_command(cmd);
796 } else if (blk_rq_bytes(req) == 0 && result && !sense_deferred) {
798 * Certain non BLOCK_PC requests are commands that don't
799 * actually transfer anything (FLUSH), so cannot use
800 * good_bytes != blk_rq_bytes(req) as the signal for an error.
801 * This sets the error explicitly for the problem case.
803 error = __scsi_error_from_host_byte(cmd, result);
806 /* no bidi support for !REQ_TYPE_BLOCK_PC yet */
807 BUG_ON(blk_bidi_rq(req));
810 * Next deal with any sectors which we were able to correctly
813 SCSI_LOG_HLCOMPLETE(1, printk("%u sectors total, "
815 blk_rq_sectors(req), good_bytes));
818 * Recovered errors need reporting, but they're always treated
819 * as success, so fiddle the result code here. For BLOCK_PC
820 * we already took a copy of the original into rq->errors which
821 * is what gets returned to the user
823 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
824 /* if ATA PASS-THROUGH INFORMATION AVAILABLE skip
825 * print since caller wants ATA registers. Only occurs on
826 * SCSI ATA PASS_THROUGH commands when CK_COND=1
828 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
830 else if (!(req->cmd_flags & REQ_QUIET))
831 scsi_print_sense("", cmd);
833 /* BLOCK_PC may have set error */
838 * A number of bytes were successfully read. If there
839 * are leftovers and there is some kind of error
840 * (result != 0), retry the rest.
842 if (scsi_end_request(cmd, error, good_bytes, result == 0) == NULL)
845 error = __scsi_error_from_host_byte(cmd, result);
847 if (host_byte(result) == DID_RESET) {
848 /* Third party bus reset or reset for error recovery
849 * reasons. Just retry the command and see what
852 action = ACTION_RETRY;
853 } else if (sense_valid && !sense_deferred) {
854 switch (sshdr.sense_key) {
856 if (cmd->device->removable) {
857 /* Detected disc change. Set a bit
858 * and quietly refuse further access.
860 cmd->device->changed = 1;
861 description = "Media Changed";
862 action = ACTION_FAIL;
864 /* Must have been a power glitch, or a
865 * bus reset. Could not have been a
866 * media change, so we just retry the
867 * command and see what happens.
869 action = ACTION_RETRY;
872 case ILLEGAL_REQUEST:
873 /* If we had an ILLEGAL REQUEST returned, then
874 * we may have performed an unsupported
875 * command. The only thing this should be
876 * would be a ten byte read where only a six
877 * byte read was supported. Also, on a system
878 * where READ CAPACITY failed, we may have
879 * read past the end of the disk.
881 if ((cmd->device->use_10_for_rw &&
882 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
883 (cmd->cmnd[0] == READ_10 ||
884 cmd->cmnd[0] == WRITE_10)) {
885 /* This will issue a new 6-byte command. */
886 cmd->device->use_10_for_rw = 0;
887 action = ACTION_REPREP;
888 } else if (sshdr.asc == 0x10) /* DIX */ {
889 description = "Host Data Integrity Failure";
890 action = ACTION_FAIL;
892 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
893 } else if ((sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
894 (cmd->cmnd[0] == UNMAP ||
895 cmd->cmnd[0] == WRITE_SAME_16 ||
896 cmd->cmnd[0] == WRITE_SAME)) {
897 description = "Discard failure";
898 action = ACTION_FAIL;
900 action = ACTION_FAIL;
902 case ABORTED_COMMAND:
903 action = ACTION_FAIL;
904 if (sshdr.asc == 0x10) { /* DIF */
905 description = "Target Data Integrity Failure";
910 /* If the device is in the process of becoming
911 * ready, or has a temporary blockage, retry.
913 if (sshdr.asc == 0x04) {
914 switch (sshdr.ascq) {
915 case 0x01: /* becoming ready */
916 case 0x04: /* format in progress */
917 case 0x05: /* rebuild in progress */
918 case 0x06: /* recalculation in progress */
919 case 0x07: /* operation in progress */
920 case 0x08: /* Long write in progress */
921 case 0x09: /* self test in progress */
922 case 0x14: /* space allocation in progress */
923 action = ACTION_DELAYED_RETRY;
926 description = "Device not ready";
927 action = ACTION_FAIL;
931 description = "Device not ready";
932 action = ACTION_FAIL;
935 case VOLUME_OVERFLOW:
936 /* See SSC3rXX or current. */
937 action = ACTION_FAIL;
940 description = "Unhandled sense code";
941 action = ACTION_FAIL;
945 description = "Unhandled error code";
946 action = ACTION_FAIL;
951 /* Give up and fail the remainder of the request */
952 scsi_release_buffers(cmd);
953 if (!(req->cmd_flags & REQ_QUIET)) {
955 scmd_printk(KERN_INFO, cmd, "%s\n",
957 scsi_print_result(cmd);
958 if (driver_byte(result) & DRIVER_SENSE)
959 scsi_print_sense("", cmd);
960 scsi_print_command(cmd);
962 if (blk_end_request_err(req, error))
963 scsi_requeue_command(q, cmd);
965 scsi_next_command(cmd);
968 /* Unprep the request and put it back at the head of the queue.
969 * A new command will be prepared and issued.
971 scsi_release_buffers(cmd);
972 scsi_requeue_command(q, cmd);
975 /* Retry the same command immediately */
976 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, 0);
978 case ACTION_DELAYED_RETRY:
979 /* Retry the same command after a delay */
980 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, 0);
985 static int scsi_init_sgtable(struct request *req, struct scsi_data_buffer *sdb,
991 * If sg table allocation fails, requeue request later.
993 if (unlikely(scsi_alloc_sgtable(sdb, req->nr_phys_segments,
995 return BLKPREP_DEFER;
1001 * Next, walk the list, and fill in the addresses and sizes of
1004 count = blk_rq_map_sg(req->q, req, sdb->table.sgl);
1005 BUG_ON(count > sdb->table.nents);
1006 sdb->table.nents = count;
1007 sdb->length = blk_rq_bytes(req);
1012 * Function: scsi_init_io()
1014 * Purpose: SCSI I/O initialize function.
1016 * Arguments: cmd - Command descriptor we wish to initialize
1018 * Returns: 0 on success
1019 * BLKPREP_DEFER if the failure is retryable
1020 * BLKPREP_KILL if the failure is fatal
1022 int scsi_init_io(struct scsi_cmnd *cmd, gfp_t gfp_mask)
1024 struct request *rq = cmd->request;
1026 int error = scsi_init_sgtable(rq, &cmd->sdb, gfp_mask);
1030 if (blk_bidi_rq(rq)) {
1031 struct scsi_data_buffer *bidi_sdb = kmem_cache_zalloc(
1032 scsi_sdb_cache, GFP_ATOMIC);
1034 error = BLKPREP_DEFER;
1038 rq->next_rq->special = bidi_sdb;
1039 error = scsi_init_sgtable(rq->next_rq, bidi_sdb, GFP_ATOMIC);
1044 if (blk_integrity_rq(rq)) {
1045 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1048 BUG_ON(prot_sdb == NULL);
1049 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
1051 if (scsi_alloc_sgtable(prot_sdb, ivecs, gfp_mask)) {
1052 error = BLKPREP_DEFER;
1056 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
1057 prot_sdb->table.sgl);
1058 BUG_ON(unlikely(count > ivecs));
1059 BUG_ON(unlikely(count > queue_max_integrity_segments(rq->q)));
1061 cmd->prot_sdb = prot_sdb;
1062 cmd->prot_sdb->table.nents = count;
1068 scsi_release_buffers(cmd);
1069 cmd->request->special = NULL;
1070 scsi_put_command(cmd);
1073 EXPORT_SYMBOL(scsi_init_io);
1075 static struct scsi_cmnd *scsi_get_cmd_from_req(struct scsi_device *sdev,
1076 struct request *req)
1078 struct scsi_cmnd *cmd;
1080 if (!req->special) {
1081 cmd = scsi_get_command(sdev, GFP_ATOMIC);
1089 /* pull a tag out of the request if we have one */
1090 cmd->tag = req->tag;
1093 cmd->cmnd = req->cmd;
1094 cmd->prot_op = SCSI_PROT_NORMAL;
1099 int scsi_setup_blk_pc_cmnd(struct scsi_device *sdev, struct request *req)
1101 struct scsi_cmnd *cmd;
1102 int ret = scsi_prep_state_check(sdev, req);
1104 if (ret != BLKPREP_OK)
1107 cmd = scsi_get_cmd_from_req(sdev, req);
1109 return BLKPREP_DEFER;
1112 * BLOCK_PC requests may transfer data, in which case they must
1113 * a bio attached to them. Or they might contain a SCSI command
1114 * that does not transfer data, in which case they may optionally
1115 * submit a request without an attached bio.
1120 BUG_ON(!req->nr_phys_segments);
1122 ret = scsi_init_io(cmd, GFP_ATOMIC);
1126 BUG_ON(blk_rq_bytes(req));
1128 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1132 cmd->cmd_len = req->cmd_len;
1133 if (!blk_rq_bytes(req))
1134 cmd->sc_data_direction = DMA_NONE;
1135 else if (rq_data_dir(req) == WRITE)
1136 cmd->sc_data_direction = DMA_TO_DEVICE;
1138 cmd->sc_data_direction = DMA_FROM_DEVICE;
1140 cmd->transfersize = blk_rq_bytes(req);
1141 cmd->allowed = req->retries;
1144 EXPORT_SYMBOL(scsi_setup_blk_pc_cmnd);
1147 * Setup a REQ_TYPE_FS command. These are simple read/write request
1148 * from filesystems that still need to be translated to SCSI CDBs from
1151 int scsi_setup_fs_cmnd(struct scsi_device *sdev, struct request *req)
1153 struct scsi_cmnd *cmd;
1154 int ret = scsi_prep_state_check(sdev, req);
1156 if (ret != BLKPREP_OK)
1159 if (unlikely(sdev->scsi_dh_data && sdev->scsi_dh_data->scsi_dh
1160 && sdev->scsi_dh_data->scsi_dh->prep_fn)) {
1161 ret = sdev->scsi_dh_data->scsi_dh->prep_fn(sdev, req);
1162 if (ret != BLKPREP_OK)
1167 * Filesystem requests must transfer data.
1169 BUG_ON(!req->nr_phys_segments);
1171 cmd = scsi_get_cmd_from_req(sdev, req);
1173 return BLKPREP_DEFER;
1175 memset(cmd->cmnd, 0, BLK_MAX_CDB);
1176 return scsi_init_io(cmd, GFP_ATOMIC);
1178 EXPORT_SYMBOL(scsi_setup_fs_cmnd);
1180 int scsi_prep_state_check(struct scsi_device *sdev, struct request *req)
1182 int ret = BLKPREP_OK;
1185 * If the device is not in running state we will reject some
1188 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1189 switch (sdev->sdev_state) {
1192 * If the device is offline we refuse to process any
1193 * commands. The device must be brought online
1194 * before trying any recovery commands.
1196 sdev_printk(KERN_ERR, sdev,
1197 "rejecting I/O to offline device\n");
1202 * If the device is fully deleted, we refuse to
1203 * process any commands as well.
1205 sdev_printk(KERN_ERR, sdev,
1206 "rejecting I/O to dead device\n");
1210 case SDEV_CREATED_BLOCK:
1211 ret = BLKPREP_DEFER;
1215 * If the devices is blocked we defer normal commands.
1217 if (!(req->cmd_flags & REQ_PREEMPT))
1218 ret = BLKPREP_DEFER;
1222 * For any other not fully online state we only allow
1223 * special commands. In particular any user initiated
1224 * command is not allowed.
1226 if (!(req->cmd_flags & REQ_PREEMPT))
1233 EXPORT_SYMBOL(scsi_prep_state_check);
1235 int scsi_prep_return(struct request_queue *q, struct request *req, int ret)
1237 struct scsi_device *sdev = q->queuedata;
1241 req->errors = DID_NO_CONNECT << 16;
1242 /* release the command and kill it */
1244 struct scsi_cmnd *cmd = req->special;
1245 scsi_release_buffers(cmd);
1246 scsi_put_command(cmd);
1247 req->special = NULL;
1252 * If we defer, the blk_peek_request() returns NULL, but the
1253 * queue must be restarted, so we schedule a callback to happen
1256 if (sdev->device_busy == 0)
1257 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1260 req->cmd_flags |= REQ_DONTPREP;
1265 EXPORT_SYMBOL(scsi_prep_return);
1267 int scsi_prep_fn(struct request_queue *q, struct request *req)
1269 struct scsi_device *sdev = q->queuedata;
1270 int ret = BLKPREP_KILL;
1272 if (req->cmd_type == REQ_TYPE_BLOCK_PC)
1273 ret = scsi_setup_blk_pc_cmnd(sdev, req);
1274 return scsi_prep_return(q, req, ret);
1276 EXPORT_SYMBOL(scsi_prep_fn);
1279 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1282 * Called with the queue_lock held.
1284 static inline int scsi_dev_queue_ready(struct request_queue *q,
1285 struct scsi_device *sdev)
1287 if (sdev->device_busy == 0 && sdev->device_blocked) {
1289 * unblock after device_blocked iterates to zero
1291 if (--sdev->device_blocked == 0) {
1293 sdev_printk(KERN_INFO, sdev,
1294 "unblocking device at zero depth\n"));
1296 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1300 if (scsi_device_is_busy(sdev))
1308 * scsi_target_queue_ready: checks if there we can send commands to target
1309 * @sdev: scsi device on starget to check.
1311 * Called with the host lock held.
1313 static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1314 struct scsi_device *sdev)
1316 struct scsi_target *starget = scsi_target(sdev);
1318 if (starget->single_lun) {
1319 if (starget->starget_sdev_user &&
1320 starget->starget_sdev_user != sdev)
1322 starget->starget_sdev_user = sdev;
1325 if (starget->target_busy == 0 && starget->target_blocked) {
1327 * unblock after target_blocked iterates to zero
1329 if (--starget->target_blocked == 0) {
1330 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1331 "unblocking target at zero depth\n"));
1336 if (scsi_target_is_busy(starget)) {
1337 if (list_empty(&sdev->starved_entry))
1338 list_add_tail(&sdev->starved_entry,
1339 &shost->starved_list);
1343 /* We're OK to process the command, so we can't be starved */
1344 if (!list_empty(&sdev->starved_entry))
1345 list_del_init(&sdev->starved_entry);
1350 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1351 * return 0. We must end up running the queue again whenever 0 is
1352 * returned, else IO can hang.
1354 * Called with host_lock held.
1356 static inline int scsi_host_queue_ready(struct request_queue *q,
1357 struct Scsi_Host *shost,
1358 struct scsi_device *sdev)
1360 if (scsi_host_in_recovery(shost))
1362 if (shost->host_busy == 0 && shost->host_blocked) {
1364 * unblock after host_blocked iterates to zero
1366 if (--shost->host_blocked == 0) {
1368 printk("scsi%d unblocking host at zero depth\n",
1374 if (scsi_host_is_busy(shost)) {
1375 if (list_empty(&sdev->starved_entry))
1376 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1380 /* We're OK to process the command, so we can't be starved */
1381 if (!list_empty(&sdev->starved_entry))
1382 list_del_init(&sdev->starved_entry);
1388 * Busy state exporting function for request stacking drivers.
1390 * For efficiency, no lock is taken to check the busy state of
1391 * shost/starget/sdev, since the returned value is not guaranteed and
1392 * may be changed after request stacking drivers call the function,
1393 * regardless of taking lock or not.
1395 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1396 * needs to return 'not busy'. Otherwise, request stacking drivers
1397 * may hold requests forever.
1399 static int scsi_lld_busy(struct request_queue *q)
1401 struct scsi_device *sdev = q->queuedata;
1402 struct Scsi_Host *shost;
1404 if (blk_queue_dead(q))
1410 * Ignore host/starget busy state.
1411 * Since block layer does not have a concept of fairness across
1412 * multiple queues, congestion of host/starget needs to be handled
1415 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
1422 * Kill a request for a dead device
1424 static void scsi_kill_request(struct request *req, struct request_queue *q)
1426 struct scsi_cmnd *cmd = req->special;
1427 struct scsi_device *sdev;
1428 struct scsi_target *starget;
1429 struct Scsi_Host *shost;
1431 blk_start_request(req);
1433 scmd_printk(KERN_INFO, cmd, "killing request\n");
1436 starget = scsi_target(sdev);
1438 scsi_init_cmd_errh(cmd);
1439 cmd->result = DID_NO_CONNECT << 16;
1440 atomic_inc(&cmd->device->iorequest_cnt);
1443 * SCSI request completion path will do scsi_device_unbusy(),
1444 * bump busy counts. To bump the counters, we need to dance
1445 * with the locks as normal issue path does.
1447 sdev->device_busy++;
1448 spin_unlock(sdev->request_queue->queue_lock);
1449 spin_lock(shost->host_lock);
1451 starget->target_busy++;
1452 spin_unlock(shost->host_lock);
1453 spin_lock(sdev->request_queue->queue_lock);
1455 blk_complete_request(req);
1458 static void scsi_softirq_done(struct request *rq)
1460 struct scsi_cmnd *cmd = rq->special;
1461 unsigned long wait_for = (cmd->allowed + 1) * rq->timeout;
1464 INIT_LIST_HEAD(&cmd->eh_entry);
1466 atomic_inc(&cmd->device->iodone_cnt);
1468 atomic_inc(&cmd->device->ioerr_cnt);
1470 disposition = scsi_decide_disposition(cmd);
1471 if (disposition != SUCCESS &&
1472 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1473 sdev_printk(KERN_ERR, cmd->device,
1474 "timing out command, waited %lus\n",
1476 disposition = SUCCESS;
1479 scsi_log_completion(cmd, disposition);
1481 switch (disposition) {
1483 scsi_finish_command(cmd);
1486 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1488 case ADD_TO_MLQUEUE:
1489 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1492 if (!scsi_eh_scmd_add(cmd, 0))
1493 scsi_finish_command(cmd);
1498 * Function: scsi_request_fn()
1500 * Purpose: Main strategy routine for SCSI.
1502 * Arguments: q - Pointer to actual queue.
1506 * Lock status: IO request lock assumed to be held when called.
1508 static void scsi_request_fn(struct request_queue *q)
1510 struct scsi_device *sdev = q->queuedata;
1511 struct Scsi_Host *shost;
1512 struct scsi_cmnd *cmd;
1513 struct request *req;
1515 if(!get_device(&sdev->sdev_gendev))
1516 /* We must be tearing the block queue down already */
1520 * To start with, we keep looping until the queue is empty, or until
1521 * the host is no longer able to accept any more requests.
1527 * get next queueable request. We do this early to make sure
1528 * that the request is fully prepared even if we cannot
1531 req = blk_peek_request(q);
1532 if (!req || !scsi_dev_queue_ready(q, sdev))
1535 if (unlikely(!scsi_device_online(sdev))) {
1536 sdev_printk(KERN_ERR, sdev,
1537 "rejecting I/O to offline device\n");
1538 scsi_kill_request(req, q);
1544 * Remove the request from the request list.
1546 if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
1547 blk_start_request(req);
1548 sdev->device_busy++;
1550 spin_unlock(q->queue_lock);
1552 if (unlikely(cmd == NULL)) {
1553 printk(KERN_CRIT "impossible request in %s.\n"
1554 "please mail a stack trace to "
1555 "linux-scsi@vger.kernel.org\n",
1557 blk_dump_rq_flags(req, "foo");
1560 spin_lock(shost->host_lock);
1563 * We hit this when the driver is using a host wide
1564 * tag map. For device level tag maps the queue_depth check
1565 * in the device ready fn would prevent us from trying
1566 * to allocate a tag. Since the map is a shared host resource
1567 * we add the dev to the starved list so it eventually gets
1568 * a run when a tag is freed.
1570 if (blk_queue_tagged(q) && !blk_rq_tagged(req)) {
1571 if (list_empty(&sdev->starved_entry))
1572 list_add_tail(&sdev->starved_entry,
1573 &shost->starved_list);
1577 if (!scsi_target_queue_ready(shost, sdev))
1580 if (!scsi_host_queue_ready(q, shost, sdev))
1583 scsi_target(sdev)->target_busy++;
1587 * XXX(hch): This is rather suboptimal, scsi_dispatch_cmd will
1588 * take the lock again.
1590 spin_unlock_irq(shost->host_lock);
1593 * Finally, initialize any error handling parameters, and set up
1594 * the timers for timeouts.
1596 scsi_init_cmd_errh(cmd);
1599 * Dispatch the command to the low-level driver.
1601 rtn = scsi_dispatch_cmd(cmd);
1602 spin_lock_irq(q->queue_lock);
1610 spin_unlock_irq(shost->host_lock);
1613 * lock q, handle tag, requeue req, and decrement device_busy. We
1614 * must return with queue_lock held.
1616 * Decrementing device_busy without checking it is OK, as all such
1617 * cases (host limits or settings) should run the queue at some
1620 spin_lock_irq(q->queue_lock);
1621 blk_requeue_request(q, req);
1622 sdev->device_busy--;
1624 if (sdev->device_busy == 0)
1625 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1627 /* must be careful here...if we trigger the ->remove() function
1628 * we cannot be holding the q lock */
1629 spin_unlock_irq(q->queue_lock);
1630 put_device(&sdev->sdev_gendev);
1631 spin_lock_irq(q->queue_lock);
1634 u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
1636 struct device *host_dev;
1637 u64 bounce_limit = 0xffffffff;
1639 if (shost->unchecked_isa_dma)
1640 return BLK_BOUNCE_ISA;
1642 * Platforms with virtual-DMA translation
1643 * hardware have no practical limit.
1645 if (!PCI_DMA_BUS_IS_PHYS)
1646 return BLK_BOUNCE_ANY;
1648 host_dev = scsi_get_device(shost);
1649 if (host_dev && host_dev->dma_mask)
1650 bounce_limit = *host_dev->dma_mask;
1652 return bounce_limit;
1654 EXPORT_SYMBOL(scsi_calculate_bounce_limit);
1656 struct request_queue *__scsi_alloc_queue(struct Scsi_Host *shost,
1657 request_fn_proc *request_fn)
1659 struct request_queue *q;
1660 struct device *dev = shost->shost_gendev.parent;
1662 q = blk_init_queue(request_fn, NULL);
1667 * this limit is imposed by hardware restrictions
1669 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
1670 SCSI_MAX_SG_CHAIN_SEGMENTS));
1672 if (scsi_host_prot_dma(shost)) {
1673 shost->sg_prot_tablesize =
1674 min_not_zero(shost->sg_prot_tablesize,
1675 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
1676 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
1677 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
1680 blk_queue_max_hw_sectors(q, shost->max_sectors);
1681 blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
1682 blk_queue_segment_boundary(q, shost->dma_boundary);
1683 dma_set_seg_boundary(dev, shost->dma_boundary);
1685 blk_queue_max_segment_size(q, dma_get_max_seg_size(dev));
1687 if (!shost->use_clustering)
1688 q->limits.cluster = 0;
1691 * Set a reasonable default alignment: The larger of 32-byte (dword),
1692 * which is a common minimum for HBAs, and the minimum DMA alignment,
1693 * which is set by the platform.
1695 * Devices that require a bigger alignment can increase it later.
1697 blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1);
1701 EXPORT_SYMBOL(__scsi_alloc_queue);
1703 struct request_queue *scsi_alloc_queue(struct scsi_device *sdev)
1705 struct request_queue *q;
1707 q = __scsi_alloc_queue(sdev->host, scsi_request_fn);
1711 blk_queue_prep_rq(q, scsi_prep_fn);
1712 blk_queue_softirq_done(q, scsi_softirq_done);
1713 blk_queue_rq_timed_out(q, scsi_times_out);
1714 blk_queue_lld_busy(q, scsi_lld_busy);
1719 * Function: scsi_block_requests()
1721 * Purpose: Utility function used by low-level drivers to prevent further
1722 * commands from being queued to the device.
1724 * Arguments: shost - Host in question
1728 * Lock status: No locks are assumed held.
1730 * Notes: There is no timer nor any other means by which the requests
1731 * get unblocked other than the low-level driver calling
1732 * scsi_unblock_requests().
1734 void scsi_block_requests(struct Scsi_Host *shost)
1736 shost->host_self_blocked = 1;
1738 EXPORT_SYMBOL(scsi_block_requests);
1741 * Function: scsi_unblock_requests()
1743 * Purpose: Utility function used by low-level drivers to allow further
1744 * commands from being queued to the device.
1746 * Arguments: shost - Host in question
1750 * Lock status: No locks are assumed held.
1752 * Notes: There is no timer nor any other means by which the requests
1753 * get unblocked other than the low-level driver calling
1754 * scsi_unblock_requests().
1756 * This is done as an API function so that changes to the
1757 * internals of the scsi mid-layer won't require wholesale
1758 * changes to drivers that use this feature.
1760 void scsi_unblock_requests(struct Scsi_Host *shost)
1762 shost->host_self_blocked = 0;
1763 scsi_run_host_queues(shost);
1765 EXPORT_SYMBOL(scsi_unblock_requests);
1767 int __init scsi_init_queue(void)
1771 scsi_sdb_cache = kmem_cache_create("scsi_data_buffer",
1772 sizeof(struct scsi_data_buffer),
1774 if (!scsi_sdb_cache) {
1775 printk(KERN_ERR "SCSI: can't init scsi sdb cache\n");
1779 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1780 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1781 int size = sgp->size * sizeof(struct scatterlist);
1783 sgp->slab = kmem_cache_create(sgp->name, size, 0,
1784 SLAB_HWCACHE_ALIGN, NULL);
1786 printk(KERN_ERR "SCSI: can't init sg slab %s\n",
1791 sgp->pool = mempool_create_slab_pool(SG_MEMPOOL_SIZE,
1794 printk(KERN_ERR "SCSI: can't init sg mempool %s\n",
1803 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1804 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1806 mempool_destroy(sgp->pool);
1808 kmem_cache_destroy(sgp->slab);
1810 kmem_cache_destroy(scsi_sdb_cache);
1815 void scsi_exit_queue(void)
1819 kmem_cache_destroy(scsi_sdb_cache);
1821 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1822 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1823 mempool_destroy(sgp->pool);
1824 kmem_cache_destroy(sgp->slab);
1829 * scsi_mode_select - issue a mode select
1830 * @sdev: SCSI device to be queried
1831 * @pf: Page format bit (1 == standard, 0 == vendor specific)
1832 * @sp: Save page bit (0 == don't save, 1 == save)
1833 * @modepage: mode page being requested
1834 * @buffer: request buffer (may not be smaller than eight bytes)
1835 * @len: length of request buffer.
1836 * @timeout: command timeout
1837 * @retries: number of retries before failing
1838 * @data: returns a structure abstracting the mode header data
1839 * @sshdr: place to put sense data (or NULL if no sense to be collected).
1840 * must be SCSI_SENSE_BUFFERSIZE big.
1842 * Returns zero if successful; negative error number or scsi
1847 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
1848 unsigned char *buffer, int len, int timeout, int retries,
1849 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1851 unsigned char cmd[10];
1852 unsigned char *real_buffer;
1855 memset(cmd, 0, sizeof(cmd));
1856 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
1858 if (sdev->use_10_for_ms) {
1861 real_buffer = kmalloc(8 + len, GFP_KERNEL);
1864 memcpy(real_buffer + 8, buffer, len);
1868 real_buffer[2] = data->medium_type;
1869 real_buffer[3] = data->device_specific;
1870 real_buffer[4] = data->longlba ? 0x01 : 0;
1872 real_buffer[6] = data->block_descriptor_length >> 8;
1873 real_buffer[7] = data->block_descriptor_length;
1875 cmd[0] = MODE_SELECT_10;
1879 if (len > 255 || data->block_descriptor_length > 255 ||
1883 real_buffer = kmalloc(4 + len, GFP_KERNEL);
1886 memcpy(real_buffer + 4, buffer, len);
1889 real_buffer[1] = data->medium_type;
1890 real_buffer[2] = data->device_specific;
1891 real_buffer[3] = data->block_descriptor_length;
1894 cmd[0] = MODE_SELECT;
1898 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
1899 sshdr, timeout, retries, NULL);
1903 EXPORT_SYMBOL_GPL(scsi_mode_select);
1906 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
1907 * @sdev: SCSI device to be queried
1908 * @dbd: set if mode sense will allow block descriptors to be returned
1909 * @modepage: mode page being requested
1910 * @buffer: request buffer (may not be smaller than eight bytes)
1911 * @len: length of request buffer.
1912 * @timeout: command timeout
1913 * @retries: number of retries before failing
1914 * @data: returns a structure abstracting the mode header data
1915 * @sshdr: place to put sense data (or NULL if no sense to be collected).
1916 * must be SCSI_SENSE_BUFFERSIZE big.
1918 * Returns zero if unsuccessful, or the header offset (either 4
1919 * or 8 depending on whether a six or ten byte command was
1920 * issued) if successful.
1923 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
1924 unsigned char *buffer, int len, int timeout, int retries,
1925 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1927 unsigned char cmd[12];
1931 struct scsi_sense_hdr my_sshdr;
1933 memset(data, 0, sizeof(*data));
1934 memset(&cmd[0], 0, 12);
1935 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
1938 /* caller might not be interested in sense, but we need it */
1943 use_10_for_ms = sdev->use_10_for_ms;
1945 if (use_10_for_ms) {
1949 cmd[0] = MODE_SENSE_10;
1956 cmd[0] = MODE_SENSE;
1961 memset(buffer, 0, len);
1963 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
1964 sshdr, timeout, retries, NULL);
1966 /* This code looks awful: what it's doing is making sure an
1967 * ILLEGAL REQUEST sense return identifies the actual command
1968 * byte as the problem. MODE_SENSE commands can return
1969 * ILLEGAL REQUEST if the code page isn't supported */
1971 if (use_10_for_ms && !scsi_status_is_good(result) &&
1972 (driver_byte(result) & DRIVER_SENSE)) {
1973 if (scsi_sense_valid(sshdr)) {
1974 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
1975 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
1977 * Invalid command operation code
1979 sdev->use_10_for_ms = 0;
1985 if(scsi_status_is_good(result)) {
1986 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
1987 (modepage == 6 || modepage == 8))) {
1988 /* Initio breakage? */
1991 data->medium_type = 0;
1992 data->device_specific = 0;
1994 data->block_descriptor_length = 0;
1995 } else if(use_10_for_ms) {
1996 data->length = buffer[0]*256 + buffer[1] + 2;
1997 data->medium_type = buffer[2];
1998 data->device_specific = buffer[3];
1999 data->longlba = buffer[4] & 0x01;
2000 data->block_descriptor_length = buffer[6]*256
2003 data->length = buffer[0] + 1;
2004 data->medium_type = buffer[1];
2005 data->device_specific = buffer[2];
2006 data->block_descriptor_length = buffer[3];
2008 data->header_length = header_length;
2013 EXPORT_SYMBOL(scsi_mode_sense);
2016 * scsi_test_unit_ready - test if unit is ready
2017 * @sdev: scsi device to change the state of.
2018 * @timeout: command timeout
2019 * @retries: number of retries before failing
2020 * @sshdr_external: Optional pointer to struct scsi_sense_hdr for
2021 * returning sense. Make sure that this is cleared before passing
2024 * Returns zero if unsuccessful or an error if TUR failed. For
2025 * removable media, UNIT_ATTENTION sets ->changed flag.
2028 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2029 struct scsi_sense_hdr *sshdr_external)
2032 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2034 struct scsi_sense_hdr *sshdr;
2037 if (!sshdr_external)
2038 sshdr = kzalloc(sizeof(*sshdr), GFP_KERNEL);
2040 sshdr = sshdr_external;
2042 /* try to eat the UNIT_ATTENTION if there are enough retries */
2044 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
2045 timeout, retries, NULL);
2046 if (sdev->removable && scsi_sense_valid(sshdr) &&
2047 sshdr->sense_key == UNIT_ATTENTION)
2049 } while (scsi_sense_valid(sshdr) &&
2050 sshdr->sense_key == UNIT_ATTENTION && --retries);
2052 if (!sshdr_external)
2056 EXPORT_SYMBOL(scsi_test_unit_ready);
2059 * scsi_device_set_state - Take the given device through the device state model.
2060 * @sdev: scsi device to change the state of.
2061 * @state: state to change to.
2063 * Returns zero if unsuccessful or an error if the requested
2064 * transition is illegal.
2067 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2069 enum scsi_device_state oldstate = sdev->sdev_state;
2071 if (state == oldstate)
2077 case SDEV_CREATED_BLOCK:
2121 case SDEV_CREATED_BLOCK:
2128 case SDEV_CREATED_BLOCK:
2163 sdev->sdev_state = state;
2167 SCSI_LOG_ERROR_RECOVERY(1,
2168 sdev_printk(KERN_ERR, sdev,
2169 "Illegal state transition %s->%s\n",
2170 scsi_device_state_name(oldstate),
2171 scsi_device_state_name(state))
2175 EXPORT_SYMBOL(scsi_device_set_state);
2178 * sdev_evt_emit - emit a single SCSI device uevent
2179 * @sdev: associated SCSI device
2180 * @evt: event to emit
2182 * Send a single uevent (scsi_event) to the associated scsi_device.
2184 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2189 switch (evt->evt_type) {
2190 case SDEV_EVT_MEDIA_CHANGE:
2191 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2201 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2205 * sdev_evt_thread - send a uevent for each scsi event
2206 * @work: work struct for scsi_device
2208 * Dispatch queued events to their associated scsi_device kobjects
2211 void scsi_evt_thread(struct work_struct *work)
2213 struct scsi_device *sdev;
2214 LIST_HEAD(event_list);
2216 sdev = container_of(work, struct scsi_device, event_work);
2219 struct scsi_event *evt;
2220 struct list_head *this, *tmp;
2221 unsigned long flags;
2223 spin_lock_irqsave(&sdev->list_lock, flags);
2224 list_splice_init(&sdev->event_list, &event_list);
2225 spin_unlock_irqrestore(&sdev->list_lock, flags);
2227 if (list_empty(&event_list))
2230 list_for_each_safe(this, tmp, &event_list) {
2231 evt = list_entry(this, struct scsi_event, node);
2232 list_del(&evt->node);
2233 scsi_evt_emit(sdev, evt);
2240 * sdev_evt_send - send asserted event to uevent thread
2241 * @sdev: scsi_device event occurred on
2242 * @evt: event to send
2244 * Assert scsi device event asynchronously.
2246 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2248 unsigned long flags;
2251 /* FIXME: currently this check eliminates all media change events
2252 * for polled devices. Need to update to discriminate between AN
2253 * and polled events */
2254 if (!test_bit(evt->evt_type, sdev->supported_events)) {
2260 spin_lock_irqsave(&sdev->list_lock, flags);
2261 list_add_tail(&evt->node, &sdev->event_list);
2262 schedule_work(&sdev->event_work);
2263 spin_unlock_irqrestore(&sdev->list_lock, flags);
2265 EXPORT_SYMBOL_GPL(sdev_evt_send);
2268 * sdev_evt_alloc - allocate a new scsi event
2269 * @evt_type: type of event to allocate
2270 * @gfpflags: GFP flags for allocation
2272 * Allocates and returns a new scsi_event.
2274 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2277 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2281 evt->evt_type = evt_type;
2282 INIT_LIST_HEAD(&evt->node);
2284 /* evt_type-specific initialization, if any */
2286 case SDEV_EVT_MEDIA_CHANGE:
2294 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2297 * sdev_evt_send_simple - send asserted event to uevent thread
2298 * @sdev: scsi_device event occurred on
2299 * @evt_type: type of event to send
2300 * @gfpflags: GFP flags for allocation
2302 * Assert scsi device event asynchronously, given an event type.
2304 void sdev_evt_send_simple(struct scsi_device *sdev,
2305 enum scsi_device_event evt_type, gfp_t gfpflags)
2307 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2309 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2314 sdev_evt_send(sdev, evt);
2316 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2319 * scsi_device_quiesce - Block user issued commands.
2320 * @sdev: scsi device to quiesce.
2322 * This works by trying to transition to the SDEV_QUIESCE state
2323 * (which must be a legal transition). When the device is in this
2324 * state, only special requests will be accepted, all others will
2325 * be deferred. Since special requests may also be requeued requests,
2326 * a successful return doesn't guarantee the device will be
2327 * totally quiescent.
2329 * Must be called with user context, may sleep.
2331 * Returns zero if unsuccessful or an error if not.
2334 scsi_device_quiesce(struct scsi_device *sdev)
2336 int err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2340 scsi_run_queue(sdev->request_queue);
2341 while (sdev->device_busy) {
2342 msleep_interruptible(200);
2343 scsi_run_queue(sdev->request_queue);
2347 EXPORT_SYMBOL(scsi_device_quiesce);
2350 * scsi_device_resume - Restart user issued commands to a quiesced device.
2351 * @sdev: scsi device to resume.
2353 * Moves the device from quiesced back to running and restarts the
2356 * Must be called with user context, may sleep.
2359 scsi_device_resume(struct scsi_device *sdev)
2361 if(scsi_device_set_state(sdev, SDEV_RUNNING))
2363 scsi_run_queue(sdev->request_queue);
2365 EXPORT_SYMBOL(scsi_device_resume);
2368 device_quiesce_fn(struct scsi_device *sdev, void *data)
2370 scsi_device_quiesce(sdev);
2374 scsi_target_quiesce(struct scsi_target *starget)
2376 starget_for_each_device(starget, NULL, device_quiesce_fn);
2378 EXPORT_SYMBOL(scsi_target_quiesce);
2381 device_resume_fn(struct scsi_device *sdev, void *data)
2383 scsi_device_resume(sdev);
2387 scsi_target_resume(struct scsi_target *starget)
2389 starget_for_each_device(starget, NULL, device_resume_fn);
2391 EXPORT_SYMBOL(scsi_target_resume);
2394 * scsi_internal_device_block - internal function to put a device temporarily into the SDEV_BLOCK state
2395 * @sdev: device to block
2397 * Block request made by scsi lld's to temporarily stop all
2398 * scsi commands on the specified device. Called from interrupt
2399 * or normal process context.
2401 * Returns zero if successful or error if not
2404 * This routine transitions the device to the SDEV_BLOCK state
2405 * (which must be a legal transition). When the device is in this
2406 * state, all commands are deferred until the scsi lld reenables
2407 * the device with scsi_device_unblock or device_block_tmo fires.
2408 * This routine assumes the host_lock is held on entry.
2411 scsi_internal_device_block(struct scsi_device *sdev)
2413 struct request_queue *q = sdev->request_queue;
2414 unsigned long flags;
2417 err = scsi_device_set_state(sdev, SDEV_BLOCK);
2419 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
2426 * The device has transitioned to SDEV_BLOCK. Stop the
2427 * block layer from calling the midlayer with this device's
2430 spin_lock_irqsave(q->queue_lock, flags);
2432 spin_unlock_irqrestore(q->queue_lock, flags);
2436 EXPORT_SYMBOL_GPL(scsi_internal_device_block);
2439 * scsi_internal_device_unblock - resume a device after a block request
2440 * @sdev: device to resume
2442 * Called by scsi lld's or the midlayer to restart the device queue
2443 * for the previously suspended scsi device. Called from interrupt or
2444 * normal process context.
2446 * Returns zero if successful or error if not.
2449 * This routine transitions the device to the SDEV_RUNNING state
2450 * (which must be a legal transition) allowing the midlayer to
2451 * goose the queue for this device. This routine assumes the
2452 * host_lock is held upon entry.
2455 scsi_internal_device_unblock(struct scsi_device *sdev)
2457 struct request_queue *q = sdev->request_queue;
2458 unsigned long flags;
2461 * Try to transition the scsi device to SDEV_RUNNING
2462 * and goose the device queue if successful.
2464 if (sdev->sdev_state == SDEV_BLOCK)
2465 sdev->sdev_state = SDEV_RUNNING;
2466 else if (sdev->sdev_state == SDEV_CREATED_BLOCK)
2467 sdev->sdev_state = SDEV_CREATED;
2468 else if (sdev->sdev_state != SDEV_CANCEL &&
2469 sdev->sdev_state != SDEV_OFFLINE)
2472 spin_lock_irqsave(q->queue_lock, flags);
2474 spin_unlock_irqrestore(q->queue_lock, flags);
2478 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock);
2481 device_block(struct scsi_device *sdev, void *data)
2483 scsi_internal_device_block(sdev);
2487 target_block(struct device *dev, void *data)
2489 if (scsi_is_target_device(dev))
2490 starget_for_each_device(to_scsi_target(dev), NULL,
2496 scsi_target_block(struct device *dev)
2498 if (scsi_is_target_device(dev))
2499 starget_for_each_device(to_scsi_target(dev), NULL,
2502 device_for_each_child(dev, NULL, target_block);
2504 EXPORT_SYMBOL_GPL(scsi_target_block);
2507 device_unblock(struct scsi_device *sdev, void *data)
2509 scsi_internal_device_unblock(sdev);
2513 target_unblock(struct device *dev, void *data)
2515 if (scsi_is_target_device(dev))
2516 starget_for_each_device(to_scsi_target(dev), NULL,
2522 scsi_target_unblock(struct device *dev)
2524 if (scsi_is_target_device(dev))
2525 starget_for_each_device(to_scsi_target(dev), NULL,
2528 device_for_each_child(dev, NULL, target_unblock);
2530 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2533 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
2534 * @sgl: scatter-gather list
2535 * @sg_count: number of segments in sg
2536 * @offset: offset in bytes into sg, on return offset into the mapped area
2537 * @len: bytes to map, on return number of bytes mapped
2539 * Returns virtual address of the start of the mapped page
2541 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
2542 size_t *offset, size_t *len)
2545 size_t sg_len = 0, len_complete = 0;
2546 struct scatterlist *sg;
2549 WARN_ON(!irqs_disabled());
2551 for_each_sg(sgl, sg, sg_count, i) {
2552 len_complete = sg_len; /* Complete sg-entries */
2553 sg_len += sg->length;
2554 if (sg_len > *offset)
2558 if (unlikely(i == sg_count)) {
2559 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2561 __func__, sg_len, *offset, sg_count);
2566 /* Offset starting from the beginning of first page in this sg-entry */
2567 *offset = *offset - len_complete + sg->offset;
2569 /* Assumption: contiguous pages can be accessed as "page + i" */
2570 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
2571 *offset &= ~PAGE_MASK;
2573 /* Bytes in this sg-entry from *offset to the end of the page */
2574 sg_len = PAGE_SIZE - *offset;
2578 return kmap_atomic(page, KM_BIO_SRC_IRQ);
2580 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2583 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
2584 * @virt: virtual address to be unmapped
2586 void scsi_kunmap_atomic_sg(void *virt)
2588 kunmap_atomic(virt, KM_BIO_SRC_IRQ);
2590 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);