[CPUFREQ] Fix the p4-clockmod N60 errata workaround.
[linux-2.6/mini2440.git] / drivers / scsi / scsi_lib.c
blob4362dcde74afddaf797587b67b5a65c79d942599
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 + 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 memcpy(req->cmd, cmd, req->cmd_len);
479 req->sense = sioc->sense;
480 req->sense_len = 0;
481 req->timeout = timeout;
482 req->retries = retries;
483 req->end_io_data = sioc;
485 sioc->data = privdata;
486 sioc->done = done;
488 blk_execute_rq_nowait(req->q, NULL, req, 1, scsi_end_async);
489 return 0;
491 free_req:
492 blk_put_request(req);
493 free_sense:
494 kfree(sioc);
495 return DRIVER_ERROR << 24;
497 EXPORT_SYMBOL_GPL(scsi_execute_async);
500 * Function: scsi_init_cmd_errh()
502 * Purpose: Initialize cmd fields related to error handling.
504 * Arguments: cmd - command that is ready to be queued.
506 * Returns: Nothing
508 * Notes: This function has the job of initializing a number of
509 * fields related to error handling. Typically this will
510 * be called once for each command, as required.
512 static int scsi_init_cmd_errh(struct scsi_cmnd *cmd)
514 cmd->serial_number = 0;
516 memset(cmd->sense_buffer, 0, sizeof cmd->sense_buffer);
518 if (cmd->cmd_len == 0)
519 cmd->cmd_len = COMMAND_SIZE(cmd->cmnd[0]);
522 * We need saved copies of a number of fields - this is because
523 * error handling may need to overwrite these with different values
524 * to run different commands, and once error handling is complete,
525 * we will need to restore these values prior to running the actual
526 * command.
528 cmd->old_use_sg = cmd->use_sg;
529 cmd->old_cmd_len = cmd->cmd_len;
530 cmd->sc_old_data_direction = cmd->sc_data_direction;
531 cmd->old_underflow = cmd->underflow;
532 memcpy(cmd->data_cmnd, cmd->cmnd, sizeof(cmd->cmnd));
533 cmd->buffer = cmd->request_buffer;
534 cmd->bufflen = cmd->request_bufflen;
536 return 1;
540 * Function: scsi_setup_cmd_retry()
542 * Purpose: Restore the command state for a retry
544 * Arguments: cmd - command to be restored
546 * Returns: Nothing
548 * Notes: Immediately prior to retrying a command, we need
549 * to restore certain fields that we saved above.
551 void scsi_setup_cmd_retry(struct scsi_cmnd *cmd)
553 memcpy(cmd->cmnd, cmd->data_cmnd, sizeof(cmd->data_cmnd));
554 cmd->request_buffer = cmd->buffer;
555 cmd->request_bufflen = cmd->bufflen;
556 cmd->use_sg = cmd->old_use_sg;
557 cmd->cmd_len = cmd->old_cmd_len;
558 cmd->sc_data_direction = cmd->sc_old_data_direction;
559 cmd->underflow = cmd->old_underflow;
562 void scsi_device_unbusy(struct scsi_device *sdev)
564 struct Scsi_Host *shost = sdev->host;
565 unsigned long flags;
567 spin_lock_irqsave(shost->host_lock, flags);
568 shost->host_busy--;
569 if (unlikely(scsi_host_in_recovery(shost) &&
570 shost->host_failed))
571 scsi_eh_wakeup(shost);
572 spin_unlock(shost->host_lock);
573 spin_lock(sdev->request_queue->queue_lock);
574 sdev->device_busy--;
575 spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
579 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
580 * and call blk_run_queue for all the scsi_devices on the target -
581 * including current_sdev first.
583 * Called with *no* scsi locks held.
585 static void scsi_single_lun_run(struct scsi_device *current_sdev)
587 struct Scsi_Host *shost = current_sdev->host;
588 struct scsi_device *sdev, *tmp;
589 struct scsi_target *starget = scsi_target(current_sdev);
590 unsigned long flags;
592 spin_lock_irqsave(shost->host_lock, flags);
593 starget->starget_sdev_user = NULL;
594 spin_unlock_irqrestore(shost->host_lock, flags);
597 * Call blk_run_queue for all LUNs on the target, starting with
598 * current_sdev. We race with others (to set starget_sdev_user),
599 * but in most cases, we will be first. Ideally, each LU on the
600 * target would get some limited time or requests on the target.
602 blk_run_queue(current_sdev->request_queue);
604 spin_lock_irqsave(shost->host_lock, flags);
605 if (starget->starget_sdev_user)
606 goto out;
607 list_for_each_entry_safe(sdev, tmp, &starget->devices,
608 same_target_siblings) {
609 if (sdev == current_sdev)
610 continue;
611 if (scsi_device_get(sdev))
612 continue;
614 spin_unlock_irqrestore(shost->host_lock, flags);
615 blk_run_queue(sdev->request_queue);
616 spin_lock_irqsave(shost->host_lock, flags);
618 scsi_device_put(sdev);
620 out:
621 spin_unlock_irqrestore(shost->host_lock, flags);
625 * Function: scsi_run_queue()
627 * Purpose: Select a proper request queue to serve next
629 * Arguments: q - last request's queue
631 * Returns: Nothing
633 * Notes: The previous command was completely finished, start
634 * a new one if possible.
636 static void scsi_run_queue(struct request_queue *q)
638 struct scsi_device *sdev = q->queuedata;
639 struct Scsi_Host *shost = sdev->host;
640 unsigned long flags;
642 if (sdev->single_lun)
643 scsi_single_lun_run(sdev);
645 spin_lock_irqsave(shost->host_lock, flags);
646 while (!list_empty(&shost->starved_list) &&
647 !shost->host_blocked && !shost->host_self_blocked &&
648 !((shost->can_queue > 0) &&
649 (shost->host_busy >= shost->can_queue))) {
651 * As long as shost is accepting commands and we have
652 * starved queues, call blk_run_queue. scsi_request_fn
653 * drops the queue_lock and can add us back to the
654 * starved_list.
656 * host_lock protects the starved_list and starved_entry.
657 * scsi_request_fn must get the host_lock before checking
658 * or modifying starved_list or starved_entry.
660 sdev = list_entry(shost->starved_list.next,
661 struct scsi_device, starved_entry);
662 list_del_init(&sdev->starved_entry);
663 spin_unlock_irqrestore(shost->host_lock, flags);
665 blk_run_queue(sdev->request_queue);
667 spin_lock_irqsave(shost->host_lock, flags);
668 if (unlikely(!list_empty(&sdev->starved_entry)))
670 * sdev lost a race, and was put back on the
671 * starved list. This is unlikely but without this
672 * in theory we could loop forever.
674 break;
676 spin_unlock_irqrestore(shost->host_lock, flags);
678 blk_run_queue(q);
682 * Function: scsi_requeue_command()
684 * Purpose: Handle post-processing of completed commands.
686 * Arguments: q - queue to operate on
687 * cmd - command that may need to be requeued.
689 * Returns: Nothing
691 * Notes: After command completion, there may be blocks left
692 * over which weren't finished by the previous command
693 * this can be for a number of reasons - the main one is
694 * I/O errors in the middle of the request, in which case
695 * we need to request the blocks that come after the bad
696 * sector.
697 * Notes: Upon return, cmd is a stale pointer.
699 static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
701 struct request *req = cmd->request;
702 unsigned long flags;
704 scsi_unprep_request(req);
705 spin_lock_irqsave(q->queue_lock, flags);
706 blk_requeue_request(q, req);
707 spin_unlock_irqrestore(q->queue_lock, flags);
709 scsi_run_queue(q);
712 void scsi_next_command(struct scsi_cmnd *cmd)
714 struct scsi_device *sdev = cmd->device;
715 struct request_queue *q = sdev->request_queue;
717 /* need to hold a reference on the device before we let go of the cmd */
718 get_device(&sdev->sdev_gendev);
720 scsi_put_command(cmd);
721 scsi_run_queue(q);
723 /* ok to remove device now */
724 put_device(&sdev->sdev_gendev);
727 void scsi_run_host_queues(struct Scsi_Host *shost)
729 struct scsi_device *sdev;
731 shost_for_each_device(sdev, shost)
732 scsi_run_queue(sdev->request_queue);
736 * Function: scsi_end_request()
738 * Purpose: Post-processing of completed commands (usually invoked at end
739 * of upper level post-processing and scsi_io_completion).
741 * Arguments: cmd - command that is complete.
742 * uptodate - 1 if I/O indicates success, <= 0 for I/O error.
743 * bytes - number of bytes of completed I/O
744 * requeue - indicates whether we should requeue leftovers.
746 * Lock status: Assumed that lock is not held upon entry.
748 * Returns: cmd if requeue required, NULL otherwise.
750 * Notes: This is called for block device requests in order to
751 * mark some number of sectors as complete.
753 * We are guaranteeing that the request queue will be goosed
754 * at some point during this call.
755 * Notes: If cmd was requeued, upon return it will be a stale pointer.
757 static struct scsi_cmnd *scsi_end_request(struct scsi_cmnd *cmd, int uptodate,
758 int bytes, int requeue)
760 request_queue_t *q = cmd->device->request_queue;
761 struct request *req = cmd->request;
762 unsigned long flags;
765 * If there are blocks left over at the end, set up the command
766 * to queue the remainder of them.
768 if (end_that_request_chunk(req, uptodate, bytes)) {
769 int leftover = (req->hard_nr_sectors << 9);
771 if (blk_pc_request(req))
772 leftover = req->data_len;
774 /* kill remainder if no retrys */
775 if (!uptodate && blk_noretry_request(req))
776 end_that_request_chunk(req, 0, leftover);
777 else {
778 if (requeue) {
780 * Bleah. Leftovers again. Stick the
781 * leftovers in the front of the
782 * queue, and goose the queue again.
784 scsi_requeue_command(q, cmd);
785 cmd = NULL;
787 return cmd;
791 add_disk_randomness(req->rq_disk);
793 spin_lock_irqsave(q->queue_lock, flags);
794 if (blk_rq_tagged(req))
795 blk_queue_end_tag(q, req);
796 end_that_request_last(req, uptodate);
797 spin_unlock_irqrestore(q->queue_lock, flags);
800 * This will goose the queue request function at the end, so we don't
801 * need to worry about launching another command.
803 scsi_next_command(cmd);
804 return NULL;
807 static struct scatterlist *scsi_alloc_sgtable(struct scsi_cmnd *cmd, gfp_t gfp_mask)
809 struct scsi_host_sg_pool *sgp;
810 struct scatterlist *sgl;
812 BUG_ON(!cmd->use_sg);
814 switch (cmd->use_sg) {
815 case 1 ... 8:
816 cmd->sglist_len = 0;
817 break;
818 case 9 ... 16:
819 cmd->sglist_len = 1;
820 break;
821 case 17 ... 32:
822 cmd->sglist_len = 2;
823 break;
824 #if (SCSI_MAX_PHYS_SEGMENTS > 32)
825 case 33 ... 64:
826 cmd->sglist_len = 3;
827 break;
828 #if (SCSI_MAX_PHYS_SEGMENTS > 64)
829 case 65 ... 128:
830 cmd->sglist_len = 4;
831 break;
832 #if (SCSI_MAX_PHYS_SEGMENTS > 128)
833 case 129 ... 256:
834 cmd->sglist_len = 5;
835 break;
836 #endif
837 #endif
838 #endif
839 default:
840 return NULL;
843 sgp = scsi_sg_pools + cmd->sglist_len;
844 sgl = mempool_alloc(sgp->pool, gfp_mask);
845 return sgl;
848 static void scsi_free_sgtable(struct scatterlist *sgl, int index)
850 struct scsi_host_sg_pool *sgp;
852 BUG_ON(index >= SG_MEMPOOL_NR);
854 sgp = scsi_sg_pools + index;
855 mempool_free(sgl, sgp->pool);
859 * Function: scsi_release_buffers()
861 * Purpose: Completion processing for block device I/O requests.
863 * Arguments: cmd - command that we are bailing.
865 * Lock status: Assumed that no lock is held upon entry.
867 * Returns: Nothing
869 * Notes: In the event that an upper level driver rejects a
870 * command, we must release resources allocated during
871 * the __init_io() function. Primarily this would involve
872 * the scatter-gather table, and potentially any bounce
873 * buffers.
875 static void scsi_release_buffers(struct scsi_cmnd *cmd)
877 struct request *req = cmd->request;
880 * Free up any indirection buffers we allocated for DMA purposes.
882 if (cmd->use_sg)
883 scsi_free_sgtable(cmd->request_buffer, cmd->sglist_len);
884 else if (cmd->request_buffer != req->buffer)
885 kfree(cmd->request_buffer);
888 * Zero these out. They now point to freed memory, and it is
889 * dangerous to hang onto the pointers.
891 cmd->buffer = NULL;
892 cmd->bufflen = 0;
893 cmd->request_buffer = NULL;
894 cmd->request_bufflen = 0;
898 * Function: scsi_io_completion()
900 * Purpose: Completion processing for block device I/O requests.
902 * Arguments: cmd - command that is finished.
904 * Lock status: Assumed that no lock is held upon entry.
906 * Returns: Nothing
908 * Notes: This function is matched in terms of capabilities to
909 * the function that created the scatter-gather list.
910 * In other words, if there are no bounce buffers
911 * (the normal case for most drivers), we don't need
912 * the logic to deal with cleaning up afterwards.
914 * We must do one of several things here:
916 * a) Call scsi_end_request. This will finish off the
917 * specified number of sectors. If we are done, the
918 * command block will be released, and the queue
919 * function will be goosed. If we are not done, then
920 * scsi_end_request will directly goose the queue.
922 * b) We can just use scsi_requeue_command() here. This would
923 * be used if we just wanted to retry, for example.
925 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes,
926 unsigned int block_bytes)
928 int result = cmd->result;
929 int this_count = cmd->bufflen;
930 request_queue_t *q = cmd->device->request_queue;
931 struct request *req = cmd->request;
932 int clear_errors = 1;
933 struct scsi_sense_hdr sshdr;
934 int sense_valid = 0;
935 int sense_deferred = 0;
938 * Free up any indirection buffers we allocated for DMA purposes.
939 * For the case of a READ, we need to copy the data out of the
940 * bounce buffer and into the real buffer.
942 if (cmd->use_sg)
943 scsi_free_sgtable(cmd->buffer, cmd->sglist_len);
944 else if (cmd->buffer != req->buffer) {
945 if (rq_data_dir(req) == READ) {
946 unsigned long flags;
947 char *to = bio_kmap_irq(req->bio, &flags);
948 memcpy(to, cmd->buffer, cmd->bufflen);
949 bio_kunmap_irq(to, &flags);
951 kfree(cmd->buffer);
954 if (result) {
955 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
956 if (sense_valid)
957 sense_deferred = scsi_sense_is_deferred(&sshdr);
959 if (blk_pc_request(req)) { /* SG_IO ioctl from block level */
960 req->errors = result;
961 if (result) {
962 clear_errors = 0;
963 if (sense_valid && req->sense) {
965 * SG_IO wants current and deferred errors
967 int len = 8 + cmd->sense_buffer[7];
969 if (len > SCSI_SENSE_BUFFERSIZE)
970 len = SCSI_SENSE_BUFFERSIZE;
971 memcpy(req->sense, cmd->sense_buffer, len);
972 req->sense_len = len;
974 } else
975 req->data_len = cmd->resid;
979 * Zero these out. They now point to freed memory, and it is
980 * dangerous to hang onto the pointers.
982 cmd->buffer = NULL;
983 cmd->bufflen = 0;
984 cmd->request_buffer = NULL;
985 cmd->request_bufflen = 0;
988 * Next deal with any sectors which we were able to correctly
989 * handle.
991 if (good_bytes >= 0) {
992 SCSI_LOG_HLCOMPLETE(1, printk("%ld sectors total, %d bytes done.\n",
993 req->nr_sectors, good_bytes));
994 SCSI_LOG_HLCOMPLETE(1, printk("use_sg is %d\n", cmd->use_sg));
996 if (clear_errors)
997 req->errors = 0;
999 * If multiple sectors are requested in one buffer, then
1000 * they will have been finished off by the first command.
1001 * If not, then we have a multi-buffer command.
1003 * If block_bytes != 0, it means we had a medium error
1004 * of some sort, and that we want to mark some number of
1005 * sectors as not uptodate. Thus we want to inhibit
1006 * requeueing right here - we will requeue down below
1007 * when we handle the bad sectors.
1011 * If the command completed without error, then either
1012 * finish off the rest of the command, or start a new one.
1014 if (scsi_end_request(cmd, 1, good_bytes, result == 0) == NULL)
1015 return;
1018 * Now, if we were good little boys and girls, Santa left us a request
1019 * sense buffer. We can extract information from this, so we
1020 * can choose a block to remap, etc.
1022 if (sense_valid && !sense_deferred) {
1023 switch (sshdr.sense_key) {
1024 case UNIT_ATTENTION:
1025 if (cmd->device->removable) {
1026 /* detected disc change. set a bit
1027 * and quietly refuse further access.
1029 cmd->device->changed = 1;
1030 scsi_end_request(cmd, 0,
1031 this_count, 1);
1032 return;
1033 } else {
1035 * Must have been a power glitch, or a
1036 * bus reset. Could not have been a
1037 * media change, so we just retry the
1038 * request and see what happens.
1040 scsi_requeue_command(q, cmd);
1041 return;
1043 break;
1044 case ILLEGAL_REQUEST:
1046 * If we had an ILLEGAL REQUEST returned, then we may
1047 * have performed an unsupported command. The only
1048 * thing this should be would be a ten byte read where
1049 * only a six byte read was supported. Also, on a
1050 * system where READ CAPACITY failed, we may have read
1051 * past the end of the disk.
1053 if ((cmd->device->use_10_for_rw &&
1054 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
1055 (cmd->cmnd[0] == READ_10 ||
1056 cmd->cmnd[0] == WRITE_10)) {
1057 cmd->device->use_10_for_rw = 0;
1059 * This will cause a retry with a 6-byte
1060 * command.
1062 scsi_requeue_command(q, cmd);
1063 result = 0;
1064 } else {
1065 scsi_end_request(cmd, 0, this_count, 1);
1066 return;
1068 break;
1069 case NOT_READY:
1071 * If the device is in the process of becoming ready,
1072 * retry.
1074 if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) {
1075 scsi_requeue_command(q, cmd);
1076 return;
1078 if (!(req->flags & REQ_QUIET))
1079 scmd_printk(KERN_INFO, cmd,
1080 "Device not ready.\n");
1081 scsi_end_request(cmd, 0, this_count, 1);
1082 return;
1083 case VOLUME_OVERFLOW:
1084 if (!(req->flags & REQ_QUIET)) {
1085 scmd_printk(KERN_INFO, cmd,
1086 "Volume overflow, CDB: ");
1087 __scsi_print_command(cmd->data_cmnd);
1088 scsi_print_sense("", cmd);
1090 scsi_end_request(cmd, 0, block_bytes, 1);
1091 return;
1092 default:
1093 break;
1095 } /* driver byte != 0 */
1096 if (host_byte(result) == DID_RESET) {
1098 * Third party bus reset or reset for error
1099 * recovery reasons. Just retry the request
1100 * and see what happens.
1102 scsi_requeue_command(q, cmd);
1103 return;
1105 if (result) {
1106 if (!(req->flags & REQ_QUIET)) {
1107 scmd_printk(KERN_INFO, cmd,
1108 "SCSI error: return code = 0x%x\n", result);
1110 if (driver_byte(result) & DRIVER_SENSE)
1111 scsi_print_sense("", cmd);
1114 * Mark a single buffer as not uptodate. Queue the remainder.
1115 * We sometimes get this cruft in the event that a medium error
1116 * isn't properly reported.
1118 block_bytes = req->hard_cur_sectors << 9;
1119 if (!block_bytes)
1120 block_bytes = req->data_len;
1121 scsi_end_request(cmd, 0, block_bytes, 1);
1124 EXPORT_SYMBOL(scsi_io_completion);
1127 * Function: scsi_init_io()
1129 * Purpose: SCSI I/O initialize function.
1131 * Arguments: cmd - Command descriptor we wish to initialize
1133 * Returns: 0 on success
1134 * BLKPREP_DEFER if the failure is retryable
1135 * BLKPREP_KILL if the failure is fatal
1137 static int scsi_init_io(struct scsi_cmnd *cmd)
1139 struct request *req = cmd->request;
1140 struct scatterlist *sgpnt;
1141 int count;
1144 * if this is a rq->data based REQ_BLOCK_PC, setup for a non-sg xfer
1146 if ((req->flags & REQ_BLOCK_PC) && !req->bio) {
1147 cmd->request_bufflen = req->data_len;
1148 cmd->request_buffer = req->data;
1149 req->buffer = req->data;
1150 cmd->use_sg = 0;
1151 return 0;
1155 * we used to not use scatter-gather for single segment request,
1156 * but now we do (it makes highmem I/O easier to support without
1157 * kmapping pages)
1159 cmd->use_sg = req->nr_phys_segments;
1162 * if sg table allocation fails, requeue request later.
1164 sgpnt = scsi_alloc_sgtable(cmd, GFP_ATOMIC);
1165 if (unlikely(!sgpnt)) {
1166 scsi_unprep_request(req);
1167 return BLKPREP_DEFER;
1170 cmd->request_buffer = (char *) sgpnt;
1171 cmd->request_bufflen = req->nr_sectors << 9;
1172 if (blk_pc_request(req))
1173 cmd->request_bufflen = req->data_len;
1174 req->buffer = NULL;
1177 * Next, walk the list, and fill in the addresses and sizes of
1178 * each segment.
1180 count = blk_rq_map_sg(req->q, req, cmd->request_buffer);
1183 * mapped well, send it off
1185 if (likely(count <= cmd->use_sg)) {
1186 cmd->use_sg = count;
1187 return 0;
1190 printk(KERN_ERR "Incorrect number of segments after building list\n");
1191 printk(KERN_ERR "counted %d, received %d\n", count, cmd->use_sg);
1192 printk(KERN_ERR "req nr_sec %lu, cur_nr_sec %u\n", req->nr_sectors,
1193 req->current_nr_sectors);
1195 /* release the command and kill it */
1196 scsi_release_buffers(cmd);
1197 scsi_put_command(cmd);
1198 return BLKPREP_KILL;
1201 static int scsi_issue_flush_fn(request_queue_t *q, struct gendisk *disk,
1202 sector_t *error_sector)
1204 struct scsi_device *sdev = q->queuedata;
1205 struct scsi_driver *drv;
1207 if (sdev->sdev_state != SDEV_RUNNING)
1208 return -ENXIO;
1210 drv = *(struct scsi_driver **) disk->private_data;
1211 if (drv->issue_flush)
1212 return drv->issue_flush(&sdev->sdev_gendev, error_sector);
1214 return -EOPNOTSUPP;
1217 static void scsi_blk_pc_done(struct scsi_cmnd *cmd)
1219 BUG_ON(!blk_pc_request(cmd->request));
1221 * This will complete the whole command with uptodate=1 so
1222 * as far as the block layer is concerned the command completed
1223 * successfully. Since this is a REQ_BLOCK_PC command the
1224 * caller should check the request's errors value
1226 scsi_io_completion(cmd, cmd->bufflen, 0);
1229 static void scsi_setup_blk_pc_cmnd(struct scsi_cmnd *cmd)
1231 struct request *req = cmd->request;
1233 BUG_ON(sizeof(req->cmd) > sizeof(cmd->cmnd));
1234 memcpy(cmd->cmnd, req->cmd, sizeof(cmd->cmnd));
1235 cmd->cmd_len = req->cmd_len;
1236 if (!req->data_len)
1237 cmd->sc_data_direction = DMA_NONE;
1238 else if (rq_data_dir(req) == WRITE)
1239 cmd->sc_data_direction = DMA_TO_DEVICE;
1240 else
1241 cmd->sc_data_direction = DMA_FROM_DEVICE;
1243 cmd->transfersize = req->data_len;
1244 cmd->allowed = req->retries;
1245 cmd->timeout_per_command = req->timeout;
1246 cmd->done = scsi_blk_pc_done;
1249 static int scsi_prep_fn(struct request_queue *q, struct request *req)
1251 struct scsi_device *sdev = q->queuedata;
1252 struct scsi_cmnd *cmd;
1253 int specials_only = 0;
1256 * Just check to see if the device is online. If it isn't, we
1257 * refuse to process any commands. The device must be brought
1258 * online before trying any recovery commands
1260 if (unlikely(!scsi_device_online(sdev))) {
1261 sdev_printk(KERN_ERR, sdev,
1262 "rejecting I/O to offline device\n");
1263 goto kill;
1265 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1266 /* OK, we're not in a running state don't prep
1267 * user commands */
1268 if (sdev->sdev_state == SDEV_DEL) {
1269 /* Device is fully deleted, no commands
1270 * at all allowed down */
1271 sdev_printk(KERN_ERR, sdev,
1272 "rejecting I/O to dead device\n");
1273 goto kill;
1275 /* OK, we only allow special commands (i.e. not
1276 * user initiated ones */
1277 specials_only = sdev->sdev_state;
1281 * Find the actual device driver associated with this command.
1282 * The SPECIAL requests are things like character device or
1283 * ioctls, which did not originate from ll_rw_blk. Note that
1284 * the special field is also used to indicate the cmd for
1285 * the remainder of a partially fulfilled request that can
1286 * come up when there is a medium error. We have to treat
1287 * these two cases differently. We differentiate by looking
1288 * at request->cmd, as this tells us the real story.
1290 if (req->flags & REQ_SPECIAL && req->special) {
1291 struct scsi_request *sreq = req->special;
1293 if (sreq->sr_magic == SCSI_REQ_MAGIC) {
1294 cmd = scsi_get_command(sreq->sr_device, GFP_ATOMIC);
1295 if (unlikely(!cmd))
1296 goto defer;
1297 scsi_init_cmd_from_req(cmd, sreq);
1298 } else
1299 cmd = req->special;
1300 } else if (req->flags & (REQ_CMD | REQ_BLOCK_PC)) {
1302 if(unlikely(specials_only) && !(req->flags & REQ_SPECIAL)) {
1303 if(specials_only == SDEV_QUIESCE ||
1304 specials_only == SDEV_BLOCK)
1305 goto defer;
1307 sdev_printk(KERN_ERR, sdev,
1308 "rejecting I/O to device being removed\n");
1309 goto kill;
1314 * Now try and find a command block that we can use.
1316 if (!req->special) {
1317 cmd = scsi_get_command(sdev, GFP_ATOMIC);
1318 if (unlikely(!cmd))
1319 goto defer;
1320 } else
1321 cmd = req->special;
1323 /* pull a tag out of the request if we have one */
1324 cmd->tag = req->tag;
1325 } else {
1326 blk_dump_rq_flags(req, "SCSI bad req");
1327 goto kill;
1330 /* note the overloading of req->special. When the tag
1331 * is active it always means cmd. If the tag goes
1332 * back for re-queueing, it may be reset */
1333 req->special = cmd;
1334 cmd->request = req;
1337 * FIXME: drop the lock here because the functions below
1338 * expect to be called without the queue lock held. Also,
1339 * previously, we dequeued the request before dropping the
1340 * lock. We hope REQ_STARTED prevents anything untoward from
1341 * happening now.
1343 if (req->flags & (REQ_CMD | REQ_BLOCK_PC)) {
1344 int ret;
1347 * This will do a couple of things:
1348 * 1) Fill in the actual SCSI command.
1349 * 2) Fill in any other upper-level specific fields
1350 * (timeout).
1352 * If this returns 0, it means that the request failed
1353 * (reading past end of disk, reading offline device,
1354 * etc). This won't actually talk to the device, but
1355 * some kinds of consistency checking may cause the
1356 * request to be rejected immediately.
1360 * This sets up the scatter-gather table (allocating if
1361 * required).
1363 ret = scsi_init_io(cmd);
1364 switch(ret) {
1365 /* For BLKPREP_KILL/DEFER the cmd was released */
1366 case BLKPREP_KILL:
1367 goto kill;
1368 case BLKPREP_DEFER:
1369 goto defer;
1373 * Initialize the actual SCSI command for this request.
1375 if (req->flags & REQ_BLOCK_PC) {
1376 scsi_setup_blk_pc_cmnd(cmd);
1377 } else if (req->rq_disk) {
1378 struct scsi_driver *drv;
1380 drv = *(struct scsi_driver **)req->rq_disk->private_data;
1381 if (unlikely(!drv->init_command(cmd))) {
1382 scsi_release_buffers(cmd);
1383 scsi_put_command(cmd);
1384 goto kill;
1390 * The request is now prepped, no need to come back here
1392 req->flags |= REQ_DONTPREP;
1393 return BLKPREP_OK;
1395 defer:
1396 /* If we defer, the elv_next_request() returns NULL, but the
1397 * queue must be restarted, so we plug here if no returning
1398 * command will automatically do that. */
1399 if (sdev->device_busy == 0)
1400 blk_plug_device(q);
1401 return BLKPREP_DEFER;
1402 kill:
1403 req->errors = DID_NO_CONNECT << 16;
1404 return BLKPREP_KILL;
1408 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1409 * return 0.
1411 * Called with the queue_lock held.
1413 static inline int scsi_dev_queue_ready(struct request_queue *q,
1414 struct scsi_device *sdev)
1416 if (sdev->device_busy >= sdev->queue_depth)
1417 return 0;
1418 if (sdev->device_busy == 0 && sdev->device_blocked) {
1420 * unblock after device_blocked iterates to zero
1422 if (--sdev->device_blocked == 0) {
1423 SCSI_LOG_MLQUEUE(3,
1424 sdev_printk(KERN_INFO, sdev,
1425 "unblocking device at zero depth\n"));
1426 } else {
1427 blk_plug_device(q);
1428 return 0;
1431 if (sdev->device_blocked)
1432 return 0;
1434 return 1;
1438 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1439 * return 0. We must end up running the queue again whenever 0 is
1440 * returned, else IO can hang.
1442 * Called with host_lock held.
1444 static inline int scsi_host_queue_ready(struct request_queue *q,
1445 struct Scsi_Host *shost,
1446 struct scsi_device *sdev)
1448 if (scsi_host_in_recovery(shost))
1449 return 0;
1450 if (shost->host_busy == 0 && shost->host_blocked) {
1452 * unblock after host_blocked iterates to zero
1454 if (--shost->host_blocked == 0) {
1455 SCSI_LOG_MLQUEUE(3,
1456 printk("scsi%d unblocking host at zero depth\n",
1457 shost->host_no));
1458 } else {
1459 blk_plug_device(q);
1460 return 0;
1463 if ((shost->can_queue > 0 && shost->host_busy >= shost->can_queue) ||
1464 shost->host_blocked || shost->host_self_blocked) {
1465 if (list_empty(&sdev->starved_entry))
1466 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1467 return 0;
1470 /* We're OK to process the command, so we can't be starved */
1471 if (!list_empty(&sdev->starved_entry))
1472 list_del_init(&sdev->starved_entry);
1474 return 1;
1478 * Kill a request for a dead device
1480 static void scsi_kill_request(struct request *req, request_queue_t *q)
1482 struct scsi_cmnd *cmd = req->special;
1484 blkdev_dequeue_request(req);
1486 if (unlikely(cmd == NULL)) {
1487 printk(KERN_CRIT "impossible request in %s.\n",
1488 __FUNCTION__);
1489 BUG();
1492 scsi_init_cmd_errh(cmd);
1493 cmd->result = DID_NO_CONNECT << 16;
1494 atomic_inc(&cmd->device->iorequest_cnt);
1495 __scsi_done(cmd);
1498 static void scsi_softirq_done(struct request *rq)
1500 struct scsi_cmnd *cmd = rq->completion_data;
1501 unsigned long wait_for = cmd->allowed * cmd->timeout_per_command;
1502 int disposition;
1504 INIT_LIST_HEAD(&cmd->eh_entry);
1506 disposition = scsi_decide_disposition(cmd);
1507 if (disposition != SUCCESS &&
1508 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1509 sdev_printk(KERN_ERR, cmd->device,
1510 "timing out command, waited %lus\n",
1511 wait_for/HZ);
1512 disposition = SUCCESS;
1515 scsi_log_completion(cmd, disposition);
1517 switch (disposition) {
1518 case SUCCESS:
1519 scsi_finish_command(cmd);
1520 break;
1521 case NEEDS_RETRY:
1522 scsi_retry_command(cmd);
1523 break;
1524 case ADD_TO_MLQUEUE:
1525 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1526 break;
1527 default:
1528 if (!scsi_eh_scmd_add(cmd, 0))
1529 scsi_finish_command(cmd);
1534 * Function: scsi_request_fn()
1536 * Purpose: Main strategy routine for SCSI.
1538 * Arguments: q - Pointer to actual queue.
1540 * Returns: Nothing
1542 * Lock status: IO request lock assumed to be held when called.
1544 static void scsi_request_fn(struct request_queue *q)
1546 struct scsi_device *sdev = q->queuedata;
1547 struct Scsi_Host *shost;
1548 struct scsi_cmnd *cmd;
1549 struct request *req;
1551 if (!sdev) {
1552 printk("scsi: killing requests for dead queue\n");
1553 while ((req = elv_next_request(q)) != NULL)
1554 scsi_kill_request(req, q);
1555 return;
1558 if(!get_device(&sdev->sdev_gendev))
1559 /* We must be tearing the block queue down already */
1560 return;
1563 * To start with, we keep looping until the queue is empty, or until
1564 * the host is no longer able to accept any more requests.
1566 shost = sdev->host;
1567 while (!blk_queue_plugged(q)) {
1568 int rtn;
1570 * get next queueable request. We do this early to make sure
1571 * that the request is fully prepared even if we cannot
1572 * accept it.
1574 req = elv_next_request(q);
1575 if (!req || !scsi_dev_queue_ready(q, sdev))
1576 break;
1578 if (unlikely(!scsi_device_online(sdev))) {
1579 sdev_printk(KERN_ERR, sdev,
1580 "rejecting I/O to offline device\n");
1581 scsi_kill_request(req, q);
1582 continue;
1587 * Remove the request from the request list.
1589 if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
1590 blkdev_dequeue_request(req);
1591 sdev->device_busy++;
1593 spin_unlock(q->queue_lock);
1594 cmd = req->special;
1595 if (unlikely(cmd == NULL)) {
1596 printk(KERN_CRIT "impossible request in %s.\n"
1597 "please mail a stack trace to "
1598 "linux-scsi@vger.kernel.org",
1599 __FUNCTION__);
1600 BUG();
1602 spin_lock(shost->host_lock);
1604 if (!scsi_host_queue_ready(q, shost, sdev))
1605 goto not_ready;
1606 if (sdev->single_lun) {
1607 if (scsi_target(sdev)->starget_sdev_user &&
1608 scsi_target(sdev)->starget_sdev_user != sdev)
1609 goto not_ready;
1610 scsi_target(sdev)->starget_sdev_user = sdev;
1612 shost->host_busy++;
1615 * XXX(hch): This is rather suboptimal, scsi_dispatch_cmd will
1616 * take the lock again.
1618 spin_unlock_irq(shost->host_lock);
1621 * Finally, initialize any error handling parameters, and set up
1622 * the timers for timeouts.
1624 scsi_init_cmd_errh(cmd);
1627 * Dispatch the command to the low-level driver.
1629 rtn = scsi_dispatch_cmd(cmd);
1630 spin_lock_irq(q->queue_lock);
1631 if(rtn) {
1632 /* we're refusing the command; because of
1633 * the way locks get dropped, we need to
1634 * check here if plugging is required */
1635 if(sdev->device_busy == 0)
1636 blk_plug_device(q);
1638 break;
1642 goto out;
1644 not_ready:
1645 spin_unlock_irq(shost->host_lock);
1648 * lock q, handle tag, requeue req, and decrement device_busy. We
1649 * must return with queue_lock held.
1651 * Decrementing device_busy without checking it is OK, as all such
1652 * cases (host limits or settings) should run the queue at some
1653 * later time.
1655 spin_lock_irq(q->queue_lock);
1656 blk_requeue_request(q, req);
1657 sdev->device_busy--;
1658 if(sdev->device_busy == 0)
1659 blk_plug_device(q);
1660 out:
1661 /* must be careful here...if we trigger the ->remove() function
1662 * we cannot be holding the q lock */
1663 spin_unlock_irq(q->queue_lock);
1664 put_device(&sdev->sdev_gendev);
1665 spin_lock_irq(q->queue_lock);
1668 u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
1670 struct device *host_dev;
1671 u64 bounce_limit = 0xffffffff;
1673 if (shost->unchecked_isa_dma)
1674 return BLK_BOUNCE_ISA;
1676 * Platforms with virtual-DMA translation
1677 * hardware have no practical limit.
1679 if (!PCI_DMA_BUS_IS_PHYS)
1680 return BLK_BOUNCE_ANY;
1682 host_dev = scsi_get_device(shost);
1683 if (host_dev && host_dev->dma_mask)
1684 bounce_limit = *host_dev->dma_mask;
1686 return bounce_limit;
1688 EXPORT_SYMBOL(scsi_calculate_bounce_limit);
1690 struct request_queue *scsi_alloc_queue(struct scsi_device *sdev)
1692 struct Scsi_Host *shost = sdev->host;
1693 struct request_queue *q;
1695 q = blk_init_queue(scsi_request_fn, NULL);
1696 if (!q)
1697 return NULL;
1699 blk_queue_prep_rq(q, scsi_prep_fn);
1701 blk_queue_max_hw_segments(q, shost->sg_tablesize);
1702 blk_queue_max_phys_segments(q, SCSI_MAX_PHYS_SEGMENTS);
1703 blk_queue_max_sectors(q, shost->max_sectors);
1704 blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
1705 blk_queue_segment_boundary(q, shost->dma_boundary);
1706 blk_queue_issue_flush_fn(q, scsi_issue_flush_fn);
1707 blk_queue_softirq_done(q, scsi_softirq_done);
1709 if (!shost->use_clustering)
1710 clear_bit(QUEUE_FLAG_CLUSTER, &q->queue_flags);
1711 return q;
1714 void scsi_free_queue(struct request_queue *q)
1716 blk_cleanup_queue(q);
1720 * Function: scsi_block_requests()
1722 * Purpose: Utility function used by low-level drivers to prevent further
1723 * commands from being queued to the device.
1725 * Arguments: shost - Host in question
1727 * Returns: Nothing
1729 * Lock status: No locks are assumed held.
1731 * Notes: There is no timer nor any other means by which the requests
1732 * get unblocked other than the low-level driver calling
1733 * scsi_unblock_requests().
1735 void scsi_block_requests(struct Scsi_Host *shost)
1737 shost->host_self_blocked = 1;
1739 EXPORT_SYMBOL(scsi_block_requests);
1742 * Function: scsi_unblock_requests()
1744 * Purpose: Utility function used by low-level drivers to allow further
1745 * commands from being queued to the device.
1747 * Arguments: shost - Host in question
1749 * Returns: Nothing
1751 * Lock status: No locks are assumed held.
1753 * Notes: There is no timer nor any other means by which the requests
1754 * get unblocked other than the low-level driver calling
1755 * scsi_unblock_requests().
1757 * This is done as an API function so that changes to the
1758 * internals of the scsi mid-layer won't require wholesale
1759 * changes to drivers that use this feature.
1761 void scsi_unblock_requests(struct Scsi_Host *shost)
1763 shost->host_self_blocked = 0;
1764 scsi_run_host_queues(shost);
1766 EXPORT_SYMBOL(scsi_unblock_requests);
1768 int __init scsi_init_queue(void)
1770 int i;
1772 scsi_io_context_cache = kmem_cache_create("scsi_io_context",
1773 sizeof(struct scsi_io_context),
1774 0, 0, NULL, NULL);
1775 if (!scsi_io_context_cache) {
1776 printk(KERN_ERR "SCSI: can't init scsi io context cache\n");
1777 return -ENOMEM;
1780 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1781 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1782 int size = sgp->size * sizeof(struct scatterlist);
1784 sgp->slab = kmem_cache_create(sgp->name, size, 0,
1785 SLAB_HWCACHE_ALIGN, NULL, NULL);
1786 if (!sgp->slab) {
1787 printk(KERN_ERR "SCSI: can't init sg slab %s\n",
1788 sgp->name);
1791 sgp->pool = mempool_create(SG_MEMPOOL_SIZE,
1792 mempool_alloc_slab, mempool_free_slab,
1793 sgp->slab);
1794 if (!sgp->pool) {
1795 printk(KERN_ERR "SCSI: can't init sg mempool %s\n",
1796 sgp->name);
1800 return 0;
1803 void scsi_exit_queue(void)
1805 int i;
1807 kmem_cache_destroy(scsi_io_context_cache);
1809 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1810 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1811 mempool_destroy(sgp->pool);
1812 kmem_cache_destroy(sgp->slab);
1816 * scsi_mode_sense - issue a mode sense, falling back from 10 to
1817 * six bytes if necessary.
1818 * @sdev: SCSI device to be queried
1819 * @dbd: set if mode sense will allow block descriptors to be returned
1820 * @modepage: mode page being requested
1821 * @buffer: request buffer (may not be smaller than eight bytes)
1822 * @len: length of request buffer.
1823 * @timeout: command timeout
1824 * @retries: number of retries before failing
1825 * @data: returns a structure abstracting the mode header data
1826 * @sense: place to put sense data (or NULL if no sense to be collected).
1827 * must be SCSI_SENSE_BUFFERSIZE big.
1829 * Returns zero if unsuccessful, or the header offset (either 4
1830 * or 8 depending on whether a six or ten byte command was
1831 * issued) if successful.
1834 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
1835 unsigned char *buffer, int len, int timeout, int retries,
1836 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr) {
1837 unsigned char cmd[12];
1838 int use_10_for_ms;
1839 int header_length;
1840 int result;
1841 struct scsi_sense_hdr my_sshdr;
1843 memset(data, 0, sizeof(*data));
1844 memset(&cmd[0], 0, 12);
1845 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
1846 cmd[2] = modepage;
1848 /* caller might not be interested in sense, but we need it */
1849 if (!sshdr)
1850 sshdr = &my_sshdr;
1852 retry:
1853 use_10_for_ms = sdev->use_10_for_ms;
1855 if (use_10_for_ms) {
1856 if (len < 8)
1857 len = 8;
1859 cmd[0] = MODE_SENSE_10;
1860 cmd[8] = len;
1861 header_length = 8;
1862 } else {
1863 if (len < 4)
1864 len = 4;
1866 cmd[0] = MODE_SENSE;
1867 cmd[4] = len;
1868 header_length = 4;
1871 memset(buffer, 0, len);
1873 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
1874 sshdr, timeout, retries);
1876 /* This code looks awful: what it's doing is making sure an
1877 * ILLEGAL REQUEST sense return identifies the actual command
1878 * byte as the problem. MODE_SENSE commands can return
1879 * ILLEGAL REQUEST if the code page isn't supported */
1881 if (use_10_for_ms && !scsi_status_is_good(result) &&
1882 (driver_byte(result) & DRIVER_SENSE)) {
1883 if (scsi_sense_valid(sshdr)) {
1884 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
1885 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
1887 * Invalid command operation code
1889 sdev->use_10_for_ms = 0;
1890 goto retry;
1895 if(scsi_status_is_good(result)) {
1896 data->header_length = header_length;
1897 if(use_10_for_ms) {
1898 data->length = buffer[0]*256 + buffer[1] + 2;
1899 data->medium_type = buffer[2];
1900 data->device_specific = buffer[3];
1901 data->longlba = buffer[4] & 0x01;
1902 data->block_descriptor_length = buffer[6]*256
1903 + buffer[7];
1904 } else {
1905 data->length = buffer[0] + 1;
1906 data->medium_type = buffer[1];
1907 data->device_specific = buffer[2];
1908 data->block_descriptor_length = buffer[3];
1912 return result;
1914 EXPORT_SYMBOL(scsi_mode_sense);
1917 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries)
1919 char cmd[] = {
1920 TEST_UNIT_READY, 0, 0, 0, 0, 0,
1922 struct scsi_sense_hdr sshdr;
1923 int result;
1925 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, &sshdr,
1926 timeout, retries);
1928 if ((driver_byte(result) & DRIVER_SENSE) && sdev->removable) {
1930 if ((scsi_sense_valid(&sshdr)) &&
1931 ((sshdr.sense_key == UNIT_ATTENTION) ||
1932 (sshdr.sense_key == NOT_READY))) {
1933 sdev->changed = 1;
1934 result = 0;
1937 return result;
1939 EXPORT_SYMBOL(scsi_test_unit_ready);
1942 * scsi_device_set_state - Take the given device through the device
1943 * state model.
1944 * @sdev: scsi device to change the state of.
1945 * @state: state to change to.
1947 * Returns zero if unsuccessful or an error if the requested
1948 * transition is illegal.
1951 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
1953 enum scsi_device_state oldstate = sdev->sdev_state;
1955 if (state == oldstate)
1956 return 0;
1958 switch (state) {
1959 case SDEV_CREATED:
1960 /* There are no legal states that come back to
1961 * created. This is the manually initialised start
1962 * state */
1963 goto illegal;
1965 case SDEV_RUNNING:
1966 switch (oldstate) {
1967 case SDEV_CREATED:
1968 case SDEV_OFFLINE:
1969 case SDEV_QUIESCE:
1970 case SDEV_BLOCK:
1971 break;
1972 default:
1973 goto illegal;
1975 break;
1977 case SDEV_QUIESCE:
1978 switch (oldstate) {
1979 case SDEV_RUNNING:
1980 case SDEV_OFFLINE:
1981 break;
1982 default:
1983 goto illegal;
1985 break;
1987 case SDEV_OFFLINE:
1988 switch (oldstate) {
1989 case SDEV_CREATED:
1990 case SDEV_RUNNING:
1991 case SDEV_QUIESCE:
1992 case SDEV_BLOCK:
1993 break;
1994 default:
1995 goto illegal;
1997 break;
1999 case SDEV_BLOCK:
2000 switch (oldstate) {
2001 case SDEV_CREATED:
2002 case SDEV_RUNNING:
2003 break;
2004 default:
2005 goto illegal;
2007 break;
2009 case SDEV_CANCEL:
2010 switch (oldstate) {
2011 case SDEV_CREATED:
2012 case SDEV_RUNNING:
2013 case SDEV_OFFLINE:
2014 case SDEV_BLOCK:
2015 break;
2016 default:
2017 goto illegal;
2019 break;
2021 case SDEV_DEL:
2022 switch (oldstate) {
2023 case SDEV_CANCEL:
2024 break;
2025 default:
2026 goto illegal;
2028 break;
2031 sdev->sdev_state = state;
2032 return 0;
2034 illegal:
2035 SCSI_LOG_ERROR_RECOVERY(1,
2036 sdev_printk(KERN_ERR, sdev,
2037 "Illegal state transition %s->%s\n",
2038 scsi_device_state_name(oldstate),
2039 scsi_device_state_name(state))
2041 return -EINVAL;
2043 EXPORT_SYMBOL(scsi_device_set_state);
2046 * scsi_device_quiesce - Block user issued commands.
2047 * @sdev: scsi device to quiesce.
2049 * This works by trying to transition to the SDEV_QUIESCE state
2050 * (which must be a legal transition). When the device is in this
2051 * state, only special requests will be accepted, all others will
2052 * be deferred. Since special requests may also be requeued requests,
2053 * a successful return doesn't guarantee the device will be
2054 * totally quiescent.
2056 * Must be called with user context, may sleep.
2058 * Returns zero if unsuccessful or an error if not.
2061 scsi_device_quiesce(struct scsi_device *sdev)
2063 int err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2064 if (err)
2065 return err;
2067 scsi_run_queue(sdev->request_queue);
2068 while (sdev->device_busy) {
2069 msleep_interruptible(200);
2070 scsi_run_queue(sdev->request_queue);
2072 return 0;
2074 EXPORT_SYMBOL(scsi_device_quiesce);
2077 * scsi_device_resume - Restart user issued commands to a quiesced device.
2078 * @sdev: scsi device to resume.
2080 * Moves the device from quiesced back to running and restarts the
2081 * queues.
2083 * Must be called with user context, may sleep.
2085 void
2086 scsi_device_resume(struct scsi_device *sdev)
2088 if(scsi_device_set_state(sdev, SDEV_RUNNING))
2089 return;
2090 scsi_run_queue(sdev->request_queue);
2092 EXPORT_SYMBOL(scsi_device_resume);
2094 static void
2095 device_quiesce_fn(struct scsi_device *sdev, void *data)
2097 scsi_device_quiesce(sdev);
2100 void
2101 scsi_target_quiesce(struct scsi_target *starget)
2103 starget_for_each_device(starget, NULL, device_quiesce_fn);
2105 EXPORT_SYMBOL(scsi_target_quiesce);
2107 static void
2108 device_resume_fn(struct scsi_device *sdev, void *data)
2110 scsi_device_resume(sdev);
2113 void
2114 scsi_target_resume(struct scsi_target *starget)
2116 starget_for_each_device(starget, NULL, device_resume_fn);
2118 EXPORT_SYMBOL(scsi_target_resume);
2121 * scsi_internal_device_block - internal function to put a device
2122 * temporarily into the SDEV_BLOCK state
2123 * @sdev: device to block
2125 * Block request made by scsi lld's to temporarily stop all
2126 * scsi commands on the specified device. Called from interrupt
2127 * or normal process context.
2129 * Returns zero if successful or error if not
2131 * Notes:
2132 * This routine transitions the device to the SDEV_BLOCK state
2133 * (which must be a legal transition). When the device is in this
2134 * state, all commands are deferred until the scsi lld reenables
2135 * the device with scsi_device_unblock or device_block_tmo fires.
2136 * This routine assumes the host_lock is held on entry.
2139 scsi_internal_device_block(struct scsi_device *sdev)
2141 request_queue_t *q = sdev->request_queue;
2142 unsigned long flags;
2143 int err = 0;
2145 err = scsi_device_set_state(sdev, SDEV_BLOCK);
2146 if (err)
2147 return err;
2150 * The device has transitioned to SDEV_BLOCK. Stop the
2151 * block layer from calling the midlayer with this device's
2152 * request queue.
2154 spin_lock_irqsave(q->queue_lock, flags);
2155 blk_stop_queue(q);
2156 spin_unlock_irqrestore(q->queue_lock, flags);
2158 return 0;
2160 EXPORT_SYMBOL_GPL(scsi_internal_device_block);
2163 * scsi_internal_device_unblock - resume a device after a block request
2164 * @sdev: device to resume
2166 * Called by scsi lld's or the midlayer to restart the device queue
2167 * for the previously suspended scsi device. Called from interrupt or
2168 * normal process context.
2170 * Returns zero if successful or error if not.
2172 * Notes:
2173 * This routine transitions the device to the SDEV_RUNNING state
2174 * (which must be a legal transition) allowing the midlayer to
2175 * goose the queue for this device. This routine assumes the
2176 * host_lock is held upon entry.
2179 scsi_internal_device_unblock(struct scsi_device *sdev)
2181 request_queue_t *q = sdev->request_queue;
2182 int err;
2183 unsigned long flags;
2186 * Try to transition the scsi device to SDEV_RUNNING
2187 * and goose the device queue if successful.
2189 err = scsi_device_set_state(sdev, SDEV_RUNNING);
2190 if (err)
2191 return err;
2193 spin_lock_irqsave(q->queue_lock, flags);
2194 blk_start_queue(q);
2195 spin_unlock_irqrestore(q->queue_lock, flags);
2197 return 0;
2199 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock);
2201 static void
2202 device_block(struct scsi_device *sdev, void *data)
2204 scsi_internal_device_block(sdev);
2207 static int
2208 target_block(struct device *dev, void *data)
2210 if (scsi_is_target_device(dev))
2211 starget_for_each_device(to_scsi_target(dev), NULL,
2212 device_block);
2213 return 0;
2216 void
2217 scsi_target_block(struct device *dev)
2219 if (scsi_is_target_device(dev))
2220 starget_for_each_device(to_scsi_target(dev), NULL,
2221 device_block);
2222 else
2223 device_for_each_child(dev, NULL, target_block);
2225 EXPORT_SYMBOL_GPL(scsi_target_block);
2227 static void
2228 device_unblock(struct scsi_device *sdev, void *data)
2230 scsi_internal_device_unblock(sdev);
2233 static int
2234 target_unblock(struct device *dev, void *data)
2236 if (scsi_is_target_device(dev))
2237 starget_for_each_device(to_scsi_target(dev), NULL,
2238 device_unblock);
2239 return 0;
2242 void
2243 scsi_target_unblock(struct device *dev)
2245 if (scsi_is_target_device(dev))
2246 starget_for_each_device(to_scsi_target(dev), NULL,
2247 device_unblock);
2248 else
2249 device_for_each_child(dev, NULL, target_unblock);
2251 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2254 struct work_queue_work {
2255 struct work_struct work;
2256 void (*fn)(void *);
2257 void *data;
2260 static void execute_in_process_context_work(void *data)
2262 void (*fn)(void *data);
2263 struct work_queue_work *wqw = data;
2265 fn = wqw->fn;
2266 data = wqw->data;
2268 kfree(wqw);
2270 fn(data);
2274 * scsi_execute_in_process_context - reliably execute the routine with user context
2275 * @fn: the function to execute
2276 * @data: data to pass to the function
2278 * Executes the function immediately if process context is available,
2279 * otherwise schedules the function for delayed execution.
2281 * Returns: 0 - function was executed
2282 * 1 - function was scheduled for execution
2283 * <0 - error
2285 int scsi_execute_in_process_context(void (*fn)(void *data), void *data)
2287 struct work_queue_work *wqw;
2289 if (!in_interrupt()) {
2290 fn(data);
2291 return 0;
2294 wqw = kmalloc(sizeof(struct work_queue_work), GFP_ATOMIC);
2296 if (unlikely(!wqw)) {
2297 printk(KERN_ERR "Failed to allocate memory\n");
2298 WARN_ON(1);
2299 return -ENOMEM;
2302 INIT_WORK(&wqw->work, execute_in_process_context_work, wqw);
2303 wqw->fn = fn;
2304 wqw->data = data;
2305 schedule_work(&wqw->work);
2307 return 1;
2309 EXPORT_SYMBOL_GPL(scsi_execute_in_process_context);