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