Linux 2.6.16.40
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / drivers / scsi / scsi_lib.c
blobe29f943a8451fdbb0b2ca5a99a7336b7068ad3fa
1 /*
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.
8 */
10 #include <linux/bio.h>
11 #include <linux/blkdev.h>
12 #include <linux/completion.h>
13 #include <linux/kernel.h>
14 #include <linux/mempool.h>
15 #include <linux/slab.h>
16 #include <linux/init.h>
17 #include <linux/pci.h>
18 #include <linux/delay.h>
19 #include <linux/hardirq.h>
21 #include <scsi/scsi.h>
22 #include <scsi/scsi_dbg.h>
23 #include <scsi/scsi_device.h>
24 #include <scsi/scsi_driver.h>
25 #include <scsi/scsi_eh.h>
26 #include <scsi/scsi_host.h>
27 #include <scsi/scsi_request.h>
29 #include "scsi_priv.h"
30 #include "scsi_logging.h"
33 #define SG_MEMPOOL_NR (sizeof(scsi_sg_pools)/sizeof(struct scsi_host_sg_pool))
34 #define SG_MEMPOOL_SIZE 32
36 struct scsi_host_sg_pool {
37 size_t size;
38 char *name;
39 kmem_cache_t *slab;
40 mempool_t *pool;
43 #if (SCSI_MAX_PHYS_SEGMENTS < 32)
44 #error SCSI_MAX_PHYS_SEGMENTS is too small
45 #endif
47 #define SP(x) { x, "sgpool-" #x }
48 static struct scsi_host_sg_pool scsi_sg_pools[] = {
49 SP(8),
50 SP(16),
51 SP(32),
52 #if (SCSI_MAX_PHYS_SEGMENTS > 32)
53 SP(64),
54 #if (SCSI_MAX_PHYS_SEGMENTS > 64)
55 SP(128),
56 #if (SCSI_MAX_PHYS_SEGMENTS > 128)
57 SP(256),
58 #if (SCSI_MAX_PHYS_SEGMENTS > 256)
59 #error SCSI_MAX_PHYS_SEGMENTS is too large
60 #endif
61 #endif
62 #endif
63 #endif
64 };
65 #undef SP
67 static void scsi_run_queue(struct request_queue *q);
70 * Function: scsi_unprep_request()
72 * Purpose: Remove all preparation done for a request, including its
73 * associated scsi_cmnd, so that it can be requeued.
75 * Arguments: req - request to unprepare
77 * Lock status: Assumed that no locks are held upon entry.
79 * Returns: Nothing.
81 static void scsi_unprep_request(struct request *req)
83 struct scsi_cmnd *cmd = req->special;
85 req->flags &= ~REQ_DONTPREP;
86 req->special = (req->flags & REQ_SPECIAL) ? cmd->sc_request : NULL;
88 scsi_put_command(cmd);
92 * Function: scsi_queue_insert()
94 * Purpose: Insert a command in the midlevel queue.
96 * Arguments: cmd - command that we are adding to queue.
97 * reason - why we are inserting command to queue.
99 * Lock status: Assumed that lock is not held upon entry.
101 * Returns: Nothing.
103 * Notes: We do this for one of two cases. Either the host is busy
104 * and it cannot accept any more commands for the time being,
105 * or the device returned QUEUE_FULL and can accept no more
106 * commands.
107 * Notes: This could be called either from an interrupt context or a
108 * normal process context.
110 int scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
112 struct Scsi_Host *host = cmd->device->host;
113 struct scsi_device *device = cmd->device;
114 struct request_queue *q = device->request_queue;
115 unsigned long flags;
117 SCSI_LOG_MLQUEUE(1,
118 printk("Inserting command %p into mlqueue\n", cmd));
121 * Set the appropriate busy bit for the device/host.
123 * If the host/device isn't busy, assume that something actually
124 * completed, and that we should be able to queue a command now.
126 * Note that the prior mid-layer assumption that any host could
127 * always queue at least one command is now broken. The mid-layer
128 * will implement a user specifiable stall (see
129 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
130 * if a command is requeued with no other commands outstanding
131 * either for the device or for the host.
133 if (reason == SCSI_MLQUEUE_HOST_BUSY)
134 host->host_blocked = host->max_host_blocked;
135 else if (reason == SCSI_MLQUEUE_DEVICE_BUSY)
136 device->device_blocked = device->max_device_blocked;
139 * Decrement the counters, since these commands are no longer
140 * active on the host/device.
142 scsi_device_unbusy(device);
145 * Requeue this command. It will go before all other commands
146 * that are already in the queue.
148 * NOTE: there is magic here about the way the queue is plugged if
149 * we have no outstanding commands.
151 * Although we *don't* plug the queue, we call the request
152 * function. The SCSI request function detects the blocked condition
153 * and plugs the queue appropriately.
155 spin_lock_irqsave(q->queue_lock, flags);
156 blk_requeue_request(q, cmd->request);
157 spin_unlock_irqrestore(q->queue_lock, flags);
159 scsi_run_queue(q);
161 return 0;
165 * Function: scsi_do_req
167 * Purpose: Queue a SCSI request
169 * Arguments: sreq - command descriptor.
170 * cmnd - actual SCSI command to be performed.
171 * buffer - data buffer.
172 * bufflen - size of data buffer.
173 * done - completion function to be run.
174 * timeout - how long to let it run before timeout.
175 * retries - number of retries we allow.
177 * Lock status: No locks held upon entry.
179 * Returns: Nothing.
181 * Notes: This function is only used for queueing requests for things
182 * like ioctls and character device requests - this is because
183 * we essentially just inject a request into the queue for the
184 * device.
186 * In order to support the scsi_device_quiesce function, we
187 * now inject requests on the *head* of the device queue
188 * rather than the tail.
190 void scsi_do_req(struct scsi_request *sreq, const void *cmnd,
191 void *buffer, unsigned bufflen,
192 void (*done)(struct scsi_cmnd *),
193 int timeout, int retries)
196 * If the upper level driver is reusing these things, then
197 * we should release the low-level block now. Another one will
198 * be allocated later when this request is getting queued.
200 __scsi_release_request(sreq);
203 * Our own function scsi_done (which marks the host as not busy,
204 * disables the timeout counter, etc) will be called by us or by the
205 * scsi_hosts[host].queuecommand() function needs to also call
206 * the completion function for the high level driver.
208 memcpy(sreq->sr_cmnd, cmnd, sizeof(sreq->sr_cmnd));
209 sreq->sr_bufflen = bufflen;
210 sreq->sr_buffer = buffer;
211 sreq->sr_allowed = retries;
212 sreq->sr_done = done;
213 sreq->sr_timeout_per_command = timeout;
215 if (sreq->sr_cmd_len == 0)
216 sreq->sr_cmd_len = COMMAND_SIZE(sreq->sr_cmnd[0]);
219 * head injection *required* here otherwise quiesce won't work
221 * Because users of this function are apt to reuse requests with no
222 * modification, we have to sanitise the request flags here
224 sreq->sr_request->flags &= ~REQ_DONTPREP;
225 blk_insert_request(sreq->sr_device->request_queue, sreq->sr_request,
226 1, sreq);
228 EXPORT_SYMBOL(scsi_do_req);
231 * scsi_execute - insert request and wait for the result
232 * @sdev: scsi device
233 * @cmd: scsi command
234 * @data_direction: data direction
235 * @buffer: data buffer
236 * @bufflen: len of buffer
237 * @sense: optional sense buffer
238 * @timeout: request timeout in seconds
239 * @retries: number of times to retry request
240 * @flags: or into request flags;
242 * returns the req->errors value which is the the scsi_cmnd result
243 * field.
245 int scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
246 int data_direction, void *buffer, unsigned bufflen,
247 unsigned char *sense, int timeout, int retries, int flags)
249 struct request *req;
250 int write = (data_direction == DMA_TO_DEVICE);
251 int ret = DRIVER_ERROR << 24;
253 req = blk_get_request(sdev->request_queue, write, __GFP_WAIT);
255 if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
256 buffer, bufflen, __GFP_WAIT))
257 goto out;
259 req->cmd_len = COMMAND_SIZE(cmd[0]);
260 memcpy(req->cmd, cmd, req->cmd_len);
261 req->sense = sense;
262 req->sense_len = 0;
263 req->retries = retries;
264 req->timeout = timeout;
265 req->flags |= flags | REQ_BLOCK_PC | REQ_SPECIAL | REQ_QUIET;
268 * head injection *required* here otherwise quiesce won't work
270 blk_execute_rq(req->q, NULL, req, 1);
272 ret = req->errors;
273 out:
274 blk_put_request(req);
276 return ret;
278 EXPORT_SYMBOL(scsi_execute);
281 int scsi_execute_req(struct scsi_device *sdev, const unsigned char *cmd,
282 int data_direction, void *buffer, unsigned bufflen,
283 struct scsi_sense_hdr *sshdr, int timeout, int retries)
285 char *sense = NULL;
286 int result;
288 if (sshdr) {
289 sense = kmalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
290 if (!sense)
291 return DRIVER_ERROR << 24;
292 memset(sense, 0, SCSI_SENSE_BUFFERSIZE);
294 result = scsi_execute(sdev, cmd, data_direction, buffer, bufflen,
295 sense, timeout, retries, 0);
296 if (sshdr)
297 scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, sshdr);
299 kfree(sense);
300 return result;
302 EXPORT_SYMBOL(scsi_execute_req);
304 struct scsi_io_context {
305 void *data;
306 void (*done)(void *data, char *sense, int result, int resid);
307 char sense[SCSI_SENSE_BUFFERSIZE];
310 static kmem_cache_t *scsi_io_context_cache;
312 static void scsi_end_async(struct request *req, int uptodate)
314 struct scsi_io_context *sioc = req->end_io_data;
316 if (sioc->done)
317 sioc->done(sioc->data, sioc->sense, req->errors, req->data_len);
319 kmem_cache_free(scsi_io_context_cache, sioc);
320 __blk_put_request(req->q, req);
323 static int scsi_merge_bio(struct request *rq, struct bio *bio)
325 struct request_queue *q = rq->q;
327 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
328 if (rq_data_dir(rq) == WRITE)
329 bio->bi_rw |= (1 << BIO_RW);
330 blk_queue_bounce(q, &bio);
332 if (!rq->bio)
333 blk_rq_bio_prep(q, rq, bio);
334 else if (!q->back_merge_fn(q, rq, bio))
335 return -EINVAL;
336 else {
337 rq->biotail->bi_next = bio;
338 rq->biotail = bio;
339 rq->hard_nr_sectors += bio_sectors(bio);
340 rq->nr_sectors = rq->hard_nr_sectors;
343 return 0;
346 static int scsi_bi_endio(struct bio *bio, unsigned int bytes_done, int error)
348 if (bio->bi_size)
349 return 1;
351 bio_put(bio);
352 return 0;
356 * scsi_req_map_sg - map a scatterlist into a request
357 * @rq: request to fill
358 * @sg: scatterlist
359 * @nsegs: number of elements
360 * @bufflen: len of buffer
361 * @gfp: memory allocation flags
363 * scsi_req_map_sg maps a scatterlist into a request so that the
364 * request can be sent to the block layer. We do not trust the scatterlist
365 * sent to use, as some ULDs use that struct to only organize the pages.
367 static int scsi_req_map_sg(struct request *rq, struct scatterlist *sgl,
368 int nsegs, unsigned bufflen, gfp_t gfp)
370 struct request_queue *q = rq->q;
371 int nr_pages = (bufflen + sgl[0].offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
372 unsigned int data_len = 0, len, bytes, off;
373 struct page *page;
374 struct bio *bio = NULL;
375 int i, err, nr_vecs = 0;
377 for (i = 0; i < nsegs; i++) {
378 page = sgl[i].page;
379 off = sgl[i].offset;
380 len = sgl[i].length;
381 data_len += len;
383 while (len > 0) {
384 bytes = min_t(unsigned int, len, PAGE_SIZE - off);
386 if (!bio) {
387 nr_vecs = min_t(int, BIO_MAX_PAGES, nr_pages);
388 nr_pages -= nr_vecs;
390 bio = bio_alloc(gfp, nr_vecs);
391 if (!bio) {
392 err = -ENOMEM;
393 goto free_bios;
395 bio->bi_end_io = scsi_bi_endio;
398 if (bio_add_pc_page(q, bio, page, bytes, off) !=
399 bytes) {
400 bio_put(bio);
401 err = -EINVAL;
402 goto free_bios;
405 if (bio->bi_vcnt >= nr_vecs) {
406 err = scsi_merge_bio(rq, bio);
407 if (err) {
408 bio_endio(bio, bio->bi_size, 0);
409 goto free_bios;
411 bio = NULL;
414 page++;
415 len -= bytes;
416 off = 0;
420 rq->buffer = rq->data = NULL;
421 rq->data_len = data_len;
422 return 0;
424 free_bios:
425 while ((bio = rq->bio) != NULL) {
426 rq->bio = bio->bi_next;
428 * call endio instead of bio_put incase it was bounced
430 bio_endio(bio, bio->bi_size, 0);
433 return err;
437 * scsi_execute_async - insert request
438 * @sdev: scsi device
439 * @cmd: scsi command
440 * @cmd_len: length of scsi cdb
441 * @data_direction: data direction
442 * @buffer: data buffer (this can be a kernel buffer or scatterlist)
443 * @bufflen: len of buffer
444 * @use_sg: if buffer is a scatterlist this is the number of elements
445 * @timeout: request timeout in seconds
446 * @retries: number of times to retry request
447 * @flags: or into request flags
449 int scsi_execute_async(struct scsi_device *sdev, const unsigned char *cmd,
450 int cmd_len, int data_direction, void *buffer, unsigned bufflen,
451 int use_sg, int timeout, int retries, void *privdata,
452 void (*done)(void *, char *, int, int), gfp_t gfp)
454 struct request *req;
455 struct scsi_io_context *sioc;
456 int err = 0;
457 int write = (data_direction == DMA_TO_DEVICE);
459 sioc = kmem_cache_alloc(scsi_io_context_cache, gfp);
460 if (!sioc)
461 return DRIVER_ERROR << 24;
462 memset(sioc, 0, sizeof(*sioc));
464 req = blk_get_request(sdev->request_queue, write, gfp);
465 if (!req)
466 goto free_sense;
467 req->flags |= REQ_BLOCK_PC | REQ_QUIET;
469 if (use_sg)
470 err = scsi_req_map_sg(req, buffer, use_sg, bufflen, gfp);
471 else if (bufflen)
472 err = blk_rq_map_kern(req->q, req, buffer, bufflen, gfp);
474 if (err)
475 goto free_req;
477 req->cmd_len = cmd_len;
478 memset(req->cmd, 0, BLK_MAX_CDB); /* ATAPI hates garbage after CDB */
479 memcpy(req->cmd, cmd, req->cmd_len);
480 req->sense = sioc->sense;
481 req->sense_len = 0;
482 req->timeout = timeout;
483 req->retries = retries;
484 req->end_io_data = sioc;
486 sioc->data = privdata;
487 sioc->done = done;
489 blk_execute_rq_nowait(req->q, NULL, req, 1, scsi_end_async);
490 return 0;
492 free_req:
493 blk_put_request(req);
494 free_sense:
495 kfree(sioc);
496 return DRIVER_ERROR << 24;
498 EXPORT_SYMBOL_GPL(scsi_execute_async);
501 * Function: scsi_init_cmd_errh()
503 * Purpose: Initialize cmd fields related to error handling.
505 * Arguments: cmd - command that is ready to be queued.
507 * Returns: Nothing
509 * Notes: This function has the job of initializing a number of
510 * fields related to error handling. Typically this will
511 * be called once for each command, as required.
513 static int scsi_init_cmd_errh(struct scsi_cmnd *cmd)
515 cmd->serial_number = 0;
517 memset(cmd->sense_buffer, 0, sizeof cmd->sense_buffer);
519 if (cmd->cmd_len == 0)
520 cmd->cmd_len = COMMAND_SIZE(cmd->cmnd[0]);
523 * We need saved copies of a number of fields - this is because
524 * error handling may need to overwrite these with different values
525 * to run different commands, and once error handling is complete,
526 * we will need to restore these values prior to running the actual
527 * command.
529 cmd->old_use_sg = cmd->use_sg;
530 cmd->old_cmd_len = cmd->cmd_len;
531 cmd->sc_old_data_direction = cmd->sc_data_direction;
532 cmd->old_underflow = cmd->underflow;
533 memcpy(cmd->data_cmnd, cmd->cmnd, sizeof(cmd->cmnd));
534 cmd->buffer = cmd->request_buffer;
535 cmd->bufflen = cmd->request_bufflen;
537 return 1;
541 * Function: scsi_setup_cmd_retry()
543 * Purpose: Restore the command state for a retry
545 * Arguments: cmd - command to be restored
547 * Returns: Nothing
549 * Notes: Immediately prior to retrying a command, we need
550 * to restore certain fields that we saved above.
552 void scsi_setup_cmd_retry(struct scsi_cmnd *cmd)
554 memcpy(cmd->cmnd, cmd->data_cmnd, sizeof(cmd->data_cmnd));
555 cmd->request_buffer = cmd->buffer;
556 cmd->request_bufflen = cmd->bufflen;
557 cmd->use_sg = cmd->old_use_sg;
558 cmd->cmd_len = cmd->old_cmd_len;
559 cmd->sc_data_direction = cmd->sc_old_data_direction;
560 cmd->underflow = cmd->old_underflow;
563 void scsi_device_unbusy(struct scsi_device *sdev)
565 struct Scsi_Host *shost = sdev->host;
566 unsigned long flags;
568 spin_lock_irqsave(shost->host_lock, flags);
569 shost->host_busy--;
570 if (unlikely(scsi_host_in_recovery(shost) &&
571 shost->host_failed))
572 scsi_eh_wakeup(shost);
573 spin_unlock(shost->host_lock);
574 spin_lock(sdev->request_queue->queue_lock);
575 sdev->device_busy--;
576 spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
580 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
581 * and call blk_run_queue for all the scsi_devices on the target -
582 * including current_sdev first.
584 * Called with *no* scsi locks held.
586 static void scsi_single_lun_run(struct scsi_device *current_sdev)
588 struct Scsi_Host *shost = current_sdev->host;
589 struct scsi_device *sdev, *tmp;
590 struct scsi_target *starget = scsi_target(current_sdev);
591 unsigned long flags;
593 spin_lock_irqsave(shost->host_lock, flags);
594 starget->starget_sdev_user = NULL;
595 spin_unlock_irqrestore(shost->host_lock, flags);
598 * Call blk_run_queue for all LUNs on the target, starting with
599 * current_sdev. We race with others (to set starget_sdev_user),
600 * but in most cases, we will be first. Ideally, each LU on the
601 * target would get some limited time or requests on the target.
603 blk_run_queue(current_sdev->request_queue);
605 spin_lock_irqsave(shost->host_lock, flags);
606 if (starget->starget_sdev_user)
607 goto out;
608 list_for_each_entry_safe(sdev, tmp, &starget->devices,
609 same_target_siblings) {
610 if (sdev == current_sdev)
611 continue;
612 if (scsi_device_get(sdev))
613 continue;
615 spin_unlock_irqrestore(shost->host_lock, flags);
616 blk_run_queue(sdev->request_queue);
617 spin_lock_irqsave(shost->host_lock, flags);
619 scsi_device_put(sdev);
621 out:
622 spin_unlock_irqrestore(shost->host_lock, flags);
626 * Function: scsi_run_queue()
628 * Purpose: Select a proper request queue to serve next
630 * Arguments: q - last request's queue
632 * Returns: Nothing
634 * Notes: The previous command was completely finished, start
635 * a new one if possible.
637 static void scsi_run_queue(struct request_queue *q)
639 struct scsi_device *sdev = q->queuedata;
640 struct Scsi_Host *shost = sdev->host;
641 unsigned long flags;
643 if (sdev->single_lun)
644 scsi_single_lun_run(sdev);
646 spin_lock_irqsave(shost->host_lock, flags);
647 while (!list_empty(&shost->starved_list) &&
648 !shost->host_blocked && !shost->host_self_blocked &&
649 !((shost->can_queue > 0) &&
650 (shost->host_busy >= shost->can_queue))) {
652 * As long as shost is accepting commands and we have
653 * starved queues, call blk_run_queue. scsi_request_fn
654 * drops the queue_lock and can add us back to the
655 * starved_list.
657 * host_lock protects the starved_list and starved_entry.
658 * scsi_request_fn must get the host_lock before checking
659 * or modifying starved_list or starved_entry.
661 sdev = list_entry(shost->starved_list.next,
662 struct scsi_device, starved_entry);
663 list_del_init(&sdev->starved_entry);
664 spin_unlock_irqrestore(shost->host_lock, flags);
666 blk_run_queue(sdev->request_queue);
668 spin_lock_irqsave(shost->host_lock, flags);
669 if (unlikely(!list_empty(&sdev->starved_entry)))
671 * sdev lost a race, and was put back on the
672 * starved list. This is unlikely but without this
673 * in theory we could loop forever.
675 break;
677 spin_unlock_irqrestore(shost->host_lock, flags);
679 blk_run_queue(q);
683 * Function: scsi_requeue_command()
685 * Purpose: Handle post-processing of completed commands.
687 * Arguments: q - queue to operate on
688 * cmd - command that may need to be requeued.
690 * Returns: Nothing
692 * Notes: After command completion, there may be blocks left
693 * over which weren't finished by the previous command
694 * this can be for a number of reasons - the main one is
695 * I/O errors in the middle of the request, in which case
696 * we need to request the blocks that come after the bad
697 * sector.
698 * Notes: Upon return, cmd is a stale pointer.
700 static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
702 struct request *req = cmd->request;
703 unsigned long flags;
705 scsi_unprep_request(req);
706 spin_lock_irqsave(q->queue_lock, flags);
707 blk_requeue_request(q, req);
708 spin_unlock_irqrestore(q->queue_lock, flags);
710 scsi_run_queue(q);
713 void scsi_next_command(struct scsi_cmnd *cmd)
715 struct scsi_device *sdev = cmd->device;
716 struct request_queue *q = sdev->request_queue;
718 /* need to hold a reference on the device before we let go of the cmd */
719 get_device(&sdev->sdev_gendev);
721 scsi_put_command(cmd);
722 scsi_run_queue(q);
724 /* ok to remove device now */
725 put_device(&sdev->sdev_gendev);
728 void scsi_run_host_queues(struct Scsi_Host *shost)
730 struct scsi_device *sdev;
732 shost_for_each_device(sdev, shost)
733 scsi_run_queue(sdev->request_queue);
737 * Function: scsi_end_request()
739 * Purpose: Post-processing of completed commands (usually invoked at end
740 * of upper level post-processing and scsi_io_completion).
742 * Arguments: cmd - command that is complete.
743 * uptodate - 1 if I/O indicates success, <= 0 for I/O error.
744 * bytes - number of bytes of completed I/O
745 * requeue - indicates whether we should requeue leftovers.
747 * Lock status: Assumed that lock is not held upon entry.
749 * Returns: cmd if requeue required, NULL otherwise.
751 * Notes: This is called for block device requests in order to
752 * mark some number of sectors as complete.
754 * We are guaranteeing that the request queue will be goosed
755 * at some point during this call.
756 * Notes: If cmd was requeued, upon return it will be a stale pointer.
758 static struct scsi_cmnd *scsi_end_request(struct scsi_cmnd *cmd, int uptodate,
759 int bytes, int requeue)
761 request_queue_t *q = cmd->device->request_queue;
762 struct request *req = cmd->request;
763 unsigned long flags;
766 * If there are blocks left over at the end, set up the command
767 * to queue the remainder of them.
769 if (end_that_request_chunk(req, uptodate, bytes)) {
770 int leftover = (req->hard_nr_sectors << 9);
772 if (blk_pc_request(req))
773 leftover = req->data_len;
775 /* kill remainder if no retrys */
776 if (!uptodate && blk_noretry_request(req))
777 end_that_request_chunk(req, 0, leftover);
778 else {
779 if (requeue) {
781 * Bleah. Leftovers again. Stick the
782 * leftovers in the front of the
783 * queue, and goose the queue again.
785 scsi_requeue_command(q, cmd);
786 cmd = NULL;
788 return cmd;
792 add_disk_randomness(req->rq_disk);
794 spin_lock_irqsave(q->queue_lock, flags);
795 if (blk_rq_tagged(req))
796 blk_queue_end_tag(q, req);
797 end_that_request_last(req, uptodate);
798 spin_unlock_irqrestore(q->queue_lock, flags);
801 * This will goose the queue request function at the end, so we don't
802 * need to worry about launching another command.
804 scsi_next_command(cmd);
805 return NULL;
808 static struct scatterlist *scsi_alloc_sgtable(struct scsi_cmnd *cmd, gfp_t gfp_mask)
810 struct scsi_host_sg_pool *sgp;
811 struct scatterlist *sgl;
813 BUG_ON(!cmd->use_sg);
815 switch (cmd->use_sg) {
816 case 1 ... 8:
817 cmd->sglist_len = 0;
818 break;
819 case 9 ... 16:
820 cmd->sglist_len = 1;
821 break;
822 case 17 ... 32:
823 cmd->sglist_len = 2;
824 break;
825 #if (SCSI_MAX_PHYS_SEGMENTS > 32)
826 case 33 ... 64:
827 cmd->sglist_len = 3;
828 break;
829 #if (SCSI_MAX_PHYS_SEGMENTS > 64)
830 case 65 ... 128:
831 cmd->sglist_len = 4;
832 break;
833 #if (SCSI_MAX_PHYS_SEGMENTS > 128)
834 case 129 ... 256:
835 cmd->sglist_len = 5;
836 break;
837 #endif
838 #endif
839 #endif
840 default:
841 return NULL;
844 sgp = scsi_sg_pools + cmd->sglist_len;
845 sgl = mempool_alloc(sgp->pool, gfp_mask);
846 return sgl;
849 static void scsi_free_sgtable(struct scatterlist *sgl, int index)
851 struct scsi_host_sg_pool *sgp;
853 BUG_ON(index >= SG_MEMPOOL_NR);
855 sgp = scsi_sg_pools + index;
856 mempool_free(sgl, sgp->pool);
860 * Function: scsi_release_buffers()
862 * Purpose: Completion processing for block device I/O requests.
864 * Arguments: cmd - command that we are bailing.
866 * Lock status: Assumed that no lock is held upon entry.
868 * Returns: Nothing
870 * Notes: In the event that an upper level driver rejects a
871 * command, we must release resources allocated during
872 * the __init_io() function. Primarily this would involve
873 * the scatter-gather table, and potentially any bounce
874 * buffers.
876 static void scsi_release_buffers(struct scsi_cmnd *cmd)
878 struct request *req = cmd->request;
881 * Free up any indirection buffers we allocated for DMA purposes.
883 if (cmd->use_sg)
884 scsi_free_sgtable(cmd->request_buffer, cmd->sglist_len);
885 else if (cmd->request_buffer != req->buffer)
886 kfree(cmd->request_buffer);
889 * Zero these out. They now point to freed memory, and it is
890 * dangerous to hang onto the pointers.
892 cmd->buffer = NULL;
893 cmd->bufflen = 0;
894 cmd->request_buffer = NULL;
895 cmd->request_bufflen = 0;
899 * Function: scsi_io_completion()
901 * Purpose: Completion processing for block device I/O requests.
903 * Arguments: cmd - command that is finished.
905 * Lock status: Assumed that no lock is held upon entry.
907 * Returns: Nothing
909 * Notes: This function is matched in terms of capabilities to
910 * the function that created the scatter-gather list.
911 * In other words, if there are no bounce buffers
912 * (the normal case for most drivers), we don't need
913 * the logic to deal with cleaning up afterwards.
915 * We must do one of several things here:
917 * a) Call scsi_end_request. This will finish off the
918 * specified number of sectors. If we are done, the
919 * command block will be released, and the queue
920 * function will be goosed. If we are not done, then
921 * scsi_end_request will directly goose the queue.
923 * b) We can just use scsi_requeue_command() here. This would
924 * be used if we just wanted to retry, for example.
926 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes,
927 unsigned int block_bytes)
929 int result = cmd->result;
930 int this_count = cmd->bufflen;
931 request_queue_t *q = cmd->device->request_queue;
932 struct request *req = cmd->request;
933 int clear_errors = 1;
934 struct scsi_sense_hdr sshdr;
935 int sense_valid = 0;
936 int sense_deferred = 0;
939 * Free up any indirection buffers we allocated for DMA purposes.
940 * For the case of a READ, we need to copy the data out of the
941 * bounce buffer and into the real buffer.
943 if (cmd->use_sg)
944 scsi_free_sgtable(cmd->buffer, cmd->sglist_len);
945 else if (cmd->buffer != req->buffer) {
946 if (rq_data_dir(req) == READ) {
947 unsigned long flags;
948 char *to = bio_kmap_irq(req->bio, &flags);
949 memcpy(to, cmd->buffer, cmd->bufflen);
950 bio_kunmap_irq(to, &flags);
952 kfree(cmd->buffer);
955 if (result) {
956 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
957 if (sense_valid)
958 sense_deferred = scsi_sense_is_deferred(&sshdr);
960 if (blk_pc_request(req)) { /* SG_IO ioctl from block level */
961 req->errors = result;
962 if (result) {
963 clear_errors = 0;
964 if (sense_valid && req->sense) {
966 * SG_IO wants current and deferred errors
968 int len = 8 + cmd->sense_buffer[7];
970 if (len > SCSI_SENSE_BUFFERSIZE)
971 len = SCSI_SENSE_BUFFERSIZE;
972 memcpy(req->sense, cmd->sense_buffer, len);
973 req->sense_len = len;
975 } else
976 req->data_len = cmd->resid;
980 * Zero these out. They now point to freed memory, and it is
981 * dangerous to hang onto the pointers.
983 cmd->buffer = NULL;
984 cmd->bufflen = 0;
985 cmd->request_buffer = NULL;
986 cmd->request_bufflen = 0;
989 * Next deal with any sectors which we were able to correctly
990 * handle.
992 if (good_bytes >= 0) {
993 SCSI_LOG_HLCOMPLETE(1, printk("%ld sectors total, %d bytes done.\n",
994 req->nr_sectors, good_bytes));
995 SCSI_LOG_HLCOMPLETE(1, printk("use_sg is %d\n", cmd->use_sg));
997 if (clear_errors)
998 req->errors = 0;
1000 * If multiple sectors are requested in one buffer, then
1001 * they will have been finished off by the first command.
1002 * If not, then we have a multi-buffer command.
1004 * If block_bytes != 0, it means we had a medium error
1005 * of some sort, and that we want to mark some number of
1006 * sectors as not uptodate. Thus we want to inhibit
1007 * requeueing right here - we will requeue down below
1008 * when we handle the bad sectors.
1012 * If the command completed without error, then either
1013 * finish off the rest of the command, or start a new one.
1015 if (scsi_end_request(cmd, 1, good_bytes, result == 0) == NULL)
1016 return;
1019 * Now, if we were good little boys and girls, Santa left us a request
1020 * sense buffer. We can extract information from this, so we
1021 * can choose a block to remap, etc.
1023 if (sense_valid && !sense_deferred) {
1024 switch (sshdr.sense_key) {
1025 case UNIT_ATTENTION:
1026 if (cmd->device->removable) {
1027 /* detected disc change. set a bit
1028 * and quietly refuse further access.
1030 cmd->device->changed = 1;
1031 scsi_end_request(cmd, 0,
1032 this_count, 1);
1033 return;
1034 } else {
1036 * Must have been a power glitch, or a
1037 * bus reset. Could not have been a
1038 * media change, so we just retry the
1039 * request and see what happens.
1041 scsi_requeue_command(q, cmd);
1042 return;
1044 break;
1045 case ILLEGAL_REQUEST:
1047 * If we had an ILLEGAL REQUEST returned, then we may
1048 * have performed an unsupported command. The only
1049 * thing this should be would be a ten byte read where
1050 * only a six byte read was supported. Also, on a
1051 * system where READ CAPACITY failed, we may have read
1052 * past the end of the disk.
1054 if ((cmd->device->use_10_for_rw &&
1055 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
1056 (cmd->cmnd[0] == READ_10 ||
1057 cmd->cmnd[0] == WRITE_10)) {
1058 cmd->device->use_10_for_rw = 0;
1060 * This will cause a retry with a 6-byte
1061 * command.
1063 scsi_requeue_command(q, cmd);
1064 result = 0;
1065 } else {
1066 scsi_end_request(cmd, 0, this_count, 1);
1067 return;
1069 break;
1070 case NOT_READY:
1072 * If the device is in the process of becoming ready,
1073 * retry.
1075 if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) {
1076 scsi_requeue_command(q, cmd);
1077 return;
1079 if (!(req->flags & REQ_QUIET))
1080 scmd_printk(KERN_INFO, cmd,
1081 "Device not ready.\n");
1082 scsi_end_request(cmd, 0, this_count, 1);
1083 return;
1084 case VOLUME_OVERFLOW:
1085 if (!(req->flags & REQ_QUIET)) {
1086 scmd_printk(KERN_INFO, cmd,
1087 "Volume overflow, CDB: ");
1088 __scsi_print_command(cmd->data_cmnd);
1089 scsi_print_sense("", cmd);
1091 scsi_end_request(cmd, 0, block_bytes, 1);
1092 return;
1093 default:
1094 break;
1096 } /* driver byte != 0 */
1097 if (host_byte(result) == DID_RESET) {
1099 * Third party bus reset or reset for error
1100 * recovery reasons. Just retry the request
1101 * and see what happens.
1103 scsi_requeue_command(q, cmd);
1104 return;
1106 if (result) {
1107 if (!(req->flags & REQ_QUIET)) {
1108 scmd_printk(KERN_INFO, cmd,
1109 "SCSI error: return code = 0x%x\n", result);
1111 if (driver_byte(result) & DRIVER_SENSE)
1112 scsi_print_sense("", cmd);
1115 * Mark a single buffer as not uptodate. Queue the remainder.
1116 * We sometimes get this cruft in the event that a medium error
1117 * isn't properly reported.
1119 block_bytes = req->hard_cur_sectors << 9;
1120 if (!block_bytes)
1121 block_bytes = req->data_len;
1122 scsi_end_request(cmd, 0, block_bytes, 1);
1125 EXPORT_SYMBOL(scsi_io_completion);
1128 * Function: scsi_init_io()
1130 * Purpose: SCSI I/O initialize function.
1132 * Arguments: cmd - Command descriptor we wish to initialize
1134 * Returns: 0 on success
1135 * BLKPREP_DEFER if the failure is retryable
1136 * BLKPREP_KILL if the failure is fatal
1138 static int scsi_init_io(struct scsi_cmnd *cmd)
1140 struct request *req = cmd->request;
1141 struct scatterlist *sgpnt;
1142 int count;
1145 * if this is a rq->data based REQ_BLOCK_PC, setup for a non-sg xfer
1147 if ((req->flags & REQ_BLOCK_PC) && !req->bio) {
1148 cmd->request_bufflen = req->data_len;
1149 cmd->request_buffer = req->data;
1150 req->buffer = req->data;
1151 cmd->use_sg = 0;
1152 return 0;
1156 * we used to not use scatter-gather for single segment request,
1157 * but now we do (it makes highmem I/O easier to support without
1158 * kmapping pages)
1160 cmd->use_sg = req->nr_phys_segments;
1163 * if sg table allocation fails, requeue request later.
1165 sgpnt = scsi_alloc_sgtable(cmd, GFP_ATOMIC);
1166 if (unlikely(!sgpnt)) {
1167 scsi_unprep_request(req);
1168 return BLKPREP_DEFER;
1171 cmd->request_buffer = (char *) sgpnt;
1172 cmd->request_bufflen = req->nr_sectors << 9;
1173 if (blk_pc_request(req))
1174 cmd->request_bufflen = req->data_len;
1175 req->buffer = NULL;
1178 * Next, walk the list, and fill in the addresses and sizes of
1179 * each segment.
1181 count = blk_rq_map_sg(req->q, req, cmd->request_buffer);
1184 * mapped well, send it off
1186 if (likely(count <= cmd->use_sg)) {
1187 cmd->use_sg = count;
1188 return 0;
1191 printk(KERN_ERR "Incorrect number of segments after building list\n");
1192 printk(KERN_ERR "counted %d, received %d\n", count, cmd->use_sg);
1193 printk(KERN_ERR "req nr_sec %lu, cur_nr_sec %u\n", req->nr_sectors,
1194 req->current_nr_sectors);
1196 /* release the command and kill it */
1197 scsi_release_buffers(cmd);
1198 scsi_put_command(cmd);
1199 return BLKPREP_KILL;
1202 static int scsi_issue_flush_fn(request_queue_t *q, struct gendisk *disk,
1203 sector_t *error_sector)
1205 struct scsi_device *sdev = q->queuedata;
1206 struct scsi_driver *drv;
1208 if (sdev->sdev_state != SDEV_RUNNING)
1209 return -ENXIO;
1211 drv = *(struct scsi_driver **) disk->private_data;
1212 if (drv->issue_flush)
1213 return drv->issue_flush(&sdev->sdev_gendev, error_sector);
1215 return -EOPNOTSUPP;
1218 static void scsi_blk_pc_done(struct scsi_cmnd *cmd)
1220 BUG_ON(!blk_pc_request(cmd->request));
1222 * This will complete the whole command with uptodate=1 so
1223 * as far as the block layer is concerned the command completed
1224 * successfully. Since this is a REQ_BLOCK_PC command the
1225 * caller should check the request's errors value
1227 scsi_io_completion(cmd, cmd->bufflen, 0);
1230 static void scsi_setup_blk_pc_cmnd(struct scsi_cmnd *cmd)
1232 struct request *req = cmd->request;
1234 BUG_ON(sizeof(req->cmd) > sizeof(cmd->cmnd));
1235 memcpy(cmd->cmnd, req->cmd, sizeof(cmd->cmnd));
1236 cmd->cmd_len = req->cmd_len;
1237 if (!req->data_len)
1238 cmd->sc_data_direction = DMA_NONE;
1239 else if (rq_data_dir(req) == WRITE)
1240 cmd->sc_data_direction = DMA_TO_DEVICE;
1241 else
1242 cmd->sc_data_direction = DMA_FROM_DEVICE;
1244 cmd->transfersize = req->data_len;
1245 cmd->allowed = req->retries;
1246 cmd->timeout_per_command = req->timeout;
1247 cmd->done = scsi_blk_pc_done;
1250 static int scsi_prep_fn(struct request_queue *q, struct request *req)
1252 struct scsi_device *sdev = q->queuedata;
1253 struct scsi_cmnd *cmd;
1254 int specials_only = 0;
1257 * Just check to see if the device is online. If it isn't, we
1258 * refuse to process any commands. The device must be brought
1259 * online before trying any recovery commands
1261 if (unlikely(!scsi_device_online(sdev))) {
1262 sdev_printk(KERN_ERR, sdev,
1263 "rejecting I/O to offline device\n");
1264 goto kill;
1266 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1267 /* OK, we're not in a running state don't prep
1268 * user commands */
1269 if (sdev->sdev_state == SDEV_DEL) {
1270 /* Device is fully deleted, no commands
1271 * at all allowed down */
1272 sdev_printk(KERN_ERR, sdev,
1273 "rejecting I/O to dead device\n");
1274 goto kill;
1276 /* OK, we only allow special commands (i.e. not
1277 * user initiated ones */
1278 specials_only = sdev->sdev_state;
1282 * Find the actual device driver associated with this command.
1283 * The SPECIAL requests are things like character device or
1284 * ioctls, which did not originate from ll_rw_blk. Note that
1285 * the special field is also used to indicate the cmd for
1286 * the remainder of a partially fulfilled request that can
1287 * come up when there is a medium error. We have to treat
1288 * these two cases differently. We differentiate by looking
1289 * at request->cmd, as this tells us the real story.
1291 if (req->flags & REQ_SPECIAL && req->special) {
1292 struct scsi_request *sreq = req->special;
1294 if (sreq->sr_magic == SCSI_REQ_MAGIC) {
1295 cmd = scsi_get_command(sreq->sr_device, GFP_ATOMIC);
1296 if (unlikely(!cmd))
1297 goto defer;
1298 scsi_init_cmd_from_req(cmd, sreq);
1299 } else
1300 cmd = req->special;
1301 } else if (req->flags & (REQ_CMD | REQ_BLOCK_PC)) {
1303 if(unlikely(specials_only) && !(req->flags & REQ_SPECIAL)) {
1304 if(specials_only == SDEV_QUIESCE ||
1305 specials_only == SDEV_BLOCK)
1306 goto defer;
1308 sdev_printk(KERN_ERR, sdev,
1309 "rejecting I/O to device being removed\n");
1310 goto kill;
1315 * Now try and find a command block that we can use.
1317 if (!req->special) {
1318 cmd = scsi_get_command(sdev, GFP_ATOMIC);
1319 if (unlikely(!cmd))
1320 goto defer;
1321 } else
1322 cmd = req->special;
1324 /* pull a tag out of the request if we have one */
1325 cmd->tag = req->tag;
1326 } else {
1327 blk_dump_rq_flags(req, "SCSI bad req");
1328 goto kill;
1331 /* note the overloading of req->special. When the tag
1332 * is active it always means cmd. If the tag goes
1333 * back for re-queueing, it may be reset */
1334 req->special = cmd;
1335 cmd->request = req;
1338 * FIXME: drop the lock here because the functions below
1339 * expect to be called without the queue lock held. Also,
1340 * previously, we dequeued the request before dropping the
1341 * lock. We hope REQ_STARTED prevents anything untoward from
1342 * happening now.
1344 if (req->flags & (REQ_CMD | REQ_BLOCK_PC)) {
1345 int ret;
1348 * This will do a couple of things:
1349 * 1) Fill in the actual SCSI command.
1350 * 2) Fill in any other upper-level specific fields
1351 * (timeout).
1353 * If this returns 0, it means that the request failed
1354 * (reading past end of disk, reading offline device,
1355 * etc). This won't actually talk to the device, but
1356 * some kinds of consistency checking may cause the
1357 * request to be rejected immediately.
1361 * This sets up the scatter-gather table (allocating if
1362 * required).
1364 ret = scsi_init_io(cmd);
1365 switch(ret) {
1366 /* For BLKPREP_KILL/DEFER the cmd was released */
1367 case BLKPREP_KILL:
1368 goto kill;
1369 case BLKPREP_DEFER:
1370 goto defer;
1374 * Initialize the actual SCSI command for this request.
1376 if (req->flags & REQ_BLOCK_PC) {
1377 scsi_setup_blk_pc_cmnd(cmd);
1378 } else if (req->rq_disk) {
1379 struct scsi_driver *drv;
1381 drv = *(struct scsi_driver **)req->rq_disk->private_data;
1382 if (unlikely(!drv->init_command(cmd))) {
1383 scsi_release_buffers(cmd);
1384 scsi_put_command(cmd);
1385 goto kill;
1391 * The request is now prepped, no need to come back here
1393 req->flags |= REQ_DONTPREP;
1394 return BLKPREP_OK;
1396 defer:
1397 /* If we defer, the elv_next_request() returns NULL, but the
1398 * queue must be restarted, so we plug here if no returning
1399 * command will automatically do that. */
1400 if (sdev->device_busy == 0)
1401 blk_plug_device(q);
1402 return BLKPREP_DEFER;
1403 kill:
1404 req->errors = DID_NO_CONNECT << 16;
1405 return BLKPREP_KILL;
1409 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1410 * return 0.
1412 * Called with the queue_lock held.
1414 static inline int scsi_dev_queue_ready(struct request_queue *q,
1415 struct scsi_device *sdev)
1417 if (sdev->device_busy >= sdev->queue_depth)
1418 return 0;
1419 if (sdev->device_busy == 0 && sdev->device_blocked) {
1421 * unblock after device_blocked iterates to zero
1423 if (--sdev->device_blocked == 0) {
1424 SCSI_LOG_MLQUEUE(3,
1425 sdev_printk(KERN_INFO, sdev,
1426 "unblocking device at zero depth\n"));
1427 } else {
1428 blk_plug_device(q);
1429 return 0;
1432 if (sdev->device_blocked)
1433 return 0;
1435 return 1;
1439 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1440 * return 0. We must end up running the queue again whenever 0 is
1441 * returned, else IO can hang.
1443 * Called with host_lock held.
1445 static inline int scsi_host_queue_ready(struct request_queue *q,
1446 struct Scsi_Host *shost,
1447 struct scsi_device *sdev)
1449 if (scsi_host_in_recovery(shost))
1450 return 0;
1451 if (shost->host_busy == 0 && shost->host_blocked) {
1453 * unblock after host_blocked iterates to zero
1455 if (--shost->host_blocked == 0) {
1456 SCSI_LOG_MLQUEUE(3,
1457 printk("scsi%d unblocking host at zero depth\n",
1458 shost->host_no));
1459 } else {
1460 blk_plug_device(q);
1461 return 0;
1464 if ((shost->can_queue > 0 && shost->host_busy >= shost->can_queue) ||
1465 shost->host_blocked || shost->host_self_blocked) {
1466 if (list_empty(&sdev->starved_entry))
1467 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1468 return 0;
1471 /* We're OK to process the command, so we can't be starved */
1472 if (!list_empty(&sdev->starved_entry))
1473 list_del_init(&sdev->starved_entry);
1475 return 1;
1479 * Kill a request for a dead device
1481 static void scsi_kill_request(struct request *req, request_queue_t *q)
1483 struct scsi_cmnd *cmd = req->special;
1485 blkdev_dequeue_request(req);
1487 if (unlikely(cmd == NULL)) {
1488 printk(KERN_CRIT "impossible request in %s.\n",
1489 __FUNCTION__);
1490 BUG();
1493 scsi_init_cmd_errh(cmd);
1494 cmd->result = DID_NO_CONNECT << 16;
1495 atomic_inc(&cmd->device->iorequest_cnt);
1496 __scsi_done(cmd);
1499 static void scsi_softirq_done(struct request *rq)
1501 struct scsi_cmnd *cmd = rq->completion_data;
1502 unsigned long wait_for = (cmd->allowed + 1) * cmd->timeout_per_command;
1503 int disposition;
1505 INIT_LIST_HEAD(&cmd->eh_entry);
1507 disposition = scsi_decide_disposition(cmd);
1508 if (disposition != SUCCESS &&
1509 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1510 sdev_printk(KERN_ERR, cmd->device,
1511 "timing out command, waited %lus\n",
1512 wait_for/HZ);
1513 disposition = SUCCESS;
1516 scsi_log_completion(cmd, disposition);
1518 switch (disposition) {
1519 case SUCCESS:
1520 scsi_finish_command(cmd);
1521 break;
1522 case NEEDS_RETRY:
1523 scsi_retry_command(cmd);
1524 break;
1525 case ADD_TO_MLQUEUE:
1526 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1527 break;
1528 default:
1529 if (!scsi_eh_scmd_add(cmd, 0))
1530 scsi_finish_command(cmd);
1535 * Function: scsi_request_fn()
1537 * Purpose: Main strategy routine for SCSI.
1539 * Arguments: q - Pointer to actual queue.
1541 * Returns: Nothing
1543 * Lock status: IO request lock assumed to be held when called.
1545 static void scsi_request_fn(struct request_queue *q)
1547 struct scsi_device *sdev = q->queuedata;
1548 struct Scsi_Host *shost;
1549 struct scsi_cmnd *cmd;
1550 struct request *req;
1552 if (!sdev) {
1553 printk("scsi: killing requests for dead queue\n");
1554 while ((req = elv_next_request(q)) != NULL)
1555 scsi_kill_request(req, q);
1556 return;
1559 if(!get_device(&sdev->sdev_gendev))
1560 /* We must be tearing the block queue down already */
1561 return;
1564 * To start with, we keep looping until the queue is empty, or until
1565 * the host is no longer able to accept any more requests.
1567 shost = sdev->host;
1568 while (!blk_queue_plugged(q)) {
1569 int rtn;
1571 * get next queueable request. We do this early to make sure
1572 * that the request is fully prepared even if we cannot
1573 * accept it.
1575 req = elv_next_request(q);
1576 if (!req || !scsi_dev_queue_ready(q, sdev))
1577 break;
1579 if (unlikely(!scsi_device_online(sdev))) {
1580 sdev_printk(KERN_ERR, sdev,
1581 "rejecting I/O to offline device\n");
1582 scsi_kill_request(req, q);
1583 continue;
1588 * Remove the request from the request list.
1590 if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
1591 blkdev_dequeue_request(req);
1592 sdev->device_busy++;
1594 spin_unlock(q->queue_lock);
1595 cmd = req->special;
1596 if (unlikely(cmd == NULL)) {
1597 printk(KERN_CRIT "impossible request in %s.\n"
1598 "please mail a stack trace to "
1599 "linux-scsi@vger.kernel.org",
1600 __FUNCTION__);
1601 BUG();
1603 spin_lock(shost->host_lock);
1605 if (!scsi_host_queue_ready(q, shost, sdev))
1606 goto not_ready;
1607 if (sdev->single_lun) {
1608 if (scsi_target(sdev)->starget_sdev_user &&
1609 scsi_target(sdev)->starget_sdev_user != sdev)
1610 goto not_ready;
1611 scsi_target(sdev)->starget_sdev_user = sdev;
1613 shost->host_busy++;
1616 * XXX(hch): This is rather suboptimal, scsi_dispatch_cmd will
1617 * take the lock again.
1619 spin_unlock_irq(shost->host_lock);
1622 * Finally, initialize any error handling parameters, and set up
1623 * the timers for timeouts.
1625 scsi_init_cmd_errh(cmd);
1628 * Dispatch the command to the low-level driver.
1630 rtn = scsi_dispatch_cmd(cmd);
1631 spin_lock_irq(q->queue_lock);
1632 if(rtn) {
1633 /* we're refusing the command; because of
1634 * the way locks get dropped, we need to
1635 * check here if plugging is required */
1636 if(sdev->device_busy == 0)
1637 blk_plug_device(q);
1639 break;
1643 goto out;
1645 not_ready:
1646 spin_unlock_irq(shost->host_lock);
1649 * lock q, handle tag, requeue req, and decrement device_busy. We
1650 * must return with queue_lock held.
1652 * Decrementing device_busy without checking it is OK, as all such
1653 * cases (host limits or settings) should run the queue at some
1654 * later time.
1656 spin_lock_irq(q->queue_lock);
1657 blk_requeue_request(q, req);
1658 sdev->device_busy--;
1659 if(sdev->device_busy == 0)
1660 blk_plug_device(q);
1661 out:
1662 /* must be careful here...if we trigger the ->remove() function
1663 * we cannot be holding the q lock */
1664 spin_unlock_irq(q->queue_lock);
1665 put_device(&sdev->sdev_gendev);
1666 spin_lock_irq(q->queue_lock);
1669 u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
1671 struct device *host_dev;
1672 u64 bounce_limit = 0xffffffff;
1674 if (shost->unchecked_isa_dma)
1675 return BLK_BOUNCE_ISA;
1677 * Platforms with virtual-DMA translation
1678 * hardware have no practical limit.
1680 if (!PCI_DMA_BUS_IS_PHYS)
1681 return BLK_BOUNCE_ANY;
1683 host_dev = scsi_get_device(shost);
1684 if (host_dev && host_dev->dma_mask)
1685 bounce_limit = *host_dev->dma_mask;
1687 return bounce_limit;
1689 EXPORT_SYMBOL(scsi_calculate_bounce_limit);
1691 struct request_queue *scsi_alloc_queue(struct scsi_device *sdev)
1693 struct Scsi_Host *shost = sdev->host;
1694 struct request_queue *q;
1696 q = blk_init_queue(scsi_request_fn, NULL);
1697 if (!q)
1698 return NULL;
1700 blk_queue_prep_rq(q, scsi_prep_fn);
1702 blk_queue_max_hw_segments(q, shost->sg_tablesize);
1703 blk_queue_max_phys_segments(q, SCSI_MAX_PHYS_SEGMENTS);
1704 blk_queue_max_sectors(q, shost->max_sectors);
1705 blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
1706 blk_queue_segment_boundary(q, shost->dma_boundary);
1707 blk_queue_issue_flush_fn(q, scsi_issue_flush_fn);
1708 blk_queue_softirq_done(q, scsi_softirq_done);
1710 if (!shost->use_clustering)
1711 clear_bit(QUEUE_FLAG_CLUSTER, &q->queue_flags);
1712 return q;
1715 void scsi_free_queue(struct request_queue *q)
1717 blk_cleanup_queue(q);
1721 * Function: scsi_block_requests()
1723 * Purpose: Utility function used by low-level drivers to prevent further
1724 * commands from being queued to the device.
1726 * Arguments: shost - Host in question
1728 * Returns: Nothing
1730 * Lock status: No locks are assumed held.
1732 * Notes: There is no timer nor any other means by which the requests
1733 * get unblocked other than the low-level driver calling
1734 * scsi_unblock_requests().
1736 void scsi_block_requests(struct Scsi_Host *shost)
1738 shost->host_self_blocked = 1;
1740 EXPORT_SYMBOL(scsi_block_requests);
1743 * Function: scsi_unblock_requests()
1745 * Purpose: Utility function used by low-level drivers to allow further
1746 * commands from being queued to the device.
1748 * Arguments: shost - Host in question
1750 * Returns: Nothing
1752 * Lock status: No locks are assumed held.
1754 * Notes: There is no timer nor any other means by which the requests
1755 * get unblocked other than the low-level driver calling
1756 * scsi_unblock_requests().
1758 * This is done as an API function so that changes to the
1759 * internals of the scsi mid-layer won't require wholesale
1760 * changes to drivers that use this feature.
1762 void scsi_unblock_requests(struct Scsi_Host *shost)
1764 shost->host_self_blocked = 0;
1765 scsi_run_host_queues(shost);
1767 EXPORT_SYMBOL(scsi_unblock_requests);
1769 int __init scsi_init_queue(void)
1771 int i;
1773 scsi_io_context_cache = kmem_cache_create("scsi_io_context",
1774 sizeof(struct scsi_io_context),
1775 0, 0, NULL, NULL);
1776 if (!scsi_io_context_cache) {
1777 printk(KERN_ERR "SCSI: can't init scsi io context cache\n");
1778 return -ENOMEM;
1781 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1782 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1783 int size = sgp->size * sizeof(struct scatterlist);
1785 sgp->slab = kmem_cache_create(sgp->name, size, 0,
1786 SLAB_HWCACHE_ALIGN, NULL, NULL);
1787 if (!sgp->slab) {
1788 printk(KERN_ERR "SCSI: can't init sg slab %s\n",
1789 sgp->name);
1792 sgp->pool = mempool_create(SG_MEMPOOL_SIZE,
1793 mempool_alloc_slab, mempool_free_slab,
1794 sgp->slab);
1795 if (!sgp->pool) {
1796 printk(KERN_ERR "SCSI: can't init sg mempool %s\n",
1797 sgp->name);
1801 return 0;
1804 void scsi_exit_queue(void)
1806 int i;
1808 kmem_cache_destroy(scsi_io_context_cache);
1810 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1811 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1812 mempool_destroy(sgp->pool);
1813 kmem_cache_destroy(sgp->slab);
1817 * scsi_mode_sense - issue a mode sense, falling back from 10 to
1818 * six bytes if necessary.
1819 * @sdev: SCSI device to be queried
1820 * @dbd: set if mode sense will allow block descriptors to be returned
1821 * @modepage: mode page being requested
1822 * @buffer: request buffer (may not be smaller than eight bytes)
1823 * @len: length of request buffer.
1824 * @timeout: command timeout
1825 * @retries: number of retries before failing
1826 * @data: returns a structure abstracting the mode header data
1827 * @sense: place to put sense data (or NULL if no sense to be collected).
1828 * must be SCSI_SENSE_BUFFERSIZE big.
1830 * Returns zero if unsuccessful, or the header offset (either 4
1831 * or 8 depending on whether a six or ten byte command was
1832 * issued) if successful.
1835 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
1836 unsigned char *buffer, int len, int timeout, int retries,
1837 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr) {
1838 unsigned char cmd[12];
1839 int use_10_for_ms;
1840 int header_length;
1841 int result;
1842 struct scsi_sense_hdr my_sshdr;
1844 memset(data, 0, sizeof(*data));
1845 memset(&cmd[0], 0, 12);
1846 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
1847 cmd[2] = modepage;
1849 /* caller might not be interested in sense, but we need it */
1850 if (!sshdr)
1851 sshdr = &my_sshdr;
1853 retry:
1854 use_10_for_ms = sdev->use_10_for_ms;
1856 if (use_10_for_ms) {
1857 if (len < 8)
1858 len = 8;
1860 cmd[0] = MODE_SENSE_10;
1861 cmd[8] = len;
1862 header_length = 8;
1863 } else {
1864 if (len < 4)
1865 len = 4;
1867 cmd[0] = MODE_SENSE;
1868 cmd[4] = len;
1869 header_length = 4;
1872 memset(buffer, 0, len);
1874 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
1875 sshdr, timeout, retries);
1877 /* This code looks awful: what it's doing is making sure an
1878 * ILLEGAL REQUEST sense return identifies the actual command
1879 * byte as the problem. MODE_SENSE commands can return
1880 * ILLEGAL REQUEST if the code page isn't supported */
1882 if (use_10_for_ms && !scsi_status_is_good(result) &&
1883 (driver_byte(result) & DRIVER_SENSE)) {
1884 if (scsi_sense_valid(sshdr)) {
1885 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
1886 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
1888 * Invalid command operation code
1890 sdev->use_10_for_ms = 0;
1891 goto retry;
1896 if(scsi_status_is_good(result)) {
1897 data->header_length = header_length;
1898 if(use_10_for_ms) {
1899 data->length = buffer[0]*256 + buffer[1] + 2;
1900 data->medium_type = buffer[2];
1901 data->device_specific = buffer[3];
1902 data->longlba = buffer[4] & 0x01;
1903 data->block_descriptor_length = buffer[6]*256
1904 + buffer[7];
1905 } else {
1906 data->length = buffer[0] + 1;
1907 data->medium_type = buffer[1];
1908 data->device_specific = buffer[2];
1909 data->block_descriptor_length = buffer[3];
1913 return result;
1915 EXPORT_SYMBOL(scsi_mode_sense);
1918 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries)
1920 char cmd[] = {
1921 TEST_UNIT_READY, 0, 0, 0, 0, 0,
1923 struct scsi_sense_hdr sshdr;
1924 int result;
1926 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, &sshdr,
1927 timeout, retries);
1929 if ((driver_byte(result) & DRIVER_SENSE) && sdev->removable) {
1931 if ((scsi_sense_valid(&sshdr)) &&
1932 ((sshdr.sense_key == UNIT_ATTENTION) ||
1933 (sshdr.sense_key == NOT_READY))) {
1934 sdev->changed = 1;
1935 result = 0;
1938 return result;
1940 EXPORT_SYMBOL(scsi_test_unit_ready);
1943 * scsi_device_set_state - Take the given device through the device
1944 * state model.
1945 * @sdev: scsi device to change the state of.
1946 * @state: state to change to.
1948 * Returns zero if unsuccessful or an error if the requested
1949 * transition is illegal.
1952 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
1954 enum scsi_device_state oldstate = sdev->sdev_state;
1956 if (state == oldstate)
1957 return 0;
1959 switch (state) {
1960 case SDEV_CREATED:
1961 /* There are no legal states that come back to
1962 * created. This is the manually initialised start
1963 * state */
1964 goto illegal;
1966 case SDEV_RUNNING:
1967 switch (oldstate) {
1968 case SDEV_CREATED:
1969 case SDEV_OFFLINE:
1970 case SDEV_QUIESCE:
1971 case SDEV_BLOCK:
1972 break;
1973 default:
1974 goto illegal;
1976 break;
1978 case SDEV_QUIESCE:
1979 switch (oldstate) {
1980 case SDEV_RUNNING:
1981 case SDEV_OFFLINE:
1982 break;
1983 default:
1984 goto illegal;
1986 break;
1988 case SDEV_OFFLINE:
1989 switch (oldstate) {
1990 case SDEV_CREATED:
1991 case SDEV_RUNNING:
1992 case SDEV_QUIESCE:
1993 case SDEV_BLOCK:
1994 break;
1995 default:
1996 goto illegal;
1998 break;
2000 case SDEV_BLOCK:
2001 switch (oldstate) {
2002 case SDEV_CREATED:
2003 case SDEV_RUNNING:
2004 break;
2005 default:
2006 goto illegal;
2008 break;
2010 case SDEV_CANCEL:
2011 switch (oldstate) {
2012 case SDEV_CREATED:
2013 case SDEV_RUNNING:
2014 case SDEV_OFFLINE:
2015 case SDEV_BLOCK:
2016 break;
2017 default:
2018 goto illegal;
2020 break;
2022 case SDEV_DEL:
2023 switch (oldstate) {
2024 case SDEV_CANCEL:
2025 break;
2026 default:
2027 goto illegal;
2029 break;
2032 sdev->sdev_state = state;
2033 return 0;
2035 illegal:
2036 SCSI_LOG_ERROR_RECOVERY(1,
2037 sdev_printk(KERN_ERR, sdev,
2038 "Illegal state transition %s->%s\n",
2039 scsi_device_state_name(oldstate),
2040 scsi_device_state_name(state))
2042 return -EINVAL;
2044 EXPORT_SYMBOL(scsi_device_set_state);
2047 * scsi_device_quiesce - Block user issued commands.
2048 * @sdev: scsi device to quiesce.
2050 * This works by trying to transition to the SDEV_QUIESCE state
2051 * (which must be a legal transition). When the device is in this
2052 * state, only special requests will be accepted, all others will
2053 * be deferred. Since special requests may also be requeued requests,
2054 * a successful return doesn't guarantee the device will be
2055 * totally quiescent.
2057 * Must be called with user context, may sleep.
2059 * Returns zero if unsuccessful or an error if not.
2062 scsi_device_quiesce(struct scsi_device *sdev)
2064 int err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2065 if (err)
2066 return err;
2068 scsi_run_queue(sdev->request_queue);
2069 while (sdev->device_busy) {
2070 msleep_interruptible(200);
2071 scsi_run_queue(sdev->request_queue);
2073 return 0;
2075 EXPORT_SYMBOL(scsi_device_quiesce);
2078 * scsi_device_resume - Restart user issued commands to a quiesced device.
2079 * @sdev: scsi device to resume.
2081 * Moves the device from quiesced back to running and restarts the
2082 * queues.
2084 * Must be called with user context, may sleep.
2086 void
2087 scsi_device_resume(struct scsi_device *sdev)
2089 if(scsi_device_set_state(sdev, SDEV_RUNNING))
2090 return;
2091 scsi_run_queue(sdev->request_queue);
2093 EXPORT_SYMBOL(scsi_device_resume);
2095 static void
2096 device_quiesce_fn(struct scsi_device *sdev, void *data)
2098 scsi_device_quiesce(sdev);
2101 void
2102 scsi_target_quiesce(struct scsi_target *starget)
2104 starget_for_each_device(starget, NULL, device_quiesce_fn);
2106 EXPORT_SYMBOL(scsi_target_quiesce);
2108 static void
2109 device_resume_fn(struct scsi_device *sdev, void *data)
2111 scsi_device_resume(sdev);
2114 void
2115 scsi_target_resume(struct scsi_target *starget)
2117 starget_for_each_device(starget, NULL, device_resume_fn);
2119 EXPORT_SYMBOL(scsi_target_resume);
2122 * scsi_internal_device_block - internal function to put a device
2123 * temporarily into the SDEV_BLOCK state
2124 * @sdev: device to block
2126 * Block request made by scsi lld's to temporarily stop all
2127 * scsi commands on the specified device. Called from interrupt
2128 * or normal process context.
2130 * Returns zero if successful or error if not
2132 * Notes:
2133 * This routine transitions the device to the SDEV_BLOCK state
2134 * (which must be a legal transition). When the device is in this
2135 * state, all commands are deferred until the scsi lld reenables
2136 * the device with scsi_device_unblock or device_block_tmo fires.
2137 * This routine assumes the host_lock is held on entry.
2140 scsi_internal_device_block(struct scsi_device *sdev)
2142 request_queue_t *q = sdev->request_queue;
2143 unsigned long flags;
2144 int err = 0;
2146 err = scsi_device_set_state(sdev, SDEV_BLOCK);
2147 if (err)
2148 return err;
2151 * The device has transitioned to SDEV_BLOCK. Stop the
2152 * block layer from calling the midlayer with this device's
2153 * request queue.
2155 spin_lock_irqsave(q->queue_lock, flags);
2156 blk_stop_queue(q);
2157 spin_unlock_irqrestore(q->queue_lock, flags);
2159 return 0;
2161 EXPORT_SYMBOL_GPL(scsi_internal_device_block);
2164 * scsi_internal_device_unblock - resume a device after a block request
2165 * @sdev: device to resume
2167 * Called by scsi lld's or the midlayer to restart the device queue
2168 * for the previously suspended scsi device. Called from interrupt or
2169 * normal process context.
2171 * Returns zero if successful or error if not.
2173 * Notes:
2174 * This routine transitions the device to the SDEV_RUNNING state
2175 * (which must be a legal transition) allowing the midlayer to
2176 * goose the queue for this device. This routine assumes the
2177 * host_lock is held upon entry.
2180 scsi_internal_device_unblock(struct scsi_device *sdev)
2182 request_queue_t *q = sdev->request_queue;
2183 int err;
2184 unsigned long flags;
2187 * Try to transition the scsi device to SDEV_RUNNING
2188 * and goose the device queue if successful.
2190 err = scsi_device_set_state(sdev, SDEV_RUNNING);
2191 if (err)
2192 return err;
2194 spin_lock_irqsave(q->queue_lock, flags);
2195 blk_start_queue(q);
2196 spin_unlock_irqrestore(q->queue_lock, flags);
2198 return 0;
2200 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock);
2202 static void
2203 device_block(struct scsi_device *sdev, void *data)
2205 scsi_internal_device_block(sdev);
2208 static int
2209 target_block(struct device *dev, void *data)
2211 if (scsi_is_target_device(dev))
2212 starget_for_each_device(to_scsi_target(dev), NULL,
2213 device_block);
2214 return 0;
2217 void
2218 scsi_target_block(struct device *dev)
2220 if (scsi_is_target_device(dev))
2221 starget_for_each_device(to_scsi_target(dev), NULL,
2222 device_block);
2223 else
2224 device_for_each_child(dev, NULL, target_block);
2226 EXPORT_SYMBOL_GPL(scsi_target_block);
2228 static void
2229 device_unblock(struct scsi_device *sdev, void *data)
2231 scsi_internal_device_unblock(sdev);
2234 static int
2235 target_unblock(struct device *dev, void *data)
2237 if (scsi_is_target_device(dev))
2238 starget_for_each_device(to_scsi_target(dev), NULL,
2239 device_unblock);
2240 return 0;
2243 void
2244 scsi_target_unblock(struct device *dev)
2246 if (scsi_is_target_device(dev))
2247 starget_for_each_device(to_scsi_target(dev), NULL,
2248 device_unblock);
2249 else
2250 device_for_each_child(dev, NULL, target_unblock);
2252 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2255 struct work_queue_work {
2256 struct work_struct work;
2257 void (*fn)(void *);
2258 void *data;
2261 static void execute_in_process_context_work(void *data)
2263 void (*fn)(void *data);
2264 struct work_queue_work *wqw = data;
2266 fn = wqw->fn;
2267 data = wqw->data;
2269 kfree(wqw);
2271 fn(data);
2275 * scsi_execute_in_process_context - reliably execute the routine with user context
2276 * @fn: the function to execute
2277 * @data: data to pass to the function
2279 * Executes the function immediately if process context is available,
2280 * otherwise schedules the function for delayed execution.
2282 * Returns: 0 - function was executed
2283 * 1 - function was scheduled for execution
2284 * <0 - error
2286 int scsi_execute_in_process_context(void (*fn)(void *data), void *data)
2288 struct work_queue_work *wqw;
2290 if (!in_interrupt()) {
2291 fn(data);
2292 return 0;
2295 wqw = kmalloc(sizeof(struct work_queue_work), GFP_ATOMIC);
2297 if (unlikely(!wqw)) {
2298 printk(KERN_ERR "Failed to allocate memory\n");
2299 WARN_ON(1);
2300 return -ENOMEM;
2303 INIT_WORK(&wqw->work, execute_in_process_context_work, wqw);
2304 wqw->fn = fn;
2305 wqw->data = data;
2306 schedule_work(&wqw->work);
2308 return 1;
2310 EXPORT_SYMBOL_GPL(scsi_execute_in_process_context);