]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/scsi/scsi_lib.c
681ed1b830f5777ac88e81ee336b667fb8dfd2e6
[linux-2.6-omap-h63xx.git] / drivers / scsi / scsi_lib.c
1 /*
2  *  scsi_lib.c Copyright (C) 1999 Eric Youngdale
3  *
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  */
9
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>
20 #include <linux/scatterlist.h>
21
22 #include <scsi/scsi.h>
23 #include <scsi/scsi_cmnd.h>
24 #include <scsi/scsi_dbg.h>
25 #include <scsi/scsi_device.h>
26 #include <scsi/scsi_driver.h>
27 #include <scsi/scsi_eh.h>
28 #include <scsi/scsi_host.h>
29
30 #include "scsi_priv.h"
31 #include "scsi_logging.h"
32
33
34 #define SG_MEMPOOL_NR           ARRAY_SIZE(scsi_sg_pools)
35 #define SG_MEMPOOL_SIZE         2
36
37 /*
38  * The maximum number of SG segments that we will put inside a scatterlist
39  * (unless chaining is used). Should ideally fit inside a single page, to
40  * avoid a higher order allocation.
41  */
42 #define SCSI_MAX_SG_SEGMENTS    128
43
44 struct scsi_host_sg_pool {
45         size_t          size;
46         char            *name;
47         struct kmem_cache       *slab;
48         mempool_t       *pool;
49 };
50
51 #define SP(x) { x, "sgpool-" #x }
52 static struct scsi_host_sg_pool scsi_sg_pools[] = {
53         SP(8),
54         SP(16),
55 #if (SCSI_MAX_SG_SEGMENTS > 16)
56         SP(32),
57 #if (SCSI_MAX_SG_SEGMENTS > 32)
58         SP(64),
59 #if (SCSI_MAX_SG_SEGMENTS > 64)
60         SP(128),
61 #endif
62 #endif
63 #endif
64 };
65 #undef SP
66
67 static struct kmem_cache *scsi_bidi_sdb_cache;
68
69 static void scsi_run_queue(struct request_queue *q);
70
71 /*
72  * Function:    scsi_unprep_request()
73  *
74  * Purpose:     Remove all preparation done for a request, including its
75  *              associated scsi_cmnd, so that it can be requeued.
76  *
77  * Arguments:   req     - request to unprepare
78  *
79  * Lock status: Assumed that no locks are held upon entry.
80  *
81  * Returns:     Nothing.
82  */
83 static void scsi_unprep_request(struct request *req)
84 {
85         struct scsi_cmnd *cmd = req->special;
86
87         req->cmd_flags &= ~REQ_DONTPREP;
88         req->special = NULL;
89
90         scsi_put_command(cmd);
91 }
92
93 /*
94  * Function:    scsi_queue_insert()
95  *
96  * Purpose:     Insert a command in the midlevel queue.
97  *
98  * Arguments:   cmd    - command that we are adding to queue.
99  *              reason - why we are inserting command to queue.
100  *
101  * Lock status: Assumed that lock is not held upon entry.
102  *
103  * Returns:     Nothing.
104  *
105  * Notes:       We do this for one of two cases.  Either the host is busy
106  *              and it cannot accept any more commands for the time being,
107  *              or the device returned QUEUE_FULL and can accept no more
108  *              commands.
109  * Notes:       This could be called either from an interrupt context or a
110  *              normal process context.
111  */
112 int scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
113 {
114         struct Scsi_Host *host = cmd->device->host;
115         struct scsi_device *device = cmd->device;
116         struct request_queue *q = device->request_queue;
117         unsigned long flags;
118
119         SCSI_LOG_MLQUEUE(1,
120                  printk("Inserting command %p into mlqueue\n", cmd));
121
122         /*
123          * Set the appropriate busy bit for the device/host.
124          *
125          * If the host/device isn't busy, assume that something actually
126          * completed, and that we should be able to queue a command now.
127          *
128          * Note that the prior mid-layer assumption that any host could
129          * always queue at least one command is now broken.  The mid-layer
130          * will implement a user specifiable stall (see
131          * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
132          * if a command is requeued with no other commands outstanding
133          * either for the device or for the host.
134          */
135         if (reason == SCSI_MLQUEUE_HOST_BUSY)
136                 host->host_blocked = host->max_host_blocked;
137         else if (reason == SCSI_MLQUEUE_DEVICE_BUSY)
138                 device->device_blocked = device->max_device_blocked;
139
140         /*
141          * Decrement the counters, since these commands are no longer
142          * active on the host/device.
143          */
144         scsi_device_unbusy(device);
145
146         /*
147          * Requeue this command.  It will go before all other commands
148          * that are already in the queue.
149          *
150          * NOTE: there is magic here about the way the queue is plugged if
151          * we have no outstanding commands.
152          * 
153          * Although we *don't* plug the queue, we call the request
154          * function.  The SCSI request function detects the blocked condition
155          * and plugs the queue appropriately.
156          */
157         spin_lock_irqsave(q->queue_lock, flags);
158         blk_requeue_request(q, cmd->request);
159         spin_unlock_irqrestore(q->queue_lock, flags);
160
161         scsi_run_queue(q);
162
163         return 0;
164 }
165
166 /**
167  * scsi_execute - insert request and wait for the result
168  * @sdev:       scsi device
169  * @cmd:        scsi command
170  * @data_direction: data direction
171  * @buffer:     data buffer
172  * @bufflen:    len of buffer
173  * @sense:      optional sense buffer
174  * @timeout:    request timeout in seconds
175  * @retries:    number of times to retry request
176  * @flags:      or into request flags;
177  *
178  * returns the req->errors value which is the scsi_cmnd result
179  * field.
180  */
181 int scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
182                  int data_direction, void *buffer, unsigned bufflen,
183                  unsigned char *sense, int timeout, int retries, int flags)
184 {
185         struct request *req;
186         int write = (data_direction == DMA_TO_DEVICE);
187         int ret = DRIVER_ERROR << 24;
188
189         req = blk_get_request(sdev->request_queue, write, __GFP_WAIT);
190
191         if (bufflen &&  blk_rq_map_kern(sdev->request_queue, req,
192                                         buffer, bufflen, __GFP_WAIT))
193                 goto out;
194
195         req->cmd_len = COMMAND_SIZE(cmd[0]);
196         memcpy(req->cmd, cmd, req->cmd_len);
197         req->sense = sense;
198         req->sense_len = 0;
199         req->retries = retries;
200         req->timeout = timeout;
201         req->cmd_type = REQ_TYPE_BLOCK_PC;
202         req->cmd_flags |= flags | REQ_QUIET | REQ_PREEMPT;
203
204         /*
205          * head injection *required* here otherwise quiesce won't work
206          */
207         blk_execute_rq(req->q, NULL, req, 1);
208
209         ret = req->errors;
210  out:
211         blk_put_request(req);
212
213         return ret;
214 }
215 EXPORT_SYMBOL(scsi_execute);
216
217
218 int scsi_execute_req(struct scsi_device *sdev, const unsigned char *cmd,
219                      int data_direction, void *buffer, unsigned bufflen,
220                      struct scsi_sense_hdr *sshdr, int timeout, int retries)
221 {
222         char *sense = NULL;
223         int result;
224         
225         if (sshdr) {
226                 sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
227                 if (!sense)
228                         return DRIVER_ERROR << 24;
229         }
230         result = scsi_execute(sdev, cmd, data_direction, buffer, bufflen,
231                               sense, timeout, retries, 0);
232         if (sshdr)
233                 scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, sshdr);
234
235         kfree(sense);
236         return result;
237 }
238 EXPORT_SYMBOL(scsi_execute_req);
239
240 struct scsi_io_context {
241         void *data;
242         void (*done)(void *data, char *sense, int result, int resid);
243         char sense[SCSI_SENSE_BUFFERSIZE];
244 };
245
246 static struct kmem_cache *scsi_io_context_cache;
247
248 static void scsi_end_async(struct request *req, int uptodate)
249 {
250         struct scsi_io_context *sioc = req->end_io_data;
251
252         if (sioc->done)
253                 sioc->done(sioc->data, sioc->sense, req->errors, req->data_len);
254
255         kmem_cache_free(scsi_io_context_cache, sioc);
256         __blk_put_request(req->q, req);
257 }
258
259 static int scsi_merge_bio(struct request *rq, struct bio *bio)
260 {
261         struct request_queue *q = rq->q;
262
263         bio->bi_flags &= ~(1 << BIO_SEG_VALID);
264         if (rq_data_dir(rq) == WRITE)
265                 bio->bi_rw |= (1 << BIO_RW);
266         blk_queue_bounce(q, &bio);
267
268         return blk_rq_append_bio(q, rq, bio);
269 }
270
271 static void scsi_bi_endio(struct bio *bio, int error)
272 {
273         bio_put(bio);
274 }
275
276 /**
277  * scsi_req_map_sg - map a scatterlist into a request
278  * @rq:         request to fill
279  * @sgl:        scatterlist
280  * @nsegs:      number of elements
281  * @bufflen:    len of buffer
282  * @gfp:        memory allocation flags
283  *
284  * scsi_req_map_sg maps a scatterlist into a request so that the
285  * request can be sent to the block layer. We do not trust the scatterlist
286  * sent to use, as some ULDs use that struct to only organize the pages.
287  */
288 static int scsi_req_map_sg(struct request *rq, struct scatterlist *sgl,
289                            int nsegs, unsigned bufflen, gfp_t gfp)
290 {
291         struct request_queue *q = rq->q;
292         int nr_pages = (bufflen + sgl[0].offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
293         unsigned int data_len = bufflen, len, bytes, off;
294         struct scatterlist *sg;
295         struct page *page;
296         struct bio *bio = NULL;
297         int i, err, nr_vecs = 0;
298
299         for_each_sg(sgl, sg, nsegs, i) {
300                 page = sg_page(sg);
301                 off = sg->offset;
302                 len = sg->length;
303                 data_len += len;
304
305                 while (len > 0 && data_len > 0) {
306                         /*
307                          * sg sends a scatterlist that is larger than
308                          * the data_len it wants transferred for certain
309                          * IO sizes
310                          */
311                         bytes = min_t(unsigned int, len, PAGE_SIZE - off);
312                         bytes = min(bytes, data_len);
313
314                         if (!bio) {
315                                 nr_vecs = min_t(int, BIO_MAX_PAGES, nr_pages);
316                                 nr_pages -= nr_vecs;
317
318                                 bio = bio_alloc(gfp, nr_vecs);
319                                 if (!bio) {
320                                         err = -ENOMEM;
321                                         goto free_bios;
322                                 }
323                                 bio->bi_end_io = scsi_bi_endio;
324                         }
325
326                         if (bio_add_pc_page(q, bio, page, bytes, off) !=
327                             bytes) {
328                                 bio_put(bio);
329                                 err = -EINVAL;
330                                 goto free_bios;
331                         }
332
333                         if (bio->bi_vcnt >= nr_vecs) {
334                                 err = scsi_merge_bio(rq, bio);
335                                 if (err) {
336                                         bio_endio(bio, 0);
337                                         goto free_bios;
338                                 }
339                                 bio = NULL;
340                         }
341
342                         page++;
343                         len -= bytes;
344                         data_len -=bytes;
345                         off = 0;
346                 }
347         }
348
349         rq->buffer = rq->data = NULL;
350         rq->data_len = bufflen;
351         return 0;
352
353 free_bios:
354         while ((bio = rq->bio) != NULL) {
355                 rq->bio = bio->bi_next;
356                 /*
357                  * call endio instead of bio_put incase it was bounced
358                  */
359                 bio_endio(bio, 0);
360         }
361
362         return err;
363 }
364
365 /**
366  * scsi_execute_async - insert request
367  * @sdev:       scsi device
368  * @cmd:        scsi command
369  * @cmd_len:    length of scsi cdb
370  * @data_direction: DMA_TO_DEVICE, DMA_FROM_DEVICE, or DMA_NONE
371  * @buffer:     data buffer (this can be a kernel buffer or scatterlist)
372  * @bufflen:    len of buffer
373  * @use_sg:     if buffer is a scatterlist this is the number of elements
374  * @timeout:    request timeout in seconds
375  * @retries:    number of times to retry request
376  * @privdata:   data passed to done()
377  * @done:       callback function when done
378  * @gfp:        memory allocation flags
379  */
380 int scsi_execute_async(struct scsi_device *sdev, const unsigned char *cmd,
381                        int cmd_len, int data_direction, void *buffer, unsigned bufflen,
382                        int use_sg, int timeout, int retries, void *privdata,
383                        void (*done)(void *, char *, int, int), gfp_t gfp)
384 {
385         struct request *req;
386         struct scsi_io_context *sioc;
387         int err = 0;
388         int write = (data_direction == DMA_TO_DEVICE);
389
390         sioc = kmem_cache_zalloc(scsi_io_context_cache, gfp);
391         if (!sioc)
392                 return DRIVER_ERROR << 24;
393
394         req = blk_get_request(sdev->request_queue, write, gfp);
395         if (!req)
396                 goto free_sense;
397         req->cmd_type = REQ_TYPE_BLOCK_PC;
398         req->cmd_flags |= REQ_QUIET;
399
400         if (use_sg)
401                 err = scsi_req_map_sg(req, buffer, use_sg, bufflen, gfp);
402         else if (bufflen)
403                 err = blk_rq_map_kern(req->q, req, buffer, bufflen, gfp);
404
405         if (err)
406                 goto free_req;
407
408         req->cmd_len = cmd_len;
409         memset(req->cmd, 0, BLK_MAX_CDB); /* ATAPI hates garbage after CDB */
410         memcpy(req->cmd, cmd, req->cmd_len);
411         req->sense = sioc->sense;
412         req->sense_len = 0;
413         req->timeout = timeout;
414         req->retries = retries;
415         req->end_io_data = sioc;
416
417         sioc->data = privdata;
418         sioc->done = done;
419
420         blk_execute_rq_nowait(req->q, NULL, req, 1, scsi_end_async);
421         return 0;
422
423 free_req:
424         blk_put_request(req);
425 free_sense:
426         kmem_cache_free(scsi_io_context_cache, sioc);
427         return DRIVER_ERROR << 24;
428 }
429 EXPORT_SYMBOL_GPL(scsi_execute_async);
430
431 /*
432  * Function:    scsi_init_cmd_errh()
433  *
434  * Purpose:     Initialize cmd fields related to error handling.
435  *
436  * Arguments:   cmd     - command that is ready to be queued.
437  *
438  * Notes:       This function has the job of initializing a number of
439  *              fields related to error handling.   Typically this will
440  *              be called once for each command, as required.
441  */
442 static void scsi_init_cmd_errh(struct scsi_cmnd *cmd)
443 {
444         cmd->serial_number = 0;
445         scsi_set_resid(cmd, 0);
446         memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
447         if (cmd->cmd_len == 0)
448                 cmd->cmd_len = COMMAND_SIZE(cmd->cmnd[0]);
449 }
450
451 void scsi_device_unbusy(struct scsi_device *sdev)
452 {
453         struct Scsi_Host *shost = sdev->host;
454         unsigned long flags;
455
456         spin_lock_irqsave(shost->host_lock, flags);
457         shost->host_busy--;
458         if (unlikely(scsi_host_in_recovery(shost) &&
459                      (shost->host_failed || shost->host_eh_scheduled)))
460                 scsi_eh_wakeup(shost);
461         spin_unlock(shost->host_lock);
462         spin_lock(sdev->request_queue->queue_lock);
463         sdev->device_busy--;
464         spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
465 }
466
467 /*
468  * Called for single_lun devices on IO completion. Clear starget_sdev_user,
469  * and call blk_run_queue for all the scsi_devices on the target -
470  * including current_sdev first.
471  *
472  * Called with *no* scsi locks held.
473  */
474 static void scsi_single_lun_run(struct scsi_device *current_sdev)
475 {
476         struct Scsi_Host *shost = current_sdev->host;
477         struct scsi_device *sdev, *tmp;
478         struct scsi_target *starget = scsi_target(current_sdev);
479         unsigned long flags;
480
481         spin_lock_irqsave(shost->host_lock, flags);
482         starget->starget_sdev_user = NULL;
483         spin_unlock_irqrestore(shost->host_lock, flags);
484
485         /*
486          * Call blk_run_queue for all LUNs on the target, starting with
487          * current_sdev. We race with others (to set starget_sdev_user),
488          * but in most cases, we will be first. Ideally, each LU on the
489          * target would get some limited time or requests on the target.
490          */
491         blk_run_queue(current_sdev->request_queue);
492
493         spin_lock_irqsave(shost->host_lock, flags);
494         if (starget->starget_sdev_user)
495                 goto out;
496         list_for_each_entry_safe(sdev, tmp, &starget->devices,
497                         same_target_siblings) {
498                 if (sdev == current_sdev)
499                         continue;
500                 if (scsi_device_get(sdev))
501                         continue;
502
503                 spin_unlock_irqrestore(shost->host_lock, flags);
504                 blk_run_queue(sdev->request_queue);
505                 spin_lock_irqsave(shost->host_lock, flags);
506         
507                 scsi_device_put(sdev);
508         }
509  out:
510         spin_unlock_irqrestore(shost->host_lock, flags);
511 }
512
513 /*
514  * Function:    scsi_run_queue()
515  *
516  * Purpose:     Select a proper request queue to serve next
517  *
518  * Arguments:   q       - last request's queue
519  *
520  * Returns:     Nothing
521  *
522  * Notes:       The previous command was completely finished, start
523  *              a new one if possible.
524  */
525 static void scsi_run_queue(struct request_queue *q)
526 {
527         struct scsi_device *sdev = q->queuedata;
528         struct Scsi_Host *shost = sdev->host;
529         unsigned long flags;
530
531         if (scsi_target(sdev)->single_lun)
532                 scsi_single_lun_run(sdev);
533
534         spin_lock_irqsave(shost->host_lock, flags);
535         while (!list_empty(&shost->starved_list) &&
536                !shost->host_blocked && !shost->host_self_blocked &&
537                 !((shost->can_queue > 0) &&
538                   (shost->host_busy >= shost->can_queue))) {
539                 /*
540                  * As long as shost is accepting commands and we have
541                  * starved queues, call blk_run_queue. scsi_request_fn
542                  * drops the queue_lock and can add us back to the
543                  * starved_list.
544                  *
545                  * host_lock protects the starved_list and starved_entry.
546                  * scsi_request_fn must get the host_lock before checking
547                  * or modifying starved_list or starved_entry.
548                  */
549                 sdev = list_entry(shost->starved_list.next,
550                                           struct scsi_device, starved_entry);
551                 list_del_init(&sdev->starved_entry);
552                 spin_unlock_irqrestore(shost->host_lock, flags);
553
554
555                 if (test_bit(QUEUE_FLAG_REENTER, &q->queue_flags) &&
556                     !test_and_set_bit(QUEUE_FLAG_REENTER,
557                                       &sdev->request_queue->queue_flags)) {
558                         blk_run_queue(sdev->request_queue);
559                         clear_bit(QUEUE_FLAG_REENTER,
560                                   &sdev->request_queue->queue_flags);
561                 } else
562                         blk_run_queue(sdev->request_queue);
563
564                 spin_lock_irqsave(shost->host_lock, flags);
565                 if (unlikely(!list_empty(&sdev->starved_entry)))
566                         /*
567                          * sdev lost a race, and was put back on the
568                          * starved list. This is unlikely but without this
569                          * in theory we could loop forever.
570                          */
571                         break;
572         }
573         spin_unlock_irqrestore(shost->host_lock, flags);
574
575         blk_run_queue(q);
576 }
577
578 /*
579  * Function:    scsi_requeue_command()
580  *
581  * Purpose:     Handle post-processing of completed commands.
582  *
583  * Arguments:   q       - queue to operate on
584  *              cmd     - command that may need to be requeued.
585  *
586  * Returns:     Nothing
587  *
588  * Notes:       After command completion, there may be blocks left
589  *              over which weren't finished by the previous command
590  *              this can be for a number of reasons - the main one is
591  *              I/O errors in the middle of the request, in which case
592  *              we need to request the blocks that come after the bad
593  *              sector.
594  * Notes:       Upon return, cmd is a stale pointer.
595  */
596 static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
597 {
598         struct request *req = cmd->request;
599         unsigned long flags;
600
601         scsi_unprep_request(req);
602         spin_lock_irqsave(q->queue_lock, flags);
603         blk_requeue_request(q, req);
604         spin_unlock_irqrestore(q->queue_lock, flags);
605
606         scsi_run_queue(q);
607 }
608
609 void scsi_next_command(struct scsi_cmnd *cmd)
610 {
611         struct scsi_device *sdev = cmd->device;
612         struct request_queue *q = sdev->request_queue;
613
614         /* need to hold a reference on the device before we let go of the cmd */
615         get_device(&sdev->sdev_gendev);
616
617         scsi_put_command(cmd);
618         scsi_run_queue(q);
619
620         /* ok to remove device now */
621         put_device(&sdev->sdev_gendev);
622 }
623
624 void scsi_run_host_queues(struct Scsi_Host *shost)
625 {
626         struct scsi_device *sdev;
627
628         shost_for_each_device(sdev, shost)
629                 scsi_run_queue(sdev->request_queue);
630 }
631
632 /*
633  * Function:    scsi_end_request()
634  *
635  * Purpose:     Post-processing of completed commands (usually invoked at end
636  *              of upper level post-processing and scsi_io_completion).
637  *
638  * Arguments:   cmd      - command that is complete.
639  *              error    - 0 if I/O indicates success, < 0 for I/O error.
640  *              bytes    - number of bytes of completed I/O
641  *              requeue  - indicates whether we should requeue leftovers.
642  *
643  * Lock status: Assumed that lock is not held upon entry.
644  *
645  * Returns:     cmd if requeue required, NULL otherwise.
646  *
647  * Notes:       This is called for block device requests in order to
648  *              mark some number of sectors as complete.
649  * 
650  *              We are guaranteeing that the request queue will be goosed
651  *              at some point during this call.
652  * Notes:       If cmd was requeued, upon return it will be a stale pointer.
653  */
654 static struct scsi_cmnd *scsi_end_request(struct scsi_cmnd *cmd, int error,
655                                           int bytes, int requeue)
656 {
657         struct request_queue *q = cmd->device->request_queue;
658         struct request *req = cmd->request;
659
660         /*
661          * If there are blocks left over at the end, set up the command
662          * to queue the remainder of them.
663          */
664         if (blk_end_request(req, error, bytes)) {
665                 int leftover = (req->hard_nr_sectors << 9);
666
667                 if (blk_pc_request(req))
668                         leftover = req->data_len;
669
670                 /* kill remainder if no retrys */
671                 if (error && blk_noretry_request(req))
672                         blk_end_request(req, error, leftover);
673                 else {
674                         if (requeue) {
675                                 /*
676                                  * Bleah.  Leftovers again.  Stick the
677                                  * leftovers in the front of the
678                                  * queue, and goose the queue again.
679                                  */
680                                 scsi_requeue_command(q, cmd);
681                                 cmd = NULL;
682                         }
683                         return cmd;
684                 }
685         }
686
687         /*
688          * This will goose the queue request function at the end, so we don't
689          * need to worry about launching another command.
690          */
691         scsi_next_command(cmd);
692         return NULL;
693 }
694
695 /*
696  * Like SCSI_MAX_SG_SEGMENTS, but for archs that have sg chaining. This limit
697  * is totally arbitrary, a setting of 2048 will get you at least 8mb ios.
698  */
699 #define SCSI_MAX_SG_CHAIN_SEGMENTS      2048
700
701 static inline unsigned int scsi_sgtable_index(unsigned short nents)
702 {
703         unsigned int index;
704
705         switch (nents) {
706         case 1 ... 8:
707                 index = 0;
708                 break;
709         case 9 ... 16:
710                 index = 1;
711                 break;
712 #if (SCSI_MAX_SG_SEGMENTS > 16)
713         case 17 ... 32:
714                 index = 2;
715                 break;
716 #if (SCSI_MAX_SG_SEGMENTS > 32)
717         case 33 ... 64:
718                 index = 3;
719                 break;
720 #if (SCSI_MAX_SG_SEGMENTS > 64)
721         case 65 ... 128:
722                 index = 4;
723                 break;
724 #endif
725 #endif
726 #endif
727         default:
728                 printk(KERN_ERR "scsi: bad segment count=%d\n", nents);
729                 BUG();
730         }
731
732         return index;
733 }
734
735 static void scsi_sg_free(struct scatterlist *sgl, unsigned int nents)
736 {
737         struct scsi_host_sg_pool *sgp;
738
739         sgp = scsi_sg_pools + scsi_sgtable_index(nents);
740         mempool_free(sgl, sgp->pool);
741 }
742
743 static struct scatterlist *scsi_sg_alloc(unsigned int nents, gfp_t gfp_mask)
744 {
745         struct scsi_host_sg_pool *sgp;
746
747         sgp = scsi_sg_pools + scsi_sgtable_index(nents);
748         return mempool_alloc(sgp->pool, gfp_mask);
749 }
750
751 static int scsi_alloc_sgtable(struct scsi_data_buffer *sdb, int nents,
752                               gfp_t gfp_mask)
753 {
754         int ret;
755
756         BUG_ON(!nents);
757
758         ret = __sg_alloc_table(&sdb->table, nents, SCSI_MAX_SG_SEGMENTS,
759                                gfp_mask, scsi_sg_alloc);
760         if (unlikely(ret))
761                 __sg_free_table(&sdb->table, SCSI_MAX_SG_SEGMENTS,
762                                 scsi_sg_free);
763
764         return ret;
765 }
766
767 static void scsi_free_sgtable(struct scsi_data_buffer *sdb)
768 {
769         __sg_free_table(&sdb->table, SCSI_MAX_SG_SEGMENTS, scsi_sg_free);
770 }
771
772 /*
773  * Function:    scsi_release_buffers()
774  *
775  * Purpose:     Completion processing for block device I/O requests.
776  *
777  * Arguments:   cmd     - command that we are bailing.
778  *
779  * Lock status: Assumed that no lock is held upon entry.
780  *
781  * Returns:     Nothing
782  *
783  * Notes:       In the event that an upper level driver rejects a
784  *              command, we must release resources allocated during
785  *              the __init_io() function.  Primarily this would involve
786  *              the scatter-gather table, and potentially any bounce
787  *              buffers.
788  */
789 void scsi_release_buffers(struct scsi_cmnd *cmd)
790 {
791         if (cmd->sdb.table.nents)
792                 scsi_free_sgtable(&cmd->sdb);
793
794         memset(&cmd->sdb, 0, sizeof(cmd->sdb));
795
796         if (scsi_bidi_cmnd(cmd)) {
797                 struct scsi_data_buffer *bidi_sdb =
798                         cmd->request->next_rq->special;
799                 scsi_free_sgtable(bidi_sdb);
800                 kmem_cache_free(scsi_bidi_sdb_cache, bidi_sdb);
801                 cmd->request->next_rq->special = NULL;
802         }
803 }
804 EXPORT_SYMBOL(scsi_release_buffers);
805
806 /*
807  * Bidi commands Must be complete as a whole, both sides at once.
808  * If part of the bytes were written and lld returned
809  * scsi_in()->resid and/or scsi_out()->resid this information will be left
810  * in req->data_len and req->next_rq->data_len. The upper-layer driver can
811  * decide what to do with this information.
812  */
813 void scsi_end_bidi_request(struct scsi_cmnd *cmd)
814 {
815         blk_end_bidi_request(cmd->request, 0, scsi_out(cmd)->resid,
816                                                         scsi_in(cmd)->resid);
817         scsi_release_buffers(cmd);
818
819         /*
820          * This will goose the queue request function at the end, so we don't
821          * need to worry about launching another command.
822          */
823         scsi_next_command(cmd);
824 }
825
826 /*
827  * Function:    scsi_io_completion()
828  *
829  * Purpose:     Completion processing for block device I/O requests.
830  *
831  * Arguments:   cmd   - command that is finished.
832  *
833  * Lock status: Assumed that no lock is held upon entry.
834  *
835  * Returns:     Nothing
836  *
837  * Notes:       This function is matched in terms of capabilities to
838  *              the function that created the scatter-gather list.
839  *              In other words, if there are no bounce buffers
840  *              (the normal case for most drivers), we don't need
841  *              the logic to deal with cleaning up afterwards.
842  *
843  *              We must do one of several things here:
844  *
845  *              a) Call scsi_end_request.  This will finish off the
846  *                 specified number of sectors.  If we are done, the
847  *                 command block will be released, and the queue
848  *                 function will be goosed.  If we are not done, then
849  *                 scsi_end_request will directly goose the queue.
850  *
851  *              b) We can just use scsi_requeue_command() here.  This would
852  *                 be used if we just wanted to retry, for example.
853  */
854 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
855 {
856         int result = cmd->result;
857         int this_count = scsi_bufflen(cmd);
858         struct request_queue *q = cmd->device->request_queue;
859         struct request *req = cmd->request;
860         int clear_errors = 1;
861         struct scsi_sense_hdr sshdr;
862         int sense_valid = 0;
863         int sense_deferred = 0;
864
865         if (result) {
866                 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
867                 if (sense_valid)
868                         sense_deferred = scsi_sense_is_deferred(&sshdr);
869         }
870
871         if (blk_pc_request(req)) { /* SG_IO ioctl from block level */
872                 req->errors = result;
873                 if (result) {
874                         clear_errors = 0;
875                         if (sense_valid && req->sense) {
876                                 /*
877                                  * SG_IO wants current and deferred errors
878                                  */
879                                 int len = 8 + cmd->sense_buffer[7];
880
881                                 if (len > SCSI_SENSE_BUFFERSIZE)
882                                         len = SCSI_SENSE_BUFFERSIZE;
883                                 memcpy(req->sense, cmd->sense_buffer,  len);
884                                 req->sense_len = len;
885                         }
886                 }
887                 if (scsi_bidi_cmnd(cmd)) {
888                         /* will also release_buffers */
889                         scsi_end_bidi_request(cmd);
890                         return;
891                 }
892                 req->data_len = scsi_get_resid(cmd);
893         }
894
895         BUG_ON(blk_bidi_rq(req)); /* bidi not support for !blk_pc_request yet */
896         scsi_release_buffers(cmd);
897
898         /*
899          * Next deal with any sectors which we were able to correctly
900          * handle.
901          */
902         SCSI_LOG_HLCOMPLETE(1, printk("%ld sectors total, "
903                                       "%d bytes done.\n",
904                                       req->nr_sectors, good_bytes));
905
906         if (clear_errors)
907                 req->errors = 0;
908
909         /* A number of bytes were successfully read.  If there
910          * are leftovers and there is some kind of error
911          * (result != 0), retry the rest.
912          */
913         if (scsi_end_request(cmd, 0, good_bytes, result == 0) == NULL)
914                 return;
915
916         /* good_bytes = 0, or (inclusive) there were leftovers and
917          * result = 0, so scsi_end_request couldn't retry.
918          */
919         if (sense_valid && !sense_deferred) {
920                 switch (sshdr.sense_key) {
921                 case UNIT_ATTENTION:
922                         if (cmd->device->removable) {
923                                 /* Detected disc change.  Set a bit
924                                  * and quietly refuse further access.
925                                  */
926                                 cmd->device->changed = 1;
927                                 scsi_end_request(cmd, -EIO, this_count, 1);
928                                 return;
929                         } else {
930                                 /* Must have been a power glitch, or a
931                                  * bus reset.  Could not have been a
932                                  * media change, so we just retry the
933                                  * request and see what happens.
934                                  */
935                                 scsi_requeue_command(q, cmd);
936                                 return;
937                         }
938                         break;
939                 case ILLEGAL_REQUEST:
940                         /* If we had an ILLEGAL REQUEST returned, then
941                          * we may have performed an unsupported
942                          * command.  The only thing this should be
943                          * would be a ten byte read where only a six
944                          * byte read was supported.  Also, on a system
945                          * where READ CAPACITY failed, we may have
946                          * read past the end of the disk.
947                          */
948                         if ((cmd->device->use_10_for_rw &&
949                             sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
950                             (cmd->cmnd[0] == READ_10 ||
951                              cmd->cmnd[0] == WRITE_10)) {
952                                 cmd->device->use_10_for_rw = 0;
953                                 /* This will cause a retry with a
954                                  * 6-byte command.
955                                  */
956                                 scsi_requeue_command(q, cmd);
957                                 return;
958                         } else {
959                                 scsi_end_request(cmd, -EIO, this_count, 1);
960                                 return;
961                         }
962                         break;
963                 case NOT_READY:
964                         /* If the device is in the process of becoming
965                          * ready, or has a temporary blockage, retry.
966                          */
967                         if (sshdr.asc == 0x04) {
968                                 switch (sshdr.ascq) {
969                                 case 0x01: /* becoming ready */
970                                 case 0x04: /* format in progress */
971                                 case 0x05: /* rebuild in progress */
972                                 case 0x06: /* recalculation in progress */
973                                 case 0x07: /* operation in progress */
974                                 case 0x08: /* Long write in progress */
975                                 case 0x09: /* self test in progress */
976                                         scsi_requeue_command(q, cmd);
977                                         return;
978                                 default:
979                                         break;
980                                 }
981                         }
982                         if (!(req->cmd_flags & REQ_QUIET))
983                                 scsi_cmd_print_sense_hdr(cmd,
984                                                          "Device not ready",
985                                                          &sshdr);
986
987                         scsi_end_request(cmd, -EIO, this_count, 1);
988                         return;
989                 case VOLUME_OVERFLOW:
990                         if (!(req->cmd_flags & REQ_QUIET)) {
991                                 scmd_printk(KERN_INFO, cmd,
992                                             "Volume overflow, CDB: ");
993                                 __scsi_print_command(cmd->cmnd);
994                                 scsi_print_sense("", cmd);
995                         }
996                         /* See SSC3rXX or current. */
997                         scsi_end_request(cmd, -EIO, this_count, 1);
998                         return;
999                 default:
1000                         break;
1001                 }
1002         }
1003         if (host_byte(result) == DID_RESET) {
1004                 /* Third party bus reset or reset for error recovery
1005                  * reasons.  Just retry the request and see what
1006                  * happens.
1007                  */
1008                 scsi_requeue_command(q, cmd);
1009                 return;
1010         }
1011         if (result) {
1012                 if (!(req->cmd_flags & REQ_QUIET)) {
1013                         scsi_print_result(cmd);
1014                         if (driver_byte(result) & DRIVER_SENSE)
1015                                 scsi_print_sense("", cmd);
1016                 }
1017         }
1018         scsi_end_request(cmd, -EIO, this_count, !result);
1019 }
1020
1021 static int scsi_init_sgtable(struct request *req, struct scsi_data_buffer *sdb,
1022                              gfp_t gfp_mask)
1023 {
1024         int count;
1025
1026         /*
1027          * If sg table allocation fails, requeue request later.
1028          */
1029         if (unlikely(scsi_alloc_sgtable(sdb, req->nr_phys_segments,
1030                                         gfp_mask))) {
1031                 return BLKPREP_DEFER;
1032         }
1033
1034         req->buffer = NULL;
1035         if (blk_pc_request(req))
1036                 sdb->length = req->data_len;
1037         else
1038                 sdb->length = req->nr_sectors << 9;
1039
1040         /* 
1041          * Next, walk the list, and fill in the addresses and sizes of
1042          * each segment.
1043          */
1044         count = blk_rq_map_sg(req->q, req, sdb->table.sgl);
1045         BUG_ON(count > sdb->table.nents);
1046         sdb->table.nents = count;
1047         return BLKPREP_OK;
1048 }
1049
1050 /*
1051  * Function:    scsi_init_io()
1052  *
1053  * Purpose:     SCSI I/O initialize function.
1054  *
1055  * Arguments:   cmd   - Command descriptor we wish to initialize
1056  *
1057  * Returns:     0 on success
1058  *              BLKPREP_DEFER if the failure is retryable
1059  *              BLKPREP_KILL if the failure is fatal
1060  */
1061 int scsi_init_io(struct scsi_cmnd *cmd, gfp_t gfp_mask)
1062 {
1063         int error = scsi_init_sgtable(cmd->request, &cmd->sdb, gfp_mask);
1064         if (error)
1065                 goto err_exit;
1066
1067         if (blk_bidi_rq(cmd->request)) {
1068                 struct scsi_data_buffer *bidi_sdb = kmem_cache_zalloc(
1069                         scsi_bidi_sdb_cache, GFP_ATOMIC);
1070                 if (!bidi_sdb) {
1071                         error = BLKPREP_DEFER;
1072                         goto err_exit;
1073                 }
1074
1075                 cmd->request->next_rq->special = bidi_sdb;
1076                 error = scsi_init_sgtable(cmd->request->next_rq, bidi_sdb,
1077                                                                     GFP_ATOMIC);
1078                 if (error)
1079                         goto err_exit;
1080         }
1081
1082         return BLKPREP_OK ;
1083
1084 err_exit:
1085         scsi_release_buffers(cmd);
1086         if (error == BLKPREP_KILL)
1087                 scsi_put_command(cmd);
1088         else /* BLKPREP_DEFER */
1089                 scsi_unprep_request(cmd->request);
1090
1091         return error;
1092 }
1093 EXPORT_SYMBOL(scsi_init_io);
1094
1095 static struct scsi_cmnd *scsi_get_cmd_from_req(struct scsi_device *sdev,
1096                 struct request *req)
1097 {
1098         struct scsi_cmnd *cmd;
1099
1100         if (!req->special) {
1101                 cmd = scsi_get_command(sdev, GFP_ATOMIC);
1102                 if (unlikely(!cmd))
1103                         return NULL;
1104                 req->special = cmd;
1105         } else {
1106                 cmd = req->special;
1107         }
1108
1109         /* pull a tag out of the request if we have one */
1110         cmd->tag = req->tag;
1111         cmd->request = req;
1112
1113         return cmd;
1114 }
1115
1116 int scsi_setup_blk_pc_cmnd(struct scsi_device *sdev, struct request *req)
1117 {
1118         struct scsi_cmnd *cmd;
1119         int ret = scsi_prep_state_check(sdev, req);
1120
1121         if (ret != BLKPREP_OK)
1122                 return ret;
1123
1124         cmd = scsi_get_cmd_from_req(sdev, req);
1125         if (unlikely(!cmd))
1126                 return BLKPREP_DEFER;
1127
1128         /*
1129          * BLOCK_PC requests may transfer data, in which case they must
1130          * a bio attached to them.  Or they might contain a SCSI command
1131          * that does not transfer data, in which case they may optionally
1132          * submit a request without an attached bio.
1133          */
1134         if (req->bio) {
1135                 int ret;
1136
1137                 BUG_ON(!req->nr_phys_segments);
1138
1139                 ret = scsi_init_io(cmd, GFP_ATOMIC);
1140                 if (unlikely(ret))
1141                         return ret;
1142         } else {
1143                 BUG_ON(req->data_len);
1144                 BUG_ON(req->data);
1145
1146                 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1147                 req->buffer = NULL;
1148         }
1149
1150         BUILD_BUG_ON(sizeof(req->cmd) > sizeof(cmd->cmnd));
1151         memcpy(cmd->cmnd, req->cmd, sizeof(cmd->cmnd));
1152         cmd->cmd_len = req->cmd_len;
1153         if (!req->data_len)
1154                 cmd->sc_data_direction = DMA_NONE;
1155         else if (rq_data_dir(req) == WRITE)
1156                 cmd->sc_data_direction = DMA_TO_DEVICE;
1157         else
1158                 cmd->sc_data_direction = DMA_FROM_DEVICE;
1159         
1160         cmd->transfersize = req->data_len;
1161         cmd->allowed = req->retries;
1162         cmd->timeout_per_command = req->timeout;
1163         return BLKPREP_OK;
1164 }
1165 EXPORT_SYMBOL(scsi_setup_blk_pc_cmnd);
1166
1167 /*
1168  * Setup a REQ_TYPE_FS command.  These are simple read/write request
1169  * from filesystems that still need to be translated to SCSI CDBs from
1170  * the ULD.
1171  */
1172 int scsi_setup_fs_cmnd(struct scsi_device *sdev, struct request *req)
1173 {
1174         struct scsi_cmnd *cmd;
1175         int ret = scsi_prep_state_check(sdev, req);
1176
1177         if (ret != BLKPREP_OK)
1178                 return ret;
1179         /*
1180          * Filesystem requests must transfer data.
1181          */
1182         BUG_ON(!req->nr_phys_segments);
1183
1184         cmd = scsi_get_cmd_from_req(sdev, req);
1185         if (unlikely(!cmd))
1186                 return BLKPREP_DEFER;
1187
1188         return scsi_init_io(cmd, GFP_ATOMIC);
1189 }
1190 EXPORT_SYMBOL(scsi_setup_fs_cmnd);
1191
1192 int scsi_prep_state_check(struct scsi_device *sdev, struct request *req)
1193 {
1194         int ret = BLKPREP_OK;
1195
1196         /*
1197          * If the device is not in running state we will reject some
1198          * or all commands.
1199          */
1200         if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1201                 switch (sdev->sdev_state) {
1202                 case SDEV_OFFLINE:
1203                         /*
1204                          * If the device is offline we refuse to process any
1205                          * commands.  The device must be brought online
1206                          * before trying any recovery commands.
1207                          */
1208                         sdev_printk(KERN_ERR, sdev,
1209                                     "rejecting I/O to offline device\n");
1210                         ret = BLKPREP_KILL;
1211                         break;
1212                 case SDEV_DEL:
1213                         /*
1214                          * If the device is fully deleted, we refuse to
1215                          * process any commands as well.
1216                          */
1217                         sdev_printk(KERN_ERR, sdev,
1218                                     "rejecting I/O to dead device\n");
1219                         ret = BLKPREP_KILL;
1220                         break;
1221                 case SDEV_QUIESCE:
1222                 case SDEV_BLOCK:
1223                         /*
1224                          * If the devices is blocked we defer normal commands.
1225                          */
1226                         if (!(req->cmd_flags & REQ_PREEMPT))
1227                                 ret = BLKPREP_DEFER;
1228                         break;
1229                 default:
1230                         /*
1231                          * For any other not fully online state we only allow
1232                          * special commands.  In particular any user initiated
1233                          * command is not allowed.
1234                          */
1235                         if (!(req->cmd_flags & REQ_PREEMPT))
1236                                 ret = BLKPREP_KILL;
1237                         break;
1238                 }
1239         }
1240         return ret;
1241 }
1242 EXPORT_SYMBOL(scsi_prep_state_check);
1243
1244 int scsi_prep_return(struct request_queue *q, struct request *req, int ret)
1245 {
1246         struct scsi_device *sdev = q->queuedata;
1247
1248         switch (ret) {
1249         case BLKPREP_KILL:
1250                 req->errors = DID_NO_CONNECT << 16;
1251                 /* release the command and kill it */
1252                 if (req->special) {
1253                         struct scsi_cmnd *cmd = req->special;
1254                         scsi_release_buffers(cmd);
1255                         scsi_put_command(cmd);
1256                         req->special = NULL;
1257                 }
1258                 break;
1259         case BLKPREP_DEFER:
1260                 /*
1261                  * If we defer, the elv_next_request() returns NULL, but the
1262                  * queue must be restarted, so we plug here if no returning
1263                  * command will automatically do that.
1264                  */
1265                 if (sdev->device_busy == 0)
1266                         blk_plug_device(q);
1267                 break;
1268         default:
1269                 req->cmd_flags |= REQ_DONTPREP;
1270         }
1271
1272         return ret;
1273 }
1274 EXPORT_SYMBOL(scsi_prep_return);
1275
1276 int scsi_prep_fn(struct request_queue *q, struct request *req)
1277 {
1278         struct scsi_device *sdev = q->queuedata;
1279         int ret = BLKPREP_KILL;
1280
1281         if (req->cmd_type == REQ_TYPE_BLOCK_PC)
1282                 ret = scsi_setup_blk_pc_cmnd(sdev, req);
1283         return scsi_prep_return(q, req, ret);
1284 }
1285
1286 /*
1287  * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1288  * return 0.
1289  *
1290  * Called with the queue_lock held.
1291  */
1292 static inline int scsi_dev_queue_ready(struct request_queue *q,
1293                                   struct scsi_device *sdev)
1294 {
1295         if (sdev->device_busy >= sdev->queue_depth)
1296                 return 0;
1297         if (sdev->device_busy == 0 && sdev->device_blocked) {
1298                 /*
1299                  * unblock after device_blocked iterates to zero
1300                  */
1301                 if (--sdev->device_blocked == 0) {
1302                         SCSI_LOG_MLQUEUE(3,
1303                                    sdev_printk(KERN_INFO, sdev,
1304                                    "unblocking device at zero depth\n"));
1305                 } else {
1306                         blk_plug_device(q);
1307                         return 0;
1308                 }
1309         }
1310         if (sdev->device_blocked)
1311                 return 0;
1312
1313         return 1;
1314 }
1315
1316 /*
1317  * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1318  * return 0. We must end up running the queue again whenever 0 is
1319  * returned, else IO can hang.
1320  *
1321  * Called with host_lock held.
1322  */
1323 static inline int scsi_host_queue_ready(struct request_queue *q,
1324                                    struct Scsi_Host *shost,
1325                                    struct scsi_device *sdev)
1326 {
1327         if (scsi_host_in_recovery(shost))
1328                 return 0;
1329         if (shost->host_busy == 0 && shost->host_blocked) {
1330                 /*
1331                  * unblock after host_blocked iterates to zero
1332                  */
1333                 if (--shost->host_blocked == 0) {
1334                         SCSI_LOG_MLQUEUE(3,
1335                                 printk("scsi%d unblocking host at zero depth\n",
1336                                         shost->host_no));
1337                 } else {
1338                         blk_plug_device(q);
1339                         return 0;
1340                 }
1341         }
1342         if ((shost->can_queue > 0 && shost->host_busy >= shost->can_queue) ||
1343             shost->host_blocked || shost->host_self_blocked) {
1344                 if (list_empty(&sdev->starved_entry))
1345                         list_add_tail(&sdev->starved_entry, &shost->starved_list);
1346                 return 0;
1347         }
1348
1349         /* We're OK to process the command, so we can't be starved */
1350         if (!list_empty(&sdev->starved_entry))
1351                 list_del_init(&sdev->starved_entry);
1352
1353         return 1;
1354 }
1355
1356 /*
1357  * Kill a request for a dead device
1358  */
1359 static void scsi_kill_request(struct request *req, struct request_queue *q)
1360 {
1361         struct scsi_cmnd *cmd = req->special;
1362         struct scsi_device *sdev = cmd->device;
1363         struct Scsi_Host *shost = sdev->host;
1364
1365         blkdev_dequeue_request(req);
1366
1367         if (unlikely(cmd == NULL)) {
1368                 printk(KERN_CRIT "impossible request in %s.\n",
1369                                  __FUNCTION__);
1370                 BUG();
1371         }
1372
1373         scsi_init_cmd_errh(cmd);
1374         cmd->result = DID_NO_CONNECT << 16;
1375         atomic_inc(&cmd->device->iorequest_cnt);
1376
1377         /*
1378          * SCSI request completion path will do scsi_device_unbusy(),
1379          * bump busy counts.  To bump the counters, we need to dance
1380          * with the locks as normal issue path does.
1381          */
1382         sdev->device_busy++;
1383         spin_unlock(sdev->request_queue->queue_lock);
1384         spin_lock(shost->host_lock);
1385         shost->host_busy++;
1386         spin_unlock(shost->host_lock);
1387         spin_lock(sdev->request_queue->queue_lock);
1388
1389         __scsi_done(cmd);
1390 }
1391
1392 static void scsi_softirq_done(struct request *rq)
1393 {
1394         struct scsi_cmnd *cmd = rq->completion_data;
1395         unsigned long wait_for = (cmd->allowed + 1) * cmd->timeout_per_command;
1396         int disposition;
1397
1398         INIT_LIST_HEAD(&cmd->eh_entry);
1399
1400         disposition = scsi_decide_disposition(cmd);
1401         if (disposition != SUCCESS &&
1402             time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1403                 sdev_printk(KERN_ERR, cmd->device,
1404                             "timing out command, waited %lus\n",
1405                             wait_for/HZ);
1406                 disposition = SUCCESS;
1407         }
1408                         
1409         scsi_log_completion(cmd, disposition);
1410
1411         switch (disposition) {
1412                 case SUCCESS:
1413                         scsi_finish_command(cmd);
1414                         break;
1415                 case NEEDS_RETRY:
1416                         scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1417                         break;
1418                 case ADD_TO_MLQUEUE:
1419                         scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1420                         break;
1421                 default:
1422                         if (!scsi_eh_scmd_add(cmd, 0))
1423                                 scsi_finish_command(cmd);
1424         }
1425 }
1426
1427 /*
1428  * Function:    scsi_request_fn()
1429  *
1430  * Purpose:     Main strategy routine for SCSI.
1431  *
1432  * Arguments:   q       - Pointer to actual queue.
1433  *
1434  * Returns:     Nothing
1435  *
1436  * Lock status: IO request lock assumed to be held when called.
1437  */
1438 static void scsi_request_fn(struct request_queue *q)
1439 {
1440         struct scsi_device *sdev = q->queuedata;
1441         struct Scsi_Host *shost;
1442         struct scsi_cmnd *cmd;
1443         struct request *req;
1444
1445         if (!sdev) {
1446                 printk("scsi: killing requests for dead queue\n");
1447                 while ((req = elv_next_request(q)) != NULL)
1448                         scsi_kill_request(req, q);
1449                 return;
1450         }
1451
1452         if(!get_device(&sdev->sdev_gendev))
1453                 /* We must be tearing the block queue down already */
1454                 return;
1455
1456         /*
1457          * To start with, we keep looping until the queue is empty, or until
1458          * the host is no longer able to accept any more requests.
1459          */
1460         shost = sdev->host;
1461         while (!blk_queue_plugged(q)) {
1462                 int rtn;
1463                 /*
1464                  * get next queueable request.  We do this early to make sure
1465                  * that the request is fully prepared even if we cannot 
1466                  * accept it.
1467                  */
1468                 req = elv_next_request(q);
1469                 if (!req || !scsi_dev_queue_ready(q, sdev))
1470                         break;
1471
1472                 if (unlikely(!scsi_device_online(sdev))) {
1473                         sdev_printk(KERN_ERR, sdev,
1474                                     "rejecting I/O to offline device\n");
1475                         scsi_kill_request(req, q);
1476                         continue;
1477                 }
1478
1479
1480                 /*
1481                  * Remove the request from the request list.
1482                  */
1483                 if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
1484                         blkdev_dequeue_request(req);
1485                 sdev->device_busy++;
1486
1487                 spin_unlock(q->queue_lock);
1488                 cmd = req->special;
1489                 if (unlikely(cmd == NULL)) {
1490                         printk(KERN_CRIT "impossible request in %s.\n"
1491                                          "please mail a stack trace to "
1492                                          "linux-scsi@vger.kernel.org\n",
1493                                          __FUNCTION__);
1494                         blk_dump_rq_flags(req, "foo");
1495                         BUG();
1496                 }
1497                 spin_lock(shost->host_lock);
1498
1499                 if (!scsi_host_queue_ready(q, shost, sdev))
1500                         goto not_ready;
1501                 if (scsi_target(sdev)->single_lun) {
1502                         if (scsi_target(sdev)->starget_sdev_user &&
1503                             scsi_target(sdev)->starget_sdev_user != sdev)
1504                                 goto not_ready;
1505                         scsi_target(sdev)->starget_sdev_user = sdev;
1506                 }
1507                 shost->host_busy++;
1508
1509                 /*
1510                  * XXX(hch): This is rather suboptimal, scsi_dispatch_cmd will
1511                  *              take the lock again.
1512                  */
1513                 spin_unlock_irq(shost->host_lock);
1514
1515                 /*
1516                  * Finally, initialize any error handling parameters, and set up
1517                  * the timers for timeouts.
1518                  */
1519                 scsi_init_cmd_errh(cmd);
1520
1521                 /*
1522                  * Dispatch the command to the low-level driver.
1523                  */
1524                 rtn = scsi_dispatch_cmd(cmd);
1525                 spin_lock_irq(q->queue_lock);
1526                 if(rtn) {
1527                         /* we're refusing the command; because of
1528                          * the way locks get dropped, we need to 
1529                          * check here if plugging is required */
1530                         if(sdev->device_busy == 0)
1531                                 blk_plug_device(q);
1532
1533                         break;
1534                 }
1535         }
1536
1537         goto out;
1538
1539  not_ready:
1540         spin_unlock_irq(shost->host_lock);
1541
1542         /*
1543          * lock q, handle tag, requeue req, and decrement device_busy. We
1544          * must return with queue_lock held.
1545          *
1546          * Decrementing device_busy without checking it is OK, as all such
1547          * cases (host limits or settings) should run the queue at some
1548          * later time.
1549          */
1550         spin_lock_irq(q->queue_lock);
1551         blk_requeue_request(q, req);
1552         sdev->device_busy--;
1553         if(sdev->device_busy == 0)
1554                 blk_plug_device(q);
1555  out:
1556         /* must be careful here...if we trigger the ->remove() function
1557          * we cannot be holding the q lock */
1558         spin_unlock_irq(q->queue_lock);
1559         put_device(&sdev->sdev_gendev);
1560         spin_lock_irq(q->queue_lock);
1561 }
1562
1563 u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
1564 {
1565         struct device *host_dev;
1566         u64 bounce_limit = 0xffffffff;
1567
1568         if (shost->unchecked_isa_dma)
1569                 return BLK_BOUNCE_ISA;
1570         /*
1571          * Platforms with virtual-DMA translation
1572          * hardware have no practical limit.
1573          */
1574         if (!PCI_DMA_BUS_IS_PHYS)
1575                 return BLK_BOUNCE_ANY;
1576
1577         host_dev = scsi_get_device(shost);
1578         if (host_dev && host_dev->dma_mask)
1579                 bounce_limit = *host_dev->dma_mask;
1580
1581         return bounce_limit;
1582 }
1583 EXPORT_SYMBOL(scsi_calculate_bounce_limit);
1584
1585 struct request_queue *__scsi_alloc_queue(struct Scsi_Host *shost,
1586                                          request_fn_proc *request_fn)
1587 {
1588         struct request_queue *q;
1589
1590         q = blk_init_queue(request_fn, NULL);
1591         if (!q)
1592                 return NULL;
1593
1594         /*
1595          * this limit is imposed by hardware restrictions
1596          */
1597         blk_queue_max_hw_segments(q, shost->sg_tablesize);
1598
1599         /*
1600          * In the future, sg chaining support will be mandatory and this
1601          * ifdef can then go away. Right now we don't have all archs
1602          * converted, so better keep it safe.
1603          */
1604 #ifdef ARCH_HAS_SG_CHAIN
1605         if (shost->use_sg_chaining)
1606                 blk_queue_max_phys_segments(q, SCSI_MAX_SG_CHAIN_SEGMENTS);
1607         else
1608                 blk_queue_max_phys_segments(q, SCSI_MAX_SG_SEGMENTS);
1609 #else
1610         blk_queue_max_phys_segments(q, SCSI_MAX_SG_SEGMENTS);
1611 #endif
1612
1613         blk_queue_max_sectors(q, shost->max_sectors);
1614         blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
1615         blk_queue_segment_boundary(q, shost->dma_boundary);
1616
1617         if (!shost->use_clustering)
1618                 clear_bit(QUEUE_FLAG_CLUSTER, &q->queue_flags);
1619
1620         /*
1621          * set a reasonable default alignment on word boundaries: the
1622          * host and device may alter it using
1623          * blk_queue_update_dma_alignment() later.
1624          */
1625         blk_queue_dma_alignment(q, 0x03);
1626
1627         return q;
1628 }
1629 EXPORT_SYMBOL(__scsi_alloc_queue);
1630
1631 struct request_queue *scsi_alloc_queue(struct scsi_device *sdev)
1632 {
1633         struct request_queue *q;
1634
1635         q = __scsi_alloc_queue(sdev->host, scsi_request_fn);
1636         if (!q)
1637                 return NULL;
1638
1639         blk_queue_prep_rq(q, scsi_prep_fn);
1640         blk_queue_softirq_done(q, scsi_softirq_done);
1641         return q;
1642 }
1643
1644 void scsi_free_queue(struct request_queue *q)
1645 {
1646         blk_cleanup_queue(q);
1647 }
1648
1649 /*
1650  * Function:    scsi_block_requests()
1651  *
1652  * Purpose:     Utility function used by low-level drivers to prevent further
1653  *              commands from being queued to the device.
1654  *
1655  * Arguments:   shost       - Host in question
1656  *
1657  * Returns:     Nothing
1658  *
1659  * Lock status: No locks are assumed held.
1660  *
1661  * Notes:       There is no timer nor any other means by which the requests
1662  *              get unblocked other than the low-level driver calling
1663  *              scsi_unblock_requests().
1664  */
1665 void scsi_block_requests(struct Scsi_Host *shost)
1666 {
1667         shost->host_self_blocked = 1;
1668 }
1669 EXPORT_SYMBOL(scsi_block_requests);
1670
1671 /*
1672  * Function:    scsi_unblock_requests()
1673  *
1674  * Purpose:     Utility function used by low-level drivers to allow further
1675  *              commands from being queued to the device.
1676  *
1677  * Arguments:   shost       - Host in question
1678  *
1679  * Returns:     Nothing
1680  *
1681  * Lock status: No locks are assumed held.
1682  *
1683  * Notes:       There is no timer nor any other means by which the requests
1684  *              get unblocked other than the low-level driver calling
1685  *              scsi_unblock_requests().
1686  *
1687  *              This is done as an API function so that changes to the
1688  *              internals of the scsi mid-layer won't require wholesale
1689  *              changes to drivers that use this feature.
1690  */
1691 void scsi_unblock_requests(struct Scsi_Host *shost)
1692 {
1693         shost->host_self_blocked = 0;
1694         scsi_run_host_queues(shost);
1695 }
1696 EXPORT_SYMBOL(scsi_unblock_requests);
1697
1698 int __init scsi_init_queue(void)
1699 {
1700         int i;
1701
1702         scsi_io_context_cache = kmem_cache_create("scsi_io_context",
1703                                         sizeof(struct scsi_io_context),
1704                                         0, 0, NULL);
1705         if (!scsi_io_context_cache) {
1706                 printk(KERN_ERR "SCSI: can't init scsi io context cache\n");
1707                 return -ENOMEM;
1708         }
1709
1710         scsi_bidi_sdb_cache = kmem_cache_create("scsi_bidi_sdb",
1711                                         sizeof(struct scsi_data_buffer),
1712                                         0, 0, NULL);
1713         if (!scsi_bidi_sdb_cache) {
1714                 printk(KERN_ERR "SCSI: can't init scsi bidi sdb cache\n");
1715                 return -ENOMEM;
1716         }
1717
1718         for (i = 0; i < SG_MEMPOOL_NR; i++) {
1719                 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1720                 int size = sgp->size * sizeof(struct scatterlist);
1721
1722                 sgp->slab = kmem_cache_create(sgp->name, size, 0,
1723                                 SLAB_HWCACHE_ALIGN, NULL);
1724                 if (!sgp->slab) {
1725                         printk(KERN_ERR "SCSI: can't init sg slab %s\n",
1726                                         sgp->name);
1727                 }
1728
1729                 sgp->pool = mempool_create_slab_pool(SG_MEMPOOL_SIZE,
1730                                                      sgp->slab);
1731                 if (!sgp->pool) {
1732                         printk(KERN_ERR "SCSI: can't init sg mempool %s\n",
1733                                         sgp->name);
1734                 }
1735         }
1736
1737         return 0;
1738 }
1739
1740 void scsi_exit_queue(void)
1741 {
1742         int i;
1743
1744         kmem_cache_destroy(scsi_io_context_cache);
1745
1746         for (i = 0; i < SG_MEMPOOL_NR; i++) {
1747                 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1748                 mempool_destroy(sgp->pool);
1749                 kmem_cache_destroy(sgp->slab);
1750         }
1751 }
1752
1753 /**
1754  *      scsi_mode_select - issue a mode select
1755  *      @sdev:  SCSI device to be queried
1756  *      @pf:    Page format bit (1 == standard, 0 == vendor specific)
1757  *      @sp:    Save page bit (0 == don't save, 1 == save)
1758  *      @modepage: mode page being requested
1759  *      @buffer: request buffer (may not be smaller than eight bytes)
1760  *      @len:   length of request buffer.
1761  *      @timeout: command timeout
1762  *      @retries: number of retries before failing
1763  *      @data: returns a structure abstracting the mode header data
1764  *      @sshdr: place to put sense data (or NULL if no sense to be collected).
1765  *              must be SCSI_SENSE_BUFFERSIZE big.
1766  *
1767  *      Returns zero if successful; negative error number or scsi
1768  *      status on error
1769  *
1770  */
1771 int
1772 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
1773                  unsigned char *buffer, int len, int timeout, int retries,
1774                  struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1775 {
1776         unsigned char cmd[10];
1777         unsigned char *real_buffer;
1778         int ret;
1779
1780         memset(cmd, 0, sizeof(cmd));
1781         cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
1782
1783         if (sdev->use_10_for_ms) {
1784                 if (len > 65535)
1785                         return -EINVAL;
1786                 real_buffer = kmalloc(8 + len, GFP_KERNEL);
1787                 if (!real_buffer)
1788                         return -ENOMEM;
1789                 memcpy(real_buffer + 8, buffer, len);
1790                 len += 8;
1791                 real_buffer[0] = 0;
1792                 real_buffer[1] = 0;
1793                 real_buffer[2] = data->medium_type;
1794                 real_buffer[3] = data->device_specific;
1795                 real_buffer[4] = data->longlba ? 0x01 : 0;
1796                 real_buffer[5] = 0;
1797                 real_buffer[6] = data->block_descriptor_length >> 8;
1798                 real_buffer[7] = data->block_descriptor_length;
1799
1800                 cmd[0] = MODE_SELECT_10;
1801                 cmd[7] = len >> 8;
1802                 cmd[8] = len;
1803         } else {
1804                 if (len > 255 || data->block_descriptor_length > 255 ||
1805                     data->longlba)
1806                         return -EINVAL;
1807
1808                 real_buffer = kmalloc(4 + len, GFP_KERNEL);
1809                 if (!real_buffer)
1810                         return -ENOMEM;
1811                 memcpy(real_buffer + 4, buffer, len);
1812                 len += 4;
1813                 real_buffer[0] = 0;
1814                 real_buffer[1] = data->medium_type;
1815                 real_buffer[2] = data->device_specific;
1816                 real_buffer[3] = data->block_descriptor_length;
1817                 
1818
1819                 cmd[0] = MODE_SELECT;
1820                 cmd[4] = len;
1821         }
1822
1823         ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
1824                                sshdr, timeout, retries);
1825         kfree(real_buffer);
1826         return ret;
1827 }
1828 EXPORT_SYMBOL_GPL(scsi_mode_select);
1829
1830 /**
1831  *      scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
1832  *      @sdev:  SCSI device to be queried
1833  *      @dbd:   set if mode sense will allow block descriptors to be returned
1834  *      @modepage: mode page being requested
1835  *      @buffer: request buffer (may not be smaller than eight bytes)
1836  *      @len:   length of request buffer.
1837  *      @timeout: command timeout
1838  *      @retries: number of retries before failing
1839  *      @data: returns a structure abstracting the mode header data
1840  *      @sshdr: place to put sense data (or NULL if no sense to be collected).
1841  *              must be SCSI_SENSE_BUFFERSIZE big.
1842  *
1843  *      Returns zero if unsuccessful, or the header offset (either 4
1844  *      or 8 depending on whether a six or ten byte command was
1845  *      issued) if successful.
1846  */
1847 int
1848 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
1849                   unsigned char *buffer, int len, int timeout, int retries,
1850                   struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1851 {
1852         unsigned char cmd[12];
1853         int use_10_for_ms;
1854         int header_length;
1855         int result;
1856         struct scsi_sense_hdr my_sshdr;
1857
1858         memset(data, 0, sizeof(*data));
1859         memset(&cmd[0], 0, 12);
1860         cmd[1] = dbd & 0x18;    /* allows DBD and LLBA bits */
1861         cmd[2] = modepage;
1862
1863         /* caller might not be interested in sense, but we need it */
1864         if (!sshdr)
1865                 sshdr = &my_sshdr;
1866
1867  retry:
1868         use_10_for_ms = sdev->use_10_for_ms;
1869
1870         if (use_10_for_ms) {
1871                 if (len < 8)
1872                         len = 8;
1873
1874                 cmd[0] = MODE_SENSE_10;
1875                 cmd[8] = len;
1876                 header_length = 8;
1877         } else {
1878                 if (len < 4)
1879                         len = 4;
1880
1881                 cmd[0] = MODE_SENSE;
1882                 cmd[4] = len;
1883                 header_length = 4;
1884         }
1885
1886         memset(buffer, 0, len);
1887
1888         result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
1889                                   sshdr, timeout, retries);
1890
1891         /* This code looks awful: what it's doing is making sure an
1892          * ILLEGAL REQUEST sense return identifies the actual command
1893          * byte as the problem.  MODE_SENSE commands can return
1894          * ILLEGAL REQUEST if the code page isn't supported */
1895
1896         if (use_10_for_ms && !scsi_status_is_good(result) &&
1897             (driver_byte(result) & DRIVER_SENSE)) {
1898                 if (scsi_sense_valid(sshdr)) {
1899                         if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
1900                             (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
1901                                 /* 
1902                                  * Invalid command operation code
1903                                  */
1904                                 sdev->use_10_for_ms = 0;
1905                                 goto retry;
1906                         }
1907                 }
1908         }
1909
1910         if(scsi_status_is_good(result)) {
1911                 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
1912                              (modepage == 6 || modepage == 8))) {
1913                         /* Initio breakage? */
1914                         header_length = 0;
1915                         data->length = 13;
1916                         data->medium_type = 0;
1917                         data->device_specific = 0;
1918                         data->longlba = 0;
1919                         data->block_descriptor_length = 0;
1920                 } else if(use_10_for_ms) {
1921                         data->length = buffer[0]*256 + buffer[1] + 2;
1922                         data->medium_type = buffer[2];
1923                         data->device_specific = buffer[3];
1924                         data->longlba = buffer[4] & 0x01;
1925                         data->block_descriptor_length = buffer[6]*256
1926                                 + buffer[7];
1927                 } else {
1928                         data->length = buffer[0] + 1;
1929                         data->medium_type = buffer[1];
1930                         data->device_specific = buffer[2];
1931                         data->block_descriptor_length = buffer[3];
1932                 }
1933                 data->header_length = header_length;
1934         }
1935
1936         return result;
1937 }
1938 EXPORT_SYMBOL(scsi_mode_sense);
1939
1940 /**
1941  *      scsi_test_unit_ready - test if unit is ready
1942  *      @sdev:  scsi device to change the state of.
1943  *      @timeout: command timeout
1944  *      @retries: number of retries before failing
1945  *      @sshdr_external: Optional pointer to struct scsi_sense_hdr for
1946  *              returning sense. Make sure that this is cleared before passing
1947  *              in.
1948  *
1949  *      Returns zero if unsuccessful or an error if TUR failed.  For
1950  *      removable media, a return of NOT_READY or UNIT_ATTENTION is
1951  *      translated to success, with the ->changed flag updated.
1952  **/
1953 int
1954 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
1955                      struct scsi_sense_hdr *sshdr_external)
1956 {
1957         char cmd[] = {
1958                 TEST_UNIT_READY, 0, 0, 0, 0, 0,
1959         };
1960         struct scsi_sense_hdr *sshdr;
1961         int result;
1962
1963         if (!sshdr_external)
1964                 sshdr = kzalloc(sizeof(*sshdr), GFP_KERNEL);
1965         else
1966                 sshdr = sshdr_external;
1967
1968         /* try to eat the UNIT_ATTENTION if there are enough retries */
1969         do {
1970                 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
1971                                           timeout, retries);
1972         } while ((driver_byte(result) & DRIVER_SENSE) &&
1973                  sshdr && sshdr->sense_key == UNIT_ATTENTION &&
1974                  --retries);
1975
1976         if (!sshdr)
1977                 /* could not allocate sense buffer, so can't process it */
1978                 return result;
1979
1980         if ((driver_byte(result) & DRIVER_SENSE) && sdev->removable) {
1981
1982                 if ((scsi_sense_valid(sshdr)) &&
1983                     ((sshdr->sense_key == UNIT_ATTENTION) ||
1984                      (sshdr->sense_key == NOT_READY))) {
1985                         sdev->changed = 1;
1986                         result = 0;
1987                 }
1988         }
1989         if (!sshdr_external)
1990                 kfree(sshdr);
1991         return result;
1992 }
1993 EXPORT_SYMBOL(scsi_test_unit_ready);
1994
1995 /**
1996  *      scsi_device_set_state - Take the given device through the device state model.
1997  *      @sdev:  scsi device to change the state of.
1998  *      @state: state to change to.
1999  *
2000  *      Returns zero if unsuccessful or an error if the requested 
2001  *      transition is illegal.
2002  */
2003 int
2004 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2005 {
2006         enum scsi_device_state oldstate = sdev->sdev_state;
2007
2008         if (state == oldstate)
2009                 return 0;
2010
2011         switch (state) {
2012         case SDEV_CREATED:
2013                 /* There are no legal states that come back to
2014                  * created.  This is the manually initialised start
2015                  * state */
2016                 goto illegal;
2017                         
2018         case SDEV_RUNNING:
2019                 switch (oldstate) {
2020                 case SDEV_CREATED:
2021                 case SDEV_OFFLINE:
2022                 case SDEV_QUIESCE:
2023                 case SDEV_BLOCK:
2024                         break;
2025                 default:
2026                         goto illegal;
2027                 }
2028                 break;
2029
2030         case SDEV_QUIESCE:
2031                 switch (oldstate) {
2032                 case SDEV_RUNNING:
2033                 case SDEV_OFFLINE:
2034                         break;
2035                 default:
2036                         goto illegal;
2037                 }
2038                 break;
2039
2040         case SDEV_OFFLINE:
2041                 switch (oldstate) {
2042                 case SDEV_CREATED:
2043                 case SDEV_RUNNING:
2044                 case SDEV_QUIESCE:
2045                 case SDEV_BLOCK:
2046                         break;
2047                 default:
2048                         goto illegal;
2049                 }
2050                 break;
2051
2052         case SDEV_BLOCK:
2053                 switch (oldstate) {
2054                 case SDEV_CREATED:
2055                 case SDEV_RUNNING:
2056                         break;
2057                 default:
2058                         goto illegal;
2059                 }
2060                 break;
2061
2062         case SDEV_CANCEL:
2063                 switch (oldstate) {
2064                 case SDEV_CREATED:
2065                 case SDEV_RUNNING:
2066                 case SDEV_QUIESCE:
2067                 case SDEV_OFFLINE:
2068                 case SDEV_BLOCK:
2069                         break;
2070                 default:
2071                         goto illegal;
2072                 }
2073                 break;
2074
2075         case SDEV_DEL:
2076                 switch (oldstate) {
2077                 case SDEV_CREATED:
2078                 case SDEV_RUNNING:
2079                 case SDEV_OFFLINE:
2080                 case SDEV_CANCEL:
2081                         break;
2082                 default:
2083                         goto illegal;
2084                 }
2085                 break;
2086
2087         }
2088         sdev->sdev_state = state;
2089         return 0;
2090
2091  illegal:
2092         SCSI_LOG_ERROR_RECOVERY(1, 
2093                                 sdev_printk(KERN_ERR, sdev,
2094                                             "Illegal state transition %s->%s\n",
2095                                             scsi_device_state_name(oldstate),
2096                                             scsi_device_state_name(state))
2097                                 );
2098         return -EINVAL;
2099 }
2100 EXPORT_SYMBOL(scsi_device_set_state);
2101
2102 /**
2103  *      sdev_evt_emit - emit a single SCSI device uevent
2104  *      @sdev: associated SCSI device
2105  *      @evt: event to emit
2106  *
2107  *      Send a single uevent (scsi_event) to the associated scsi_device.
2108  */
2109 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2110 {
2111         int idx = 0;
2112         char *envp[3];
2113
2114         switch (evt->evt_type) {
2115         case SDEV_EVT_MEDIA_CHANGE:
2116                 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2117                 break;
2118
2119         default:
2120                 /* do nothing */
2121                 break;
2122         }
2123
2124         envp[idx++] = NULL;
2125
2126         kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2127 }
2128
2129 /**
2130  *      sdev_evt_thread - send a uevent for each scsi event
2131  *      @work: work struct for scsi_device
2132  *
2133  *      Dispatch queued events to their associated scsi_device kobjects
2134  *      as uevents.
2135  */
2136 void scsi_evt_thread(struct work_struct *work)
2137 {
2138         struct scsi_device *sdev;
2139         LIST_HEAD(event_list);
2140
2141         sdev = container_of(work, struct scsi_device, event_work);
2142
2143         while (1) {
2144                 struct scsi_event *evt;
2145                 struct list_head *this, *tmp;
2146                 unsigned long flags;
2147
2148                 spin_lock_irqsave(&sdev->list_lock, flags);
2149                 list_splice_init(&sdev->event_list, &event_list);
2150                 spin_unlock_irqrestore(&sdev->list_lock, flags);
2151
2152                 if (list_empty(&event_list))
2153                         break;
2154
2155                 list_for_each_safe(this, tmp, &event_list) {
2156                         evt = list_entry(this, struct scsi_event, node);
2157                         list_del(&evt->node);
2158                         scsi_evt_emit(sdev, evt);
2159                         kfree(evt);
2160                 }
2161         }
2162 }
2163
2164 /**
2165  *      sdev_evt_send - send asserted event to uevent thread
2166  *      @sdev: scsi_device event occurred on
2167  *      @evt: event to send
2168  *
2169  *      Assert scsi device event asynchronously.
2170  */
2171 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2172 {
2173         unsigned long flags;
2174
2175         if (!test_bit(evt->evt_type, sdev->supported_events)) {
2176                 kfree(evt);
2177                 return;
2178         }
2179
2180         spin_lock_irqsave(&sdev->list_lock, flags);
2181         list_add_tail(&evt->node, &sdev->event_list);
2182         schedule_work(&sdev->event_work);
2183         spin_unlock_irqrestore(&sdev->list_lock, flags);
2184 }
2185 EXPORT_SYMBOL_GPL(sdev_evt_send);
2186
2187 /**
2188  *      sdev_evt_alloc - allocate a new scsi event
2189  *      @evt_type: type of event to allocate
2190  *      @gfpflags: GFP flags for allocation
2191  *
2192  *      Allocates and returns a new scsi_event.
2193  */
2194 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2195                                   gfp_t gfpflags)
2196 {
2197         struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2198         if (!evt)
2199                 return NULL;
2200
2201         evt->evt_type = evt_type;
2202         INIT_LIST_HEAD(&evt->node);
2203
2204         /* evt_type-specific initialization, if any */
2205         switch (evt_type) {
2206         case SDEV_EVT_MEDIA_CHANGE:
2207         default:
2208                 /* do nothing */
2209                 break;
2210         }
2211
2212         return evt;
2213 }
2214 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2215
2216 /**
2217  *      sdev_evt_send_simple - send asserted event to uevent thread
2218  *      @sdev: scsi_device event occurred on
2219  *      @evt_type: type of event to send
2220  *      @gfpflags: GFP flags for allocation
2221  *
2222  *      Assert scsi device event asynchronously, given an event type.
2223  */
2224 void sdev_evt_send_simple(struct scsi_device *sdev,
2225                           enum scsi_device_event evt_type, gfp_t gfpflags)
2226 {
2227         struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2228         if (!evt) {
2229                 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2230                             evt_type);
2231                 return;
2232         }
2233
2234         sdev_evt_send(sdev, evt);
2235 }
2236 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2237
2238 /**
2239  *      scsi_device_quiesce - Block user issued commands.
2240  *      @sdev:  scsi device to quiesce.
2241  *
2242  *      This works by trying to transition to the SDEV_QUIESCE state
2243  *      (which must be a legal transition).  When the device is in this
2244  *      state, only special requests will be accepted, all others will
2245  *      be deferred.  Since special requests may also be requeued requests,
2246  *      a successful return doesn't guarantee the device will be 
2247  *      totally quiescent.
2248  *
2249  *      Must be called with user context, may sleep.
2250  *
2251  *      Returns zero if unsuccessful or an error if not.
2252  */
2253 int
2254 scsi_device_quiesce(struct scsi_device *sdev)
2255 {
2256         int err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2257         if (err)
2258                 return err;
2259
2260         scsi_run_queue(sdev->request_queue);
2261         while (sdev->device_busy) {
2262                 msleep_interruptible(200);
2263                 scsi_run_queue(sdev->request_queue);
2264         }
2265         return 0;
2266 }
2267 EXPORT_SYMBOL(scsi_device_quiesce);
2268
2269 /**
2270  *      scsi_device_resume - Restart user issued commands to a quiesced device.
2271  *      @sdev:  scsi device to resume.
2272  *
2273  *      Moves the device from quiesced back to running and restarts the
2274  *      queues.
2275  *
2276  *      Must be called with user context, may sleep.
2277  */
2278 void
2279 scsi_device_resume(struct scsi_device *sdev)
2280 {
2281         if(scsi_device_set_state(sdev, SDEV_RUNNING))
2282                 return;
2283         scsi_run_queue(sdev->request_queue);
2284 }
2285 EXPORT_SYMBOL(scsi_device_resume);
2286
2287 static void
2288 device_quiesce_fn(struct scsi_device *sdev, void *data)
2289 {
2290         scsi_device_quiesce(sdev);
2291 }
2292
2293 void
2294 scsi_target_quiesce(struct scsi_target *starget)
2295 {
2296         starget_for_each_device(starget, NULL, device_quiesce_fn);
2297 }
2298 EXPORT_SYMBOL(scsi_target_quiesce);
2299
2300 static void
2301 device_resume_fn(struct scsi_device *sdev, void *data)
2302 {
2303         scsi_device_resume(sdev);
2304 }
2305
2306 void
2307 scsi_target_resume(struct scsi_target *starget)
2308 {
2309         starget_for_each_device(starget, NULL, device_resume_fn);
2310 }
2311 EXPORT_SYMBOL(scsi_target_resume);
2312
2313 /**
2314  * scsi_internal_device_block - internal function to put a device temporarily into the SDEV_BLOCK state
2315  * @sdev:       device to block
2316  *
2317  * Block request made by scsi lld's to temporarily stop all
2318  * scsi commands on the specified device.  Called from interrupt
2319  * or normal process context.
2320  *
2321  * Returns zero if successful or error if not
2322  *
2323  * Notes:       
2324  *      This routine transitions the device to the SDEV_BLOCK state
2325  *      (which must be a legal transition).  When the device is in this
2326  *      state, all commands are deferred until the scsi lld reenables
2327  *      the device with scsi_device_unblock or device_block_tmo fires.
2328  *      This routine assumes the host_lock is held on entry.
2329  */
2330 int
2331 scsi_internal_device_block(struct scsi_device *sdev)
2332 {
2333         struct request_queue *q = sdev->request_queue;
2334         unsigned long flags;
2335         int err = 0;
2336
2337         err = scsi_device_set_state(sdev, SDEV_BLOCK);
2338         if (err)
2339                 return err;
2340
2341         /* 
2342          * The device has transitioned to SDEV_BLOCK.  Stop the
2343          * block layer from calling the midlayer with this device's
2344          * request queue. 
2345          */
2346         spin_lock_irqsave(q->queue_lock, flags);
2347         blk_stop_queue(q);
2348         spin_unlock_irqrestore(q->queue_lock, flags);
2349
2350         return 0;
2351 }
2352 EXPORT_SYMBOL_GPL(scsi_internal_device_block);
2353  
2354 /**
2355  * scsi_internal_device_unblock - resume a device after a block request
2356  * @sdev:       device to resume
2357  *
2358  * Called by scsi lld's or the midlayer to restart the device queue
2359  * for the previously suspended scsi device.  Called from interrupt or
2360  * normal process context.
2361  *
2362  * Returns zero if successful or error if not.
2363  *
2364  * Notes:       
2365  *      This routine transitions the device to the SDEV_RUNNING state
2366  *      (which must be a legal transition) allowing the midlayer to
2367  *      goose the queue for this device.  This routine assumes the 
2368  *      host_lock is held upon entry.
2369  */
2370 int
2371 scsi_internal_device_unblock(struct scsi_device *sdev)
2372 {
2373         struct request_queue *q = sdev->request_queue; 
2374         int err;
2375         unsigned long flags;
2376         
2377         /* 
2378          * Try to transition the scsi device to SDEV_RUNNING
2379          * and goose the device queue if successful.  
2380          */
2381         err = scsi_device_set_state(sdev, SDEV_RUNNING);
2382         if (err)
2383                 return err;
2384
2385         spin_lock_irqsave(q->queue_lock, flags);
2386         blk_start_queue(q);
2387         spin_unlock_irqrestore(q->queue_lock, flags);
2388
2389         return 0;
2390 }
2391 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock);
2392
2393 static void
2394 device_block(struct scsi_device *sdev, void *data)
2395 {
2396         scsi_internal_device_block(sdev);
2397 }
2398
2399 static int
2400 target_block(struct device *dev, void *data)
2401 {
2402         if (scsi_is_target_device(dev))
2403                 starget_for_each_device(to_scsi_target(dev), NULL,
2404                                         device_block);
2405         return 0;
2406 }
2407
2408 void
2409 scsi_target_block(struct device *dev)
2410 {
2411         if (scsi_is_target_device(dev))
2412                 starget_for_each_device(to_scsi_target(dev), NULL,
2413                                         device_block);
2414         else
2415                 device_for_each_child(dev, NULL, target_block);
2416 }
2417 EXPORT_SYMBOL_GPL(scsi_target_block);
2418
2419 static void
2420 device_unblock(struct scsi_device *sdev, void *data)
2421 {
2422         scsi_internal_device_unblock(sdev);
2423 }
2424
2425 static int
2426 target_unblock(struct device *dev, void *data)
2427 {
2428         if (scsi_is_target_device(dev))
2429                 starget_for_each_device(to_scsi_target(dev), NULL,
2430                                         device_unblock);
2431         return 0;
2432 }
2433
2434 void
2435 scsi_target_unblock(struct device *dev)
2436 {
2437         if (scsi_is_target_device(dev))
2438                 starget_for_each_device(to_scsi_target(dev), NULL,
2439                                         device_unblock);
2440         else
2441                 device_for_each_child(dev, NULL, target_unblock);
2442 }
2443 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2444
2445 /**
2446  * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
2447  * @sgl:        scatter-gather list
2448  * @sg_count:   number of segments in sg
2449  * @offset:     offset in bytes into sg, on return offset into the mapped area
2450  * @len:        bytes to map, on return number of bytes mapped
2451  *
2452  * Returns virtual address of the start of the mapped page
2453  */
2454 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
2455                           size_t *offset, size_t *len)
2456 {
2457         int i;
2458         size_t sg_len = 0, len_complete = 0;
2459         struct scatterlist *sg;
2460         struct page *page;
2461
2462         WARN_ON(!irqs_disabled());
2463
2464         for_each_sg(sgl, sg, sg_count, i) {
2465                 len_complete = sg_len; /* Complete sg-entries */
2466                 sg_len += sg->length;
2467                 if (sg_len > *offset)
2468                         break;
2469         }
2470
2471         if (unlikely(i == sg_count)) {
2472                 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2473                         "elements %d\n",
2474                        __FUNCTION__, sg_len, *offset, sg_count);
2475                 WARN_ON(1);
2476                 return NULL;
2477         }
2478
2479         /* Offset starting from the beginning of first page in this sg-entry */
2480         *offset = *offset - len_complete + sg->offset;
2481
2482         /* Assumption: contiguous pages can be accessed as "page + i" */
2483         page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
2484         *offset &= ~PAGE_MASK;
2485
2486         /* Bytes in this sg-entry from *offset to the end of the page */
2487         sg_len = PAGE_SIZE - *offset;
2488         if (*len > sg_len)
2489                 *len = sg_len;
2490
2491         return kmap_atomic(page, KM_BIO_SRC_IRQ);
2492 }
2493 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2494
2495 /**
2496  * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
2497  * @virt:       virtual address to be unmapped
2498  */
2499 void scsi_kunmap_atomic_sg(void *virt)
2500 {
2501         kunmap_atomic(virt, KM_BIO_SRC_IRQ);
2502 }
2503 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);