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