+- add patches.fixes/linux-post-2.6.3-20040220
[linux-flexiantxendom0-3.2.10.git] / drivers / scsi / scsi.c
1 /*
2  *  scsi.c Copyright (C) 1992 Drew Eckhardt
3  *         Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
4  *         Copyright (C) 2002, 2003 Christoph Hellwig
5  *
6  *  generic mid-level SCSI driver
7  *      Initial versions: Drew Eckhardt
8  *      Subsequent revisions: Eric Youngdale
9  *
10  *  <drew@colorado.edu>
11  *
12  *  Bug correction thanks go to :
13  *      Rik Faith <faith@cs.unc.edu>
14  *      Tommy Thorn <tthorn>
15  *      Thomas Wuensche <tw@fgb1.fgb.mw.tu-muenchen.de>
16  *
17  *  Modified by Eric Youngdale eric@andante.org or ericy@gnu.ai.mit.edu to
18  *  add scatter-gather, multiple outstanding request, and other
19  *  enhancements.
20  *
21  *  Native multichannel, wide scsi, /proc/scsi and hot plugging
22  *  support added by Michael Neuffer <mike@i-connect.net>
23  *
24  *  Added request_module("scsi_hostadapter") for kerneld:
25  *  (Put an "alias scsi_hostadapter your_hostadapter" in /etc/modprobe.conf)
26  *  Bjorn Ekwall  <bj0rn@blox.se>
27  *  (changed to kmod)
28  *
29  *  Major improvements to the timeout, abort, and reset processing,
30  *  as well as performance modifications for large queue depths by
31  *  Leonard N. Zubkoff <lnz@dandelion.com>
32  *
33  *  Converted cli() code to spinlocks, Ingo Molnar
34  *
35  *  Jiffies wrap fixes (host->resetting), 3 Dec 1998 Andrea Arcangeli
36  *
37  *  out_of_space hacks, D. Gilbert (dpg) 990608
38  */
39
40 #include <linux/module.h>
41 #include <linux/moduleparam.h>
42 #include <linux/kernel.h>
43 #include <linux/sched.h>
44 #include <linux/timer.h>
45 #include <linux/string.h>
46 #include <linux/slab.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/init.h>
50 #include <linux/completion.h>
51 #include <linux/devfs_fs_kernel.h>
52 #include <linux/unistd.h>
53 #include <linux/spinlock.h>
54 #include <linux/kmod.h>
55 #include <linux/interrupt.h>
56
57 #include <scsi/scsi_host.h>
58 #include "scsi.h"
59
60 #include "scsi_priv.h"
61 #include "scsi_logging.h"
62
63
64 /*
65  * Definitions and constants.
66  */
67
68 #define MIN_RESET_DELAY (2*HZ)
69
70 /* Do not call reset on error if we just did a reset within 15 sec. */
71 #define MIN_RESET_PERIOD (15*HZ)
72
73 /*
74  * Macro to determine the size of SCSI command. This macro takes vendor
75  * unique commands into account. SCSI commands in groups 6 and 7 are
76  * vendor unique and we will depend upon the command length being
77  * supplied correctly in cmd_len.
78  */
79 #define CDB_SIZE(cmd)   (((((cmd)->cmnd[0] >> 5) & 7) < 6) ? \
80                                 COMMAND_SIZE((cmd)->cmnd[0]) : (cmd)->cmd_len)
81
82 /*
83  * Data declarations.
84  */
85 unsigned long scsi_pid;
86 static unsigned long serial_number;
87
88 /*
89  * Note - the initial logging level can be set here to log events at boot time.
90  * After the system is up, you may enable logging via the /proc interface.
91  */
92 unsigned int scsi_logging_level;
93
94 const char *const scsi_device_types[MAX_SCSI_DEVICE_CODE] = {
95         "Direct-Access    ",
96         "Sequential-Access",
97         "Printer          ",
98         "Processor        ",
99         "WORM             ",
100         "CD-ROM           ",
101         "Scanner          ",
102         "Optical Device   ",
103         "Medium Changer   ",
104         "Communications   ",
105         "Unknown          ",
106         "Unknown          ",
107         "RAID             ",
108         "Enclosure        ",
109 };
110
111 /*
112  * Function:    scsi_allocate_request
113  *
114  * Purpose:     Allocate a request descriptor.
115  *
116  * Arguments:   device          - device for which we want a request
117  *              gfp_mask        - allocation flags passed to kmalloc
118  *
119  * Lock status: No locks assumed to be held.  This function is SMP-safe.
120  *
121  * Returns:     Pointer to request block.
122  */
123 struct scsi_request *scsi_allocate_request(struct scsi_device *sdev,
124                                            int gfp_mask)
125 {
126         const int offset = ALIGN(sizeof(struct scsi_request), 4);
127         const int size = offset + sizeof(struct request);
128         struct scsi_request *sreq;
129   
130         sreq = kmalloc(size, gfp_mask);
131         if (likely(sreq != NULL)) {
132                 memset(sreq, 0, size);
133                 sreq->sr_request = (struct request *)(((char *)sreq) + offset);
134                 sreq->sr_device = sdev;
135                 sreq->sr_host = sdev->host;
136                 sreq->sr_magic = SCSI_REQ_MAGIC;
137                 sreq->sr_data_direction = DMA_BIDIRECTIONAL;
138         }
139
140         return sreq;
141 }
142
143 void __scsi_release_request(struct scsi_request *sreq)
144 {
145         struct request *req = sreq->sr_request;
146
147         /* unlikely because the tag was usually ended earlier by the
148          * mid-layer. However, for layering reasons ULD's don't end
149          * the tag of commands they generate. */
150         if (unlikely(blk_rq_tagged(req))) {
151                 unsigned long flags;
152                 struct request_queue *q = req->q;
153
154                 spin_lock_irqsave(q->queue_lock, flags);
155                 blk_queue_end_tag(q, req);
156                 spin_unlock_irqrestore(q->queue_lock, flags);
157         }
158
159
160         if (likely(sreq->sr_command != NULL)) {
161                 struct scsi_cmnd *cmd = sreq->sr_command;
162
163                 sreq->sr_command = NULL;
164                 scsi_next_command(cmd);
165         }
166 }
167
168 /*
169  * Function:    scsi_release_request
170  *
171  * Purpose:     Release a request descriptor.
172  *
173  * Arguments:   sreq    - request to release
174  *
175  * Lock status: No locks assumed to be held.  This function is SMP-safe.
176  */
177 void scsi_release_request(struct scsi_request *sreq)
178 {
179         __scsi_release_request(sreq);
180         kfree(sreq);
181 }
182
183 struct scsi_host_cmd_pool {
184         kmem_cache_t    *slab;
185         unsigned int    users;
186         char            *name;
187         unsigned int    slab_flags;
188         unsigned int    gfp_mask;
189 };
190
191 static struct scsi_host_cmd_pool scsi_cmd_pool = {
192         .name           = "scsi_cmd_cache",
193         .slab_flags     = SLAB_HWCACHE_ALIGN,
194 };
195
196 static struct scsi_host_cmd_pool scsi_cmd_dma_pool = {
197         .name           = "scsi_cmd_cache(DMA)",
198         .slab_flags     = SLAB_HWCACHE_ALIGN|SLAB_CACHE_DMA,
199         .gfp_mask       = __GFP_DMA,
200 };
201
202 static DECLARE_MUTEX(host_cmd_pool_mutex);
203
204 static struct scsi_cmnd *__scsi_get_command(struct Scsi_Host *shost,
205                                             int gfp_mask)
206 {
207         struct scsi_cmnd *cmd;
208
209         cmd = kmem_cache_alloc(shost->cmd_pool->slab,
210                         gfp_mask | shost->cmd_pool->gfp_mask);
211
212         if (unlikely(!cmd)) {
213                 unsigned long flags;
214
215                 spin_lock_irqsave(&shost->free_list_lock, flags);
216                 if (likely(!list_empty(&shost->free_list))) {
217                         cmd = list_entry(shost->free_list.next,
218                                          struct scsi_cmnd, list);
219                         list_del_init(&cmd->list);
220                 }
221                 spin_unlock_irqrestore(&shost->free_list_lock, flags);
222         }
223
224         return cmd;
225 }
226
227 /*
228  * Function:    scsi_get_command()
229  *
230  * Purpose:     Allocate and setup a scsi command block
231  *
232  * Arguments:   dev     - parent scsi device
233  *              gfp_mask- allocator flags
234  *
235  * Returns:     The allocated scsi command structure.
236  */
237 struct scsi_cmnd *scsi_get_command(struct scsi_device *dev, int gfp_mask)
238 {
239         struct scsi_cmnd *cmd = __scsi_get_command(dev->host, gfp_mask);
240
241         if (likely(cmd != NULL)) {
242                 unsigned long flags;
243
244                 memset(cmd, 0, sizeof(*cmd));
245                 cmd->device = dev;
246                 cmd->state = SCSI_STATE_UNUSED;
247                 cmd->owner = SCSI_OWNER_NOBODY;
248                 init_timer(&cmd->eh_timeout);
249                 INIT_LIST_HEAD(&cmd->list);
250                 spin_lock_irqsave(&dev->list_lock, flags);
251                 list_add_tail(&cmd->list, &dev->cmd_list);
252                 spin_unlock_irqrestore(&dev->list_lock, flags);
253         }
254
255         return cmd;
256 }                               
257
258 /*
259  * Function:    scsi_put_command()
260  *
261  * Purpose:     Free a scsi command block
262  *
263  * Arguments:   cmd     - command block to free
264  *
265  * Returns:     Nothing.
266  *
267  * Notes:       The command must not belong to any lists.
268  */
269 void scsi_put_command(struct scsi_cmnd *cmd)
270 {
271         struct Scsi_Host *shost = cmd->device->host;
272         unsigned long flags;
273         
274         /* serious error if the command hasn't come from a device list */
275         spin_lock_irqsave(&cmd->device->list_lock, flags);
276         BUG_ON(list_empty(&cmd->list));
277         list_del_init(&cmd->list);
278         spin_unlock(&cmd->device->list_lock);
279         /* changing locks here, don't need to restore the irq state */
280         spin_lock(&shost->free_list_lock);
281         if (unlikely(list_empty(&shost->free_list))) {
282                 list_add(&cmd->list, &shost->free_list);
283                 cmd = NULL;
284         }
285         spin_unlock_irqrestore(&shost->free_list_lock, flags);
286
287         if (likely(cmd != NULL))
288                 kmem_cache_free(shost->cmd_pool->slab, cmd);
289 }
290
291 /*
292  * Function:    scsi_setup_command_freelist()
293  *
294  * Purpose:     Setup the command freelist for a scsi host.
295  *
296  * Arguments:   shost   - host to allocate the freelist for.
297  *
298  * Returns:     Nothing.
299  */
300 int scsi_setup_command_freelist(struct Scsi_Host *shost)
301 {
302         struct scsi_host_cmd_pool *pool;
303         struct scsi_cmnd *cmd;
304
305         spin_lock_init(&shost->free_list_lock);
306         INIT_LIST_HEAD(&shost->free_list);
307
308         /*
309          * Select a command slab for this host and create it if not
310          * yet existant.
311          */
312         down(&host_cmd_pool_mutex);
313         pool = (shost->unchecked_isa_dma ? &scsi_cmd_dma_pool : &scsi_cmd_pool);
314         if (!pool->users) {
315                 pool->slab = kmem_cache_create(pool->name,
316                                 sizeof(struct scsi_cmnd), 0,
317                                 pool->slab_flags, NULL, NULL);
318                 if (!pool->slab)
319                         goto fail;
320         }
321
322         pool->users++;
323         shost->cmd_pool = pool;
324         up(&host_cmd_pool_mutex);
325
326         /*
327          * Get one backup command for this host.
328          */
329         cmd = kmem_cache_alloc(shost->cmd_pool->slab,
330                         GFP_KERNEL | shost->cmd_pool->gfp_mask);
331         if (!cmd)
332                 goto fail2;
333         list_add(&cmd->list, &shost->free_list);                
334         return 0;
335
336  fail2:
337         if (!--pool->users)
338                 kmem_cache_destroy(pool->slab);
339         return -ENOMEM;
340  fail:
341         up(&host_cmd_pool_mutex);
342         return -ENOMEM;
343
344 }
345
346 /*
347  * Function:    scsi_destroy_command_freelist()
348  *
349  * Purpose:     Release the command freelist for a scsi host.
350  *
351  * Arguments:   shost   - host that's freelist is going to be destroyed
352  */
353 void scsi_destroy_command_freelist(struct Scsi_Host *shost)
354 {
355         while (!list_empty(&shost->free_list)) {
356                 struct scsi_cmnd *cmd;
357
358                 cmd = list_entry(shost->free_list.next, struct scsi_cmnd, list);
359                 list_del_init(&cmd->list);
360                 kmem_cache_free(shost->cmd_pool->slab, cmd);
361         }
362
363         down(&host_cmd_pool_mutex);
364         if (!--shost->cmd_pool->users)
365                 kmem_cache_destroy(shost->cmd_pool->slab);
366         up(&host_cmd_pool_mutex);
367 }
368
369 #ifdef CONFIG_SCSI_LOGGING
370 void scsi_log_send(struct scsi_cmnd *cmd)
371 {
372         unsigned int level;
373         struct scsi_device *sdev;
374
375         /*
376          * If ML QUEUE log level is greater than or equal to:
377          *
378          * 1: nothing (match completion)
379          *
380          * 2: log opcode + command of all commands
381          *
382          * 3: same as 2 plus dump cmd address
383          *
384          * 4: same as 3 plus dump extra junk
385          */
386         if (unlikely(scsi_logging_level)) {
387                 level = SCSI_LOG_LEVEL(SCSI_LOG_MLQUEUE_SHIFT,
388                                        SCSI_LOG_MLQUEUE_BITS);
389                 if (level > 1) {
390                         sdev = cmd->device;
391                         printk(KERN_INFO "scsi <%d:%d:%d:%d> send ",
392                                sdev->host->host_no, sdev->channel, sdev->id,
393                                sdev->lun);
394                         if (level > 2)
395                                 printk("0x%p ", cmd);
396                         /*
397                          * spaces to match disposition and cmd->result
398                          * output in scsi_log_completion.
399                          */
400                         printk("                 ");
401                         print_command(cmd->cmnd);
402                         if (level > 3) {
403                                 printk(KERN_INFO "buffer = 0x%p, bufflen = %d,"
404                                        " done = 0x%p, queuecommand 0x%p\n",
405                                         cmd->buffer, cmd->bufflen,
406                                         cmd->done,
407                                         sdev->host->hostt->queuecommand);
408
409                         }
410                 }
411         }
412 }
413
414 void scsi_log_completion(struct scsi_cmnd *cmd, int disposition)
415 {
416         unsigned int level;
417         struct scsi_device *sdev;
418
419         /*
420          * If ML COMPLETE log level is greater than or equal to:
421          *
422          * 1: log disposition, result, opcode + command, and conditionally
423          * sense data for failures or non SUCCESS dispositions.
424          *
425          * 2: same as 1 but for all command completions.
426          *
427          * 3: same as 2 plus dump cmd address
428          *
429          * 4: same as 3 plus dump extra junk
430          */
431         if (unlikely(scsi_logging_level)) {
432                 level = SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
433                                        SCSI_LOG_MLCOMPLETE_BITS);
434                 if (((level > 0) && (cmd->result || disposition != SUCCESS)) ||
435                     (level > 1)) {
436                         sdev = cmd->device;
437                         printk(KERN_INFO "scsi <%d:%d:%d:%d> done ",
438                                sdev->host->host_no, sdev->channel, sdev->id,
439                                sdev->lun);
440                         if (level > 2)
441                                 printk("0x%p ", cmd);
442                         /*
443                          * Dump truncated values, so we usually fit within
444                          * 80 chars.
445                          */
446                         switch (disposition) {
447                         case SUCCESS:
448                                 printk("SUCCESS");
449                                 break;
450                         case NEEDS_RETRY:
451                                 printk("RETRY  ");
452                                 break;
453                         case ADD_TO_MLQUEUE:
454                                 printk("MLQUEUE");
455                                 break;
456                         case FAILED:
457                                 printk("FAILED ");
458                                 break;
459                         case TIMEOUT_ERROR:
460                                 /* 
461                                  * If called via scsi_times_out.
462                                  */
463                                 printk("TIMEOUT");
464                                 break;
465                         default:
466                                 printk("UNKNOWN");
467                         }
468                         printk(" %8x ", cmd->result);
469                         print_command(cmd->cmnd);
470                         if (status_byte(cmd->result) & CHECK_CONDITION) {
471                                 /*
472                                  * XXX The print_sense formatting/prefix
473                                  * doesn't match this function.
474                                  */
475                                 print_sense("", cmd);
476                         }
477                         if (level > 3) {
478                                 printk(KERN_INFO "scsi host busy %d failed %d\n",
479                                        sdev->host->host_busy,
480                                        sdev->host->host_failed);
481                         }
482                 }
483         }
484 }
485 #endif
486
487 /*
488  * Function:    scsi_dispatch_command
489  *
490  * Purpose:     Dispatch a command to the low-level driver.
491  *
492  * Arguments:   cmd - command block we are dispatching.
493  *
494  * Notes:
495  */
496 int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
497 {
498         struct Scsi_Host *host = cmd->device->host;
499         unsigned long flags = 0;
500         unsigned long timeout;
501         int rtn = 0;
502
503         /* check if the device is still usable */
504         if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
505                 /* in SDEV_DEL we error all commands. DID_NO_CONNECT
506                  * returns an immediate error upwards, and signals
507                  * that the device is no longer present */
508                 cmd->result = DID_NO_CONNECT << 16;
509                 scsi_done(cmd);
510                 /* return 0 (because the command has been processed) */
511                 goto out;
512         }
513         /* Assign a unique nonzero serial_number. */
514         /* XXX(hch): this is racy */
515         if (++serial_number == 0)
516                 serial_number = 1;
517         cmd->serial_number = serial_number;
518         cmd->pid = scsi_pid++;
519
520         /* 
521          * If SCSI-2 or lower, store the LUN value in cmnd.
522          */
523         if (cmd->device->scsi_level <= SCSI_2) {
524                 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
525                                (cmd->device->lun << 5 & 0xe0);
526         }
527
528         /*
529          * We will wait MIN_RESET_DELAY clock ticks after the last reset so
530          * we can avoid the drive not being ready.
531          */
532         timeout = host->last_reset + MIN_RESET_DELAY;
533
534         if (host->resetting && time_before(jiffies, timeout)) {
535                 int ticks_remaining = timeout - jiffies;
536                 /*
537                  * NOTE: This may be executed from within an interrupt
538                  * handler!  This is bad, but for now, it'll do.  The irq
539                  * level of the interrupt handler has been masked out by the
540                  * platform dependent interrupt handling code already, so the
541                  * sti() here will not cause another call to the SCSI host's
542                  * interrupt handler (assuming there is one irq-level per
543                  * host).
544                  */
545                 while (--ticks_remaining >= 0)
546                         mdelay(1 + 999 / HZ);
547                 host->resetting = 0;
548         }
549
550         scsi_add_timer(cmd, cmd->timeout_per_command, scsi_times_out);
551
552         scsi_log_send(cmd);
553
554         /*
555          * We will use a queued command if possible, otherwise we will
556          * emulate the queuing and calling of completion function ourselves.
557          */
558
559         cmd->state = SCSI_STATE_QUEUED;
560         cmd->owner = SCSI_OWNER_LOWLEVEL;
561
562         /*
563          * Before we queue this command, check if the command
564          * length exceeds what the host adapter can handle.
565          */
566         if (CDB_SIZE(cmd) > cmd->device->host->max_cmd_len) {
567                 SCSI_LOG_MLQUEUE(3,
568                                 printk("queuecommand : command too long.\n"));
569                 cmd->result = (DID_ABORT << 16);
570
571                 spin_lock_irqsave(host->host_lock, flags);
572                 scsi_done(cmd);
573                 spin_unlock_irqrestore(host->host_lock, flags);
574                 goto out;
575         }
576
577         spin_lock_irqsave(host->host_lock, flags);
578         if (unlikely(test_bit(SHOST_CANCEL, &host->shost_state))) {
579                 cmd->result = (DID_NO_CONNECT << 16);
580                 scsi_done(cmd);
581         } else {
582                 rtn = host->hostt->queuecommand(cmd, scsi_done);
583         }
584         spin_unlock_irqrestore(host->host_lock, flags);
585         if (rtn) {
586                 scsi_queue_insert(cmd,
587                                 (rtn == SCSI_MLQUEUE_DEVICE_BUSY) ?
588                                  rtn : SCSI_MLQUEUE_HOST_BUSY);
589                 SCSI_LOG_MLQUEUE(3,
590                     printk("queuecommand : request rejected\n"));
591         }
592
593  out:
594         SCSI_LOG_MLQUEUE(3, printk("leaving scsi_dispatch_cmnd()\n"));
595         return rtn;
596 }
597
598 /*
599  * Function:    scsi_init_cmd_from_req
600  *
601  * Purpose:     Queue a SCSI command
602  * Purpose:     Initialize a struct scsi_cmnd from a struct scsi_request
603  *
604  * Arguments:   cmd       - command descriptor.
605  *              sreq      - Request from the queue.
606  *
607  * Lock status: None needed.
608  *
609  * Returns:     Nothing.
610  *
611  * Notes:       Mainly transfer data from the request structure to the
612  *              command structure.  The request structure is allocated
613  *              using the normal memory allocator, and requests can pile
614  *              up to more or less any depth.  The command structure represents
615  *              a consumable resource, as these are allocated into a pool
616  *              when the SCSI subsystem initializes.  The preallocation is
617  *              required so that in low-memory situations a disk I/O request
618  *              won't cause the memory manager to try and write out a page.
619  *              The request structure is generally used by ioctls and character
620  *              devices.
621  */
622 void scsi_init_cmd_from_req(struct scsi_cmnd *cmd, struct scsi_request *sreq)
623 {
624         sreq->sr_command = cmd;
625
626         cmd->owner = SCSI_OWNER_MIDLEVEL;
627         cmd->cmd_len = sreq->sr_cmd_len;
628         cmd->use_sg = sreq->sr_use_sg;
629
630         cmd->request = sreq->sr_request;
631         memcpy(cmd->data_cmnd, sreq->sr_cmnd, sizeof(cmd->data_cmnd));
632         cmd->serial_number = 0;
633         cmd->serial_number_at_timeout = 0;
634         cmd->bufflen = sreq->sr_bufflen;
635         cmd->buffer = sreq->sr_buffer;
636         cmd->retries = 0;
637         cmd->allowed = sreq->sr_allowed;
638         cmd->done = sreq->sr_done;
639         cmd->timeout_per_command = sreq->sr_timeout_per_command;
640         cmd->sc_data_direction = sreq->sr_data_direction;
641         cmd->sglist_len = sreq->sr_sglist_len;
642         cmd->underflow = sreq->sr_underflow;
643         cmd->sc_request = sreq;
644         memcpy(cmd->cmnd, sreq->sr_cmnd, sizeof(sreq->sr_cmnd));
645
646         /*
647          * Zero the sense buffer.  Some host adapters automatically request
648          * sense on error.  0 is not a valid sense code.
649          */
650         memset(cmd->sense_buffer, 0, sizeof(sreq->sr_sense_buffer));
651         cmd->request_buffer = sreq->sr_buffer;
652         cmd->request_bufflen = sreq->sr_bufflen;
653         cmd->old_use_sg = cmd->use_sg;
654         if (cmd->cmd_len == 0)
655                 cmd->cmd_len = COMMAND_SIZE(cmd->cmnd[0]);
656         cmd->old_cmd_len = cmd->cmd_len;
657         cmd->sc_old_data_direction = cmd->sc_data_direction;
658         cmd->old_underflow = cmd->underflow;
659
660         /*
661          * Start the timer ticking.
662          */
663         cmd->internal_timeout = NORMAL_TIMEOUT;
664         cmd->abort_reason = 0;
665         cmd->result = 0;
666
667         SCSI_LOG_MLQUEUE(3, printk("Leaving scsi_init_cmd_from_req()\n"));
668 }
669
670 /*
671  * Per-CPU I/O completion queue.
672  */
673 static DEFINE_PER_CPU(struct list_head, scsi_done_q);
674
675 /**
676  * scsi_done - Enqueue the finished SCSI command into the done queue.
677  * @cmd: The SCSI Command for which a low-level device driver (LLDD) gives
678  * ownership back to SCSI Core -- i.e. the LLDD has finished with it.
679  *
680  * This function is the mid-level's (SCSI Core) interrupt routine, which
681  * regains ownership of the SCSI command (de facto) from a LLDD, and enqueues
682  * the command to the done queue for further processing.
683  *
684  * This is the producer of the done queue who enqueues at the tail.
685  *
686  * This function is interrupt context safe.
687  */
688 void scsi_done(struct scsi_cmnd *cmd)
689 {
690         unsigned long flags;
691
692         /*
693          * We don't have to worry about this one timing out any more.
694          * If we are unable to remove the timer, then the command
695          * has already timed out.  In which case, we have no choice but to
696          * let the timeout function run, as we have no idea where in fact
697          * that function could really be.  It might be on another processor,
698          * etc, etc.
699          */
700         if (!scsi_delete_timer(cmd))
701                 return;
702
703         /*
704          * Set the serial numbers back to zero
705          */
706         cmd->serial_number = 0;
707         cmd->serial_number_at_timeout = 0;
708         cmd->state = SCSI_STATE_BHQUEUE;
709         cmd->owner = SCSI_OWNER_BH_HANDLER;
710
711         /*
712          * Next, enqueue the command into the done queue.
713          * It is a per-CPU queue, so we just disable local interrupts
714          * and need no spinlock.
715          */
716         local_irq_save(flags);
717         list_add_tail(&cmd->eh_entry, &__get_cpu_var(scsi_done_q));
718         raise_softirq_irqoff(SCSI_SOFTIRQ);
719         local_irq_restore(flags);
720 }
721
722 /**
723  * scsi_softirq - Perform post-interrupt processing of finished SCSI commands.
724  *
725  * This is the consumer of the done queue.
726  *
727  * This is called with all interrupts enabled.  This should reduce
728  * interrupt latency, stack depth, and reentrancy of the low-level
729  * drivers.
730  */
731 static void scsi_softirq(struct softirq_action *h)
732 {
733         int disposition;
734         LIST_HEAD(local_q);
735
736         local_irq_disable();
737         list_splice_init(&__get_cpu_var(scsi_done_q), &local_q);
738         local_irq_enable();
739
740         while (!list_empty(&local_q)) {
741                 struct scsi_cmnd *cmd = list_entry(local_q.next,
742                                                    struct scsi_cmnd, eh_entry);
743                 list_del_init(&cmd->eh_entry);
744
745                 disposition = scsi_decide_disposition(cmd);
746                 scsi_log_completion(cmd, disposition);
747                 switch (disposition) {
748                 case SUCCESS:
749                         scsi_finish_command(cmd);
750                         break;
751                 case NEEDS_RETRY:
752                         scsi_retry_command(cmd);
753                         break;
754                 case ADD_TO_MLQUEUE:
755                         scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
756                         break;
757                 default:
758                         if (!scsi_eh_scmd_add(cmd, 0))
759                                 scsi_finish_command(cmd);
760                 }
761         }
762 }
763
764 /*
765  * Function:    scsi_retry_command
766  *
767  * Purpose:     Send a command back to the low level to be retried.
768  *
769  * Notes:       This command is always executed in the context of the
770  *              bottom half handler, or the error handler thread. Low
771  *              level drivers should not become re-entrant as a result of
772  *              this.
773  */
774 int scsi_retry_command(struct scsi_cmnd *cmd)
775 {
776         /*
777          * Restore the SCSI command state.
778          */
779         scsi_setup_cmd_retry(cmd);
780
781         /*
782          * Zero the sense information from the last time we tried
783          * this command.
784          */
785         memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
786
787         return scsi_dispatch_cmd(cmd);
788 }
789
790 /*
791  * Function:    scsi_finish_command
792  *
793  * Purpose:     Pass command off to upper layer for finishing of I/O
794  *              request, waking processes that are waiting on results,
795  *              etc.
796  */
797 void scsi_finish_command(struct scsi_cmnd *cmd)
798 {
799         struct scsi_device *sdev = cmd->device;
800         struct Scsi_Host *shost = sdev->host;
801         struct scsi_request *sreq;
802
803         scsi_device_unbusy(sdev);
804
805         /*
806          * Clear the flags which say that the device/host is no longer
807          * capable of accepting new commands.  These are set in scsi_queue.c
808          * for both the queue full condition on a device, and for a
809          * host full condition on the host.
810          *
811          * XXX(hch): What about locking?
812          */
813         shost->host_blocked = 0;
814         sdev->device_blocked = 0;
815
816         /*
817          * If we have valid sense information, then some kind of recovery
818          * must have taken place.  Make a note of this.
819          */
820         if (SCSI_SENSE_VALID(cmd))
821                 cmd->result |= (DRIVER_SENSE << 24);
822
823         SCSI_LOG_MLCOMPLETE(4, printk("Notifying upper driver of completion "
824                                 "for device %d %x\n", sdev->id, cmd->result));
825
826         cmd->owner = SCSI_OWNER_HIGHLEVEL;
827         cmd->state = SCSI_STATE_FINISHED;
828
829         /*
830          * We can get here with use_sg=0, causing a panic in the upper level
831          */
832         cmd->use_sg = cmd->old_use_sg;
833
834         /*
835          * If there is an associated request structure, copy the data over
836          * before we call the completion function.
837          */
838         sreq = cmd->sc_request;
839         if (sreq) {
840                sreq->sr_result = sreq->sr_command->result;
841                if (sreq->sr_result) {
842                        memcpy(sreq->sr_sense_buffer,
843                               sreq->sr_command->sense_buffer,
844                               sizeof(sreq->sr_sense_buffer));
845                }
846         }
847
848         cmd->done(cmd);
849 }
850
851 /*
852  * Function:    scsi_adjust_queue_depth()
853  *
854  * Purpose:     Allow low level drivers to tell us to change the queue depth
855  *              on a specific SCSI device
856  *
857  * Arguments:   sdev    - SCSI Device in question
858  *              tagged  - Do we use tagged queueing (non-0) or do we treat
859  *                        this device as an untagged device (0)
860  *              tags    - Number of tags allowed if tagged queueing enabled,
861  *                        or number of commands the low level driver can
862  *                        queue up in non-tagged mode (as per cmd_per_lun).
863  *
864  * Returns:     Nothing
865  *
866  * Lock Status: None held on entry
867  *
868  * Notes:       Low level drivers may call this at any time and we will do
869  *              the right thing depending on whether or not the device is
870  *              currently active and whether or not it even has the
871  *              command blocks built yet.
872  *
873  * XXX(hch):    What exactly is device_request_lock trying to protect?
874  */
875 void scsi_adjust_queue_depth(struct scsi_device *sdev, int tagged, int tags)
876 {
877         static spinlock_t device_request_lock = SPIN_LOCK_UNLOCKED;
878         unsigned long flags;
879
880         /*
881          * refuse to set tagged depth to an unworkable size
882          */
883         if (tags <= 0)
884                 return;
885         /*
886          * Limit max queue depth on a single lun to 256 for now.  Remember,
887          * we allocate a struct scsi_command for each of these and keep it
888          * around forever.  Too deep of a depth just wastes memory.
889          */
890         if (tags > 256)
891                 return;
892
893         spin_lock_irqsave(&device_request_lock, flags);
894         sdev->queue_depth = tags;
895         switch (tagged) {
896                 case MSG_ORDERED_TAG:
897                         sdev->ordered_tags = 1;
898                         sdev->simple_tags = 1;
899                         break;
900                 case MSG_SIMPLE_TAG:
901                         sdev->ordered_tags = 0;
902                         sdev->simple_tags = 1;
903                         break;
904                 default:
905                         printk(KERN_WARNING "(scsi%d:%d:%d:%d) "
906                                 "scsi_adjust_queue_depth, bad queue type, "
907                                 "disabled\n", sdev->host->host_no,
908                                 sdev->channel, sdev->id, sdev->lun); 
909                 case 0:
910                         sdev->ordered_tags = sdev->simple_tags = 0;
911                         sdev->queue_depth = tags;
912                         break;
913         }
914         spin_unlock_irqrestore(&device_request_lock, flags);
915 }
916
917 /*
918  * Function:    scsi_track_queue_full()
919  *
920  * Purpose:     This function will track successive QUEUE_FULL events on a
921  *              specific SCSI device to determine if and when there is a
922  *              need to adjust the queue depth on the device.
923  *
924  * Arguments:   sdev    - SCSI Device in question
925  *              depth   - Current number of outstanding SCSI commands on
926  *                        this device, not counting the one returned as
927  *                        QUEUE_FULL.
928  *
929  * Returns:     0 - No change needed
930  *              >0 - Adjust queue depth to this new depth
931  *              -1 - Drop back to untagged operation using host->cmd_per_lun
932  *                      as the untagged command depth
933  *
934  * Lock Status: None held on entry
935  *
936  * Notes:       Low level drivers may call this at any time and we will do
937  *              "The Right Thing."  We are interrupt context safe.
938  */
939 int scsi_track_queue_full(struct scsi_device *sdev, int depth)
940 {
941         if ((jiffies >> 4) == sdev->last_queue_full_time)
942                 return 0;
943
944         sdev->last_queue_full_time = (jiffies >> 4);
945         if (sdev->last_queue_full_depth != depth) {
946                 sdev->last_queue_full_count = 1;
947                 sdev->last_queue_full_depth = depth;
948         } else {
949                 sdev->last_queue_full_count++;
950         }
951
952         if (sdev->last_queue_full_count <= 10)
953                 return 0;
954         if (sdev->last_queue_full_depth < 8) {
955                 /* Drop back to untagged */
956                 scsi_adjust_queue_depth(sdev, 0, sdev->host->cmd_per_lun);
957                 return -1;
958         }
959         
960         if (sdev->ordered_tags)
961                 scsi_adjust_queue_depth(sdev, MSG_ORDERED_TAG, depth);
962         else
963                 scsi_adjust_queue_depth(sdev, MSG_SIMPLE_TAG, depth);
964         return depth;
965 }
966
967 /**
968  * scsi_device_get  -  get an addition reference to a scsi_device
969  * @sdev:       device to get a reference to
970  *
971  * Gets a reference to the scsi_device and increments the use count
972  * of the underlying LLDD module.  You must hold host_lock of the
973  * parent Scsi_Host or already have a reference when calling this.
974  */
975 int scsi_device_get(struct scsi_device *sdev)
976 {
977         if (sdev->sdev_state == SDEV_DEL)
978                 return -ENXIO;
979         if (!get_device(&sdev->sdev_gendev))
980                 return -ENXIO;
981         if (!try_module_get(sdev->host->hostt->module)) {
982                 put_device(&sdev->sdev_gendev);
983                 return -ENXIO;
984         }
985         return 0;
986 }
987 EXPORT_SYMBOL(scsi_device_get);
988
989 /**
990  * scsi_device_put  -  release a reference to a scsi_device
991  * @sdev:       device to release a reference on.
992  *
993  * Release a reference to the scsi_device and decrements the use count
994  * of the underlying LLDD module.  The device is freed once the last
995  * user vanishes.
996  */
997 void scsi_device_put(struct scsi_device *sdev)
998 {
999         module_put(sdev->host->hostt->module);
1000         put_device(&sdev->sdev_gendev);
1001 }
1002 EXPORT_SYMBOL(scsi_device_put);
1003
1004 /* helper for shost_for_each_device, thus not documented */
1005 struct scsi_device *__scsi_iterate_devices(struct Scsi_Host *shost,
1006                                            struct scsi_device *prev)
1007 {
1008         struct list_head *list = (prev ? &prev->siblings : &shost->__devices);
1009         struct scsi_device *next = NULL;
1010         unsigned long flags;
1011
1012         spin_lock_irqsave(shost->host_lock, flags);
1013         while (list->next != &shost->__devices) {
1014                 next = list_entry(list->next, struct scsi_device, siblings);
1015                 /* skip devices that we can't get a reference to */
1016                 if (!scsi_device_get(next))
1017                         break;
1018                 list = list->next;
1019         }
1020         spin_unlock_irqrestore(shost->host_lock, flags);
1021
1022         if (prev)
1023                 scsi_device_put(prev);
1024         return next;
1025 }
1026 EXPORT_SYMBOL(__scsi_iterate_devices);
1027
1028 /**
1029  * scsi_device_lookup - find a device given the host (UNLOCKED)
1030  * @shost:      SCSI host pointer
1031  * @channel:    SCSI channel (zero if only one channel)
1032  * @pun:        SCSI target number (physical unit number)
1033  * @lun:        SCSI Logical Unit Number
1034  *
1035  * Looks up the scsi_device with the specified @channel, @id, @lun for a
1036  * give host. The returned scsi_device does not have an additional reference.
1037  * You must hold the host's host_lock over this call and any access to the
1038  * returned scsi_device.
1039  *
1040  * Note:  The only reason why drivers would want to use this is because
1041  * they're need to access the device list in irq context.  Otherwise you
1042  * really want to use scsi_device_lookup instead.
1043  **/
1044 struct scsi_device *__scsi_device_lookup(struct Scsi_Host *shost,
1045                 uint channel, uint id, uint lun)
1046 {
1047         struct scsi_device *sdev;
1048
1049         list_for_each_entry(sdev, &shost->__devices, siblings) {
1050                 if (sdev->channel == channel && sdev->id == id &&
1051                                 sdev->lun ==lun)
1052                         return sdev;
1053         }
1054
1055         return NULL;
1056 }
1057 EXPORT_SYMBOL(__scsi_device_lookup);
1058
1059 /**
1060  * scsi_device_lookup - find a device given the host
1061  * @shost:      SCSI host pointer
1062  * @channel:    SCSI channel (zero if only one channel)
1063  * @id:         SCSI target number (physical unit number)
1064  * @lun:        SCSI Logical Unit Number
1065  *
1066  * Looks up the scsi_device with the specified @channel, @id, @lun for a
1067  * give host.  The returned scsi_device has an additional reference that
1068  * needs to be release with scsi_host_put once you're done with it.
1069  **/
1070 struct scsi_device *scsi_device_lookup(struct Scsi_Host *shost,
1071                 uint channel, uint id, uint lun)
1072 {
1073         struct scsi_device *sdev;
1074         unsigned long flags;
1075
1076         spin_lock_irqsave(shost->host_lock, flags);
1077         sdev = __scsi_device_lookup(shost, channel, id, lun);
1078         if (sdev && scsi_device_get(sdev))
1079                 sdev = NULL;
1080         spin_unlock_irqrestore(shost->host_lock, flags);
1081
1082         return sdev;
1083 }
1084 EXPORT_SYMBOL(scsi_device_lookup);
1085
1086 /**
1087  * scsi_device_cancel - cancel outstanding IO to this device
1088  * @sdev:       pointer to struct scsi_device
1089  * @data:       pointer to cancel value.
1090  *
1091  **/
1092 int scsi_device_cancel(struct scsi_device *sdev, int recovery)
1093 {
1094         struct scsi_cmnd *scmd;
1095         LIST_HEAD(active_list);
1096         struct list_head *lh, *lh_sf;
1097         unsigned long flags;
1098
1099         sdev->sdev_state = SDEV_CANCEL;
1100
1101         spin_lock_irqsave(&sdev->list_lock, flags);
1102         list_for_each_entry(scmd, &sdev->cmd_list, list) {
1103                 if (scmd->request && scmd->request->rq_status != RQ_INACTIVE) {
1104                         /*
1105                          * If we are unable to remove the timer, it means
1106                          * that the command has already timed out or
1107                          * finished.
1108                          */
1109                         if (!scsi_delete_timer(scmd))
1110                                 continue;
1111                         list_add_tail(&scmd->eh_entry, &active_list);
1112                 }
1113         }
1114         spin_unlock_irqrestore(&sdev->list_lock, flags);
1115
1116         if (!list_empty(&active_list)) {
1117                 list_for_each_safe(lh, lh_sf, &active_list) {
1118                         scmd = list_entry(lh, struct scsi_cmnd, eh_entry);
1119                         list_del_init(lh);
1120                         if (recovery) {
1121                                 scsi_eh_scmd_add(scmd, SCSI_EH_CANCEL_CMD);
1122                         } else {
1123                                 scmd->result = (DID_ABORT << 16);
1124                                 scsi_finish_command(scmd);
1125                         }
1126                 }
1127         }
1128
1129         return 0;
1130 }
1131
1132 MODULE_DESCRIPTION("SCSI core");
1133 MODULE_LICENSE("GPL");
1134
1135 module_param(scsi_logging_level, int, S_IRUGO|S_IWUSR);
1136 MODULE_PARM_DESC(scsi_logging_level, "a bit mask of logging levels");
1137
1138 static int __init init_scsi(void)
1139 {
1140         int error, i;
1141
1142         error = scsi_init_queue();
1143         if (error)
1144                 return error;
1145         error = scsi_init_procfs();
1146         if (error)
1147                 goto cleanup_queue;
1148         error = scsi_init_devinfo();
1149         if (error)
1150                 goto cleanup_procfs;
1151         error = scsi_init_hosts();
1152         if (error)
1153                 goto cleanup_devlist;
1154         error = scsi_init_sysctl();
1155         if (error)
1156                 goto cleanup_hosts;
1157         error = scsi_sysfs_register();
1158         if (error)
1159                 goto cleanup_sysctl;
1160
1161         for (i = 0; i < NR_CPUS; i++)
1162                 INIT_LIST_HEAD(&per_cpu(scsi_done_q, i));
1163
1164         devfs_mk_dir("scsi");
1165         open_softirq(SCSI_SOFTIRQ, scsi_softirq, NULL);
1166         printk(KERN_NOTICE "SCSI subsystem initialized\n");
1167         return 0;
1168
1169 cleanup_sysctl:
1170         scsi_exit_sysctl();
1171 cleanup_hosts:
1172         scsi_exit_hosts();
1173 cleanup_devlist:
1174         scsi_exit_devinfo();
1175 cleanup_procfs:
1176         scsi_exit_procfs();
1177 cleanup_queue:
1178         scsi_exit_queue();
1179         printk(KERN_ERR "SCSI subsystem failed to initialize, error = %d\n",
1180                -error);
1181         return error;
1182 }
1183
1184 static void __exit exit_scsi(void)
1185 {
1186         scsi_sysfs_unregister();
1187         scsi_exit_sysctl();
1188         scsi_exit_hosts();
1189         scsi_exit_devinfo();
1190         devfs_remove("scsi");
1191         scsi_exit_procfs();
1192         scsi_exit_queue();
1193 }
1194
1195 subsys_initcall(init_scsi);
1196 module_exit(exit_scsi);