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