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