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