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