linux 2.6.16.38 w/ vs2.0.3-rc1
[linux-2.6.git] / drivers / scsi / ncr53c8xx.c
1 /******************************************************************************
2 **  Device driver for the PCI-SCSI NCR538XX controller family.
3 **
4 **  Copyright (C) 1994  Wolfgang Stanglmeier
5 **
6 **  This program is free software; you can redistribute it and/or modify
7 **  it under the terms of the GNU General Public License as published by
8 **  the Free Software Foundation; either version 2 of the License, or
9 **  (at your option) any later version.
10 **
11 **  This program is distributed in the hope that it will be useful,
12 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 **  GNU General Public License for more details.
15 **
16 **  You should have received a copy of the GNU General Public License
17 **  along with this program; if not, write to the Free Software
18 **  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 **
20 **-----------------------------------------------------------------------------
21 **
22 **  This driver has been ported to Linux from the FreeBSD NCR53C8XX driver
23 **  and is currently maintained by
24 **
25 **          Gerard Roudier              <groudier@free.fr>
26 **
27 **  Being given that this driver originates from the FreeBSD version, and
28 **  in order to keep synergy on both, any suggested enhancements and corrections
29 **  received on Linux are automatically a potential candidate for the FreeBSD 
30 **  version.
31 **
32 **  The original driver has been written for 386bsd and FreeBSD by
33 **          Wolfgang Stanglmeier        <wolf@cologne.de>
34 **          Stefan Esser                <se@mi.Uni-Koeln.de>
35 **
36 **  And has been ported to NetBSD by
37 **          Charles M. Hannum           <mycroft@gnu.ai.mit.edu>
38 **
39 **-----------------------------------------------------------------------------
40 **
41 **                     Brief history
42 **
43 **  December 10 1995 by Gerard Roudier:
44 **     Initial port to Linux.
45 **
46 **  June 23 1996 by Gerard Roudier:
47 **     Support for 64 bits architectures (Alpha).
48 **
49 **  November 30 1996 by Gerard Roudier:
50 **     Support for Fast-20 scsi.
51 **     Support for large DMA fifo and 128 dwords bursting.
52 **
53 **  February 27 1997 by Gerard Roudier:
54 **     Support for Fast-40 scsi.
55 **     Support for on-Board RAM.
56 **
57 **  May 3 1997 by Gerard Roudier:
58 **     Full support for scsi scripts instructions pre-fetching.
59 **
60 **  May 19 1997 by Richard Waltham <dormouse@farsrobt.demon.co.uk>:
61 **     Support for NvRAM detection and reading.
62 **
63 **  August 18 1997 by Cort <cort@cs.nmt.edu>:
64 **     Support for Power/PC (Big Endian).
65 **
66 **  June 20 1998 by Gerard Roudier
67 **     Support for up to 64 tags per lun.
68 **     O(1) everywhere (C and SCRIPTS) for normal cases.
69 **     Low PCI traffic for command handling when on-chip RAM is present.
70 **     Aggressive SCSI SCRIPTS optimizations.
71 **
72 *******************************************************************************
73 */
74
75 /*
76 **      Supported SCSI-II features:
77 **          Synchronous negotiation
78 **          Wide negotiation        (depends on the NCR Chip)
79 **          Enable disconnection
80 **          Tagged command queuing
81 **          Parity checking
82 **          Etc...
83 **
84 **      Supported NCR/SYMBIOS chips:
85 **              53C720          (Wide,   Fast SCSI-2, intfly problems)
86 */
87
88 /* Name and version of the driver */
89 #define SCSI_NCR_DRIVER_NAME    "ncr53c8xx-3.4.3g"
90
91 #define SCSI_NCR_DEBUG_FLAGS    (0)
92
93 /*==========================================================
94 **
95 **      Include files
96 **
97 **==========================================================
98 */
99
100 #include <linux/blkdev.h>
101 #include <linux/delay.h>
102 #include <linux/dma-mapping.h>
103 #include <linux/errno.h>
104 #include <linux/init.h>
105 #include <linux/interrupt.h>
106 #include <linux/ioport.h>
107 #include <linux/mm.h>
108 #include <linux/module.h>
109 #include <linux/sched.h>
110 #include <linux/signal.h>
111 #include <linux/spinlock.h>
112 #include <linux/stat.h>
113 #include <linux/string.h>
114 #include <linux/time.h>
115 #include <linux/timer.h>
116 #include <linux/types.h>
117
118 #include <asm/dma.h>
119 #include <asm/io.h>
120 #include <asm/system.h>
121
122 #include <scsi/scsi.h>
123 #include <scsi/scsi_cmnd.h>
124 #include <scsi/scsi_device.h>
125 #include <scsi/scsi_tcq.h>
126 #include <scsi/scsi_transport.h>
127 #include <scsi/scsi_transport_spi.h>
128
129 #include "ncr53c8xx.h"
130
131 #define NAME53C                 "ncr53c"
132 #define NAME53C8XX              "ncr53c8xx"
133
134
135 /*==========================================================
136 **
137 **      Debugging tags
138 **
139 **==========================================================
140 */
141
142 #define DEBUG_ALLOC    (0x0001)
143 #define DEBUG_PHASE    (0x0002)
144 #define DEBUG_QUEUE    (0x0008)
145 #define DEBUG_RESULT   (0x0010)
146 #define DEBUG_POINTER  (0x0020)
147 #define DEBUG_SCRIPT   (0x0040)
148 #define DEBUG_TINY     (0x0080)
149 #define DEBUG_TIMING   (0x0100)
150 #define DEBUG_NEGO     (0x0200)
151 #define DEBUG_TAGS     (0x0400)
152 #define DEBUG_SCATTER  (0x0800)
153 #define DEBUG_IC        (0x1000)
154
155 /*
156 **    Enable/Disable debug messages.
157 **    Can be changed at runtime too.
158 */
159
160 #ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
161 static int ncr_debug = SCSI_NCR_DEBUG_FLAGS;
162         #define DEBUG_FLAGS ncr_debug
163 #else
164         #define DEBUG_FLAGS     SCSI_NCR_DEBUG_FLAGS
165 #endif
166
167 static inline struct list_head *ncr_list_pop(struct list_head *head)
168 {
169         if (!list_empty(head)) {
170                 struct list_head *elem = head->next;
171
172                 list_del(elem);
173                 return elem;
174         }
175
176         return NULL;
177 }
178
179 /*==========================================================
180 **
181 **      Simple power of two buddy-like allocator.
182 **
183 **      This simple code is not intended to be fast, but to 
184 **      provide power of 2 aligned memory allocations.
185 **      Since the SCRIPTS processor only supplies 8 bit 
186 **      arithmetic, this allocator allows simple and fast 
187 **      address calculations  from the SCRIPTS code.
188 **      In addition, cache line alignment is guaranteed for 
189 **      power of 2 cache line size.
190 **      Enhanced in linux-2.3.44 to provide a memory pool 
191 **      per pcidev to support dynamic dma mapping. (I would 
192 **      have preferred a real bus astraction, btw).
193 **
194 **==========================================================
195 */
196
197 #define MEMO_SHIFT      4       /* 16 bytes minimum memory chunk */
198 #if PAGE_SIZE >= 8192
199 #define MEMO_PAGE_ORDER 0       /* 1 PAGE  maximum */
200 #else
201 #define MEMO_PAGE_ORDER 1       /* 2 PAGES maximum */
202 #endif
203 #define MEMO_FREE_UNUSED        /* Free unused pages immediately */
204 #define MEMO_WARN       1
205 #define MEMO_GFP_FLAGS  GFP_ATOMIC
206 #define MEMO_CLUSTER_SHIFT      (PAGE_SHIFT+MEMO_PAGE_ORDER)
207 #define MEMO_CLUSTER_SIZE       (1UL << MEMO_CLUSTER_SHIFT)
208 #define MEMO_CLUSTER_MASK       (MEMO_CLUSTER_SIZE-1)
209
210 typedef u_long m_addr_t;        /* Enough bits to bit-hack addresses */
211 typedef struct device *m_bush_t;        /* Something that addresses DMAable */
212
213 typedef struct m_link {         /* Link between free memory chunks */
214         struct m_link *next;
215 } m_link_s;
216
217 typedef struct m_vtob {         /* Virtual to Bus address translation */
218         struct m_vtob *next;
219         m_addr_t vaddr;
220         m_addr_t baddr;
221 } m_vtob_s;
222 #define VTOB_HASH_SHIFT         5
223 #define VTOB_HASH_SIZE          (1UL << VTOB_HASH_SHIFT)
224 #define VTOB_HASH_MASK          (VTOB_HASH_SIZE-1)
225 #define VTOB_HASH_CODE(m)       \
226         ((((m_addr_t) (m)) >> MEMO_CLUSTER_SHIFT) & VTOB_HASH_MASK)
227
228 typedef struct m_pool {         /* Memory pool of a given kind */
229         m_bush_t bush;
230         m_addr_t (*getp)(struct m_pool *);
231         void (*freep)(struct m_pool *, m_addr_t);
232         int nump;
233         m_vtob_s *(vtob[VTOB_HASH_SIZE]);
234         struct m_pool *next;
235         struct m_link h[PAGE_SHIFT-MEMO_SHIFT+MEMO_PAGE_ORDER+1];
236 } m_pool_s;
237
238 static void *___m_alloc(m_pool_s *mp, int size)
239 {
240         int i = 0;
241         int s = (1 << MEMO_SHIFT);
242         int j;
243         m_addr_t a;
244         m_link_s *h = mp->h;
245
246         if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
247                 return NULL;
248
249         while (size > s) {
250                 s <<= 1;
251                 ++i;
252         }
253
254         j = i;
255         while (!h[j].next) {
256                 if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
257                         h[j].next = (m_link_s *)mp->getp(mp);
258                         if (h[j].next)
259                                 h[j].next->next = NULL;
260                         break;
261                 }
262                 ++j;
263                 s <<= 1;
264         }
265         a = (m_addr_t) h[j].next;
266         if (a) {
267                 h[j].next = h[j].next->next;
268                 while (j > i) {
269                         j -= 1;
270                         s >>= 1;
271                         h[j].next = (m_link_s *) (a+s);
272                         h[j].next->next = NULL;
273                 }
274         }
275 #ifdef DEBUG
276         printk("___m_alloc(%d) = %p\n", size, (void *) a);
277 #endif
278         return (void *) a;
279 }
280
281 static void ___m_free(m_pool_s *mp, void *ptr, int size)
282 {
283         int i = 0;
284         int s = (1 << MEMO_SHIFT);
285         m_link_s *q;
286         m_addr_t a, b;
287         m_link_s *h = mp->h;
288
289 #ifdef DEBUG
290         printk("___m_free(%p, %d)\n", ptr, size);
291 #endif
292
293         if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
294                 return;
295
296         while (size > s) {
297                 s <<= 1;
298                 ++i;
299         }
300
301         a = (m_addr_t) ptr;
302
303         while (1) {
304 #ifdef MEMO_FREE_UNUSED
305                 if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
306                         mp->freep(mp, a);
307                         break;
308                 }
309 #endif
310                 b = a ^ s;
311                 q = &h[i];
312                 while (q->next && q->next != (m_link_s *) b) {
313                         q = q->next;
314                 }
315                 if (!q->next) {
316                         ((m_link_s *) a)->next = h[i].next;
317                         h[i].next = (m_link_s *) a;
318                         break;
319                 }
320                 q->next = q->next->next;
321                 a = a & b;
322                 s <<= 1;
323                 ++i;
324         }
325 }
326
327 static DEFINE_SPINLOCK(ncr53c8xx_lock);
328
329 static void *__m_calloc2(m_pool_s *mp, int size, char *name, int uflags)
330 {
331         void *p;
332
333         p = ___m_alloc(mp, size);
334
335         if (DEBUG_FLAGS & DEBUG_ALLOC)
336                 printk ("new %-10s[%4d] @%p.\n", name, size, p);
337
338         if (p)
339                 memset(p, 0, size);
340         else if (uflags & MEMO_WARN)
341                 printk (NAME53C8XX ": failed to allocate %s[%d]\n", name, size);
342
343         return p;
344 }
345
346 #define __m_calloc(mp, s, n)    __m_calloc2(mp, s, n, MEMO_WARN)
347
348 static void __m_free(m_pool_s *mp, void *ptr, int size, char *name)
349 {
350         if (DEBUG_FLAGS & DEBUG_ALLOC)
351                 printk ("freeing %-10s[%4d] @%p.\n", name, size, ptr);
352
353         ___m_free(mp, ptr, size);
354
355 }
356
357 /*
358  * With pci bus iommu support, we use a default pool of unmapped memory 
359  * for memory we donnot need to DMA from/to and one pool per pcidev for 
360  * memory accessed by the PCI chip. `mp0' is the default not DMAable pool.
361  */
362
363 static m_addr_t ___mp0_getp(m_pool_s *mp)
364 {
365         m_addr_t m = __get_free_pages(MEMO_GFP_FLAGS, MEMO_PAGE_ORDER);
366         if (m)
367                 ++mp->nump;
368         return m;
369 }
370
371 static void ___mp0_freep(m_pool_s *mp, m_addr_t m)
372 {
373         free_pages(m, MEMO_PAGE_ORDER);
374         --mp->nump;
375 }
376
377 static m_pool_s mp0 = {NULL, ___mp0_getp, ___mp0_freep};
378
379 /*
380  * DMAable pools.
381  */
382
383 /*
384  * With pci bus iommu support, we maintain one pool per pcidev and a 
385  * hashed reverse table for virtual to bus physical address translations.
386  */
387 static m_addr_t ___dma_getp(m_pool_s *mp)
388 {
389         m_addr_t vp;
390         m_vtob_s *vbp;
391
392         vbp = __m_calloc(&mp0, sizeof(*vbp), "VTOB");
393         if (vbp) {
394                 dma_addr_t daddr;
395                 vp = (m_addr_t) dma_alloc_coherent(mp->bush,
396                                                 PAGE_SIZE<<MEMO_PAGE_ORDER,
397                                                 &daddr, GFP_ATOMIC);
398                 if (vp) {
399                         int hc = VTOB_HASH_CODE(vp);
400                         vbp->vaddr = vp;
401                         vbp->baddr = daddr;
402                         vbp->next = mp->vtob[hc];
403                         mp->vtob[hc] = vbp;
404                         ++mp->nump;
405                         return vp;
406                 }
407         }
408         if (vbp)
409                 __m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
410         return 0;
411 }
412
413 static void ___dma_freep(m_pool_s *mp, m_addr_t m)
414 {
415         m_vtob_s **vbpp, *vbp;
416         int hc = VTOB_HASH_CODE(m);
417
418         vbpp = &mp->vtob[hc];
419         while (*vbpp && (*vbpp)->vaddr != m)
420                 vbpp = &(*vbpp)->next;
421         if (*vbpp) {
422                 vbp = *vbpp;
423                 *vbpp = (*vbpp)->next;
424                 dma_free_coherent(mp->bush, PAGE_SIZE<<MEMO_PAGE_ORDER,
425                                   (void *)vbp->vaddr, (dma_addr_t)vbp->baddr);
426                 __m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
427                 --mp->nump;
428         }
429 }
430
431 static inline m_pool_s *___get_dma_pool(m_bush_t bush)
432 {
433         m_pool_s *mp;
434         for (mp = mp0.next; mp && mp->bush != bush; mp = mp->next);
435         return mp;
436 }
437
438 static m_pool_s *___cre_dma_pool(m_bush_t bush)
439 {
440         m_pool_s *mp;
441         mp = __m_calloc(&mp0, sizeof(*mp), "MPOOL");
442         if (mp) {
443                 memset(mp, 0, sizeof(*mp));
444                 mp->bush = bush;
445                 mp->getp = ___dma_getp;
446                 mp->freep = ___dma_freep;
447                 mp->next = mp0.next;
448                 mp0.next = mp;
449         }
450         return mp;
451 }
452
453 static void ___del_dma_pool(m_pool_s *p)
454 {
455         struct m_pool **pp = &mp0.next;
456
457         while (*pp && *pp != p)
458                 pp = &(*pp)->next;
459         if (*pp) {
460                 *pp = (*pp)->next;
461                 __m_free(&mp0, p, sizeof(*p), "MPOOL");
462         }
463 }
464
465 static void *__m_calloc_dma(m_bush_t bush, int size, char *name)
466 {
467         u_long flags;
468         struct m_pool *mp;
469         void *m = NULL;
470
471         spin_lock_irqsave(&ncr53c8xx_lock, flags);
472         mp = ___get_dma_pool(bush);
473         if (!mp)
474                 mp = ___cre_dma_pool(bush);
475         if (mp)
476                 m = __m_calloc(mp, size, name);
477         if (mp && !mp->nump)
478                 ___del_dma_pool(mp);
479         spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
480
481         return m;
482 }
483
484 static void __m_free_dma(m_bush_t bush, void *m, int size, char *name)
485 {
486         u_long flags;
487         struct m_pool *mp;
488
489         spin_lock_irqsave(&ncr53c8xx_lock, flags);
490         mp = ___get_dma_pool(bush);
491         if (mp)
492                 __m_free(mp, m, size, name);
493         if (mp && !mp->nump)
494                 ___del_dma_pool(mp);
495         spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
496 }
497
498 static m_addr_t __vtobus(m_bush_t bush, void *m)
499 {
500         u_long flags;
501         m_pool_s *mp;
502         int hc = VTOB_HASH_CODE(m);
503         m_vtob_s *vp = NULL;
504         m_addr_t a = ((m_addr_t) m) & ~MEMO_CLUSTER_MASK;
505
506         spin_lock_irqsave(&ncr53c8xx_lock, flags);
507         mp = ___get_dma_pool(bush);
508         if (mp) {
509                 vp = mp->vtob[hc];
510                 while (vp && (m_addr_t) vp->vaddr != a)
511                         vp = vp->next;
512         }
513         spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
514         return vp ? vp->baddr + (((m_addr_t) m) - a) : 0;
515 }
516
517 #define _m_calloc_dma(np, s, n)         __m_calloc_dma(np->dev, s, n)
518 #define _m_free_dma(np, p, s, n)        __m_free_dma(np->dev, p, s, n)
519 #define m_calloc_dma(s, n)              _m_calloc_dma(np, s, n)
520 #define m_free_dma(p, s, n)             _m_free_dma(np, p, s, n)
521 #define _vtobus(np, p)                  __vtobus(np->dev, p)
522 #define vtobus(p)                       _vtobus(np, p)
523
524 /*
525  *  Deal with DMA mapping/unmapping.
526  */
527
528 /* To keep track of the dma mapping (sg/single) that has been set */
529 #define __data_mapped   SCp.phase
530 #define __data_mapping  SCp.have_data_in
531
532 static void __unmap_scsi_data(struct device *dev, struct scsi_cmnd *cmd)
533 {
534         switch(cmd->__data_mapped) {
535         case 2:
536                 dma_unmap_sg(dev, cmd->buffer, cmd->use_sg,
537                                 cmd->sc_data_direction);
538                 break;
539         case 1:
540                 dma_unmap_single(dev, cmd->__data_mapping,
541                                  cmd->request_bufflen,
542                                  cmd->sc_data_direction);
543                 break;
544         }
545         cmd->__data_mapped = 0;
546 }
547
548 static u_long __map_scsi_single_data(struct device *dev, struct scsi_cmnd *cmd)
549 {
550         dma_addr_t mapping;
551
552         if (cmd->request_bufflen == 0)
553                 return 0;
554
555         mapping = dma_map_single(dev, cmd->request_buffer,
556                                  cmd->request_bufflen,
557                                  cmd->sc_data_direction);
558         cmd->__data_mapped = 1;
559         cmd->__data_mapping = mapping;
560
561         return mapping;
562 }
563
564 static int __map_scsi_sg_data(struct device *dev, struct scsi_cmnd *cmd)
565 {
566         int use_sg;
567
568         if (cmd->use_sg == 0)
569                 return 0;
570
571         use_sg = dma_map_sg(dev, cmd->buffer, cmd->use_sg,
572                         cmd->sc_data_direction);
573         cmd->__data_mapped = 2;
574         cmd->__data_mapping = use_sg;
575
576         return use_sg;
577 }
578
579 #define unmap_scsi_data(np, cmd)        __unmap_scsi_data(np->dev, cmd)
580 #define map_scsi_single_data(np, cmd)   __map_scsi_single_data(np->dev, cmd)
581 #define map_scsi_sg_data(np, cmd)       __map_scsi_sg_data(np->dev, cmd)
582
583 /*==========================================================
584 **
585 **      Driver setup.
586 **
587 **      This structure is initialized from linux config 
588 **      options. It can be overridden at boot-up by the boot 
589 **      command line.
590 **
591 **==========================================================
592 */
593 static struct ncr_driver_setup
594         driver_setup                    = SCSI_NCR_DRIVER_SETUP;
595
596 #ifdef  SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
597 static struct ncr_driver_setup
598         driver_safe_setup __initdata    = SCSI_NCR_DRIVER_SAFE_SETUP;
599 #endif
600
601 #define initverbose (driver_setup.verbose)
602 #define bootverbose (np->verbose)
603
604
605 /*===================================================================
606 **
607 **      Driver setup from the boot command line
608 **
609 **===================================================================
610 */
611
612 #ifdef MODULE
613 #define ARG_SEP ' '
614 #else
615 #define ARG_SEP ','
616 #endif
617
618 #define OPT_TAGS                1
619 #define OPT_MASTER_PARITY       2
620 #define OPT_SCSI_PARITY         3
621 #define OPT_DISCONNECTION       4
622 #define OPT_SPECIAL_FEATURES    5
623 #define OPT_UNUSED_1            6
624 #define OPT_FORCE_SYNC_NEGO     7
625 #define OPT_REVERSE_PROBE       8
626 #define OPT_DEFAULT_SYNC        9
627 #define OPT_VERBOSE             10
628 #define OPT_DEBUG               11
629 #define OPT_BURST_MAX           12
630 #define OPT_LED_PIN             13
631 #define OPT_MAX_WIDE            14
632 #define OPT_SETTLE_DELAY        15
633 #define OPT_DIFF_SUPPORT        16
634 #define OPT_IRQM                17
635 #define OPT_PCI_FIX_UP          18
636 #define OPT_BUS_CHECK           19
637 #define OPT_OPTIMIZE            20
638 #define OPT_RECOVERY            21
639 #define OPT_SAFE_SETUP          22
640 #define OPT_USE_NVRAM           23
641 #define OPT_EXCLUDE             24
642 #define OPT_HOST_ID             25
643
644 #ifdef SCSI_NCR_IARB_SUPPORT
645 #define OPT_IARB                26
646 #endif
647
648 static char setup_token[] __initdata = 
649         "tags:"   "mpar:"
650         "spar:"   "disc:"
651         "specf:"  "ultra:"
652         "fsn:"    "revprob:"
653         "sync:"   "verb:"
654         "debug:"  "burst:"
655         "led:"    "wide:"
656         "settle:" "diff:"
657         "irqm:"   "pcifix:"
658         "buschk:" "optim:"
659         "recovery:"
660         "safe:"   "nvram:"
661         "excl:"   "hostid:"
662 #ifdef SCSI_NCR_IARB_SUPPORT
663         "iarb:"
664 #endif
665         ;       /* DONNOT REMOVE THIS ';' */
666
667 #ifdef MODULE
668 #define ARG_SEP ' '
669 #else
670 #define ARG_SEP ','
671 #endif
672
673 static int __init get_setup_token(char *p)
674 {
675         char *cur = setup_token;
676         char *pc;
677         int i = 0;
678
679         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
680                 ++pc;
681                 ++i;
682                 if (!strncmp(p, cur, pc - cur))
683                         return i;
684                 cur = pc;
685         }
686         return 0;
687 }
688
689
690 static int __init sym53c8xx__setup(char *str)
691 {
692 #ifdef SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
693         char *cur = str;
694         char *pc, *pv;
695         int i, val, c;
696         int xi = 0;
697
698         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
699                 char *pe;
700
701                 val = 0;
702                 pv = pc;
703                 c = *++pv;
704
705                 if      (c == 'n')
706                         val = 0;
707                 else if (c == 'y')
708                         val = 1;
709                 else
710                         val = (int) simple_strtoul(pv, &pe, 0);
711
712                 switch (get_setup_token(cur)) {
713                 case OPT_TAGS:
714                         driver_setup.default_tags = val;
715                         if (pe && *pe == '/') {
716                                 i = 0;
717                                 while (*pe && *pe != ARG_SEP && 
718                                         i < sizeof(driver_setup.tag_ctrl)-1) {
719                                         driver_setup.tag_ctrl[i++] = *pe++;
720                                 }
721                                 driver_setup.tag_ctrl[i] = '\0';
722                         }
723                         break;
724                 case OPT_MASTER_PARITY:
725                         driver_setup.master_parity = val;
726                         break;
727                 case OPT_SCSI_PARITY:
728                         driver_setup.scsi_parity = val;
729                         break;
730                 case OPT_DISCONNECTION:
731                         driver_setup.disconnection = val;
732                         break;
733                 case OPT_SPECIAL_FEATURES:
734                         driver_setup.special_features = val;
735                         break;
736                 case OPT_FORCE_SYNC_NEGO:
737                         driver_setup.force_sync_nego = val;
738                         break;
739                 case OPT_REVERSE_PROBE:
740                         driver_setup.reverse_probe = val;
741                         break;
742                 case OPT_DEFAULT_SYNC:
743                         driver_setup.default_sync = val;
744                         break;
745                 case OPT_VERBOSE:
746                         driver_setup.verbose = val;
747                         break;
748                 case OPT_DEBUG:
749                         driver_setup.debug = val;
750                         break;
751                 case OPT_BURST_MAX:
752                         driver_setup.burst_max = val;
753                         break;
754                 case OPT_LED_PIN:
755                         driver_setup.led_pin = val;
756                         break;
757                 case OPT_MAX_WIDE:
758                         driver_setup.max_wide = val? 1:0;
759                         break;
760                 case OPT_SETTLE_DELAY:
761                         driver_setup.settle_delay = val;
762                         break;
763                 case OPT_DIFF_SUPPORT:
764                         driver_setup.diff_support = val;
765                         break;
766                 case OPT_IRQM:
767                         driver_setup.irqm = val;
768                         break;
769                 case OPT_PCI_FIX_UP:
770                         driver_setup.pci_fix_up = val;
771                         break;
772                 case OPT_BUS_CHECK:
773                         driver_setup.bus_check = val;
774                         break;
775                 case OPT_OPTIMIZE:
776                         driver_setup.optimize = val;
777                         break;
778                 case OPT_RECOVERY:
779                         driver_setup.recovery = val;
780                         break;
781                 case OPT_USE_NVRAM:
782                         driver_setup.use_nvram = val;
783                         break;
784                 case OPT_SAFE_SETUP:
785                         memcpy(&driver_setup, &driver_safe_setup,
786                                 sizeof(driver_setup));
787                         break;
788                 case OPT_EXCLUDE:
789                         if (xi < SCSI_NCR_MAX_EXCLUDES)
790                                 driver_setup.excludes[xi++] = val;
791                         break;
792                 case OPT_HOST_ID:
793                         driver_setup.host_id = val;
794                         break;
795 #ifdef SCSI_NCR_IARB_SUPPORT
796                 case OPT_IARB:
797                         driver_setup.iarb = val;
798                         break;
799 #endif
800                 default:
801                         printk("sym53c8xx_setup: unexpected boot option '%.*s' ignored\n", (int)(pc-cur+1), cur);
802                         break;
803                 }
804
805                 if ((cur = strchr(cur, ARG_SEP)) != NULL)
806                         ++cur;
807         }
808 #endif /* SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT */
809         return 1;
810 }
811
812 /*===================================================================
813 **
814 **      Get device queue depth from boot command line.
815 **
816 **===================================================================
817 */
818 #define DEF_DEPTH       (driver_setup.default_tags)
819 #define ALL_TARGETS     -2
820 #define NO_TARGET       -1
821 #define ALL_LUNS        -2
822 #define NO_LUN          -1
823
824 static int device_queue_depth(int unit, int target, int lun)
825 {
826         int c, h, t, u, v;
827         char *p = driver_setup.tag_ctrl;
828         char *ep;
829
830         h = -1;
831         t = NO_TARGET;
832         u = NO_LUN;
833         while ((c = *p++) != 0) {
834                 v = simple_strtoul(p, &ep, 0);
835                 switch(c) {
836                 case '/':
837                         ++h;
838                         t = ALL_TARGETS;
839                         u = ALL_LUNS;
840                         break;
841                 case 't':
842                         if (t != target)
843                                 t = (target == v) ? v : NO_TARGET;
844                         u = ALL_LUNS;
845                         break;
846                 case 'u':
847                         if (u != lun)
848                                 u = (lun == v) ? v : NO_LUN;
849                         break;
850                 case 'q':
851                         if (h == unit &&
852                                 (t == ALL_TARGETS || t == target) &&
853                                 (u == ALL_LUNS    || u == lun))
854                                 return v;
855                         break;
856                 case '-':
857                         t = ALL_TARGETS;
858                         u = ALL_LUNS;
859                         break;
860                 default:
861                         break;
862                 }
863                 p = ep;
864         }
865         return DEF_DEPTH;
866 }
867
868
869 /*==========================================================
870 **
871 **      The CCB done queue uses an array of CCB virtual 
872 **      addresses. Empty entries are flagged using the bogus 
873 **      virtual address 0xffffffff.
874 **
875 **      Since PCI ensures that only aligned DWORDs are accessed 
876 **      atomically, 64 bit little-endian architecture requires 
877 **      to test the high order DWORD of the entry to determine 
878 **      if it is empty or valid.
879 **
880 **      BTW, I will make things differently as soon as I will 
881 **      have a better idea, but this is simple and should work.
882 **
883 **==========================================================
884 */
885  
886 #define SCSI_NCR_CCB_DONE_SUPPORT
887 #ifdef  SCSI_NCR_CCB_DONE_SUPPORT
888
889 #define MAX_DONE 24
890 #define CCB_DONE_EMPTY 0xffffffffUL
891
892 /* All 32 bit architectures */
893 #if BITS_PER_LONG == 32
894 #define CCB_DONE_VALID(cp)  (((u_long) cp) != CCB_DONE_EMPTY)
895
896 /* All > 32 bit (64 bit) architectures regardless endian-ness */
897 #else
898 #define CCB_DONE_VALID(cp)  \
899         ((((u_long) cp) & 0xffffffff00000000ul) &&      \
900          (((u_long) cp) & 0xfffffffful) != CCB_DONE_EMPTY)
901 #endif
902
903 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
904
905 /*==========================================================
906 **
907 **      Configuration and Debugging
908 **
909 **==========================================================
910 */
911
912 /*
913 **    SCSI address of this device.
914 **    The boot routines should have set it.
915 **    If not, use this.
916 */
917
918 #ifndef SCSI_NCR_MYADDR
919 #define SCSI_NCR_MYADDR      (7)
920 #endif
921
922 /*
923 **    The maximum number of tags per logic unit.
924 **    Used only for disk devices that support tags.
925 */
926
927 #ifndef SCSI_NCR_MAX_TAGS
928 #define SCSI_NCR_MAX_TAGS    (8)
929 #endif
930
931 /*
932 **    TAGS are actually limited to 64 tags/lun.
933 **    We need to deal with power of 2, for alignment constraints.
934 */
935 #if     SCSI_NCR_MAX_TAGS > 64
936 #define MAX_TAGS (64)
937 #else
938 #define MAX_TAGS SCSI_NCR_MAX_TAGS
939 #endif
940
941 #define NO_TAG  (255)
942
943 /*
944 **      Choose appropriate type for tag bitmap.
945 */
946 #if     MAX_TAGS > 32
947 typedef u64 tagmap_t;
948 #else
949 typedef u32 tagmap_t;
950 #endif
951
952 /*
953 **    Number of targets supported by the driver.
954 **    n permits target numbers 0..n-1.
955 **    Default is 16, meaning targets #0..#15.
956 **    #7 .. is myself.
957 */
958
959 #ifdef SCSI_NCR_MAX_TARGET
960 #define MAX_TARGET  (SCSI_NCR_MAX_TARGET)
961 #else
962 #define MAX_TARGET  (16)
963 #endif
964
965 /*
966 **    Number of logic units supported by the driver.
967 **    n enables logic unit numbers 0..n-1.
968 **    The common SCSI devices require only
969 **    one lun, so take 1 as the default.
970 */
971
972 #ifdef SCSI_NCR_MAX_LUN
973 #define MAX_LUN    SCSI_NCR_MAX_LUN
974 #else
975 #define MAX_LUN    (1)
976 #endif
977
978 /*
979 **    Asynchronous pre-scaler (ns). Shall be 40
980 */
981  
982 #ifndef SCSI_NCR_MIN_ASYNC
983 #define SCSI_NCR_MIN_ASYNC (40)
984 #endif
985
986 /*
987 **    The maximum number of jobs scheduled for starting.
988 **    There should be one slot per target, and one slot
989 **    for each tag of each target in use.
990 **    The calculation below is actually quite silly ...
991 */
992
993 #ifdef SCSI_NCR_CAN_QUEUE
994 #define MAX_START   (SCSI_NCR_CAN_QUEUE + 4)
995 #else
996 #define MAX_START   (MAX_TARGET + 7 * MAX_TAGS)
997 #endif
998
999 /*
1000 **   We limit the max number of pending IO to 250.
1001 **   since we donnot want to allocate more than 1 
1002 **   PAGE for 'scripth'.
1003 */
1004 #if     MAX_START > 250
1005 #undef  MAX_START
1006 #define MAX_START 250
1007 #endif
1008
1009 /*
1010 **    The maximum number of segments a transfer is split into.
1011 **    We support up to 127 segments for both read and write.
1012 **    The data scripts are broken into 2 sub-scripts.
1013 **    80 (MAX_SCATTERL) segments are moved from a sub-script
1014 **    in on-chip RAM. This makes data transfers shorter than 
1015 **    80k (assuming 1k fs) as fast as possible.
1016 */
1017
1018 #define MAX_SCATTER (SCSI_NCR_MAX_SCATTER)
1019
1020 #if (MAX_SCATTER > 80)
1021 #define MAX_SCATTERL    80
1022 #define MAX_SCATTERH    (MAX_SCATTER - MAX_SCATTERL)
1023 #else
1024 #define MAX_SCATTERL    (MAX_SCATTER-1)
1025 #define MAX_SCATTERH    1
1026 #endif
1027
1028 /*
1029 **      other
1030 */
1031
1032 #define NCR_SNOOP_TIMEOUT (1000000)
1033
1034 /*
1035 **      Other definitions
1036 */
1037
1038 #define ScsiResult(host_code, scsi_code) (((host_code) << 16) + ((scsi_code) & 0x7f))
1039
1040 #define initverbose (driver_setup.verbose)
1041 #define bootverbose (np->verbose)
1042
1043 /*==========================================================
1044 **
1045 **      Command control block states.
1046 **
1047 **==========================================================
1048 */
1049
1050 #define HS_IDLE         (0)
1051 #define HS_BUSY         (1)
1052 #define HS_NEGOTIATE    (2)     /* sync/wide data transfer*/
1053 #define HS_DISCONNECT   (3)     /* Disconnected by target */
1054
1055 #define HS_DONEMASK     (0x80)
1056 #define HS_COMPLETE     (4|HS_DONEMASK)
1057 #define HS_SEL_TIMEOUT  (5|HS_DONEMASK) /* Selection timeout      */
1058 #define HS_RESET        (6|HS_DONEMASK) /* SCSI reset             */
1059 #define HS_ABORTED      (7|HS_DONEMASK) /* Transfer aborted       */
1060 #define HS_TIMEOUT      (8|HS_DONEMASK) /* Software timeout       */
1061 #define HS_FAIL         (9|HS_DONEMASK) /* SCSI or PCI bus errors */
1062 #define HS_UNEXPECTED   (10|HS_DONEMASK)/* Unexpected disconnect  */
1063
1064 /*
1065 **      Invalid host status values used by the SCRIPTS processor 
1066 **      when the nexus is not fully identified.
1067 **      Shall never appear in a CCB.
1068 */
1069
1070 #define HS_INVALMASK    (0x40)
1071 #define HS_SELECTING    (0|HS_INVALMASK)
1072 #define HS_IN_RESELECT  (1|HS_INVALMASK)
1073 #define HS_STARTING     (2|HS_INVALMASK)
1074
1075 /*
1076 **      Flags set by the SCRIPT processor for commands 
1077 **      that have been skipped.
1078 */
1079 #define HS_SKIPMASK     (0x20)
1080
1081 /*==========================================================
1082 **
1083 **      Software Interrupt Codes
1084 **
1085 **==========================================================
1086 */
1087
1088 #define SIR_BAD_STATUS          (1)
1089 #define SIR_XXXXXXXXXX          (2)
1090 #define SIR_NEGO_SYNC           (3)
1091 #define SIR_NEGO_WIDE           (4)
1092 #define SIR_NEGO_FAILED         (5)
1093 #define SIR_NEGO_PROTO          (6)
1094 #define SIR_REJECT_RECEIVED     (7)
1095 #define SIR_REJECT_SENT         (8)
1096 #define SIR_IGN_RESIDUE         (9)
1097 #define SIR_MISSING_SAVE        (10)
1098 #define SIR_RESEL_NO_MSG_IN     (11)
1099 #define SIR_RESEL_NO_IDENTIFY   (12)
1100 #define SIR_RESEL_BAD_LUN       (13)
1101 #define SIR_RESEL_BAD_TARGET    (14)
1102 #define SIR_RESEL_BAD_I_T_L     (15)
1103 #define SIR_RESEL_BAD_I_T_L_Q   (16)
1104 #define SIR_DONE_OVERFLOW       (17)
1105 #define SIR_INTFLY              (18)
1106 #define SIR_MAX                 (18)
1107
1108 /*==========================================================
1109 **
1110 **      Extended error codes.
1111 **      xerr_status field of struct ccb.
1112 **
1113 **==========================================================
1114 */
1115
1116 #define XE_OK           (0)
1117 #define XE_EXTRA_DATA   (1)     /* unexpected data phase */
1118 #define XE_BAD_PHASE    (2)     /* illegal phase (4/5)   */
1119
1120 /*==========================================================
1121 **
1122 **      Negotiation status.
1123 **      nego_status field       of struct ccb.
1124 **
1125 **==========================================================
1126 */
1127
1128 #define NS_NOCHANGE     (0)
1129 #define NS_SYNC         (1)
1130 #define NS_WIDE         (2)
1131 #define NS_PPR          (4)
1132
1133 /*==========================================================
1134 **
1135 **      Misc.
1136 **
1137 **==========================================================
1138 */
1139
1140 #define CCB_MAGIC       (0xf2691ad2)
1141
1142 /*==========================================================
1143 **
1144 **      Declaration of structs.
1145 **
1146 **==========================================================
1147 */
1148
1149 static struct scsi_transport_template *ncr53c8xx_transport_template = NULL;
1150
1151 struct tcb;
1152 struct lcb;
1153 struct ccb;
1154 struct ncb;
1155 struct script;
1156
1157 struct link {
1158         ncrcmd  l_cmd;
1159         ncrcmd  l_paddr;
1160 };
1161
1162 struct  usrcmd {
1163         u_long  target;
1164         u_long  lun;
1165         u_long  data;
1166         u_long  cmd;
1167 };
1168
1169 #define UC_SETSYNC      10
1170 #define UC_SETTAGS      11
1171 #define UC_SETDEBUG     12
1172 #define UC_SETORDER     13
1173 #define UC_SETWIDE      14
1174 #define UC_SETFLAG      15
1175 #define UC_SETVERBOSE   17
1176
1177 #define UF_TRACE        (0x01)
1178 #define UF_NODISC       (0x02)
1179 #define UF_NOSCAN       (0x04)
1180
1181 /*========================================================================
1182 **
1183 **      Declaration of structs:         target control block
1184 **
1185 **========================================================================
1186 */
1187 struct tcb {
1188         /*----------------------------------------------------------------
1189         **      During reselection the ncr jumps to this point with SFBR 
1190         **      set to the encoded target number with bit 7 set.
1191         **      if it's not this target, jump to the next.
1192         **
1193         **      JUMP  IF (SFBR != #target#), @(next tcb)
1194         **----------------------------------------------------------------
1195         */
1196         struct link   jump_tcb;
1197
1198         /*----------------------------------------------------------------
1199         **      Load the actual values for the sxfer and the scntl3
1200         **      register (sync/wide mode).
1201         **
1202         **      SCR_COPY (1), @(sval field of this tcb), @(sxfer  register)
1203         **      SCR_COPY (1), @(wval field of this tcb), @(scntl3 register)
1204         **----------------------------------------------------------------
1205         */
1206         ncrcmd  getscr[6];
1207
1208         /*----------------------------------------------------------------
1209         **      Get the IDENTIFY message and load the LUN to SFBR.
1210         **
1211         **      CALL, <RESEL_LUN>
1212         **----------------------------------------------------------------
1213         */
1214         struct link   call_lun;
1215
1216         /*----------------------------------------------------------------
1217         **      Now look for the right lun.
1218         **
1219         **      For i = 0 to 3
1220         **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(first lcb mod. i)
1221         **
1222         **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
1223         **      It is kind of hashcoding.
1224         **----------------------------------------------------------------
1225         */
1226         struct link     jump_lcb[4];    /* JUMPs for reselection        */
1227         struct lcb *    lp[MAX_LUN];    /* The lcb's of this tcb        */
1228
1229         /*----------------------------------------------------------------
1230         **      Pointer to the ccb used for negotiation.
1231         **      Prevent from starting a negotiation for all queued commands 
1232         **      when tagged command queuing is enabled.
1233         **----------------------------------------------------------------
1234         */
1235         struct ccb *   nego_cp;
1236
1237         /*----------------------------------------------------------------
1238         **      statistical data
1239         **----------------------------------------------------------------
1240         */
1241         u_long  transfers;
1242         u_long  bytes;
1243
1244         /*----------------------------------------------------------------
1245         **      negotiation of wide and synch transfer and device quirks.
1246         **----------------------------------------------------------------
1247         */
1248 #ifdef SCSI_NCR_BIG_ENDIAN
1249 /*0*/   u16     period;
1250 /*2*/   u_char  sval;
1251 /*3*/   u_char  minsync;
1252 /*0*/   u_char  wval;
1253 /*1*/   u_char  widedone;
1254 /*2*/   u_char  quirks;
1255 /*3*/   u_char  maxoffs;
1256 #else
1257 /*0*/   u_char  minsync;
1258 /*1*/   u_char  sval;
1259 /*2*/   u16     period;
1260 /*0*/   u_char  maxoffs;
1261 /*1*/   u_char  quirks;
1262 /*2*/   u_char  widedone;
1263 /*3*/   u_char  wval;
1264 #endif
1265
1266         /* User settable limits and options.  */
1267         u_char  usrsync;
1268         u_char  usrwide;
1269         u_char  usrtags;
1270         u_char  usrflag;
1271         struct scsi_target *starget;
1272 };
1273
1274 /*========================================================================
1275 **
1276 **      Declaration of structs:         lun control block
1277 **
1278 **========================================================================
1279 */
1280 struct lcb {
1281         /*----------------------------------------------------------------
1282         **      During reselection the ncr jumps to this point
1283         **      with SFBR set to the "Identify" message.
1284         **      if it's not this lun, jump to the next.
1285         **
1286         **      JUMP  IF (SFBR != #lun#), @(next lcb of this target)
1287         **
1288         **      It is this lun. Load TEMP with the nexus jumps table 
1289         **      address and jump to RESEL_TAG (or RESEL_NOTAG).
1290         **
1291         **              SCR_COPY (4), p_jump_ccb, TEMP,
1292         **              SCR_JUMP, <RESEL_TAG>
1293         **----------------------------------------------------------------
1294         */
1295         struct link     jump_lcb;
1296         ncrcmd          load_jump_ccb[3];
1297         struct link     jump_tag;
1298         ncrcmd          p_jump_ccb;     /* Jump table bus address       */
1299
1300         /*----------------------------------------------------------------
1301         **      Jump table used by the script processor to directly jump 
1302         **      to the CCB corresponding to the reselected nexus.
1303         **      Address is allocated on 256 bytes boundary in order to 
1304         **      allow 8 bit calculation of the tag jump entry for up to 
1305         **      64 possible tags.
1306         **----------------------------------------------------------------
1307         */
1308         u32             jump_ccb_0;     /* Default table if no tags     */
1309         u32             *jump_ccb;      /* Virtual address              */
1310
1311         /*----------------------------------------------------------------
1312         **      CCB queue management.
1313         **----------------------------------------------------------------
1314         */
1315         struct list_head free_ccbq;     /* Queue of available CCBs      */
1316         struct list_head busy_ccbq;     /* Queue of busy CCBs           */
1317         struct list_head wait_ccbq;     /* Queue of waiting for IO CCBs */
1318         struct list_head skip_ccbq;     /* Queue of skipped CCBs        */
1319         u_char          actccbs;        /* Number of allocated CCBs     */
1320         u_char          busyccbs;       /* CCBs busy for this lun       */
1321         u_char          queuedccbs;     /* CCBs queued to the controller*/
1322         u_char          queuedepth;     /* Queue depth for this lun     */
1323         u_char          scdev_depth;    /* SCSI device queue depth      */
1324         u_char          maxnxs;         /* Max possible nexuses         */
1325
1326         /*----------------------------------------------------------------
1327         **      Control of tagged command queuing.
1328         **      Tags allocation is performed using a circular buffer.
1329         **      This avoids using a loop for tag allocation.
1330         **----------------------------------------------------------------
1331         */
1332         u_char          ia_tag;         /* Allocation index             */
1333         u_char          if_tag;         /* Freeing index                */
1334         u_char cb_tags[MAX_TAGS];       /* Circular tags buffer */
1335         u_char          usetags;        /* Command queuing is active    */
1336         u_char          maxtags;        /* Max nr of tags asked by user */
1337         u_char          numtags;        /* Current number of tags       */
1338
1339         /*----------------------------------------------------------------
1340         **      QUEUE FULL control and ORDERED tag control.
1341         **----------------------------------------------------------------
1342         */
1343         /*----------------------------------------------------------------
1344         **      QUEUE FULL and ORDERED tag control.
1345         **----------------------------------------------------------------
1346         */
1347         u16             num_good;       /* Nr of GOOD since QUEUE FULL  */
1348         tagmap_t        tags_umap;      /* Used tags bitmap             */
1349         tagmap_t        tags_smap;      /* Tags in use at 'tag_stime'   */
1350         u_long          tags_stime;     /* Last time we set smap=umap   */
1351         struct ccb *    held_ccb;       /* CCB held for QUEUE FULL      */
1352 };
1353
1354 /*========================================================================
1355 **
1356 **      Declaration of structs:     the launch script.
1357 **
1358 **========================================================================
1359 **
1360 **      It is part of the CCB and is called by the scripts processor to 
1361 **      start or restart the data structure (nexus).
1362 **      This 6 DWORDs mini script makes use of prefetching.
1363 **
1364 **------------------------------------------------------------------------
1365 */
1366 struct launch {
1367         /*----------------------------------------------------------------
1368         **      SCR_COPY(4),    @(p_phys), @(dsa register)
1369         **      SCR_JUMP,       @(scheduler_point)
1370         **----------------------------------------------------------------
1371         */
1372         ncrcmd          setup_dsa[3];   /* Copy 'phys' address to dsa   */
1373         struct link     schedule;       /* Jump to scheduler point      */
1374         ncrcmd          p_phys;         /* 'phys' header bus address    */
1375 };
1376
1377 /*========================================================================
1378 **
1379 **      Declaration of structs:     global HEADER.
1380 **
1381 **========================================================================
1382 **
1383 **      This substructure is copied from the ccb to a global address after 
1384 **      selection (or reselection) and copied back before disconnect.
1385 **
1386 **      These fields are accessible to the script processor.
1387 **
1388 **------------------------------------------------------------------------
1389 */
1390
1391 struct head {
1392         /*----------------------------------------------------------------
1393         **      Saved data pointer.
1394         **      Points to the position in the script responsible for the
1395         **      actual transfer transfer of data.
1396         **      It's written after reception of a SAVE_DATA_POINTER message.
1397         **      The goalpointer points after the last transfer command.
1398         **----------------------------------------------------------------
1399         */
1400         u32             savep;
1401         u32             lastp;
1402         u32             goalp;
1403
1404         /*----------------------------------------------------------------
1405         **      Alternate data pointer.
1406         **      They are copied back to savep/lastp/goalp by the SCRIPTS 
1407         **      when the direction is unknown and the device claims data out.
1408         **----------------------------------------------------------------
1409         */
1410         u32             wlastp;
1411         u32             wgoalp;
1412
1413         /*----------------------------------------------------------------
1414         **      The virtual address of the ccb containing this header.
1415         **----------------------------------------------------------------
1416         */
1417         struct ccb *    cp;
1418
1419         /*----------------------------------------------------------------
1420         **      Status fields.
1421         **----------------------------------------------------------------
1422         */
1423         u_char          scr_st[4];      /* script status                */
1424         u_char          status[4];      /* host status. must be the     */
1425                                         /*  last DWORD of the header.   */
1426 };
1427
1428 /*
1429 **      The status bytes are used by the host and the script processor.
1430 **
1431 **      The byte corresponding to the host_status must be stored in the 
1432 **      last DWORD of the CCB header since it is used for command 
1433 **      completion (ncr_wakeup()). Doing so, we are sure that the header 
1434 **      has been entirely copied back to the CCB when the host_status is 
1435 **      seen complete by the CPU.
1436 **
1437 **      The last four bytes (status[4]) are copied to the scratchb register
1438 **      (declared as scr0..scr3 in ncr_reg.h) just after the select/reselect,
1439 **      and copied back just after disconnecting.
1440 **      Inside the script the XX_REG are used.
1441 **
1442 **      The first four bytes (scr_st[4]) are used inside the script by 
1443 **      "COPY" commands.
1444 **      Because source and destination must have the same alignment
1445 **      in a DWORD, the fields HAVE to be at the choosen offsets.
1446 **              xerr_st         0       (0x34)  scratcha
1447 **              sync_st         1       (0x05)  sxfer
1448 **              wide_st         3       (0x03)  scntl3
1449 */
1450
1451 /*
1452 **      Last four bytes (script)
1453 */
1454 #define  QU_REG scr0
1455 #define  HS_REG scr1
1456 #define  HS_PRT nc_scr1
1457 #define  SS_REG scr2
1458 #define  SS_PRT nc_scr2
1459 #define  PS_REG scr3
1460
1461 /*
1462 **      Last four bytes (host)
1463 */
1464 #ifdef SCSI_NCR_BIG_ENDIAN
1465 #define  actualquirks  phys.header.status[3]
1466 #define  host_status   phys.header.status[2]
1467 #define  scsi_status   phys.header.status[1]
1468 #define  parity_status phys.header.status[0]
1469 #else
1470 #define  actualquirks  phys.header.status[0]
1471 #define  host_status   phys.header.status[1]
1472 #define  scsi_status   phys.header.status[2]
1473 #define  parity_status phys.header.status[3]
1474 #endif
1475
1476 /*
1477 **      First four bytes (script)
1478 */
1479 #define  xerr_st       header.scr_st[0]
1480 #define  sync_st       header.scr_st[1]
1481 #define  nego_st       header.scr_st[2]
1482 #define  wide_st       header.scr_st[3]
1483
1484 /*
1485 **      First four bytes (host)
1486 */
1487 #define  xerr_status   phys.xerr_st
1488 #define  nego_status   phys.nego_st
1489
1490 #if 0
1491 #define  sync_status   phys.sync_st
1492 #define  wide_status   phys.wide_st
1493 #endif
1494
1495 /*==========================================================
1496 **
1497 **      Declaration of structs:     Data structure block
1498 **
1499 **==========================================================
1500 **
1501 **      During execution of a ccb by the script processor,
1502 **      the DSA (data structure address) register points
1503 **      to this substructure of the ccb.
1504 **      This substructure contains the header with
1505 **      the script-processor-changable data and
1506 **      data blocks for the indirect move commands.
1507 **
1508 **----------------------------------------------------------
1509 */
1510
1511 struct dsb {
1512
1513         /*
1514         **      Header.
1515         */
1516
1517         struct head     header;
1518
1519         /*
1520         **      Table data for Script
1521         */
1522
1523         struct scr_tblsel  select;
1524         struct scr_tblmove smsg  ;
1525         struct scr_tblmove cmd   ;
1526         struct scr_tblmove sense ;
1527         struct scr_tblmove data[MAX_SCATTER];
1528 };
1529
1530
1531 /*========================================================================
1532 **
1533 **      Declaration of structs:     Command control block.
1534 **
1535 **========================================================================
1536 */
1537 struct ccb {
1538         /*----------------------------------------------------------------
1539         **      This is the data structure which is pointed by the DSA 
1540         **      register when it is executed by the script processor.
1541         **      It must be the first entry because it contains the header 
1542         **      as first entry that must be cache line aligned.
1543         **----------------------------------------------------------------
1544         */
1545         struct dsb      phys;
1546
1547         /*----------------------------------------------------------------
1548         **      Mini-script used at CCB execution start-up.
1549         **      Load the DSA with the data structure address (phys) and 
1550         **      jump to SELECT. Jump to CANCEL if CCB is to be canceled.
1551         **----------------------------------------------------------------
1552         */
1553         struct launch   start;
1554
1555         /*----------------------------------------------------------------
1556         **      Mini-script used at CCB relection to restart the nexus.
1557         **      Load the DSA with the data structure address (phys) and 
1558         **      jump to RESEL_DSA. Jump to ABORT if CCB is to be aborted.
1559         **----------------------------------------------------------------
1560         */
1561         struct launch   restart;
1562
1563         /*----------------------------------------------------------------
1564         **      If a data transfer phase is terminated too early
1565         **      (after reception of a message (i.e. DISCONNECT)),
1566         **      we have to prepare a mini script to transfer
1567         **      the rest of the data.
1568         **----------------------------------------------------------------
1569         */
1570         ncrcmd          patch[8];
1571
1572         /*----------------------------------------------------------------
1573         **      The general SCSI driver provides a
1574         **      pointer to a control block.
1575         **----------------------------------------------------------------
1576         */
1577         struct scsi_cmnd        *cmd;           /* SCSI command                 */
1578         u_char          cdb_buf[16];    /* Copy of CDB                  */
1579         u_char          sense_buf[64];
1580         int             data_len;       /* Total data length            */
1581
1582         /*----------------------------------------------------------------
1583         **      Message areas.
1584         **      We prepare a message to be sent after selection.
1585         **      We may use a second one if the command is rescheduled 
1586         **      due to GETCC or QFULL.
1587         **      Contents are IDENTIFY and SIMPLE_TAG.
1588         **      While negotiating sync or wide transfer,
1589         **      a SDTR or WDTR message is appended.
1590         **----------------------------------------------------------------
1591         */
1592         u_char          scsi_smsg [8];
1593         u_char          scsi_smsg2[8];
1594
1595         /*----------------------------------------------------------------
1596         **      Other fields.
1597         **----------------------------------------------------------------
1598         */
1599         u_long          p_ccb;          /* BUS address of this CCB      */
1600         u_char          sensecmd[6];    /* Sense command                */
1601         u_char          tag;            /* Tag for this transfer        */
1602                                         /*  255 means no tag            */
1603         u_char          target;
1604         u_char          lun;
1605         u_char          queued;
1606         u_char          auto_sense;
1607         struct ccb *    link_ccb;       /* Host adapter CCB chain       */
1608         struct list_head link_ccbq;     /* Link to unit CCB queue       */
1609         u32             startp;         /* Initial data pointer         */
1610         u_long          magic;          /* Free / busy  CCB flag        */
1611 };
1612
1613 #define CCB_PHYS(cp,lbl)        (cp->p_ccb + offsetof(struct ccb, lbl))
1614
1615
1616 /*========================================================================
1617 **
1618 **      Declaration of structs:     NCR device descriptor
1619 **
1620 **========================================================================
1621 */
1622 struct ncb {
1623         /*----------------------------------------------------------------
1624         **      The global header.
1625         **      It is accessible to both the host and the script processor.
1626         **      Must be cache line size aligned (32 for x86) in order to 
1627         **      allow cache line bursting when it is copied to/from CCB.
1628         **----------------------------------------------------------------
1629         */
1630         struct head     header;
1631
1632         /*----------------------------------------------------------------
1633         **      CCBs management queues.
1634         **----------------------------------------------------------------
1635         */
1636         struct scsi_cmnd        *waiting_list;  /* Commands waiting for a CCB   */
1637                                         /*  when lcb is not allocated.  */
1638         struct scsi_cmnd        *done_list;     /* Commands waiting for done()  */
1639                                         /* callback to be invoked.      */ 
1640         spinlock_t      smp_lock;       /* Lock for SMP threading       */
1641
1642         /*----------------------------------------------------------------
1643         **      Chip and controller indentification.
1644         **----------------------------------------------------------------
1645         */
1646         int             unit;           /* Unit number                  */
1647         char            inst_name[16];  /* ncb instance name            */
1648
1649         /*----------------------------------------------------------------
1650         **      Initial value of some IO register bits.
1651         **      These values are assumed to have been set by BIOS, and may 
1652         **      be used for probing adapter implementation differences.
1653         **----------------------------------------------------------------
1654         */
1655         u_char  sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest0, sv_ctest3,
1656                 sv_ctest4, sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4;
1657
1658         /*----------------------------------------------------------------
1659         **      Actual initial value of IO register bits used by the 
1660         **      driver. They are loaded at initialisation according to  
1661         **      features that are to be enabled.
1662         **----------------------------------------------------------------
1663         */
1664         u_char  rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest0, rv_ctest3,
1665                 rv_ctest4, rv_ctest5, rv_stest2;
1666
1667         /*----------------------------------------------------------------
1668         **      Targets management.
1669         **      During reselection the ncr jumps to jump_tcb.
1670         **      The SFBR register is loaded with the encoded target id.
1671         **      For i = 0 to 3
1672         **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(next tcb mod. i)
1673         **
1674         **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
1675         **      It is kind of hashcoding.
1676         **----------------------------------------------------------------
1677         */
1678         struct link     jump_tcb[4];    /* JUMPs for reselection        */
1679         struct tcb  target[MAX_TARGET]; /* Target data                  */
1680
1681         /*----------------------------------------------------------------
1682         **      Virtual and physical bus addresses of the chip.
1683         **----------------------------------------------------------------
1684         */
1685         void __iomem *vaddr;            /* Virtual and bus address of   */
1686         unsigned long   paddr;          /*  chip's IO registers.        */
1687         unsigned long   paddr2;         /* On-chip RAM bus address.     */
1688         volatile                        /* Pointer to volatile for      */
1689         struct ncr_reg  __iomem *reg;   /*  memory mapped IO.           */
1690
1691         /*----------------------------------------------------------------
1692         **      SCRIPTS virtual and physical bus addresses.
1693         **      'script'  is loaded in the on-chip RAM if present.
1694         **      'scripth' stays in main memory.
1695         **----------------------------------------------------------------
1696         */
1697         struct script   *script0;       /* Copies of script and scripth */
1698         struct scripth  *scripth0;      /*  relocated for this ncb.     */
1699         struct scripth  *scripth;       /* Actual scripth virt. address */
1700         u_long          p_script;       /* Actual script and scripth    */
1701         u_long          p_scripth;      /*  bus addresses.              */
1702
1703         /*----------------------------------------------------------------
1704         **      General controller parameters and configuration.
1705         **----------------------------------------------------------------
1706         */
1707         struct device   *dev;
1708         u_char          revision_id;    /* PCI device revision id       */
1709         u32             irq;            /* IRQ level                    */
1710         u32             features;       /* Chip features map            */
1711         u_char          myaddr;         /* SCSI id of the adapter       */
1712         u_char          maxburst;       /* log base 2 of dwords burst   */
1713         u_char          maxwide;        /* Maximum transfer width       */
1714         u_char          minsync;        /* Minimum sync period factor   */
1715         u_char          maxsync;        /* Maximum sync period factor   */
1716         u_char          maxoffs;        /* Max scsi offset              */
1717         u_char          multiplier;     /* Clock multiplier (1,2,4)     */
1718         u_char          clock_divn;     /* Number of clock divisors     */
1719         u_long          clock_khz;      /* SCSI clock frequency in KHz  */
1720
1721         /*----------------------------------------------------------------
1722         **      Start queue management.
1723         **      It is filled up by the host processor and accessed by the 
1724         **      SCRIPTS processor in order to start SCSI commands.
1725         **----------------------------------------------------------------
1726         */
1727         u16             squeueput;      /* Next free slot of the queue  */
1728         u16             actccbs;        /* Number of allocated CCBs     */
1729         u16             queuedccbs;     /* Number of CCBs in start queue*/
1730         u16             queuedepth;     /* Start queue depth            */
1731
1732         /*----------------------------------------------------------------
1733         **      Timeout handler.
1734         **----------------------------------------------------------------
1735         */
1736         struct timer_list timer;        /* Timer handler link header    */
1737         u_long          lasttime;
1738         u_long          settle_time;    /* Resetting the SCSI BUS       */
1739
1740         /*----------------------------------------------------------------
1741         **      Debugging and profiling.
1742         **----------------------------------------------------------------
1743         */
1744         struct ncr_reg  regdump;        /* Register dump                */
1745         u_long          regtime;        /* Time it has been done        */
1746
1747         /*----------------------------------------------------------------
1748         **      Miscellaneous buffers accessed by the scripts-processor.
1749         **      They shall be DWORD aligned, because they may be read or 
1750         **      written with a SCR_COPY script command.
1751         **----------------------------------------------------------------
1752         */
1753         u_char          msgout[8];      /* Buffer for MESSAGE OUT       */
1754         u_char          msgin [8];      /* Buffer for MESSAGE IN        */
1755         u32             lastmsg;        /* Last SCSI message sent       */
1756         u_char          scratch;        /* Scratch for SCSI receive     */
1757
1758         /*----------------------------------------------------------------
1759         **      Miscellaneous configuration and status parameters.
1760         **----------------------------------------------------------------
1761         */
1762         u_char          disc;           /* Diconnection allowed         */
1763         u_char          scsi_mode;      /* Current SCSI BUS mode        */
1764         u_char          order;          /* Tag order to use             */
1765         u_char          verbose;        /* Verbosity for this controller*/
1766         int             ncr_cache;      /* Used for cache test at init. */
1767         u_long          p_ncb;          /* BUS address of this NCB      */
1768
1769         /*----------------------------------------------------------------
1770         **      Command completion handling.
1771         **----------------------------------------------------------------
1772         */
1773 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
1774         struct ccb      *(ccb_done[MAX_DONE]);
1775         int             ccb_done_ic;
1776 #endif
1777         /*----------------------------------------------------------------
1778         **      Fields that should be removed or changed.
1779         **----------------------------------------------------------------
1780         */
1781         struct ccb      *ccb;           /* Global CCB                   */
1782         struct usrcmd   user;           /* Command from user            */
1783         volatile u_char release_stage;  /* Synchronisation stage on release  */
1784 };
1785
1786 #define NCB_SCRIPT_PHYS(np,lbl)  (np->p_script  + offsetof (struct script, lbl))
1787 #define NCB_SCRIPTH_PHYS(np,lbl) (np->p_scripth + offsetof (struct scripth,lbl))
1788
1789 /*==========================================================
1790 **
1791 **
1792 **      Script for NCR-Processor.
1793 **
1794 **      Use ncr_script_fill() to create the variable parts.
1795 **      Use ncr_script_copy_and_bind() to make a copy and
1796 **      bind to physical addresses.
1797 **
1798 **
1799 **==========================================================
1800 **
1801 **      We have to know the offsets of all labels before
1802 **      we reach them (for forward jumps).
1803 **      Therefore we declare a struct here.
1804 **      If you make changes inside the script,
1805 **      DONT FORGET TO CHANGE THE LENGTHS HERE!
1806 **
1807 **----------------------------------------------------------
1808 */
1809
1810 /*
1811 **      For HP Zalon/53c720 systems, the Zalon interface
1812 **      between CPU and 53c720 does prefetches, which causes
1813 **      problems with self modifying scripts.  The problem
1814 **      is overcome by calling a dummy subroutine after each
1815 **      modification, to force a refetch of the script on
1816 **      return from the subroutine.
1817 */
1818
1819 #ifdef CONFIG_NCR53C8XX_PREFETCH
1820 #define PREFETCH_FLUSH_CNT      2
1821 #define PREFETCH_FLUSH          SCR_CALL, PADDRH (wait_dma),
1822 #else
1823 #define PREFETCH_FLUSH_CNT      0
1824 #define PREFETCH_FLUSH
1825 #endif
1826
1827 /*
1828 **      Script fragments which are loaded into the on-chip RAM 
1829 **      of 825A, 875 and 895 chips.
1830 */
1831 struct script {
1832         ncrcmd  start           [  5];
1833         ncrcmd  startpos        [  1];
1834         ncrcmd  select          [  6];
1835         ncrcmd  select2         [  9 + PREFETCH_FLUSH_CNT];
1836         ncrcmd  loadpos         [  4];
1837         ncrcmd  send_ident      [  9];
1838         ncrcmd  prepare         [  6];
1839         ncrcmd  prepare2        [  7];
1840         ncrcmd  command         [  6];
1841         ncrcmd  dispatch        [ 32];
1842         ncrcmd  clrack          [  4];
1843         ncrcmd  no_data         [ 17];
1844         ncrcmd  status          [  8];
1845         ncrcmd  msg_in          [  2];
1846         ncrcmd  msg_in2         [ 16];
1847         ncrcmd  msg_bad         [  4];
1848         ncrcmd  setmsg          [  7];
1849         ncrcmd  cleanup         [  6];
1850         ncrcmd  complete        [  9];
1851         ncrcmd  cleanup_ok      [  8 + PREFETCH_FLUSH_CNT];
1852         ncrcmd  cleanup0        [  1];
1853 #ifndef SCSI_NCR_CCB_DONE_SUPPORT
1854         ncrcmd  signal          [ 12];
1855 #else
1856         ncrcmd  signal          [  9];
1857         ncrcmd  done_pos        [  1];
1858         ncrcmd  done_plug       [  2];
1859         ncrcmd  done_end        [  7];
1860 #endif
1861         ncrcmd  save_dp         [  7];
1862         ncrcmd  restore_dp      [  5];
1863         ncrcmd  disconnect      [ 10];
1864         ncrcmd  msg_out         [  9];
1865         ncrcmd  msg_out_done    [  7];
1866         ncrcmd  idle            [  2];
1867         ncrcmd  reselect        [  8];
1868         ncrcmd  reselected      [  8];
1869         ncrcmd  resel_dsa       [  6 + PREFETCH_FLUSH_CNT];
1870         ncrcmd  loadpos1        [  4];
1871         ncrcmd  resel_lun       [  6];
1872         ncrcmd  resel_tag       [  6];
1873         ncrcmd  jump_to_nexus   [  4 + PREFETCH_FLUSH_CNT];
1874         ncrcmd  nexus_indirect  [  4];
1875         ncrcmd  resel_notag     [  4];
1876         ncrcmd  data_in         [MAX_SCATTERL * 4];
1877         ncrcmd  data_in2        [  4];
1878         ncrcmd  data_out        [MAX_SCATTERL * 4];
1879         ncrcmd  data_out2       [  4];
1880 };
1881
1882 /*
1883 **      Script fragments which stay in main memory for all chips.
1884 */
1885 struct scripth {
1886         ncrcmd  tryloop         [MAX_START*2];
1887         ncrcmd  tryloop2        [  2];
1888 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
1889         ncrcmd  done_queue      [MAX_DONE*5];
1890         ncrcmd  done_queue2     [  2];
1891 #endif
1892         ncrcmd  select_no_atn   [  8];
1893         ncrcmd  cancel          [  4];
1894         ncrcmd  skip            [  9 + PREFETCH_FLUSH_CNT];
1895         ncrcmd  skip2           [ 19];
1896         ncrcmd  par_err_data_in [  6];
1897         ncrcmd  par_err_other   [  4];
1898         ncrcmd  msg_reject      [  8];
1899         ncrcmd  msg_ign_residue [ 24];
1900         ncrcmd  msg_extended    [ 10];
1901         ncrcmd  msg_ext_2       [ 10];
1902         ncrcmd  msg_wdtr        [ 14];
1903         ncrcmd  send_wdtr       [  7];
1904         ncrcmd  msg_ext_3       [ 10];
1905         ncrcmd  msg_sdtr        [ 14];
1906         ncrcmd  send_sdtr       [  7];
1907         ncrcmd  nego_bad_phase  [  4];
1908         ncrcmd  msg_out_abort   [ 10];
1909         ncrcmd  hdata_in        [MAX_SCATTERH * 4];
1910         ncrcmd  hdata_in2       [  2];
1911         ncrcmd  hdata_out       [MAX_SCATTERH * 4];
1912         ncrcmd  hdata_out2      [  2];
1913         ncrcmd  reset           [  4];
1914         ncrcmd  aborttag        [  4];
1915         ncrcmd  abort           [  2];
1916         ncrcmd  abort_resel     [ 20];
1917         ncrcmd  resend_ident    [  4];
1918         ncrcmd  clratn_go_on    [  3];
1919         ncrcmd  nxtdsp_go_on    [  1];
1920         ncrcmd  sdata_in        [  8];
1921         ncrcmd  data_io         [ 18];
1922         ncrcmd  bad_identify    [ 12];
1923         ncrcmd  bad_i_t_l       [  4];
1924         ncrcmd  bad_i_t_l_q     [  4];
1925         ncrcmd  bad_target      [  8];
1926         ncrcmd  bad_status      [  8];
1927         ncrcmd  start_ram       [  4 + PREFETCH_FLUSH_CNT];
1928         ncrcmd  start_ram0      [  4];
1929         ncrcmd  sto_restart     [  5];
1930         ncrcmd  wait_dma        [  2];
1931         ncrcmd  snooptest       [  9];
1932         ncrcmd  snoopend        [  2];
1933 };
1934
1935 /*==========================================================
1936 **
1937 **
1938 **      Function headers.
1939 **
1940 **
1941 **==========================================================
1942 */
1943
1944 static  void    ncr_alloc_ccb   (struct ncb *np, u_char tn, u_char ln);
1945 static  void    ncr_complete    (struct ncb *np, struct ccb *cp);
1946 static  void    ncr_exception   (struct ncb *np);
1947 static  void    ncr_free_ccb    (struct ncb *np, struct ccb *cp);
1948 static  void    ncr_init_ccb    (struct ncb *np, struct ccb *cp);
1949 static  void    ncr_init_tcb    (struct ncb *np, u_char tn);
1950 static  struct lcb *    ncr_alloc_lcb   (struct ncb *np, u_char tn, u_char ln);
1951 static  struct lcb *    ncr_setup_lcb   (struct ncb *np, struct scsi_device *sdev);
1952 static  void    ncr_getclock    (struct ncb *np, int mult);
1953 static  void    ncr_selectclock (struct ncb *np, u_char scntl3);
1954 static  struct ccb *ncr_get_ccb (struct ncb *np, struct scsi_cmnd *cmd);
1955 static  void    ncr_chip_reset  (struct ncb *np, int delay);
1956 static  void    ncr_init        (struct ncb *np, int reset, char * msg, u_long code);
1957 static  int     ncr_int_sbmc    (struct ncb *np);
1958 static  int     ncr_int_par     (struct ncb *np);
1959 static  void    ncr_int_ma      (struct ncb *np);
1960 static  void    ncr_int_sir     (struct ncb *np);
1961 static  void    ncr_int_sto     (struct ncb *np);
1962 static  void    ncr_negotiate   (struct ncb* np, struct tcb* tp);
1963 static  int     ncr_prepare_nego(struct ncb *np, struct ccb *cp, u_char *msgptr);
1964
1965 static  void    ncr_script_copy_and_bind
1966                                 (struct ncb *np, ncrcmd *src, ncrcmd *dst, int len);
1967 static  void    ncr_script_fill (struct script * scr, struct scripth * scripth);
1968 static  int     ncr_scatter     (struct ncb *np, struct ccb *cp, struct scsi_cmnd *cmd);
1969 static  void    ncr_getsync     (struct ncb *np, u_char sfac, u_char *fakp, u_char *scntl3p);
1970 static  void    ncr_setsync     (struct ncb *np, struct ccb *cp, u_char scntl3, u_char sxfer);
1971 static  void    ncr_setup_tags  (struct ncb *np, struct scsi_device *sdev);
1972 static  void    ncr_setwide     (struct ncb *np, struct ccb *cp, u_char wide, u_char ack);
1973 static  int     ncr_snooptest   (struct ncb *np);
1974 static  void    ncr_timeout     (struct ncb *np);
1975 static  void    ncr_wakeup      (struct ncb *np, u_long code);
1976 static  void    ncr_wakeup_done (struct ncb *np);
1977 static  void    ncr_start_next_ccb (struct ncb *np, struct lcb * lp, int maxn);
1978 static  void    ncr_put_start_queue(struct ncb *np, struct ccb *cp);
1979
1980 static void insert_into_waiting_list(struct ncb *np, struct scsi_cmnd *cmd);
1981 static struct scsi_cmnd *retrieve_from_waiting_list(int to_remove, struct ncb *np, struct scsi_cmnd *cmd);
1982 static void process_waiting_list(struct ncb *np, int sts);
1983
1984 #define remove_from_waiting_list(np, cmd) \
1985                 retrieve_from_waiting_list(1, (np), (cmd))
1986 #define requeue_waiting_list(np) process_waiting_list((np), DID_OK)
1987 #define reset_waiting_list(np) process_waiting_list((np), DID_RESET)
1988
1989 static inline char *ncr_name (struct ncb *np)
1990 {
1991         return np->inst_name;
1992 }
1993
1994
1995 /*==========================================================
1996 **
1997 **
1998 **      Scripts for NCR-Processor.
1999 **
2000 **      Use ncr_script_bind for binding to physical addresses.
2001 **
2002 **
2003 **==========================================================
2004 **
2005 **      NADDR generates a reference to a field of the controller data.
2006 **      PADDR generates a reference to another part of the script.
2007 **      RADDR generates a reference to a script processor register.
2008 **      FADDR generates a reference to a script processor register
2009 **              with offset.
2010 **
2011 **----------------------------------------------------------
2012 */
2013
2014 #define RELOC_SOFTC     0x40000000
2015 #define RELOC_LABEL     0x50000000
2016 #define RELOC_REGISTER  0x60000000
2017 #if 0
2018 #define RELOC_KVAR      0x70000000
2019 #endif
2020 #define RELOC_LABELH    0x80000000
2021 #define RELOC_MASK      0xf0000000
2022
2023 #define NADDR(label)    (RELOC_SOFTC | offsetof(struct ncb, label))
2024 #define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
2025 #define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
2026 #define RADDR(label)    (RELOC_REGISTER | REG(label))
2027 #define FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
2028 #if 0
2029 #define KVAR(which)     (RELOC_KVAR | (which))
2030 #endif
2031
2032 #if 0
2033 #define SCRIPT_KVAR_JIFFIES     (0)
2034 #define SCRIPT_KVAR_FIRST               SCRIPT_KVAR_JIFFIES
2035 #define SCRIPT_KVAR_LAST                SCRIPT_KVAR_JIFFIES
2036 /*
2037  * Kernel variables referenced in the scripts.
2038  * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
2039  */
2040 static void *script_kvars[] __initdata =
2041         { (void *)&jiffies };
2042 #endif
2043
2044 static  struct script script0 __initdata = {
2045 /*--------------------------< START >-----------------------*/ {
2046         /*
2047         **      This NOP will be patched with LED ON
2048         **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2049         */
2050         SCR_NO_OP,
2051                 0,
2052         /*
2053         **      Clear SIGP.
2054         */
2055         SCR_FROM_REG (ctest2),
2056                 0,
2057         /*
2058         **      Then jump to a certain point in tryloop.
2059         **      Due to the lack of indirect addressing the code
2060         **      is self modifying here.
2061         */
2062         SCR_JUMP,
2063 }/*-------------------------< STARTPOS >--------------------*/,{
2064                 PADDRH(tryloop),
2065
2066 }/*-------------------------< SELECT >----------------------*/,{
2067         /*
2068         **      DSA     contains the address of a scheduled
2069         **              data structure.
2070         **
2071         **      SCRATCHA contains the address of the script,
2072         **              which starts the next entry.
2073         **
2074         **      Set Initiator mode.
2075         **
2076         **      (Target mode is left as an exercise for the reader)
2077         */
2078
2079         SCR_CLR (SCR_TRG),
2080                 0,
2081         SCR_LOAD_REG (HS_REG, HS_SELECTING),
2082                 0,
2083
2084         /*
2085         **      And try to select this target.
2086         */
2087         SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
2088                 PADDR (reselect),
2089
2090 }/*-------------------------< SELECT2 >----------------------*/,{
2091         /*
2092         **      Now there are 4 possibilities:
2093         **
2094         **      (1) The ncr loses arbitration.
2095         **      This is ok, because it will try again,
2096         **      when the bus becomes idle.
2097         **      (But beware of the timeout function!)
2098         **
2099         **      (2) The ncr is reselected.
2100         **      Then the script processor takes the jump
2101         **      to the RESELECT label.
2102         **
2103         **      (3) The ncr wins arbitration.
2104         **      Then it will execute SCRIPTS instruction until 
2105         **      the next instruction that checks SCSI phase.
2106         **      Then will stop and wait for selection to be 
2107         **      complete or selection time-out to occur.
2108         **      As a result the SCRIPTS instructions until 
2109         **      LOADPOS + 2 should be executed in parallel with 
2110         **      the SCSI core performing selection.
2111         */
2112
2113         /*
2114         **      The M_REJECT problem seems to be due to a selection 
2115         **      timing problem.
2116         **      Wait immediately for the selection to complete. 
2117         **      (2.5x behaves so)
2118         */
2119         SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2120                 0,
2121
2122         /*
2123         **      Next time use the next slot.
2124         */
2125         SCR_COPY (4),
2126                 RADDR (temp),
2127                 PADDR (startpos),
2128         /*
2129         **      The ncr doesn't have an indirect load
2130         **      or store command. So we have to
2131         **      copy part of the control block to a
2132         **      fixed place, where we can access it.
2133         **
2134         **      We patch the address part of a
2135         **      COPY command with the DSA-register.
2136         */
2137         SCR_COPY_F (4),
2138                 RADDR (dsa),
2139                 PADDR (loadpos),
2140         /*
2141         **      Flush script prefetch if required
2142         */
2143         PREFETCH_FLUSH
2144         /*
2145         **      then we do the actual copy.
2146         */
2147         SCR_COPY (sizeof (struct head)),
2148         /*
2149         **      continued after the next label ...
2150         */
2151 }/*-------------------------< LOADPOS >---------------------*/,{
2152                 0,
2153                 NADDR (header),
2154         /*
2155         **      Wait for the next phase or the selection
2156         **      to complete or time-out.
2157         */
2158         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2159                 PADDR (prepare),
2160
2161 }/*-------------------------< SEND_IDENT >----------------------*/,{
2162         /*
2163         **      Selection complete.
2164         **      Send the IDENTIFY and SIMPLE_TAG messages
2165         **      (and the M_X_SYNC_REQ message)
2166         */
2167         SCR_MOVE_TBL ^ SCR_MSG_OUT,
2168                 offsetof (struct dsb, smsg),
2169         SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2170                 PADDRH (resend_ident),
2171         SCR_LOAD_REG (scratcha, 0x80),
2172                 0,
2173         SCR_COPY (1),
2174                 RADDR (scratcha),
2175                 NADDR (lastmsg),
2176 }/*-------------------------< PREPARE >----------------------*/,{
2177         /*
2178         **      load the savep (saved pointer) into
2179         **      the TEMP register (actual pointer)
2180         */
2181         SCR_COPY (4),
2182                 NADDR (header.savep),
2183                 RADDR (temp),
2184         /*
2185         **      Initialize the status registers
2186         */
2187         SCR_COPY (4),
2188                 NADDR (header.status),
2189                 RADDR (scr0),
2190 }/*-------------------------< PREPARE2 >---------------------*/,{
2191         /*
2192         **      Initialize the msgout buffer with a NOOP message.
2193         */
2194         SCR_LOAD_REG (scratcha, M_NOOP),
2195                 0,
2196         SCR_COPY (1),
2197                 RADDR (scratcha),
2198                 NADDR (msgout),
2199 #if 0
2200         SCR_COPY (1),
2201                 RADDR (scratcha),
2202                 NADDR (msgin),
2203 #endif
2204         /*
2205         **      Anticipate the COMMAND phase.
2206         **      This is the normal case for initial selection.
2207         */
2208         SCR_JUMP ^ IFFALSE (WHEN (SCR_COMMAND)),
2209                 PADDR (dispatch),
2210
2211 }/*-------------------------< COMMAND >--------------------*/,{
2212         /*
2213         **      ... and send the command
2214         */
2215         SCR_MOVE_TBL ^ SCR_COMMAND,
2216                 offsetof (struct dsb, cmd),
2217         /*
2218         **      If status is still HS_NEGOTIATE, negotiation failed.
2219         **      We check this here, since we want to do that 
2220         **      only once.
2221         */
2222         SCR_FROM_REG (HS_REG),
2223                 0,
2224         SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2225                 SIR_NEGO_FAILED,
2226
2227 }/*-----------------------< DISPATCH >----------------------*/,{
2228         /*
2229         **      MSG_IN is the only phase that shall be 
2230         **      entered at least once for each (re)selection.
2231         **      So we test it first.
2232         */
2233         SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
2234                 PADDR (msg_in),
2235
2236         SCR_RETURN ^ IFTRUE (IF (SCR_DATA_OUT)),
2237                 0,
2238         /*
2239         **      DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 4.
2240         **      Possible data corruption during Memory Write and Invalidate.
2241         **      This work-around resets the addressing logic prior to the 
2242         **      start of the first MOVE of a DATA IN phase.
2243         **      (See Documentation/scsi/ncr53c8xx.txt for more information)
2244         */
2245         SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
2246                 20,
2247         SCR_COPY (4),
2248                 RADDR (scratcha),
2249                 RADDR (scratcha),
2250         SCR_RETURN,
2251                 0,
2252         SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
2253                 PADDR (status),
2254         SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
2255                 PADDR (command),
2256         SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
2257                 PADDR (msg_out),
2258         /*
2259         **      Discard one illegal phase byte, if required.
2260         */
2261         SCR_LOAD_REG (scratcha, XE_BAD_PHASE),
2262                 0,
2263         SCR_COPY (1),
2264                 RADDR (scratcha),
2265                 NADDR (xerr_st),
2266         SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
2267                 8,
2268         SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
2269                 NADDR (scratch),
2270         SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
2271                 8,
2272         SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
2273                 NADDR (scratch),
2274         SCR_JUMP,
2275                 PADDR (dispatch),
2276
2277 }/*-------------------------< CLRACK >----------------------*/,{
2278         /*
2279         **      Terminate possible pending message phase.
2280         */
2281         SCR_CLR (SCR_ACK),
2282                 0,
2283         SCR_JUMP,
2284                 PADDR (dispatch),
2285
2286 }/*-------------------------< NO_DATA >--------------------*/,{
2287         /*
2288         **      The target wants to tranfer too much data
2289         **      or in the wrong direction.
2290         **      Remember that in extended error.
2291         */
2292         SCR_LOAD_REG (scratcha, XE_EXTRA_DATA),
2293                 0,
2294         SCR_COPY (1),
2295                 RADDR (scratcha),
2296                 NADDR (xerr_st),
2297         /*
2298         **      Discard one data byte, if required.
2299         */
2300         SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2301                 8,
2302         SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
2303                 NADDR (scratch),
2304         SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
2305                 8,
2306         SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2307                 NADDR (scratch),
2308         /*
2309         **      .. and repeat as required.
2310         */
2311         SCR_CALL,
2312                 PADDR (dispatch),
2313         SCR_JUMP,
2314                 PADDR (no_data),
2315
2316 }/*-------------------------< STATUS >--------------------*/,{
2317         /*
2318         **      get the status
2319         */
2320         SCR_MOVE_ABS (1) ^ SCR_STATUS,
2321                 NADDR (scratch),
2322         /*
2323         **      save status to scsi_status.
2324         **      mark as complete.
2325         */
2326         SCR_TO_REG (SS_REG),
2327                 0,
2328         SCR_LOAD_REG (HS_REG, HS_COMPLETE),
2329                 0,
2330         SCR_JUMP,
2331                 PADDR (dispatch),
2332 }/*-------------------------< MSG_IN >--------------------*/,{
2333         /*
2334         **      Get the first byte of the message
2335         **      and save it to SCRATCHA.
2336         **
2337         **      The script processor doesn't negate the
2338         **      ACK signal after this transfer.
2339         */
2340         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2341                 NADDR (msgin[0]),
2342 }/*-------------------------< MSG_IN2 >--------------------*/,{
2343         /*
2344         **      Handle this message.
2345         */
2346         SCR_JUMP ^ IFTRUE (DATA (M_COMPLETE)),
2347                 PADDR (complete),
2348         SCR_JUMP ^ IFTRUE (DATA (M_DISCONNECT)),
2349                 PADDR (disconnect),
2350         SCR_JUMP ^ IFTRUE (DATA (M_SAVE_DP)),
2351                 PADDR (save_dp),
2352         SCR_JUMP ^ IFTRUE (DATA (M_RESTORE_DP)),
2353                 PADDR (restore_dp),
2354         SCR_JUMP ^ IFTRUE (DATA (M_EXTENDED)),
2355                 PADDRH (msg_extended),
2356         SCR_JUMP ^ IFTRUE (DATA (M_NOOP)),
2357                 PADDR (clrack),
2358         SCR_JUMP ^ IFTRUE (DATA (M_REJECT)),
2359                 PADDRH (msg_reject),
2360         SCR_JUMP ^ IFTRUE (DATA (M_IGN_RESIDUE)),
2361                 PADDRH (msg_ign_residue),
2362         /*
2363         **      Rest of the messages left as
2364         **      an exercise ...
2365         **
2366         **      Unimplemented messages:
2367         **      fall through to MSG_BAD.
2368         */
2369 }/*-------------------------< MSG_BAD >------------------*/,{
2370         /*
2371         **      unimplemented message - reject it.
2372         */
2373         SCR_INT,
2374                 SIR_REJECT_SENT,
2375         SCR_LOAD_REG (scratcha, M_REJECT),
2376                 0,
2377 }/*-------------------------< SETMSG >----------------------*/,{
2378         SCR_COPY (1),
2379                 RADDR (scratcha),
2380                 NADDR (msgout),
2381         SCR_SET (SCR_ATN),
2382                 0,
2383         SCR_JUMP,
2384                 PADDR (clrack),
2385 }/*-------------------------< CLEANUP >-------------------*/,{
2386         /*
2387         **      dsa:    Pointer to ccb
2388         **            or xxxxxxFF (no ccb)
2389         **
2390         **      HS_REG:   Host-Status (<>0!)
2391         */
2392         SCR_FROM_REG (dsa),
2393                 0,
2394         SCR_JUMP ^ IFTRUE (DATA (0xff)),
2395                 PADDR (start),
2396         /*
2397         **      dsa is valid.
2398         **      complete the cleanup.
2399         */
2400         SCR_JUMP,
2401                 PADDR (cleanup_ok),
2402
2403 }/*-------------------------< COMPLETE >-----------------*/,{
2404         /*
2405         **      Complete message.
2406         **
2407         **      Copy TEMP register to LASTP in header.
2408         */
2409         SCR_COPY (4),
2410                 RADDR (temp),
2411                 NADDR (header.lastp),
2412         /*
2413         **      When we terminate the cycle by clearing ACK,
2414         **      the target may disconnect immediately.
2415         **
2416         **      We don't want to be told of an
2417         **      "unexpected disconnect",
2418         **      so we disable this feature.
2419         */
2420         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2421                 0,
2422         /*
2423         **      Terminate cycle ...
2424         */
2425         SCR_CLR (SCR_ACK|SCR_ATN),
2426                 0,
2427         /*
2428         **      ... and wait for the disconnect.
2429         */
2430         SCR_WAIT_DISC,
2431                 0,
2432 }/*-------------------------< CLEANUP_OK >----------------*/,{
2433         /*
2434         **      Save host status to header.
2435         */
2436         SCR_COPY (4),
2437                 RADDR (scr0),
2438                 NADDR (header.status),
2439         /*
2440         **      and copy back the header to the ccb.
2441         */
2442         SCR_COPY_F (4),
2443                 RADDR (dsa),
2444                 PADDR (cleanup0),
2445         /*
2446         **      Flush script prefetch if required
2447         */
2448         PREFETCH_FLUSH
2449         SCR_COPY (sizeof (struct head)),
2450                 NADDR (header),
2451 }/*-------------------------< CLEANUP0 >--------------------*/,{
2452                 0,
2453 }/*-------------------------< SIGNAL >----------------------*/,{
2454         /*
2455         **      if job not completed ...
2456         */
2457         SCR_FROM_REG (HS_REG),
2458                 0,
2459         /*
2460         **      ... start the next command.
2461         */
2462         SCR_JUMP ^ IFTRUE (MASK (0, (HS_DONEMASK|HS_SKIPMASK))),
2463                 PADDR(start),
2464         /*
2465         **      If command resulted in not GOOD status,
2466         **      call the C code if needed.
2467         */
2468         SCR_FROM_REG (SS_REG),
2469                 0,
2470         SCR_CALL ^ IFFALSE (DATA (S_GOOD)),
2471                 PADDRH (bad_status),
2472
2473 #ifndef SCSI_NCR_CCB_DONE_SUPPORT
2474
2475         /*
2476         **      ... signal completion to the host
2477         */
2478         SCR_INT,
2479                 SIR_INTFLY,
2480         /*
2481         **      Auf zu neuen Schandtaten!
2482         */
2483         SCR_JUMP,
2484                 PADDR(start),
2485
2486 #else   /* defined SCSI_NCR_CCB_DONE_SUPPORT */
2487
2488         /*
2489         **      ... signal completion to the host
2490         */
2491         SCR_JUMP,
2492 }/*------------------------< DONE_POS >---------------------*/,{
2493                 PADDRH (done_queue),
2494 }/*------------------------< DONE_PLUG >--------------------*/,{
2495         SCR_INT,
2496                 SIR_DONE_OVERFLOW,
2497 }/*------------------------< DONE_END >---------------------*/,{
2498         SCR_INT,
2499                 SIR_INTFLY,
2500         SCR_COPY (4),
2501                 RADDR (temp),
2502                 PADDR (done_pos),
2503         SCR_JUMP,
2504                 PADDR (start),
2505
2506 #endif  /* SCSI_NCR_CCB_DONE_SUPPORT */
2507
2508 }/*-------------------------< SAVE_DP >------------------*/,{
2509         /*
2510         **      SAVE_DP message:
2511         **      Copy TEMP register to SAVEP in header.
2512         */
2513         SCR_COPY (4),
2514                 RADDR (temp),
2515                 NADDR (header.savep),
2516         SCR_CLR (SCR_ACK),
2517                 0,
2518         SCR_JUMP,
2519                 PADDR (dispatch),
2520 }/*-------------------------< RESTORE_DP >---------------*/,{
2521         /*
2522         **      RESTORE_DP message:
2523         **      Copy SAVEP in header to TEMP register.
2524         */
2525         SCR_COPY (4),
2526                 NADDR (header.savep),
2527                 RADDR (temp),
2528         SCR_JUMP,
2529                 PADDR (clrack),
2530
2531 }/*-------------------------< DISCONNECT >---------------*/,{
2532         /*
2533         **      DISCONNECTing  ...
2534         **
2535         **      disable the "unexpected disconnect" feature,
2536         **      and remove the ACK signal.
2537         */
2538         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2539                 0,
2540         SCR_CLR (SCR_ACK|SCR_ATN),
2541                 0,
2542         /*
2543         **      Wait for the disconnect.
2544         */
2545         SCR_WAIT_DISC,
2546                 0,
2547         /*
2548         **      Status is: DISCONNECTED.
2549         */
2550         SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
2551                 0,
2552         SCR_JUMP,
2553                 PADDR (cleanup_ok),
2554
2555 }/*-------------------------< MSG_OUT >-------------------*/,{
2556         /*
2557         **      The target requests a message.
2558         */
2559         SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2560                 NADDR (msgout),
2561         SCR_COPY (1),
2562                 NADDR (msgout),
2563                 NADDR (lastmsg),
2564         /*
2565         **      If it was no ABORT message ...
2566         */
2567         SCR_JUMP ^ IFTRUE (DATA (M_ABORT)),
2568                 PADDRH (msg_out_abort),
2569         /*
2570         **      ... wait for the next phase
2571         **      if it's a message out, send it again, ...
2572         */
2573         SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2574                 PADDR (msg_out),
2575 }/*-------------------------< MSG_OUT_DONE >--------------*/,{
2576         /*
2577         **      ... else clear the message ...
2578         */
2579         SCR_LOAD_REG (scratcha, M_NOOP),
2580                 0,
2581         SCR_COPY (4),
2582                 RADDR (scratcha),
2583                 NADDR (msgout),
2584         /*
2585         **      ... and process the next phase
2586         */
2587         SCR_JUMP,
2588                 PADDR (dispatch),
2589 }/*-------------------------< IDLE >------------------------*/,{
2590         /*
2591         **      Nothing to do?
2592         **      Wait for reselect.
2593         **      This NOP will be patched with LED OFF
2594         **      SCR_REG_REG (gpreg, SCR_OR, 0x01)
2595         */
2596         SCR_NO_OP,
2597                 0,
2598 }/*-------------------------< RESELECT >--------------------*/,{
2599         /*
2600         **      make the DSA invalid.
2601         */
2602         SCR_LOAD_REG (dsa, 0xff),
2603                 0,
2604         SCR_CLR (SCR_TRG),
2605                 0,
2606         SCR_LOAD_REG (HS_REG, HS_IN_RESELECT),
2607                 0,
2608         /*
2609         **      Sleep waiting for a reselection.
2610         **      If SIGP is set, special treatment.
2611         **
2612         **      Zu allem bereit ..
2613         */
2614         SCR_WAIT_RESEL,
2615                 PADDR(start),
2616 }/*-------------------------< RESELECTED >------------------*/,{
2617         /*
2618         **      This NOP will be patched with LED ON
2619         **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2620         */
2621         SCR_NO_OP,
2622                 0,
2623         /*
2624         **      ... zu nichts zu gebrauchen ?
2625         **
2626         **      load the target id into the SFBR
2627         **      and jump to the control block.
2628         **
2629         **      Look at the declarations of
2630         **      - struct ncb
2631         **      - struct tcb
2632         **      - struct lcb
2633         **      - struct ccb
2634         **      to understand what's going on.
2635         */
2636         SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2637                 0,
2638         SCR_TO_REG (sdid),
2639                 0,
2640         SCR_JUMP,
2641                 NADDR (jump_tcb),
2642
2643 }/*-------------------------< RESEL_DSA >-------------------*/,{
2644         /*
2645         **      Ack the IDENTIFY or TAG previously received.
2646         */
2647         SCR_CLR (SCR_ACK),
2648                 0,
2649         /*
2650         **      The ncr doesn't have an indirect load
2651         **      or store command. So we have to
2652         **      copy part of the control block to a
2653         **      fixed place, where we can access it.
2654         **
2655         **      We patch the address part of a
2656         **      COPY command with the DSA-register.
2657         */
2658         SCR_COPY_F (4),
2659                 RADDR (dsa),
2660                 PADDR (loadpos1),
2661         /*
2662         **      Flush script prefetch if required
2663         */
2664         PREFETCH_FLUSH
2665         /*
2666         **      then we do the actual copy.
2667         */
2668         SCR_COPY (sizeof (struct head)),
2669         /*
2670         **      continued after the next label ...
2671         */
2672
2673 }/*-------------------------< LOADPOS1 >-------------------*/,{
2674                 0,
2675                 NADDR (header),
2676         /*
2677         **      The DSA contains the data structure address.
2678         */
2679         SCR_JUMP,
2680                 PADDR (prepare),
2681
2682 }/*-------------------------< RESEL_LUN >-------------------*/,{
2683         /*
2684         **      come back to this point
2685         **      to get an IDENTIFY message
2686         **      Wait for a msg_in phase.
2687         */
2688         SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
2689                 SIR_RESEL_NO_MSG_IN,
2690         /*
2691         **      message phase.
2692         **      Read the data directly from the BUS DATA lines.
2693         **      This helps to support very old SCSI devices that 
2694         **      may reselect without sending an IDENTIFY.
2695         */
2696         SCR_FROM_REG (sbdl),
2697                 0,
2698         /*
2699         **      It should be an Identify message.
2700         */
2701         SCR_RETURN,
2702                 0,
2703 }/*-------------------------< RESEL_TAG >-------------------*/,{
2704         /*
2705         **      Read IDENTIFY + SIMPLE + TAG using a single MOVE.
2706         **      Agressive optimization, is'nt it?
2707         **      No need to test the SIMPLE TAG message, since the 
2708         **      driver only supports conformant devices for tags. ;-)
2709         */
2710         SCR_MOVE_ABS (3) ^ SCR_MSG_IN,
2711                 NADDR (msgin),
2712         /*
2713         **      Read the TAG from the SIDL.
2714         **      Still an aggressive optimization. ;-)
2715         **      Compute the CCB indirect jump address which 
2716         **      is (#TAG*2 & 0xfc) due to tag numbering using 
2717         **      1,3,5..MAXTAGS*2+1 actual values.
2718         */
2719         SCR_REG_SFBR (sidl, SCR_SHL, 0),
2720                 0,
2721         SCR_SFBR_REG (temp, SCR_AND, 0xfc),
2722                 0,
2723 }/*-------------------------< JUMP_TO_NEXUS >-------------------*/,{
2724         SCR_COPY_F (4),
2725                 RADDR (temp),
2726                 PADDR (nexus_indirect),
2727         /*
2728         **      Flush script prefetch if required
2729         */
2730         PREFETCH_FLUSH
2731         SCR_COPY (4),
2732 }/*-------------------------< NEXUS_INDIRECT >-------------------*/,{
2733                 0,
2734                 RADDR (temp),
2735         SCR_RETURN,
2736                 0,
2737 }/*-------------------------< RESEL_NOTAG >-------------------*/,{
2738         /*
2739         **      No tag expected.
2740         **      Read an throw away the IDENTIFY.
2741         */
2742         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2743                 NADDR (msgin),
2744         SCR_JUMP,
2745                 PADDR (jump_to_nexus),
2746 }/*-------------------------< DATA_IN >--------------------*/,{
2747 /*
2748 **      Because the size depends on the
2749 **      #define MAX_SCATTERL parameter,
2750 **      it is filled in at runtime.
2751 **
2752 **  ##===========< i=0; i<MAX_SCATTERL >=========
2753 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2754 **  ||          PADDR (dispatch),
2755 **  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
2756 **  ||          offsetof (struct dsb, data[ i]),
2757 **  ##==========================================
2758 **
2759 **---------------------------------------------------------
2760 */
2761 0
2762 }/*-------------------------< DATA_IN2 >-------------------*/,{
2763         SCR_CALL,
2764                 PADDR (dispatch),
2765         SCR_JUMP,
2766                 PADDR (no_data),
2767 }/*-------------------------< DATA_OUT >--------------------*/,{
2768 /*
2769 **      Because the size depends on the
2770 **      #define MAX_SCATTERL parameter,
2771 **      it is filled in at runtime.
2772 **
2773 **  ##===========< i=0; i<MAX_SCATTERL >=========
2774 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2775 **  ||          PADDR (dispatch),
2776 **  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
2777 **  ||          offsetof (struct dsb, data[ i]),
2778 **  ##==========================================
2779 **
2780 **---------------------------------------------------------
2781 */
2782 0
2783 }/*-------------------------< DATA_OUT2 >-------------------*/,{
2784         SCR_CALL,
2785                 PADDR (dispatch),
2786         SCR_JUMP,
2787                 PADDR (no_data),
2788 }/*--------------------------------------------------------*/
2789 };
2790
2791 static  struct scripth scripth0 __initdata = {
2792 /*-------------------------< TRYLOOP >---------------------*/{
2793 /*
2794 **      Start the next entry.
2795 **      Called addresses point to the launch script in the CCB.
2796 **      They are patched by the main processor.
2797 **
2798 **      Because the size depends on the
2799 **      #define MAX_START parameter, it is filled
2800 **      in at runtime.
2801 **
2802 **-----------------------------------------------------------
2803 **
2804 **  ##===========< I=0; i<MAX_START >===========
2805 **  ||  SCR_CALL,
2806 **  ||          PADDR (idle),
2807 **  ##==========================================
2808 **
2809 **-----------------------------------------------------------
2810 */
2811 0
2812 }/*------------------------< TRYLOOP2 >---------------------*/,{
2813         SCR_JUMP,
2814                 PADDRH(tryloop),
2815
2816 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
2817
2818 }/*------------------------< DONE_QUEUE >-------------------*/,{
2819 /*
2820 **      Copy the CCB address to the next done entry.
2821 **      Because the size depends on the
2822 **      #define MAX_DONE parameter, it is filled
2823 **      in at runtime.
2824 **
2825 **-----------------------------------------------------------
2826 **
2827 **  ##===========< I=0; i<MAX_DONE >===========
2828 **  ||  SCR_COPY (sizeof(struct ccb *),
2829 **  ||          NADDR (header.cp),
2830 **  ||          NADDR (ccb_done[i]),
2831 **  ||  SCR_CALL,
2832 **  ||          PADDR (done_end),
2833 **  ##==========================================
2834 **
2835 **-----------------------------------------------------------
2836 */
2837 0
2838 }/*------------------------< DONE_QUEUE2 >------------------*/,{
2839         SCR_JUMP,
2840                 PADDRH (done_queue),
2841
2842 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
2843 }/*------------------------< SELECT_NO_ATN >-----------------*/,{
2844         /*
2845         **      Set Initiator mode.
2846         **      And try to select this target without ATN.
2847         */
2848
2849         SCR_CLR (SCR_TRG),
2850                 0,
2851         SCR_LOAD_REG (HS_REG, HS_SELECTING),
2852                 0,
2853         SCR_SEL_TBL ^ offsetof (struct dsb, select),
2854                 PADDR (reselect),
2855         SCR_JUMP,
2856                 PADDR (select2),
2857
2858 }/*-------------------------< CANCEL >------------------------*/,{
2859
2860         SCR_LOAD_REG (scratcha, HS_ABORTED),
2861                 0,
2862         SCR_JUMPR,
2863                 8,
2864 }/*-------------------------< SKIP >------------------------*/,{
2865         SCR_LOAD_REG (scratcha, 0),
2866                 0,
2867         /*
2868         **      This entry has been canceled.
2869         **      Next time use the next slot.
2870         */
2871         SCR_COPY (4),
2872                 RADDR (temp),
2873                 PADDR (startpos),
2874         /*
2875         **      The ncr doesn't have an indirect load
2876         **      or store command. So we have to
2877         **      copy part of the control block to a
2878         **      fixed place, where we can access it.
2879         **
2880         **      We patch the address part of a
2881         **      COPY command with the DSA-register.
2882         */
2883         SCR_COPY_F (4),
2884                 RADDR (dsa),
2885                 PADDRH (skip2),
2886         /*
2887         **      Flush script prefetch if required
2888         */
2889         PREFETCH_FLUSH
2890         /*
2891         **      then we do the actual copy.
2892         */
2893         SCR_COPY (sizeof (struct head)),
2894         /*
2895         **      continued after the next label ...
2896         */
2897 }/*-------------------------< SKIP2 >---------------------*/,{
2898                 0,
2899                 NADDR (header),
2900         /*
2901         **      Initialize the status registers
2902         */
2903         SCR_COPY (4),
2904                 NADDR (header.status),
2905                 RADDR (scr0),
2906         /*
2907         **      Force host status.
2908         */
2909         SCR_FROM_REG (scratcha),
2910                 0,
2911         SCR_JUMPR ^ IFFALSE (MASK (0, HS_DONEMASK)),
2912                 16,
2913         SCR_REG_REG (HS_REG, SCR_OR, HS_SKIPMASK),
2914                 0,
2915         SCR_JUMPR,
2916                 8,
2917         SCR_TO_REG (HS_REG),
2918                 0,
2919         SCR_LOAD_REG (SS_REG, S_GOOD),
2920                 0,
2921         SCR_JUMP,
2922                 PADDR (cleanup_ok),
2923
2924 },/*-------------------------< PAR_ERR_DATA_IN >---------------*/{
2925         /*
2926         **      Ignore all data in byte, until next phase
2927         */
2928         SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
2929                 PADDRH (par_err_other),
2930         SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2931                 NADDR (scratch),
2932         SCR_JUMPR,
2933                 -24,
2934 },/*-------------------------< PAR_ERR_OTHER >------------------*/{
2935         /*
2936         **      count it.
2937         */
2938         SCR_REG_REG (PS_REG, SCR_ADD, 0x01),
2939                 0,
2940         /*
2941         **      jump to dispatcher.
2942         */
2943         SCR_JUMP,
2944                 PADDR (dispatch),
2945 }/*-------------------------< MSG_REJECT >---------------*/,{
2946         /*
2947         **      If a negotiation was in progress,
2948         **      negotiation failed.
2949         **      Otherwise, let the C code print 
2950         **      some message.
2951         */
2952         SCR_FROM_REG (HS_REG),
2953                 0,
2954         SCR_INT ^ IFFALSE (DATA (HS_NEGOTIATE)),
2955                 SIR_REJECT_RECEIVED,
2956         SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2957                 SIR_NEGO_FAILED,
2958         SCR_JUMP,
2959                 PADDR (clrack),
2960
2961 }/*-------------------------< MSG_IGN_RESIDUE >----------*/,{
2962         /*
2963         **      Terminate cycle
2964         */
2965         SCR_CLR (SCR_ACK),
2966                 0,
2967         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2968                 PADDR (dispatch),
2969         /*
2970         **      get residue size.
2971         */
2972         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2973                 NADDR (msgin[1]),
2974         /*
2975         **      Size is 0 .. ignore message.
2976         */
2977         SCR_JUMP ^ IFTRUE (DATA (0)),
2978                 PADDR (clrack),
2979         /*
2980         **      Size is not 1 .. have to interrupt.
2981         */
2982         SCR_JUMPR ^ IFFALSE (DATA (1)),
2983                 40,
2984         /*
2985         **      Check for residue byte in swide register
2986         */
2987         SCR_FROM_REG (scntl2),
2988                 0,
2989         SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
2990                 16,
2991         /*
2992         **      There IS data in the swide register.
2993         **      Discard it.
2994         */
2995         SCR_REG_REG (scntl2, SCR_OR, WSR),
2996                 0,
2997         SCR_JUMP,
2998                 PADDR (clrack),
2999         /*
3000         **      Load again the size to the sfbr register.
3001         */
3002         SCR_FROM_REG (scratcha),
3003                 0,
3004         SCR_INT,
3005                 SIR_IGN_RESIDUE,
3006         SCR_JUMP,
3007                 PADDR (clrack),
3008
3009 }/*-------------------------< MSG_EXTENDED >-------------*/,{
3010         /*
3011         **      Terminate cycle
3012         */
3013         SCR_CLR (SCR_ACK),
3014                 0,
3015         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3016                 PADDR (dispatch),
3017         /*
3018         **      get length.
3019         */
3020         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3021                 NADDR (msgin[1]),
3022         /*
3023         */
3024         SCR_JUMP ^ IFTRUE (DATA (3)),
3025                 PADDRH (msg_ext_3),
3026         SCR_JUMP ^ IFFALSE (DATA (2)),
3027                 PADDR (msg_bad),
3028 }/*-------------------------< MSG_EXT_2 >----------------*/,{
3029         SCR_CLR (SCR_ACK),
3030                 0,
3031         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3032                 PADDR (dispatch),
3033         /*
3034         **      get extended message code.
3035         */
3036         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3037                 NADDR (msgin[2]),
3038         SCR_JUMP ^ IFTRUE (DATA (M_X_WIDE_REQ)),
3039                 PADDRH (msg_wdtr),
3040         /*
3041         **      unknown extended message
3042         */
3043         SCR_JUMP,
3044                 PADDR (msg_bad)
3045 }/*-------------------------< MSG_WDTR >-----------------*/,{
3046         SCR_CLR (SCR_ACK),
3047                 0,
3048         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3049                 PADDR (dispatch),
3050         /*
3051         **      get data bus width
3052         */
3053         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3054                 NADDR (msgin[3]),
3055         /*
3056         **      let the host do the real work.
3057         */
3058         SCR_INT,
3059                 SIR_NEGO_WIDE,
3060         /*
3061         **      let the target fetch our answer.
3062         */
3063         SCR_SET (SCR_ATN),
3064                 0,
3065         SCR_CLR (SCR_ACK),
3066                 0,
3067         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3068                 PADDRH (nego_bad_phase),
3069
3070 }/*-------------------------< SEND_WDTR >----------------*/,{
3071         /*
3072         **      Send the M_X_WIDE_REQ
3073         */
3074         SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
3075                 NADDR (msgout),
3076         SCR_COPY (1),
3077                 NADDR (msgout),
3078                 NADDR (lastmsg),
3079         SCR_JUMP,
3080                 PADDR (msg_out_done),
3081
3082 }/*-------------------------< MSG_EXT_3 >----------------*/,{
3083         SCR_CLR (SCR_ACK),
3084                 0,
3085         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3086                 PADDR (dispatch),
3087         /*
3088         **      get extended message code.
3089         */
3090         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3091                 NADDR (msgin[2]),
3092         SCR_JUMP ^ IFTRUE (DATA (M_X_SYNC_REQ)),
3093                 PADDRH (msg_sdtr),
3094         /*
3095         **      unknown extended message
3096         */
3097         SCR_JUMP,
3098                 PADDR (msg_bad)
3099
3100 }/*-------------------------< MSG_SDTR >-----------------*/,{
3101         SCR_CLR (SCR_ACK),
3102                 0,
3103         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3104                 PADDR (dispatch),
3105         /*
3106         **      get period and offset
3107         */
3108         SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
3109                 NADDR (msgin[3]),
3110         /*
3111         **      let the host do the real work.
3112         */
3113         SCR_INT,
3114                 SIR_NEGO_SYNC,
3115         /*
3116         **      let the target fetch our answer.
3117         */
3118         SCR_SET (SCR_ATN),
3119                 0,
3120         SCR_CLR (SCR_ACK),
3121                 0,
3122         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3123                 PADDRH (nego_bad_phase),
3124
3125 }/*-------------------------< SEND_SDTR >-------------*/,{
3126         /*
3127         **      Send the M_X_SYNC_REQ
3128         */
3129         SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
3130                 NADDR (msgout),
3131         SCR_COPY (1),
3132                 NADDR (msgout),
3133                 NADDR (lastmsg),
3134         SCR_JUMP,
3135                 PADDR (msg_out_done),
3136
3137 }/*-------------------------< NEGO_BAD_PHASE >------------*/,{
3138         SCR_INT,
3139                 SIR_NEGO_PROTO,
3140         SCR_JUMP,
3141                 PADDR (dispatch),
3142
3143 }/*-------------------------< MSG_OUT_ABORT >-------------*/,{
3144         /*
3145         **      After ABORT message,
3146         **
3147         **      expect an immediate disconnect, ...
3148         */
3149         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3150                 0,
3151         SCR_CLR (SCR_ACK|SCR_ATN),
3152                 0,
3153         SCR_WAIT_DISC,
3154                 0,
3155         /*
3156         **      ... and set the status to "ABORTED"
3157         */
3158         SCR_LOAD_REG (HS_REG, HS_ABORTED),
3159                 0,
3160         SCR_JUMP,
3161                 PADDR (cleanup),
3162
3163 }/*-------------------------< HDATA_IN >-------------------*/,{
3164 /*
3165 **      Because the size depends on the
3166 **      #define MAX_SCATTERH parameter,
3167 **      it is filled in at runtime.
3168 **
3169 **  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
3170 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
3171 **  ||          PADDR (dispatch),
3172 **  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
3173 **  ||          offsetof (struct dsb, data[ i]),
3174 **  ##===================================================
3175 **
3176 **---------------------------------------------------------
3177 */
3178 0
3179 }/*-------------------------< HDATA_IN2 >------------------*/,{
3180         SCR_JUMP,
3181                 PADDR (data_in),
3182
3183 }/*-------------------------< HDATA_OUT >-------------------*/,{
3184 /*
3185 **      Because the size depends on the
3186 **      #define MAX_SCATTERH parameter,
3187 **      it is filled in at runtime.
3188 **
3189 **  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
3190 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
3191 **  ||          PADDR (dispatch),
3192 **  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
3193 **  ||          offsetof (struct dsb, data[ i]),
3194 **  ##===================================================
3195 **
3196 **---------------------------------------------------------
3197 */
3198 0
3199 }/*-------------------------< HDATA_OUT2 >------------------*/,{
3200         SCR_JUMP,
3201                 PADDR (data_out),
3202
3203 }/*-------------------------< RESET >----------------------*/,{
3204         /*
3205         **      Send a M_RESET message if bad IDENTIFY 
3206         **      received on reselection.
3207         */
3208         SCR_LOAD_REG (scratcha, M_ABORT_TAG),
3209                 0,
3210         SCR_JUMP,
3211                 PADDRH (abort_resel),
3212 }/*-------------------------< ABORTTAG >-------------------*/,{
3213         /*
3214         **      Abort a wrong tag received on reselection.
3215         */
3216         SCR_LOAD_REG (scratcha, M_ABORT_TAG),
3217                 0,
3218         SCR_JUMP,
3219                 PADDRH (abort_resel),
3220 }/*-------------------------< ABORT >----------------------*/,{
3221         /*
3222         **      Abort a reselection when no active CCB.
3223         */
3224         SCR_LOAD_REG (scratcha, M_ABORT),
3225                 0,
3226 }/*-------------------------< ABORT_RESEL >----------------*/,{
3227         SCR_COPY (1),
3228                 RADDR (scratcha),
3229                 NADDR (msgout),
3230         SCR_SET (SCR_ATN),
3231                 0,
3232         SCR_CLR (SCR_ACK),
3233                 0,
3234         /*
3235         **      and send it.
3236         **      we expect an immediate disconnect
3237         */
3238         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3239                 0,
3240         SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
3241                 NADDR (msgout),
3242         SCR_COPY (1),
3243                 NADDR (msgout),
3244                 NADDR (lastmsg),
3245         SCR_CLR (SCR_ACK|SCR_ATN),
3246                 0,
3247         SCR_WAIT_DISC,
3248                 0,
3249         SCR_JUMP,
3250                 PADDR (start),
3251 }/*-------------------------< RESEND_IDENT >-------------------*/,{
3252         /*
3253         **      The target stays in MSG OUT phase after having acked 
3254         **      Identify [+ Tag [+ Extended message ]]. Targets shall
3255         **      behave this way on parity error.
3256         **      We must send it again all the messages.
3257         */
3258         SCR_SET (SCR_ATN), /* Shall be asserted 2 deskew delays before the  */
3259                 0,         /* 1rst ACK = 90 ns. Hope the NCR is'nt too fast */
3260         SCR_JUMP,
3261                 PADDR (send_ident),
3262 }/*-------------------------< CLRATN_GO_ON >-------------------*/,{
3263         SCR_CLR (SCR_ATN),
3264                 0,
3265         SCR_JUMP,
3266 }/*-------------------------< NXTDSP_GO_ON >-------------------*/,{
3267                 0,
3268 }/*-------------------------< SDATA_IN >-------------------*/,{
3269         SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
3270                 PADDR (dispatch),
3271         SCR_MOVE_TBL ^ SCR_DATA_IN,
3272                 offsetof (struct dsb, sense),
3273         SCR_CALL,
3274                 PADDR (dispatch),
3275         SCR_JUMP,
3276                 PADDR (no_data),
3277 }/*-------------------------< DATA_IO >--------------------*/,{
3278         /*
3279         **      We jump here if the data direction was unknown at the 
3280         **      time we had to queue the command to the scripts processor.
3281         **      Pointers had been set as follow in this situation:
3282         **        savep   -->   DATA_IO
3283         **        lastp   -->   start pointer when DATA_IN
3284         **        goalp   -->   goal  pointer when DATA_IN
3285         **        wlastp  -->   start pointer when DATA_OUT
3286         **        wgoalp  -->   goal  pointer when DATA_OUT
3287         **      This script sets savep/lastp/goalp according to the 
3288         **      direction chosen by the target.
3289         */
3290         SCR_JUMPR ^ IFTRUE (WHEN (SCR_DATA_OUT)),
3291                 32,
3292         /*
3293         **      Direction is DATA IN.
3294         **      Warning: we jump here, even when phase is DATA OUT.
3295         */
3296         SCR_COPY (4),
3297                 NADDR (header.lastp),
3298                 NADDR (header.savep),
3299
3300         /*
3301         **      Jump to the SCRIPTS according to actual direction.
3302         */
3303         SCR_COPY (4),
3304                 NADDR (header.savep),
3305                 RADDR (temp),
3306         SCR_RETURN,
3307                 0,
3308         /*
3309         **      Direction is DATA OUT.
3310         */
3311         SCR_COPY (4),
3312                 NADDR (header.wlastp),
3313                 NADDR (header.lastp),
3314         SCR_COPY (4),
3315                 NADDR (header.wgoalp),
3316                 NADDR (header.goalp),
3317         SCR_JUMPR,
3318                 -64,
3319 }/*-------------------------< BAD_IDENTIFY >---------------*/,{
3320         /*
3321         **      If message phase but not an IDENTIFY,
3322         **      get some help from the C code.
3323         **      Old SCSI device may behave so.
3324         */
3325         SCR_JUMPR ^ IFTRUE (MASK (0x80, 0x80)),
3326                 16,
3327         SCR_INT,
3328                 SIR_RESEL_NO_IDENTIFY,
3329         SCR_JUMP,
3330                 PADDRH (reset),
3331         /*
3332         **      Message is an IDENTIFY, but lun is unknown.
3333         **      Read the message, since we got it directly 
3334         **      from the SCSI BUS data lines.
3335         **      Signal problem to C code for logging the event.
3336         **      Send a M_ABORT to clear all pending tasks.
3337         */
3338         SCR_INT,
3339                 SIR_RESEL_BAD_LUN,
3340         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3341                 NADDR (msgin),
3342         SCR_JUMP,
3343                 PADDRH (abort),
3344 }/*-------------------------< BAD_I_T_L >------------------*/,{
3345         /*
3346         **      We donnot have a task for that I_T_L.
3347         **      Signal problem to C code for logging the event.
3348         **      Send a M_ABORT message.
3349         */
3350         SCR_INT,
3351                 SIR_RESEL_BAD_I_T_L,
3352         SCR_JUMP,
3353                 PADDRH (abort),
3354 }/*-------------------------< BAD_I_T_L_Q >----------------*/,{
3355         /*
3356         **      We donnot have a task that matches the tag.
3357         **      Signal problem to C code for logging the event.
3358         **      Send a M_ABORTTAG message.
3359         */
3360         SCR_INT,
3361                 SIR_RESEL_BAD_I_T_L_Q,
3362         SCR_JUMP,
3363                 PADDRH (aborttag),
3364 }/*-------------------------< BAD_TARGET >-----------------*/,{
3365         /*
3366         **      We donnot know the target that reselected us.
3367         **      Grab the first message if any (IDENTIFY).
3368         **      Signal problem to C code for logging the event.
3369         **      M_RESET message.
3370         */
3371         SCR_INT,
3372                 SIR_RESEL_BAD_TARGET,
3373         SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
3374                 8,
3375         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3376                 NADDR (msgin),
3377         SCR_JUMP,
3378                 PADDRH (reset),
3379 }/*-------------------------< BAD_STATUS >-----------------*/,{
3380         /*
3381         **      If command resulted in either QUEUE FULL,
3382         **      CHECK CONDITION or COMMAND TERMINATED,
3383         **      call the C code.
3384         */
3385         SCR_INT ^ IFTRUE (DATA (S_QUEUE_FULL)),
3386                 SIR_BAD_STATUS,
3387         SCR_INT ^ IFTRUE (DATA (S_CHECK_COND)),
3388                 SIR_BAD_STATUS,
3389         SCR_INT ^ IFTRUE (DATA (S_TERMINATED)),
3390                 SIR_BAD_STATUS,
3391         SCR_RETURN,
3392                 0,
3393 }/*-------------------------< START_RAM >-------------------*/,{
3394         /*
3395         **      Load the script into on-chip RAM, 
3396         **      and jump to start point.
3397         */
3398         SCR_COPY_F (4),
3399                 RADDR (scratcha),
3400                 PADDRH (start_ram0),
3401         /*
3402         **      Flush script prefetch if required
3403         */
3404         PREFETCH_FLUSH
3405         SCR_COPY (sizeof (struct script)),
3406 }/*-------------------------< START_RAM0 >--------------------*/,{
3407                 0,
3408                 PADDR (start),
3409         SCR_JUMP,
3410                 PADDR (start),
3411 }/*-------------------------< STO_RESTART >-------------------*/,{
3412         /*
3413         **
3414         **      Repair start queue (e.g. next time use the next slot) 
3415         **      and jump to start point.
3416         */
3417         SCR_COPY (4),
3418                 RADDR (temp),
3419                 PADDR (startpos),
3420         SCR_JUMP,
3421                 PADDR (start),
3422 }/*-------------------------< WAIT_DMA >-------------------*/,{
3423         /*
3424         **      For HP Zalon/53c720 systems, the Zalon interface
3425         **      between CPU and 53c720 does prefetches, which causes
3426         **      problems with self modifying scripts.  The problem
3427         **      is overcome by calling a dummy subroutine after each
3428         **      modification, to force a refetch of the script on
3429         **      return from the subroutine.
3430         */
3431         SCR_RETURN,
3432                 0,
3433 }/*-------------------------< SNOOPTEST >-------------------*/,{
3434         /*
3435         **      Read the variable.
3436         */
3437         SCR_COPY (4),
3438                 NADDR(ncr_cache),
3439                 RADDR (scratcha),
3440         /*
3441         **      Write the variable.
3442         */
3443         SCR_COPY (4),
3444                 RADDR (temp),
3445                 NADDR(ncr_cache),
3446         /*
3447         **      Read back the variable.
3448         */
3449         SCR_COPY (4),
3450                 NADDR(ncr_cache),
3451                 RADDR (temp),
3452 }/*-------------------------< SNOOPEND >-------------------*/,{
3453         /*
3454         **      And stop.
3455         */
3456         SCR_INT,
3457                 99,
3458 }/*--------------------------------------------------------*/
3459 };
3460
3461 /*==========================================================
3462 **
3463 **
3464 **      Fill in #define dependent parts of the script
3465 **
3466 **
3467 **==========================================================
3468 */
3469
3470 void __init ncr_script_fill (struct script * scr, struct scripth * scrh)
3471 {
3472         int     i;
3473         ncrcmd  *p;
3474
3475         p = scrh->tryloop;
3476         for (i=0; i<MAX_START; i++) {
3477                 *p++ =SCR_CALL;
3478                 *p++ =PADDR (idle);
3479         }
3480
3481         BUG_ON((u_long)p != (u_long)&scrh->tryloop + sizeof (scrh->tryloop));
3482
3483 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
3484
3485         p = scrh->done_queue;
3486         for (i = 0; i<MAX_DONE; i++) {
3487                 *p++ =SCR_COPY (sizeof(struct ccb *));
3488                 *p++ =NADDR (header.cp);
3489                 *p++ =NADDR (ccb_done[i]);
3490                 *p++ =SCR_CALL;
3491                 *p++ =PADDR (done_end);
3492         }
3493
3494         BUG_ON((u_long)p != (u_long)&scrh->done_queue+sizeof(scrh->done_queue));
3495
3496 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
3497
3498         p = scrh->hdata_in;
3499         for (i=0; i<MAX_SCATTERH; i++) {
3500                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
3501                 *p++ =PADDR (dispatch);
3502                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3503                 *p++ =offsetof (struct dsb, data[i]);
3504         }
3505
3506         BUG_ON((u_long)p != (u_long)&scrh->hdata_in + sizeof (scrh->hdata_in));
3507
3508         p = scr->data_in;
3509         for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
3510                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
3511                 *p++ =PADDR (dispatch);
3512                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3513                 *p++ =offsetof (struct dsb, data[i]);
3514         }
3515
3516         BUG_ON((u_long)p != (u_long)&scr->data_in + sizeof (scr->data_in));
3517
3518         p = scrh->hdata_out;
3519         for (i=0; i<MAX_SCATTERH; i++) {
3520                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
3521                 *p++ =PADDR (dispatch);
3522                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3523                 *p++ =offsetof (struct dsb, data[i]);
3524         }
3525
3526         BUG_ON((u_long)p != (u_long)&scrh->hdata_out + sizeof (scrh->hdata_out));
3527
3528         p = scr->data_out;
3529         for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
3530                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
3531                 *p++ =PADDR (dispatch);
3532                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3533                 *p++ =offsetof (struct dsb, data[i]);
3534         }
3535
3536         BUG_ON((u_long) p != (u_long)&scr->data_out + sizeof (scr->data_out));
3537 }
3538
3539 /*==========================================================
3540 **
3541 **
3542 **      Copy and rebind a script.
3543 **
3544 **
3545 **==========================================================
3546 */
3547
3548 static void __init 
3549 ncr_script_copy_and_bind (struct ncb *np, ncrcmd *src, ncrcmd *dst, int len)
3550 {
3551         ncrcmd  opcode, new, old, tmp1, tmp2;
3552         ncrcmd  *start, *end;
3553         int relocs;
3554         int opchanged = 0;
3555
3556         start = src;
3557         end = src + len/4;
3558
3559         while (src < end) {
3560
3561                 opcode = *src++;
3562                 *dst++ = cpu_to_scr(opcode);
3563
3564                 /*
3565                 **      If we forget to change the length
3566                 **      in struct script, a field will be
3567                 **      padded with 0. This is an illegal
3568                 **      command.
3569                 */
3570
3571                 if (opcode == 0) {
3572                         printk (KERN_ERR "%s: ERROR0 IN SCRIPT at %d.\n",
3573                                 ncr_name(np), (int) (src-start-1));
3574                         mdelay(1000);
3575                 }
3576
3577                 if (DEBUG_FLAGS & DEBUG_SCRIPT)
3578                         printk (KERN_DEBUG "%p:  <%x>\n",
3579                                 (src-1), (unsigned)opcode);
3580
3581                 /*
3582                 **      We don't have to decode ALL commands
3583                 */
3584                 switch (opcode >> 28) {
3585
3586                 case 0xc:
3587                         /*
3588                         **      COPY has TWO arguments.
3589                         */
3590                         relocs = 2;
3591                         tmp1 = src[0];
3592 #ifdef  RELOC_KVAR
3593                         if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
3594                                 tmp1 = 0;
3595 #endif
3596                         tmp2 = src[1];
3597 #ifdef  RELOC_KVAR
3598                         if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
3599                                 tmp2 = 0;
3600 #endif
3601                         if ((tmp1 ^ tmp2) & 3) {
3602                                 printk (KERN_ERR"%s: ERROR1 IN SCRIPT at %d.\n",
3603                                         ncr_name(np), (int) (src-start-1));
3604                                 mdelay(1000);
3605                         }
3606                         /*
3607                         **      If PREFETCH feature not enabled, remove 
3608                         **      the NO FLUSH bit if present.
3609                         */
3610                         if ((opcode & SCR_NO_FLUSH) && !(np->features & FE_PFEN)) {
3611                                 dst[-1] = cpu_to_scr(opcode & ~SCR_NO_FLUSH);
3612                                 ++opchanged;
3613                         }
3614                         break;
3615
3616                 case 0x0:
3617                         /*
3618                         **      MOVE (absolute address)
3619                         */
3620                         relocs = 1;
3621                         break;
3622
3623                 case 0x8:
3624                         /*
3625                         **      JUMP / CALL
3626                         **      don't relocate if relative :-)
3627                         */
3628                         if (opcode & 0x00800000)
3629                                 relocs = 0;
3630                         else
3631                                 relocs = 1;
3632                         break;
3633
3634                 case 0x4:
3635                 case 0x5:
3636                 case 0x6:
3637                 case 0x7:
3638                         relocs = 1;
3639                         break;
3640
3641                 default:
3642                         relocs = 0;
3643                         break;
3644                 }
3645
3646                 if (relocs) {
3647                         while (relocs--) {
3648                                 old = *src++;
3649
3650                                 switch (old & RELOC_MASK) {
3651                                 case RELOC_REGISTER:
3652                                         new = (old & ~RELOC_MASK) + np->paddr;
3653                                         break;
3654                                 case RELOC_LABEL:
3655                                         new = (old & ~RELOC_MASK) + np->p_script;
3656                                         break;
3657                                 case RELOC_LABELH:
3658                                         new = (old & ~RELOC_MASK) + np->p_scripth;
3659                                         break;
3660                                 case RELOC_SOFTC:
3661                                         new = (old & ~RELOC_MASK) + np->p_ncb;
3662                                         break;
3663 #ifdef  RELOC_KVAR
3664                                 case RELOC_KVAR:
3665                                         if (((old & ~RELOC_MASK) <
3666                                              SCRIPT_KVAR_FIRST) ||
3667                                             ((old & ~RELOC_MASK) >
3668                                              SCRIPT_KVAR_LAST))
3669                                                 panic("ncr KVAR out of range");
3670                                         new = vtophys(script_kvars[old &
3671                                             ~RELOC_MASK]);
3672                                         break;
3673 #endif
3674                                 case 0:
3675                                         /* Don't relocate a 0 address. */
3676                                         if (old == 0) {
3677                                                 new = old;
3678                                                 break;
3679                                         }
3680                                         /* fall through */
3681                                 default:
3682                                         panic("ncr_script_copy_and_bind: weird relocation %x\n", old);
3683                                         break;
3684                                 }
3685
3686                                 *dst++ = cpu_to_scr(new);
3687                         }
3688                 } else
3689                         *dst++ = cpu_to_scr(*src++);
3690
3691         }
3692 }
3693
3694 /*
3695 **      Linux host data structure
3696 */
3697
3698 struct host_data {
3699      struct ncb *ncb;
3700 };
3701
3702 #define PRINT_ADDR(cmd, arg...) dev_info(&cmd->device->sdev_gendev , ## arg)
3703
3704 static void ncr_print_msg(struct ccb *cp, char *label, u_char *msg)
3705 {
3706         PRINT_ADDR(cp->cmd, "%s: ", label);
3707
3708         spi_print_msg(msg);
3709         printk("\n");
3710 }
3711
3712 /*==========================================================
3713 **
3714 **      NCR chip clock divisor table.
3715 **      Divisors are multiplied by 10,000,000 in order to make 
3716 **      calculations more simple.
3717 **
3718 **==========================================================
3719 */
3720
3721 #define _5M 5000000
3722 static u_long div_10M[] =
3723         {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3724
3725
3726 /*===============================================================
3727 **
3728 **      Prepare io register values used by ncr_init() according 
3729 **      to selected and supported features.
3730 **
3731 **      NCR chips allow burst lengths of 2, 4, 8, 16, 32, 64, 128 
3732 **      transfers. 32,64,128 are only supported by 875 and 895 chips.
3733 **      We use log base 2 (burst length) as internal code, with 
3734 **      value 0 meaning "burst disabled".
3735 **
3736 **===============================================================
3737 */
3738
3739 /*
3740  *      Burst length from burst code.
3741  */
3742 #define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3743
3744 /*
3745  *      Burst code from io register bits.  Burst enable is ctest0 for c720
3746  */
3747 #define burst_code(dmode, ctest0) \
3748         (ctest0) & 0x80 ? 0 : (((dmode) & 0xc0) >> 6) + 1
3749
3750 /*
3751  *      Set initial io register bits from burst code.
3752  */
3753 static inline void ncr_init_burst(struct ncb *np, u_char bc)
3754 {
3755         u_char *be = &np->rv_ctest0;
3756         *be             &= ~0x80;
3757         np->rv_dmode    &= ~(0x3 << 6);
3758         np->rv_ctest5   &= ~0x4;
3759
3760         if (!bc) {
3761                 *be             |= 0x80;
3762         } else {
3763                 --bc;
3764                 np->rv_dmode    |= ((bc & 0x3) << 6);
3765                 np->rv_ctest5   |= (bc & 0x4);
3766         }
3767 }
3768
3769 static void __init ncr_prepare_setting(struct ncb *np)
3770 {
3771         u_char  burst_max;
3772         u_long  period;
3773         int i;
3774
3775         /*
3776         **      Save assumed BIOS setting
3777         */
3778
3779         np->sv_scntl0   = INB(nc_scntl0) & 0x0a;
3780         np->sv_scntl3   = INB(nc_scntl3) & 0x07;
3781         np->sv_dmode    = INB(nc_dmode)  & 0xce;
3782         np->sv_dcntl    = INB(nc_dcntl)  & 0xa8;
3783         np->sv_ctest0   = INB(nc_ctest0) & 0x84;
3784         np->sv_ctest3   = INB(nc_ctest3) & 0x01;
3785         np->sv_ctest4   = INB(nc_ctest4) & 0x80;
3786         np->sv_ctest5   = INB(nc_ctest5) & 0x24;
3787         np->sv_gpcntl   = INB(nc_gpcntl);
3788         np->sv_stest2   = INB(nc_stest2) & 0x20;
3789         np->sv_stest4   = INB(nc_stest4);
3790
3791         /*
3792         **      Wide ?
3793         */
3794
3795         np->maxwide     = (np->features & FE_WIDE)? 1 : 0;
3796
3797         /*
3798          *  Guess the frequency of the chip's clock.
3799          */
3800         if (np->features & FE_ULTRA)
3801                 np->clock_khz = 80000;
3802         else
3803                 np->clock_khz = 40000;
3804
3805         /*
3806          *  Get the clock multiplier factor.
3807          */
3808         if      (np->features & FE_QUAD)
3809                 np->multiplier  = 4;
3810         else if (np->features & FE_DBLR)
3811                 np->multiplier  = 2;
3812         else
3813                 np->multiplier  = 1;
3814
3815         /*
3816          *  Measure SCSI clock frequency for chips 
3817          *  it may vary from assumed one.
3818          */
3819         if (np->features & FE_VARCLK)
3820                 ncr_getclock(np, np->multiplier);
3821
3822         /*
3823          * Divisor to be used for async (timer pre-scaler).
3824          */
3825         i = np->clock_divn - 1;
3826         while (--i >= 0) {
3827                 if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz > div_10M[i]) {
3828                         ++i;
3829                         break;
3830                 }
3831         }
3832         np->rv_scntl3 = i+1;
3833
3834         /*
3835          * Minimum synchronous period factor supported by the chip.
3836          * Btw, 'period' is in tenths of nanoseconds.
3837          */
3838
3839         period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
3840         if      (period <= 250)         np->minsync = 10;
3841         else if (period <= 303)         np->minsync = 11;
3842         else if (period <= 500)         np->minsync = 12;
3843         else                            np->minsync = (period + 40 - 1) / 40;
3844
3845         /*
3846          * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
3847          */
3848
3849         if      (np->minsync < 25 && !(np->features & FE_ULTRA))
3850                 np->minsync = 25;
3851
3852         /*
3853          * Maximum synchronous period factor supported by the chip.
3854          */
3855
3856         period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
3857         np->maxsync = period > 2540 ? 254 : period / 10;
3858
3859         /*
3860         **      Prepare initial value of other IO registers
3861         */
3862 #if defined SCSI_NCR_TRUST_BIOS_SETTING
3863         np->rv_scntl0   = np->sv_scntl0;
3864         np->rv_dmode    = np->sv_dmode;
3865         np->rv_dcntl    = np->sv_dcntl;
3866         np->rv_ctest0   = np->sv_ctest0;
3867         np->rv_ctest3   = np->sv_ctest3;
3868         np->rv_ctest4   = np->sv_ctest4;
3869         np->rv_ctest5   = np->sv_ctest5;
3870         burst_max       = burst_code(np->sv_dmode, np->sv_ctest0);
3871 #else
3872
3873         /*
3874         **      Select burst length (dwords)
3875         */
3876         burst_max       = driver_setup.burst_max;
3877         if (burst_max == 255)
3878                 burst_max = burst_code(np->sv_dmode, np->sv_ctest0);
3879         if (burst_max > 7)
3880                 burst_max = 7;
3881         if (burst_max > np->maxburst)
3882                 burst_max = np->maxburst;
3883
3884         /*
3885         **      Select all supported special features
3886         */
3887         if (np->features & FE_ERL)
3888                 np->rv_dmode    |= ERL;         /* Enable Read Line */
3889         if (np->features & FE_BOF)
3890                 np->rv_dmode    |= BOF;         /* Burst Opcode Fetch */
3891         if (np->features & FE_ERMP)
3892                 np->rv_dmode    |= ERMP;        /* Enable Read Multiple */
3893         if (np->features & FE_PFEN)
3894                 np->rv_dcntl    |= PFEN;        /* Prefetch Enable */
3895         if (np->features & FE_CLSE)
3896                 np->rv_dcntl    |= CLSE;        /* Cache Line Size Enable */
3897         if (np->features & FE_WRIE)
3898                 np->rv_ctest3   |= WRIE;        /* Write and Invalidate */
3899         if (np->features & FE_DFS)
3900                 np->rv_ctest5   |= DFS;         /* Dma Fifo Size */
3901         if (np->features & FE_MUX)
3902                 np->rv_ctest4   |= MUX;         /* Host bus multiplex mode */
3903         if (np->features & FE_EA)
3904                 np->rv_dcntl    |= EA;          /* Enable ACK */
3905         if (np->features & FE_EHP)
3906                 np->rv_ctest0   |= EHP;         /* Even host parity */
3907
3908         /*
3909         **      Select some other
3910         */
3911         if (driver_setup.master_parity)
3912                 np->rv_ctest4   |= MPEE;        /* Master parity checking */
3913         if (driver_setup.scsi_parity)
3914                 np->rv_scntl0   |= 0x0a;        /*  full arb., ena parity, par->ATN  */
3915
3916         /*
3917         **  Get SCSI addr of host adapter (set by bios?).
3918         */
3919         if (np->myaddr == 255) {
3920                 np->myaddr = INB(nc_scid) & 0x07;
3921                 if (!np->myaddr)
3922                         np->myaddr = SCSI_NCR_MYADDR;
3923         }
3924
3925 #endif /* SCSI_NCR_TRUST_BIOS_SETTING */
3926
3927         /*
3928          *      Prepare initial io register bits for burst length
3929          */
3930         ncr_init_burst(np, burst_max);
3931
3932         /*
3933         **      Set SCSI BUS mode.
3934         **
3935         **      - ULTRA2 chips (895/895A/896) report the current 
3936         **        BUS mode through the STEST4 IO register.
3937         **      - For previous generation chips (825/825A/875), 
3938         **        user has to tell us how to check against HVD, 
3939         **        since a 100% safe algorithm is not possible.
3940         */
3941         np->scsi_mode = SMODE_SE;
3942         if (np->features & FE_DIFF) {
3943                 switch(driver_setup.diff_support) {
3944                 case 4: /* Trust previous settings if present, then GPIO3 */
3945                         if (np->sv_scntl3) {
3946                                 if (np->sv_stest2 & 0x20)
3947                                         np->scsi_mode = SMODE_HVD;
3948                                 break;
3949                         }
3950                 case 3: /* SYMBIOS controllers report HVD through GPIO3 */
3951                         if (INB(nc_gpreg) & 0x08)
3952                                 break;
3953                 case 2: /* Set HVD unconditionally */
3954                         np->scsi_mode = SMODE_HVD;
3955                 case 1: /* Trust previous settings for HVD */
3956                         if (np->sv_stest2 & 0x20)
3957                                 np->scsi_mode = SMODE_HVD;
3958                         break;
3959                 default:/* Don't care about HVD */      
3960                         break;
3961                 }
3962         }
3963         if (np->scsi_mode == SMODE_HVD)
3964                 np->rv_stest2 |= 0x20;
3965
3966         /*
3967         **      Set LED support from SCRIPTS.
3968         **      Ignore this feature for boards known to use a 
3969         **      specific GPIO wiring and for the 895A or 896 
3970         **      that drive the LED directly.
3971         **      Also probe initial setting of GPIO0 as output.
3972         */
3973         if ((driver_setup.led_pin) &&
3974             !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
3975                 np->features |= FE_LED0;
3976
3977         /*
3978         **      Set irq mode.
3979         */
3980         switch(driver_setup.irqm & 3) {
3981         case 2:
3982                 np->rv_dcntl    |= IRQM;
3983                 break;
3984         case 1:
3985                 np->rv_dcntl    |= (np->sv_dcntl & IRQM);
3986                 break;
3987         default:
3988                 break;
3989         }
3990
3991         /*
3992         **      Configure targets according to driver setup.
3993         **      Allow to override sync, wide and NOSCAN from 
3994         **      boot command line.
3995         */
3996         for (i = 0 ; i < MAX_TARGET ; i++) {
3997                 struct tcb *tp = &np->target[i];
3998
3999                 tp->usrsync = driver_setup.default_sync;
4000                 tp->usrwide = driver_setup.max_wide;
4001                 tp->usrtags = MAX_TAGS;
4002                 tp->period = 0xffff;
4003                 if (!driver_setup.disconnection)
4004                         np->target[i].usrflag = UF_NODISC;
4005         }
4006
4007         /*
4008         **      Announce all that stuff to user.
4009         */
4010
4011         printk(KERN_INFO "%s: ID %d, Fast-%d%s%s\n", ncr_name(np),
4012                 np->myaddr,
4013                 np->minsync < 12 ? 40 : (np->minsync < 25 ? 20 : 10),
4014                 (np->rv_scntl0 & 0xa)   ? ", Parity Checking"   : ", NO Parity",
4015                 (np->rv_stest2 & 0x20)  ? ", Differential"      : "");
4016
4017         if (bootverbose > 1) {
4018                 printk (KERN_INFO "%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
4019                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
4020                         ncr_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
4021                         np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
4022
4023                 printk (KERN_INFO "%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
4024                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
4025                         ncr_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
4026                         np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
4027         }
4028
4029         if (bootverbose && np->paddr2)
4030                 printk (KERN_INFO "%s: on-chip RAM at 0x%lx\n",
4031                         ncr_name(np), np->paddr2);
4032 }
4033
4034 /*==========================================================
4035 **
4036 **
4037 **      Done SCSI commands list management.
4038 **
4039 **      We donnot enter the scsi_done() callback immediately 
4040 **      after a command has been seen as completed but we 
4041 **      insert it into a list which is flushed outside any kind 
4042 **      of driver critical section.
4043 **      This allows to do minimal stuff under interrupt and 
4044 **      inside critical sections and to also avoid locking up 
4045 **      on recursive calls to driver entry points under SMP.
4046 **      In fact, the only kernel point which is entered by the 
4047 **      driver with a driver lock set is kmalloc(GFP_ATOMIC) 
4048 **      that shall not reenter the driver under any circumstances,
4049 **      AFAIK.
4050 **
4051 **==========================================================
4052 */
4053 static inline void ncr_queue_done_cmd(struct ncb *np, struct scsi_cmnd *cmd)
4054 {
4055         unmap_scsi_data(np, cmd);
4056         cmd->host_scribble = (char *) np->done_list;
4057         np->done_list = cmd;
4058 }
4059
4060 static inline void ncr_flush_done_cmds(struct scsi_cmnd *lcmd)
4061 {
4062         struct scsi_cmnd *cmd;
4063
4064         while (lcmd) {
4065                 cmd = lcmd;
4066                 lcmd = (struct scsi_cmnd *) cmd->host_scribble;
4067                 cmd->scsi_done(cmd);
4068         }
4069 }
4070
4071 /*==========================================================
4072 **
4073 **
4074 **      Prepare the next negotiation message if needed.
4075 **
4076 **      Fill in the part of message buffer that contains the 
4077 **      negotiation and the nego_status field of the CCB.
4078 **      Returns the size of the message in bytes.
4079 **
4080 **
4081 **==========================================================
4082 */
4083
4084
4085 static int ncr_prepare_nego(struct ncb *np, struct ccb *cp, u_char *msgptr)
4086 {
4087         struct tcb *tp = &np->target[cp->target];
4088         int msglen = 0;
4089         int nego = 0;
4090         struct scsi_target *starget = tp->starget;
4091
4092         /* negotiate wide transfers ?  */
4093         if (!tp->widedone) {
4094                 if (spi_support_wide(starget)) {
4095                         nego = NS_WIDE;
4096                 } else
4097                         tp->widedone=1;
4098         }
4099
4100         /* negotiate synchronous transfers?  */
4101         if (!nego && !tp->period) {
4102                 if (spi_support_sync(starget)) {
4103                         nego = NS_SYNC;
4104                 } else {
4105                         tp->period  =0xffff;
4106                         dev_info(&starget->dev, "target did not report SYNC.\n");
4107                 }
4108         }
4109
4110         switch (nego) {
4111         case NS_SYNC:
4112                 msgptr[msglen++] = M_EXTENDED;
4113                 msgptr[msglen++] = 3;
4114                 msgptr[msglen++] = M_X_SYNC_REQ;
4115                 msgptr[msglen++] = tp->maxoffs ? tp->minsync : 0;
4116                 msgptr[msglen++] = tp->maxoffs;
4117                 break;
4118         case NS_WIDE:
4119                 msgptr[msglen++] = M_EXTENDED;
4120                 msgptr[msglen++] = 2;
4121                 msgptr[msglen++] = M_X_WIDE_REQ;
4122                 msgptr[msglen++] = tp->usrwide;
4123                 break;
4124         }
4125
4126         cp->nego_status = nego;
4127
4128         if (nego) {
4129                 tp->nego_cp = cp;
4130                 if (DEBUG_FLAGS & DEBUG_NEGO) {
4131                         ncr_print_msg(cp, nego == NS_WIDE ?
4132                                           "wide msgout":"sync_msgout", msgptr);
4133                 }
4134         }
4135
4136         return msglen;
4137 }
4138
4139
4140
4141 /*==========================================================
4142 **
4143 **
4144 **      Start execution of a SCSI command.
4145 **      This is called from the generic SCSI driver.
4146 **
4147 **
4148 **==========================================================
4149 */
4150 static int ncr_queue_command (struct ncb *np, struct scsi_cmnd *cmd)
4151 {
4152         struct scsi_device *sdev = cmd->device;
4153         struct tcb *tp = &np->target[sdev->id];
4154         struct lcb *lp = tp->lp[sdev->lun];
4155         struct ccb *cp;
4156
4157         int     segments;
4158         u_char  idmsg, *msgptr;
4159         u32     msglen;
4160         int     direction;
4161         u32     lastp, goalp;
4162
4163         /*---------------------------------------------
4164         **
4165         **      Some shortcuts ...
4166         **
4167         **---------------------------------------------
4168         */
4169         if ((sdev->id == np->myaddr       ) ||
4170                 (sdev->id >= MAX_TARGET) ||
4171                 (sdev->lun    >= MAX_LUN   )) {
4172                 return(DID_BAD_TARGET);
4173         }
4174
4175         /*---------------------------------------------
4176         **
4177         **      Complete the 1st TEST UNIT READY command
4178         **      with error condition if the device is 
4179         **      flagged NOSCAN, in order to speed up 
4180         **      the boot.
4181         **
4182         **---------------------------------------------
4183         */
4184         if ((cmd->cmnd[0] == 0 || cmd->cmnd[0] == 0x12) && 
4185             (tp->usrflag & UF_NOSCAN)) {
4186                 tp->usrflag &= ~UF_NOSCAN;
4187                 return DID_BAD_TARGET;
4188         }
4189
4190         if (DEBUG_FLAGS & DEBUG_TINY) {
4191                 PRINT_ADDR(cmd, "CMD=%x ", cmd->cmnd[0]);
4192         }
4193
4194         /*---------------------------------------------------
4195         **
4196         **      Assign a ccb / bind cmd.
4197         **      If resetting, shorten settle_time if necessary
4198         **      in order to avoid spurious timeouts.
4199         **      If resetting or no free ccb,
4200         **      insert cmd into the waiting list.
4201         **
4202         **----------------------------------------------------
4203         */
4204         if (np->settle_time && cmd->timeout_per_command >= HZ) {
4205                 u_long tlimit = jiffies + cmd->timeout_per_command - HZ;
4206                 if (time_after(np->settle_time, tlimit))
4207                         np->settle_time = tlimit;
4208         }
4209
4210         if (np->settle_time || !(cp=ncr_get_ccb (np, cmd))) {
4211                 insert_into_waiting_list(np, cmd);
4212                 return(DID_OK);
4213         }
4214         cp->cmd = cmd;
4215
4216         /*----------------------------------------------------
4217         **
4218         **      Build the identify / tag / sdtr message
4219         **
4220         **----------------------------------------------------
4221         */
4222
4223         idmsg = M_IDENTIFY | sdev->lun;
4224
4225         if (cp ->tag != NO_TAG ||
4226                 (cp != np->ccb && np->disc && !(tp->usrflag & UF_NODISC)))
4227                 idmsg |= 0x40;
4228
4229         msgptr = cp->scsi_smsg;
4230         msglen = 0;
4231         msgptr[msglen++] = idmsg;
4232
4233         if (cp->tag != NO_TAG) {
4234                 char order = np->order;
4235
4236                 /*
4237                 **      Force ordered tag if necessary to avoid timeouts 
4238                 **      and to preserve interactivity.
4239                 */
4240                 if (lp && time_after(jiffies, lp->tags_stime)) {
4241                         if (lp->tags_smap) {
4242                                 order = M_ORDERED_TAG;
4243                                 if ((DEBUG_FLAGS & DEBUG_TAGS)||bootverbose>2){ 
4244                                         PRINT_ADDR(cmd,
4245                                                 "ordered tag forced.\n");
4246                                 }
4247                         }
4248                         lp->tags_stime = jiffies + 3*HZ;
4249                         lp->tags_smap = lp->tags_umap;
4250                 }
4251
4252                 if (order == 0) {
4253                         /*
4254                         **      Ordered write ops, unordered read ops.
4255                         */
4256                         switch (cmd->cmnd[0]) {
4257                         case 0x08:  /* READ_SMALL (6) */
4258                         case 0x28:  /* READ_BIG  (10) */
4259                         case 0xa8:  /* READ_HUGE (12) */
4260                                 order = M_SIMPLE_TAG;
4261                                 break;
4262                         default:
4263                                 order = M_ORDERED_TAG;
4264                         }
4265                 }
4266                 msgptr[msglen++] = order;
4267                 /*
4268                 **      Actual tags are numbered 1,3,5,..2*MAXTAGS+1,
4269                 **      since we may have to deal with devices that have 
4270                 **      problems with #TAG 0 or too great #TAG numbers.
4271                 */
4272                 msgptr[msglen++] = (cp->tag << 1) + 1;
4273         }
4274
4275         /*----------------------------------------------------
4276         **
4277         **      Build the data descriptors
4278         **
4279         **----------------------------------------------------
4280         */
4281
4282         direction = cmd->sc_data_direction;
4283         if (direction != DMA_NONE) {
4284                 segments = ncr_scatter(np, cp, cp->cmd);
4285                 if (segments < 0) {
4286                         ncr_free_ccb(np, cp);
4287                         return(DID_ERROR);
4288                 }
4289         }
4290         else {
4291                 cp->data_len = 0;
4292                 segments = 0;
4293         }
4294
4295         /*---------------------------------------------------
4296         **
4297         **      negotiation required?
4298         **
4299         **      (nego_status is filled by ncr_prepare_nego())
4300         **
4301         **---------------------------------------------------
4302         */
4303
4304         cp->nego_status = 0;
4305
4306         if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
4307                 msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
4308         }
4309
4310         /*----------------------------------------------------
4311         **
4312         **      Determine xfer direction.
4313         **
4314         **----------------------------------------------------
4315         */
4316         if (!cp->data_len)
4317                 direction = DMA_NONE;
4318
4319         /*
4320         **      If data direction is BIDIRECTIONAL, speculate FROM_DEVICE
4321         **      but prepare alternate pointers for TO_DEVICE in case 
4322         **      of our speculation will be just wrong.
4323         **      SCRIPTS will swap values if needed.
4324         */
4325         switch(direction) {
4326         case DMA_BIDIRECTIONAL:
4327         case DMA_TO_DEVICE:
4328                 goalp = NCB_SCRIPT_PHYS (np, data_out2) + 8;
4329                 if (segments <= MAX_SCATTERL)
4330                         lastp = goalp - 8 - (segments * 16);
4331                 else {
4332                         lastp = NCB_SCRIPTH_PHYS (np, hdata_out2);
4333                         lastp -= (segments - MAX_SCATTERL) * 16;
4334                 }
4335                 if (direction != DMA_BIDIRECTIONAL)
4336                         break;
4337                 cp->phys.header.wgoalp  = cpu_to_scr(goalp);
4338                 cp->phys.header.wlastp  = cpu_to_scr(lastp);
4339                 /* fall through */
4340         case DMA_FROM_DEVICE:
4341                 goalp = NCB_SCRIPT_PHYS (np, data_in2) + 8;
4342                 if (segments <= MAX_SCATTERL)
4343                         lastp = goalp - 8 - (segments * 16);
4344                 else {
4345                         lastp = NCB_SCRIPTH_PHYS (np, hdata_in2);
4346                         lastp -= (segments - MAX_SCATTERL) * 16;
4347                 }
4348                 break;
4349         default:
4350         case DMA_NONE:
4351                 lastp = goalp = NCB_SCRIPT_PHYS (np, no_data);
4352                 break;
4353         }
4354
4355         /*
4356         **      Set all pointers values needed by SCRIPTS.
4357         **      If direction is unknown, start at data_io.
4358         */
4359         cp->phys.header.lastp = cpu_to_scr(lastp);
4360         cp->phys.header.goalp = cpu_to_scr(goalp);
4361
4362         if (direction == DMA_BIDIRECTIONAL)
4363                 cp->phys.header.savep = 
4364                         cpu_to_scr(NCB_SCRIPTH_PHYS (np, data_io));
4365         else
4366                 cp->phys.header.savep= cpu_to_scr(lastp);
4367
4368         /*
4369         **      Save the initial data pointer in order to be able 
4370         **      to redo the command.
4371         */
4372         cp->startp = cp->phys.header.savep;
4373
4374         /*----------------------------------------------------
4375         **
4376         **      fill in ccb
4377         **
4378         **----------------------------------------------------
4379         **
4380         **
4381         **      physical -> virtual backlink
4382         **      Generic SCSI command
4383         */
4384
4385         /*
4386         **      Startqueue
4387         */
4388         cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
4389         cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_dsa));
4390         /*
4391         **      select
4392         */
4393         cp->phys.select.sel_id          = sdev_id(sdev);
4394         cp->phys.select.sel_scntl3      = tp->wval;
4395         cp->phys.select.sel_sxfer       = tp->sval;
4396         /*
4397         **      message
4398         */
4399         cp->phys.smsg.addr              = cpu_to_scr(CCB_PHYS (cp, scsi_smsg));
4400         cp->phys.smsg.size              = cpu_to_scr(msglen);
4401
4402         /*
4403         **      command
4404         */
4405         memcpy(cp->cdb_buf, cmd->cmnd, min_t(int, cmd->cmd_len, sizeof(cp->cdb_buf)));
4406         cp->phys.cmd.addr               = cpu_to_scr(CCB_PHYS (cp, cdb_buf[0]));
4407         cp->phys.cmd.size               = cpu_to_scr(cmd->cmd_len);
4408
4409         /*
4410         **      status
4411         */
4412         cp->actualquirks                = 0;
4413         cp->host_status                 = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
4414         cp->scsi_status                 = S_ILLEGAL;
4415         cp->parity_status               = 0;
4416
4417         cp->xerr_status                 = XE_OK;
4418 #if 0
4419         cp->sync_status                 = tp->sval;
4420         cp->wide_status                 = tp->wval;
4421 #endif
4422
4423         /*----------------------------------------------------
4424         **
4425         **      Critical region: start this job.
4426         **
4427         **----------------------------------------------------
4428         */
4429
4430         /* activate this job.  */
4431         cp->magic               = CCB_MAGIC;
4432
4433         /*
4434         **      insert next CCBs into start queue.
4435         **      2 max at a time is enough to flush the CCB wait queue.
4436         */
4437         cp->auto_sense = 0;
4438         if (lp)
4439                 ncr_start_next_ccb(np, lp, 2);
4440         else
4441                 ncr_put_start_queue(np, cp);
4442
4443         /* Command is successfully queued.  */
4444
4445         return DID_OK;
4446 }
4447
4448
4449 /*==========================================================
4450 **
4451 **
4452 **      Insert a CCB into the start queue and wake up the 
4453 **      SCRIPTS processor.
4454 **
4455 **
4456 **==========================================================
4457 */
4458
4459 static void ncr_start_next_ccb(struct ncb *np, struct lcb *lp, int maxn)
4460 {
4461         struct list_head *qp;
4462         struct ccb *cp;
4463
4464         if (lp->held_ccb)
4465                 return;
4466
4467         while (maxn-- && lp->queuedccbs < lp->queuedepth) {
4468                 qp = ncr_list_pop(&lp->wait_ccbq);
4469                 if (!qp)
4470                         break;
4471                 ++lp->queuedccbs;
4472                 cp = list_entry(qp, struct ccb, link_ccbq);
4473                 list_add_tail(qp, &lp->busy_ccbq);
4474                 lp->jump_ccb[cp->tag == NO_TAG ? 0 : cp->tag] =
4475                         cpu_to_scr(CCB_PHYS (cp, restart));
4476                 ncr_put_start_queue(np, cp);
4477         }
4478 }
4479
4480 static void ncr_put_start_queue(struct ncb *np, struct ccb *cp)
4481 {
4482         u16     qidx;
4483
4484         /*
4485         **      insert into start queue.
4486         */
4487         if (!np->squeueput) np->squeueput = 1;
4488         qidx = np->squeueput + 2;
4489         if (qidx >= MAX_START + MAX_START) qidx = 1;
4490
4491         np->scripth->tryloop [qidx] = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
4492         MEMORY_BARRIER();
4493         np->scripth->tryloop [np->squeueput] = cpu_to_scr(CCB_PHYS (cp, start));
4494
4495         np->squeueput = qidx;
4496         ++np->queuedccbs;
4497         cp->queued = 1;
4498
4499         if (DEBUG_FLAGS & DEBUG_QUEUE)
4500                 printk ("%s: queuepos=%d.\n", ncr_name (np), np->squeueput);
4501
4502         /*
4503         **      Script processor may be waiting for reselect.
4504         **      Wake it up.
4505         */
4506         MEMORY_BARRIER();
4507         OUTB (nc_istat, SIGP);
4508 }
4509
4510
4511 static int ncr_reset_scsi_bus(struct ncb *np, int enab_int, int settle_delay)
4512 {
4513         u32 term;
4514         int retv = 0;
4515
4516         np->settle_time = jiffies + settle_delay * HZ;
4517
4518         if (bootverbose > 1)
4519                 printk("%s: resetting, "
4520                         "command processing suspended for %d seconds\n",
4521                         ncr_name(np), settle_delay);
4522
4523         ncr_chip_reset(np, 100);
4524         udelay(2000);   /* The 895 needs time for the bus mode to settle */
4525         if (enab_int)
4526                 OUTW (nc_sien, RST);
4527         /*
4528         **      Enable Tolerant, reset IRQD if present and 
4529         **      properly set IRQ mode, prior to resetting the bus.
4530         */
4531         OUTB (nc_stest3, TE);
4532         OUTB (nc_scntl1, CRST);
4533         udelay(200);
4534
4535         if (!driver_setup.bus_check)
4536                 goto out;
4537         /*
4538         **      Check for no terminators or SCSI bus shorts to ground.
4539         **      Read SCSI data bus, data parity bits and control signals.
4540         **      We are expecting RESET to be TRUE and other signals to be 
4541         **      FALSE.
4542         */
4543
4544         term =  INB(nc_sstat0);
4545         term =  ((term & 2) << 7) + ((term & 1) << 17); /* rst sdp0 */
4546         term |= ((INB(nc_sstat2) & 0x01) << 26) |       /* sdp1     */
4547                 ((INW(nc_sbdl) & 0xff)   << 9)  |       /* d7-0     */
4548                 ((INW(nc_sbdl) & 0xff00) << 10) |       /* d15-8    */
4549                 INB(nc_sbcl);   /* req ack bsy sel atn msg cd io    */
4550
4551         if (!(np->features & FE_WIDE))
4552                 term &= 0x3ffff;
4553
4554         if (term != (2<<7)) {
4555                 printk("%s: suspicious SCSI data while resetting the BUS.\n",
4556                         ncr_name(np));
4557                 printk("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
4558                         "0x%lx, expecting 0x%lx\n",
4559                         ncr_name(np),
4560                         (np->features & FE_WIDE) ? "dp1,d15-8," : "",
4561                         (u_long)term, (u_long)(2<<7));
4562                 if (driver_setup.bus_check == 1)
4563                         retv = 1;
4564         }
4565 out:
4566         OUTB (nc_scntl1, 0);
4567         return retv;
4568 }
4569
4570 /*
4571  * Start reset process.
4572  * If reset in progress do nothing.
4573  * The interrupt handler will reinitialize the chip.
4574  * The timeout handler will wait for settle_time before 
4575  * clearing it and so resuming command processing.
4576  */
4577 static void ncr_start_reset(struct ncb *np)
4578 {
4579         if (!np->settle_time) {
4580                 ncr_reset_scsi_bus(np, 1, driver_setup.settle_delay);
4581         }
4582 }
4583  
4584 /*==========================================================
4585 **
4586 **
4587 **      Reset the SCSI BUS.
4588 **      This is called from the generic SCSI driver.
4589 **
4590 **
4591 **==========================================================
4592 */
4593 static int ncr_reset_bus (struct ncb *np, struct scsi_cmnd *cmd, int sync_reset)
4594 {
4595 /*      struct scsi_device        *device    = cmd->device; */
4596         struct ccb *cp;
4597         int found;
4598
4599 /*
4600  * Return immediately if reset is in progress.
4601  */
4602         if (np->settle_time) {
4603                 return FAILED;
4604         }
4605 /*
4606  * Start the reset process.
4607  * The script processor is then assumed to be stopped.
4608  * Commands will now be queued in the waiting list until a settle 
4609  * delay of 2 seconds will be completed.
4610  */
4611         ncr_start_reset(np);
4612 /*
4613  * First, look in the wakeup list
4614  */
4615         for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4616                 /*
4617                 **      look for the ccb of this command.
4618                 */
4619                 if (cp->host_status == HS_IDLE) continue;
4620                 if (cp->cmd == cmd) {
4621                         found = 1;
4622                         break;
4623                 }
4624         }
4625 /*
4626  * Then, look in the waiting list
4627  */
4628         if (!found && retrieve_from_waiting_list(0, np, cmd))
4629                 found = 1;
4630 /*
4631  * Wake-up all awaiting commands with DID_RESET.
4632  */
4633         reset_waiting_list(np);
4634 /*
4635  * Wake-up all pending commands with HS_RESET -> DID_RESET.
4636  */
4637         ncr_wakeup(np, HS_RESET);
4638 /*
4639  * If the involved command was not in a driver queue, and the 
4640  * scsi driver told us reset is synchronous, and the command is not 
4641  * currently in the waiting list, complete it with DID_RESET status,
4642  * in order to keep it alive.
4643  */
4644         if (!found && sync_reset && !retrieve_from_waiting_list(0, np, cmd)) {
4645                 cmd->result = ScsiResult(DID_RESET, 0);
4646                 ncr_queue_done_cmd(np, cmd);
4647         }
4648
4649         return SUCCESS;
4650 }
4651
4652 #if 0 /* unused and broken.. */
4653 /*==========================================================
4654 **
4655 **
4656 **      Abort an SCSI command.
4657 **      This is called from the generic SCSI driver.
4658 **
4659 **
4660 **==========================================================
4661 */
4662 static int ncr_abort_command (struct ncb *np, struct scsi_cmnd *cmd)
4663 {
4664 /*      struct scsi_device        *device    = cmd->device; */
4665         struct ccb *cp;
4666         int found;
4667         int retv;
4668
4669 /*
4670  * First, look for the scsi command in the waiting list
4671  */
4672         if (remove_from_waiting_list(np, cmd)) {
4673                 cmd->result = ScsiResult(DID_ABORT, 0);
4674                 ncr_queue_done_cmd(np, cmd);
4675                 return SCSI_ABORT_SUCCESS;
4676         }
4677
4678 /*
4679  * Then, look in the wakeup list
4680  */
4681         for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4682                 /*
4683                 **      look for the ccb of this command.
4684                 */
4685                 if (cp->host_status == HS_IDLE) continue;
4686                 if (cp->cmd == cmd) {
4687                         found = 1;
4688                         break;
4689                 }
4690         }
4691
4692         if (!found) {
4693                 return SCSI_ABORT_NOT_RUNNING;
4694         }
4695
4696         if (np->settle_time) {
4697                 return SCSI_ABORT_SNOOZE;
4698         }
4699
4700         /*
4701         **      If the CCB is active, patch schedule jumps for the 
4702         **      script to abort the command.
4703         */
4704
4705         switch(cp->host_status) {
4706         case HS_BUSY:
4707         case HS_NEGOTIATE:
4708                 printk ("%s: abort ccb=%p (cancel)\n", ncr_name (np), cp);
4709                         cp->start.schedule.l_paddr =
4710                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, cancel));
4711                 retv = SCSI_ABORT_PENDING;
4712                 break;
4713         case HS_DISCONNECT:
4714                 cp->restart.schedule.l_paddr =
4715                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
4716                 retv = SCSI_ABORT_PENDING;
4717                 break;
4718         default:
4719                 retv = SCSI_ABORT_NOT_RUNNING;
4720                 break;
4721
4722         }
4723
4724         /*
4725         **      If there are no requests, the script
4726         **      processor will sleep on SEL_WAIT_RESEL.
4727         **      Let's wake it up, since it may have to work.
4728         */
4729         OUTB (nc_istat, SIGP);
4730
4731         return retv;
4732 }
4733 #endif
4734
4735 static void ncr_detach(struct ncb *np)
4736 {
4737         struct ccb *cp;
4738         struct tcb *tp;
4739         struct lcb *lp;
4740         int target, lun;
4741         int i;
4742         char inst_name[16];
4743
4744         /* Local copy so we don't access np after freeing it! */
4745         strlcpy(inst_name, ncr_name(np), sizeof(inst_name));
4746
4747         printk("%s: releasing host resources\n", ncr_name(np));
4748
4749 /*
4750 **      Stop the ncr_timeout process
4751 **      Set release_stage to 1 and wait that ncr_timeout() set it to 2.
4752 */
4753
4754 #ifdef DEBUG_NCR53C8XX
4755         printk("%s: stopping the timer\n", ncr_name(np));
4756 #endif
4757         np->release_stage = 1;
4758         for (i = 50 ; i && np->release_stage != 2 ; i--)
4759                 mdelay(100);
4760         if (np->release_stage != 2)
4761                 printk("%s: the timer seems to be already stopped\n", ncr_name(np));
4762         else np->release_stage = 2;
4763
4764 /*
4765 **      Disable chip interrupts
4766 */
4767
4768 #ifdef DEBUG_NCR53C8XX
4769         printk("%s: disabling chip interrupts\n", ncr_name(np));
4770 #endif
4771         OUTW (nc_sien , 0);
4772         OUTB (nc_dien , 0);
4773
4774         /*
4775         **      Reset NCR chip
4776         **      Restore bios setting for automatic clock detection.
4777         */
4778
4779         printk("%s: resetting chip\n", ncr_name(np));
4780         ncr_chip_reset(np, 100);
4781
4782         OUTB(nc_dmode,  np->sv_dmode);
4783         OUTB(nc_dcntl,  np->sv_dcntl);
4784         OUTB(nc_ctest0, np->sv_ctest0);
4785         OUTB(nc_ctest3, np->sv_ctest3);
4786         OUTB(nc_ctest4, np->sv_ctest4);
4787         OUTB(nc_ctest5, np->sv_ctest5);
4788         OUTB(nc_gpcntl, np->sv_gpcntl);
4789         OUTB(nc_stest2, np->sv_stest2);
4790
4791         ncr_selectclock(np, np->sv_scntl3);
4792
4793         /*
4794         **      Free allocated ccb(s)
4795         */
4796
4797         while ((cp=np->ccb->link_ccb) != NULL) {
4798                 np->ccb->link_ccb = cp->link_ccb;
4799                 if (cp->host_status) {
4800                 printk("%s: shall free an active ccb (host_status=%d)\n",
4801                         ncr_name(np), cp->host_status);
4802                 }
4803 #ifdef DEBUG_NCR53C8XX
4804         printk("%s: freeing ccb (%lx)\n", ncr_name(np), (u_long) cp);
4805 #endif
4806                 m_free_dma(cp, sizeof(*cp), "CCB");
4807         }
4808
4809         /* Free allocated tp(s) */
4810
4811         for (target = 0; target < MAX_TARGET ; target++) {
4812                 tp=&np->target[target];
4813                 for (lun = 0 ; lun < MAX_LUN ; lun++) {
4814                         lp = tp->lp[lun];
4815                         if (lp) {
4816 #ifdef DEBUG_NCR53C8XX
4817         printk("%s: freeing lp (%lx)\n", ncr_name(np), (u_long) lp);
4818 #endif
4819                                 if (lp->jump_ccb != &lp->jump_ccb_0)
4820                                         m_free_dma(lp->jump_ccb,256,"JUMP_CCB");
4821                                 m_free_dma(lp, sizeof(*lp), "LCB");
4822                         }
4823                 }
4824         }
4825
4826         if (np->scripth0)
4827                 m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
4828         if (np->script0)
4829                 m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
4830         if (np->ccb)
4831                 m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
4832         m_free_dma(np, sizeof(struct ncb), "NCB");
4833
4834         printk("%s: host resources successfully released\n", inst_name);
4835 }
4836
4837 /*==========================================================
4838 **
4839 **
4840 **      Complete execution of a SCSI command.
4841 **      Signal completion to the generic SCSI driver.
4842 **
4843 **
4844 **==========================================================
4845 */
4846
4847 void ncr_complete (struct ncb *np, struct ccb *cp)
4848 {
4849         struct scsi_cmnd *cmd;
4850         struct tcb *tp;
4851         struct lcb *lp;
4852
4853         /*
4854         **      Sanity check
4855         */
4856
4857         if (!cp || cp->magic != CCB_MAGIC || !cp->cmd)
4858                 return;
4859
4860         /*
4861         **      Print minimal debug information.
4862         */
4863
4864         if (DEBUG_FLAGS & DEBUG_TINY)
4865                 printk ("CCB=%lx STAT=%x/%x\n", (unsigned long)cp,
4866                         cp->host_status,cp->scsi_status);
4867
4868         /*
4869         **      Get command, target and lun pointers.
4870         */
4871
4872         cmd = cp->cmd;
4873         cp->cmd = NULL;
4874         tp = &np->target[cmd->device->id];
4875         lp = tp->lp[cmd->device->lun];
4876
4877         /*
4878         **      We donnot queue more than 1 ccb per target 
4879         **      with negotiation at any time. If this ccb was 
4880         **      used for negotiation, clear this info in the tcb.
4881         */
4882
4883         if (cp == tp->nego_cp)
4884                 tp->nego_cp = NULL;
4885
4886         /*
4887         **      If auto-sense performed, change scsi status.
4888         */
4889         if (cp->auto_sense) {
4890                 cp->scsi_status = cp->auto_sense;
4891         }
4892
4893         /*
4894         **      If we were recovering from queue full or performing 
4895         **      auto-sense, requeue skipped CCBs to the wait queue.
4896         */
4897
4898         if (lp && lp->held_ccb) {
4899                 if (cp == lp->held_ccb) {
4900                         list_splice_init(&lp->skip_ccbq, &lp->wait_ccbq);
4901                         lp->held_ccb = NULL;
4902                 }
4903         }
4904
4905         /*
4906         **      Check for parity errors.
4907         */
4908
4909         if (cp->parity_status > 1) {
4910                 PRINT_ADDR(cmd, "%d parity error(s).\n",cp->parity_status);
4911         }
4912
4913         /*
4914         **      Check for extended errors.
4915         */
4916
4917         if (cp->xerr_status != XE_OK) {
4918                 switch (cp->xerr_status) {
4919                 case XE_EXTRA_DATA:
4920                         PRINT_ADDR(cmd, "extraneous data discarded.\n");
4921                         break;
4922                 case XE_BAD_PHASE:
4923                         PRINT_ADDR(cmd, "invalid scsi phase (4/5).\n");
4924                         break;
4925                 default:
4926                         PRINT_ADDR(cmd, "extended error %d.\n",
4927                                         cp->xerr_status);
4928                         break;
4929                 }
4930                 if (cp->host_status==HS_COMPLETE)
4931                         cp->host_status = HS_FAIL;
4932         }
4933
4934         /*
4935         **      Print out any error for debugging purpose.
4936         */
4937         if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
4938                 if (cp->host_status!=HS_COMPLETE || cp->scsi_status!=S_GOOD) {
4939                         PRINT_ADDR(cmd, "ERROR: cmd=%x host_status=%x "
4940                                         "scsi_status=%x\n", cmd->cmnd[0],
4941                                         cp->host_status, cp->scsi_status);
4942                 }
4943         }
4944
4945         /*
4946         **      Check the status.
4947         */
4948         if (   (cp->host_status == HS_COMPLETE)
4949                 && (cp->scsi_status == S_GOOD ||
4950                     cp->scsi_status == S_COND_MET)) {
4951                 /*
4952                  *      All went well (GOOD status).
4953                  *      CONDITION MET status is returned on 
4954                  *      `Pre-Fetch' or `Search data' success.
4955                  */
4956                 cmd->result = ScsiResult(DID_OK, cp->scsi_status);
4957
4958                 /*
4959                 **      @RESID@
4960                 **      Could dig out the correct value for resid,
4961                 **      but it would be quite complicated.
4962                 */
4963                 /* if (cp->phys.header.lastp != cp->phys.header.goalp) */
4964
4965                 /*
4966                 **      Allocate the lcb if not yet.
4967                 */
4968                 if (!lp)
4969                         ncr_alloc_lcb (np, cmd->device->id, cmd->device->lun);
4970
4971                 tp->bytes     += cp->data_len;
4972                 tp->transfers ++;
4973
4974                 /*
4975                 **      If tags was reduced due to queue full,
4976                 **      increase tags if 1000 good status received.
4977                 */
4978                 if (lp && lp->usetags && lp->numtags < lp->maxtags) {
4979                         ++lp->num_good;
4980                         if (lp->num_good >= 1000) {
4981                                 lp->num_good = 0;
4982                                 ++lp->numtags;
4983                                 ncr_setup_tags (np, cmd->device);
4984                         }
4985                 }
4986         } else if ((cp->host_status == HS_COMPLETE)
4987                 && (cp->scsi_status == S_CHECK_COND)) {
4988                 /*
4989                 **   Check condition code
4990                 */
4991                 cmd->result = ScsiResult(DID_OK, S_CHECK_COND);
4992
4993                 /*
4994                 **      Copy back sense data to caller's buffer.
4995                 */
4996                 memcpy(cmd->sense_buffer, cp->sense_buf,
4997                        min(sizeof(cmd->sense_buffer), sizeof(cp->sense_buf)));
4998
4999                 if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
5000                         u_char * p = (u_char*) & cmd->sense_buffer;
5001                         int i;
5002                         PRINT_ADDR(cmd, "sense data:");
5003                         for (i=0; i<14; i++) printk (" %x", *p++);
5004                         printk (".\n");
5005                 }
5006         } else if ((cp->host_status == HS_COMPLETE)
5007                 && (cp->scsi_status == S_CONFLICT)) {
5008                 /*
5009                 **   Reservation Conflict condition code
5010                 */
5011                 cmd->result = ScsiResult(DID_OK, S_CONFLICT);
5012         
5013         } else if ((cp->host_status == HS_COMPLETE)
5014                 && (cp->scsi_status == S_BUSY ||
5015                     cp->scsi_status == S_QUEUE_FULL)) {
5016
5017                 /*
5018                 **   Target is busy.
5019                 */
5020                 cmd->result = ScsiResult(DID_OK, cp->scsi_status);
5021
5022         } else if ((cp->host_status == HS_SEL_TIMEOUT)
5023                 || (cp->host_status == HS_TIMEOUT)) {
5024
5025                 /*
5026                 **   No response
5027                 */
5028                 cmd->result = ScsiResult(DID_TIME_OUT, cp->scsi_status);
5029
5030         } else if (cp->host_status == HS_RESET) {
5031
5032                 /*
5033                 **   SCSI bus reset
5034                 */
5035                 cmd->result = ScsiResult(DID_RESET, cp->scsi_status);
5036
5037         } else if (cp->host_status == HS_ABORTED) {
5038
5039                 /*
5040                 **   Transfer aborted
5041                 */
5042                 cmd->result = ScsiResult(DID_ABORT, cp->scsi_status);
5043
5044         } else {
5045
5046                 /*
5047                 **  Other protocol messes
5048                 */
5049                 PRINT_ADDR(cmd, "COMMAND FAILED (%x %x) @%p.\n",
5050                         cp->host_status, cp->scsi_status, cp);
5051
5052                 cmd->result = ScsiResult(DID_ERROR, cp->scsi_status);
5053         }
5054
5055         /*
5056         **      trace output
5057         */
5058
5059         if (tp->usrflag & UF_TRACE) {
5060                 u_char * p;
5061                 int i;
5062                 PRINT_ADDR(cmd, " CMD:");
5063                 p = (u_char*) &cmd->cmnd[0];
5064                 for (i=0; i<cmd->cmd_len; i++) printk (" %x", *p++);
5065
5066                 if (cp->host_status==HS_COMPLETE) {
5067                         switch (cp->scsi_status) {
5068                         case S_GOOD:
5069                                 printk ("  GOOD");
5070                                 break;
5071                         case S_CHECK_COND:
5072                                 printk ("  SENSE:");
5073                                 p = (u_char*) &cmd->sense_buffer;
5074                                 for (i=0; i<14; i++)
5075                                         printk (" %x", *p++);
5076                                 break;
5077                         default:
5078                                 printk ("  STAT: %x\n", cp->scsi_status);
5079                                 break;
5080                         }
5081                 } else printk ("  HOSTERROR: %x", cp->host_status);
5082                 printk ("\n");
5083         }
5084
5085         /*
5086         **      Free this ccb
5087         */
5088         ncr_free_ccb (np, cp);
5089
5090         /*
5091         **      requeue awaiting scsi commands for this lun.
5092         */
5093         if (lp && lp->queuedccbs < lp->queuedepth &&
5094             !list_empty(&lp->wait_ccbq))
5095                 ncr_start_next_ccb(np, lp, 2);
5096
5097         /*
5098         **      requeue awaiting scsi commands for this controller.
5099         */
5100         if (np->waiting_list)
5101                 requeue_waiting_list(np);
5102
5103         /*
5104         **      signal completion to generic driver.
5105         */
5106         ncr_queue_done_cmd(np, cmd);
5107 }
5108
5109 /*==========================================================
5110 **
5111 **
5112 **      Signal all (or one) control block done.
5113 **
5114 **
5115 **==========================================================
5116 */
5117
5118 /*
5119 **      This CCB has been skipped by the NCR.
5120 **      Queue it in the correponding unit queue.
5121 */
5122 static void ncr_ccb_skipped(struct ncb *np, struct ccb *cp)
5123 {
5124         struct tcb *tp = &np->target[cp->target];
5125         struct lcb *lp = tp->lp[cp->lun];
5126
5127         if (lp && cp != np->ccb) {
5128                 cp->host_status &= ~HS_SKIPMASK;
5129                 cp->start.schedule.l_paddr = 
5130                         cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
5131                 list_del(&cp->link_ccbq);
5132                 list_add_tail(&cp->link_ccbq, &lp->skip_ccbq);
5133                 if (cp->queued) {
5134                         --lp->queuedccbs;
5135                 }
5136         }
5137         if (cp->queued) {
5138                 --np->queuedccbs;
5139                 cp->queued = 0;
5140         }
5141 }
5142
5143 /*
5144 **      The NCR has completed CCBs.
5145 **      Look at the DONE QUEUE if enabled, otherwise scan all CCBs
5146 */
5147 void ncr_wakeup_done (struct ncb *np)
5148 {
5149         struct ccb *cp;
5150 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
5151         int i, j;
5152
5153         i = np->ccb_done_ic;
5154         while (1) {
5155                 j = i+1;
5156                 if (j >= MAX_DONE)
5157                         j = 0;
5158
5159                 cp = np->ccb_done[j];
5160                 if (!CCB_DONE_VALID(cp))
5161                         break;
5162
5163                 np->ccb_done[j] = (struct ccb *)CCB_DONE_EMPTY;
5164                 np->scripth->done_queue[5*j + 4] =
5165                                 cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5166                 MEMORY_BARRIER();
5167                 np->scripth->done_queue[5*i + 4] =
5168                                 cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5169
5170                 if (cp->host_status & HS_DONEMASK)
5171                         ncr_complete (np, cp);
5172                 else if (cp->host_status & HS_SKIPMASK)
5173                         ncr_ccb_skipped (np, cp);
5174
5175                 i = j;
5176         }
5177         np->ccb_done_ic = i;
5178 #else
5179         cp = np->ccb;
5180         while (cp) {
5181                 if (cp->host_status & HS_DONEMASK)
5182                         ncr_complete (np, cp);
5183                 else if (cp->host_status & HS_SKIPMASK)
5184                         ncr_ccb_skipped (np, cp);
5185                 cp = cp->link_ccb;
5186         }
5187 #endif
5188 }
5189
5190 /*
5191 **      Complete all active CCBs.
5192 */
5193 void ncr_wakeup (struct ncb *np, u_long code)
5194 {
5195         struct ccb *cp = np->ccb;
5196
5197         while (cp) {
5198                 if (cp->host_status != HS_IDLE) {
5199                         cp->host_status = code;
5200                         ncr_complete (np, cp);
5201                 }
5202                 cp = cp->link_ccb;
5203         }
5204 }
5205
5206 /*
5207 ** Reset ncr chip.
5208 */
5209
5210 /* Some initialisation must be done immediately following reset, for 53c720,
5211  * at least.  EA (dcntl bit 5) isn't set here as it is set once only in
5212  * the _detect function.
5213  */
5214 static void ncr_chip_reset(struct ncb *np, int delay)
5215 {
5216         OUTB (nc_istat,  SRST);
5217         udelay(delay);
5218         OUTB (nc_istat,  0   );
5219
5220         if (np->features & FE_EHP)
5221                 OUTB (nc_ctest0, EHP);
5222         if (np->features & FE_MUX)
5223                 OUTB (nc_ctest4, MUX);
5224 }
5225
5226
5227 /*==========================================================
5228 **
5229 **
5230 **      Start NCR chip.
5231 **
5232 **
5233 **==========================================================
5234 */
5235
5236 void ncr_init (struct ncb *np, int reset, char * msg, u_long code)
5237 {
5238         int     i;
5239
5240         /*
5241         **      Reset chip if asked, otherwise just clear fifos.
5242         */
5243
5244         if (reset) {
5245                 OUTB (nc_istat,  SRST);
5246                 udelay(100);
5247         }
5248         else {
5249                 OUTB (nc_stest3, TE|CSF);
5250                 OUTONB (nc_ctest3, CLF);
5251         }
5252  
5253         /*
5254         **      Message.
5255         */
5256
5257         if (msg) printk (KERN_INFO "%s: restart (%s).\n", ncr_name (np), msg);
5258
5259         /*
5260         **      Clear Start Queue
5261         */
5262         np->queuedepth = MAX_START - 1; /* 1 entry needed as end marker */
5263         for (i = 1; i < MAX_START + MAX_START; i += 2)
5264                 np->scripth0->tryloop[i] =
5265                                 cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5266
5267         /*
5268         **      Start at first entry.
5269         */
5270         np->squeueput = 0;
5271         np->script0->startpos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np, tryloop));
5272
5273 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
5274         /*
5275         **      Clear Done Queue
5276         */
5277         for (i = 0; i < MAX_DONE; i++) {
5278                 np->ccb_done[i] = (struct ccb *)CCB_DONE_EMPTY;
5279                 np->scripth0->done_queue[5*i + 4] =
5280                         cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5281         }
5282 #endif
5283
5284         /*
5285         **      Start at first entry.
5286         */
5287         np->script0->done_pos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np,done_queue));
5288         np->ccb_done_ic = MAX_DONE-1;
5289         np->scripth0->done_queue[5*(MAX_DONE-1) + 4] =
5290                         cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5291
5292         /*
5293         **      Wakeup all pending jobs.
5294         */
5295         ncr_wakeup (np, code);
5296
5297         /*
5298         **      Init chip.
5299         */
5300
5301         /*
5302         ** Remove reset; big delay because the 895 needs time for the
5303         ** bus mode to settle
5304         */
5305         ncr_chip_reset(np, 2000);
5306
5307         OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
5308                                         /*  full arb., ena parity, par->ATN  */
5309         OUTB (nc_scntl1, 0x00);         /*  odd parity, and remove CRST!! */
5310
5311         ncr_selectclock(np, np->rv_scntl3);     /* Select SCSI clock */
5312
5313         OUTB (nc_scid  , RRE|np->myaddr);       /* Adapter SCSI address */
5314         OUTW (nc_respid, 1ul<<np->myaddr);      /* Id to respond to */
5315         OUTB (nc_istat , SIGP   );              /*  Signal Process */
5316         OUTB (nc_dmode , np->rv_dmode);         /* Burst length, dma mode */
5317         OUTB (nc_ctest5, np->rv_ctest5);        /* Large fifo + large burst */
5318
5319         OUTB (nc_dcntl , NOCOM|np->rv_dcntl);   /* Protect SFBR */
5320         OUTB (nc_ctest0, np->rv_ctest0);        /* 720: CDIS and EHP */
5321         OUTB (nc_ctest3, np->rv_ctest3);        /* Write and invalidate */
5322         OUTB (nc_ctest4, np->rv_ctest4);        /* Master parity checking */
5323
5324         OUTB (nc_stest2, EXT|np->rv_stest2);    /* Extended Sreq/Sack filtering */
5325         OUTB (nc_stest3, TE);                   /* TolerANT enable */
5326         OUTB (nc_stime0, 0x0c   );              /* HTH disabled  STO 0.25 sec */
5327
5328         /*
5329         **      Disable disconnects.
5330         */
5331
5332         np->disc = 0;
5333
5334         /*
5335         **    Enable GPIO0 pin for writing if LED support.
5336         */
5337
5338         if (np->features & FE_LED0) {
5339                 OUTOFFB (nc_gpcntl, 0x01);
5340         }
5341
5342         /*
5343         **      enable ints
5344         */
5345
5346         OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
5347         OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
5348
5349         /*
5350         **      Fill in target structure.
5351         **      Reinitialize usrsync.
5352         **      Reinitialize usrwide.
5353         **      Prepare sync negotiation according to actual SCSI bus mode.
5354         */
5355
5356         for (i=0;i<MAX_TARGET;i++) {
5357                 struct tcb *tp = &np->target[i];
5358
5359                 tp->sval    = 0;
5360                 tp->wval    = np->rv_scntl3;
5361
5362                 if (tp->usrsync != 255) {
5363                         if (tp->usrsync <= np->maxsync) {
5364                                 if (tp->usrsync < np->minsync) {
5365                                         tp->usrsync = np->minsync;
5366                                 }
5367                         }
5368                         else
5369                                 tp->usrsync = 255;
5370                 }
5371
5372                 if (tp->usrwide > np->maxwide)
5373                         tp->usrwide = np->maxwide;
5374
5375         }
5376
5377         /*
5378         **    Start script processor.
5379         */
5380         if (np->paddr2) {
5381                 if (bootverbose)
5382                         printk ("%s: Downloading SCSI SCRIPTS.\n",
5383                                 ncr_name(np));
5384                 OUTL (nc_scratcha, vtobus(np->script0));
5385                 OUTL_DSP (NCB_SCRIPTH_PHYS (np, start_ram));
5386         }
5387         else
5388                 OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
5389 }
5390
5391 /*==========================================================
5392 **
5393 **      Prepare the negotiation values for wide and
5394 **      synchronous transfers.
5395 **
5396 **==========================================================
5397 */
5398
5399 static void ncr_negotiate (struct ncb* np, struct tcb* tp)
5400 {
5401         /*
5402         **      minsync unit is 4ns !
5403         */
5404
5405         u_long minsync = tp->usrsync;
5406
5407         /*
5408         **      SCSI bus mode limit
5409         */
5410
5411         if (np->scsi_mode && np->scsi_mode == SMODE_SE) {
5412                 if (minsync < 12) minsync = 12;
5413         }
5414
5415         /*
5416         **      our limit ..
5417         */
5418
5419         if (minsync < np->minsync)
5420                 minsync = np->minsync;
5421
5422         /*
5423         **      divider limit
5424         */
5425
5426         if (minsync > np->maxsync)
5427                 minsync = 255;
5428
5429         if (tp->maxoffs > np->maxoffs)
5430                 tp->maxoffs = np->maxoffs;
5431
5432         tp->minsync = minsync;
5433         tp->maxoffs = (minsync<255 ? tp->maxoffs : 0);
5434
5435         /*
5436         **      period=0: has to negotiate sync transfer
5437         */
5438
5439         tp->period=0;
5440
5441         /*
5442         **      widedone=0: has to negotiate wide transfer
5443         */
5444         tp->widedone=0;
5445 }
5446
5447 /*==========================================================
5448 **
5449 **      Get clock factor and sync divisor for a given 
5450 **      synchronous factor period.
5451 **      Returns the clock factor (in sxfer) and scntl3 
5452 **      synchronous divisor field.
5453 **
5454 **==========================================================
5455 */
5456
5457 static void ncr_getsync(struct ncb *np, u_char sfac, u_char *fakp, u_char *scntl3p)
5458 {
5459         u_long  clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
5460         int     div = np->clock_divn;   /* Number of divisors supported */
5461         u_long  fak;                    /* Sync factor in sxfer         */
5462         u_long  per;                    /* Period in tenths of ns       */
5463         u_long  kpc;                    /* (per * clk)                  */
5464
5465         /*
5466         **      Compute the synchronous period in tenths of nano-seconds
5467         */
5468         if      (sfac <= 10)    per = 250;
5469         else if (sfac == 11)    per = 303;
5470         else if (sfac == 12)    per = 500;
5471         else                    per = 40 * sfac;
5472
5473         /*
5474         **      Look for the greatest clock divisor that allows an 
5475         **      input speed faster than the period.
5476         */
5477         kpc = per * clk;
5478         while (--div >= 0)
5479                 if (kpc >= (div_10M[div] << 2)) break;
5480
5481         /*
5482         **      Calculate the lowest clock factor that allows an output 
5483         **      speed not faster than the period.
5484         */
5485         fak = (kpc - 1) / div_10M[div] + 1;
5486
5487 #if 0   /* This optimization does not seem very useful */
5488
5489         per = (fak * div_10M[div]) / clk;
5490
5491         /*
5492         **      Why not to try the immediate lower divisor and to choose 
5493         **      the one that allows the fastest output speed ?
5494         **      We don't want input speed too much greater than output speed.
5495         */
5496         if (div >= 1 && fak < 8) {
5497                 u_long fak2, per2;
5498                 fak2 = (kpc - 1) / div_10M[div-1] + 1;
5499                 per2 = (fak2 * div_10M[div-1]) / clk;
5500                 if (per2 < per && fak2 <= 8) {
5501                         fak = fak2;
5502                         per = per2;
5503                         --div;
5504                 }
5505         }
5506 #endif
5507
5508         if (fak < 4) fak = 4;   /* Should never happen, too bad ... */
5509
5510         /*
5511         **      Compute and return sync parameters for the ncr
5512         */
5513         *fakp           = fak - 4;
5514         *scntl3p        = ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
5515 }
5516
5517
5518 /*==========================================================
5519 **
5520 **      Set actual values, sync status and patch all ccbs of 
5521 **      a target according to new sync/wide agreement.
5522 **
5523 **==========================================================
5524 */
5525
5526 static void ncr_set_sync_wide_status (struct ncb *np, u_char target)
5527 {
5528         struct ccb *cp;
5529         struct tcb *tp = &np->target[target];
5530
5531         /*
5532         **      set actual value and sync_status
5533         */
5534         OUTB (nc_sxfer, tp->sval);
5535         np->sync_st = tp->sval;
5536         OUTB (nc_scntl3, tp->wval);
5537         np->wide_st = tp->wval;
5538
5539         /*
5540         **      patch ALL ccbs of this target.
5541         */
5542         for (cp = np->ccb; cp; cp = cp->link_ccb) {
5543                 if (!cp->cmd) continue;
5544                 if (scmd_id(cp->cmd) != target) continue;
5545 #if 0
5546                 cp->sync_status = tp->sval;
5547                 cp->wide_status = tp->wval;
5548 #endif
5549                 cp->phys.select.sel_scntl3 = tp->wval;
5550                 cp->phys.select.sel_sxfer  = tp->sval;
5551         }
5552 }
5553
5554 /*==========================================================
5555 **
5556 **      Switch sync mode for current job and it's target
5557 **
5558 **==========================================================
5559 */
5560
5561 static void ncr_setsync (struct ncb *np, struct ccb *cp, u_char scntl3, u_char sxfer)
5562 {
5563         struct scsi_cmnd *cmd = cp->cmd;
5564         struct tcb *tp;
5565         u_char target = INB (nc_sdid) & 0x0f;
5566         u_char idiv;
5567
5568         BUG_ON(target != (scmd_id(cmd) & 0xf));
5569
5570         tp = &np->target[target];
5571
5572         if (!scntl3 || !(sxfer & 0x1f))
5573                 scntl3 = np->rv_scntl3;
5574         scntl3 = (scntl3 & 0xf0) | (tp->wval & EWS) | (np->rv_scntl3 & 0x07);
5575
5576         /*
5577         **      Deduce the value of controller sync period from scntl3.
5578         **      period is in tenths of nano-seconds.
5579         */
5580
5581         idiv = ((scntl3 >> 4) & 0x7);
5582         if ((sxfer & 0x1f) && idiv)
5583                 tp->period = (((sxfer>>5)+4)*div_10M[idiv-1])/np->clock_khz;
5584         else
5585                 tp->period = 0xffff;
5586
5587         /* Stop there if sync parameters are unchanged */
5588         if (tp->sval == sxfer && tp->wval == scntl3)
5589                 return;
5590         tp->sval = sxfer;
5591         tp->wval = scntl3;
5592
5593         if (sxfer & 0x01f) {
5594                 /* Disable extended Sreq/Sack filtering */
5595                 if (tp->period <= 2000)
5596                         OUTOFFB(nc_stest2, EXT);
5597         }
5598  
5599         spi_display_xfer_agreement(tp->starget);
5600
5601         /*
5602         **      set actual value and sync_status
5603         **      patch ALL ccbs of this target.
5604         */
5605         ncr_set_sync_wide_status(np, target);
5606 }
5607
5608 /*==========================================================
5609 **
5610 **      Switch wide mode for current job and it's target
5611 **      SCSI specs say: a SCSI device that accepts a WDTR 
5612 **      message shall reset the synchronous agreement to 
5613 **      asynchronous mode.
5614 **
5615 **==========================================================
5616 */
5617
5618 static void ncr_setwide (struct ncb *np, struct ccb *cp, u_char wide, u_char ack)
5619 {
5620         struct scsi_cmnd *cmd = cp->cmd;
5621         u16 target = INB (nc_sdid) & 0x0f;
5622         struct tcb *tp;
5623         u_char  scntl3;
5624         u_char  sxfer;
5625
5626         BUG_ON(target != (scmd_id(cmd) & 0xf));
5627
5628         tp = &np->target[target];
5629         tp->widedone  =  wide+1;
5630         scntl3 = (tp->wval & (~EWS)) | (wide ? EWS : 0);
5631
5632         sxfer = ack ? 0 : tp->sval;
5633
5634         /*
5635         **       Stop there if sync/wide parameters are unchanged
5636         */
5637         if (tp->sval == sxfer && tp->wval == scntl3) return;
5638         tp->sval = sxfer;
5639         tp->wval = scntl3;
5640
5641         /*
5642         **      Bells and whistles   ;-)
5643         */
5644         if (bootverbose >= 2) {
5645                 dev_info(&cmd->device->sdev_target->dev, "WIDE SCSI %sabled.\n",
5646                                 (scntl3 & EWS) ? "en" : "dis");
5647         }
5648
5649         /*
5650         **      set actual value and sync_status
5651         **      patch ALL ccbs of this target.
5652         */
5653         ncr_set_sync_wide_status(np, target);
5654 }
5655
5656 /*==========================================================
5657 **
5658 **      Switch tagged mode for a target.
5659 **
5660 **==========================================================
5661 */
5662
5663 static void ncr_setup_tags (struct ncb *np, struct scsi_device *sdev)
5664 {
5665         unsigned char tn = sdev->id, ln = sdev->lun;
5666         struct tcb *tp = &np->target[tn];
5667         struct lcb *lp = tp->lp[ln];
5668         u_char   reqtags, maxdepth;
5669
5670         /*
5671         **      Just in case ...
5672         */
5673         if ((!tp) || (!lp) || !sdev)
5674                 return;
5675
5676         /*
5677         **      If SCSI device queue depth is not yet set, leave here.
5678         */
5679         if (!lp->scdev_depth)
5680                 return;
5681
5682         /*
5683         **      Donnot allow more tags than the SCSI driver can queue 
5684         **      for this device.
5685         **      Donnot allow more tags than we can handle.
5686         */
5687         maxdepth = lp->scdev_depth;
5688         if (maxdepth > lp->maxnxs)      maxdepth    = lp->maxnxs;
5689         if (lp->maxtags > maxdepth)     lp->maxtags = maxdepth;
5690         if (lp->numtags > maxdepth)     lp->numtags = maxdepth;
5691
5692         /*
5693         **      only devices conformant to ANSI Version >= 2
5694         **      only devices capable of tagged commands
5695         **      only if enabled by user ..
5696         */
5697         if (sdev->tagged_supported && lp->numtags > 1) {
5698                 reqtags = lp->numtags;
5699         } else {
5700                 reqtags = 1;
5701         }
5702
5703         /*
5704         **      Update max number of tags
5705         */
5706         lp->numtags = reqtags;
5707         if (lp->numtags > lp->maxtags)
5708                 lp->maxtags = lp->numtags;
5709
5710         /*
5711         **      If we want to switch tag mode, we must wait 
5712         **      for no CCB to be active.
5713         */
5714         if      (reqtags > 1 && lp->usetags) {   /* Stay in tagged mode    */
5715                 if (lp->queuedepth == reqtags)   /* Already announced      */
5716                         return;
5717                 lp->queuedepth  = reqtags;
5718         }
5719         else if (reqtags <= 1 && !lp->usetags) { /* Stay in untagged mode  */
5720                 lp->queuedepth  = reqtags;
5721                 return;
5722         }
5723         else {                                   /* Want to switch tag mode */
5724                 if (lp->busyccbs)                /* If not yet safe, return */
5725                         return;
5726                 lp->queuedepth  = reqtags;
5727                 lp->usetags     = reqtags > 1 ? 1 : 0;
5728         }
5729
5730         /*
5731         **      Patch the lun mini-script, according to tag mode.
5732         */
5733         lp->jump_tag.l_paddr = lp->usetags?
5734                         cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_tag)) :
5735                         cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_notag));
5736
5737         /*
5738         **      Announce change to user.
5739         */
5740         if (bootverbose) {
5741                 if (lp->usetags) {
5742                         dev_info(&sdev->sdev_gendev,
5743                                 "tagged command queue depth set to %d\n",
5744                                 reqtags);
5745                 } else {
5746                         dev_info(&sdev->sdev_gendev,
5747                                         "tagged command queueing disabled\n");
5748                 }
5749         }
5750 }
5751
5752 /*==========================================================
5753 **
5754 **
5755 **      ncr timeout handler.
5756 **
5757 **
5758 **==========================================================
5759 **
5760 **      Misused to keep the driver running when
5761 **      interrupts are not configured correctly.
5762 **
5763 **----------------------------------------------------------
5764 */
5765
5766 static void ncr_timeout (struct ncb *np)
5767 {
5768         u_long  thistime = jiffies;
5769
5770         /*
5771         **      If release process in progress, let's go
5772         **      Set the release stage from 1 to 2 to synchronize
5773         **      with the release process.
5774         */
5775
5776         if (np->release_stage) {
5777                 if (np->release_stage == 1) np->release_stage = 2;
5778                 return;
5779         }
5780
5781         np->timer.expires = jiffies + SCSI_NCR_TIMER_INTERVAL;
5782         add_timer(&np->timer);
5783
5784         /*
5785         **      If we are resetting the ncr, wait for settle_time before 
5786         **      clearing it. Then command processing will be resumed.
5787         */
5788         if (np->settle_time) {
5789                 if (np->settle_time <= thistime) {
5790                         if (bootverbose > 1)
5791                                 printk("%s: command processing resumed\n", ncr_name(np));
5792                         np->settle_time = 0;
5793                         np->disc        = 1;
5794                         requeue_waiting_list(np);
5795                 }
5796                 return;
5797         }
5798
5799         /*
5800         **      Since the generic scsi driver only allows us 0.5 second 
5801         **      to perform abort of a command, we must look at ccbs about 
5802         **      every 0.25 second.
5803         */
5804         if (np->lasttime + 4*HZ < thistime) {
5805                 /*
5806                 **      block ncr interrupts
5807                 */
5808                 np->lasttime = thistime;
5809         }
5810
5811 #ifdef SCSI_NCR_BROKEN_INTR
5812         if (INB(nc_istat) & (INTF|SIP|DIP)) {
5813
5814                 /*
5815                 **      Process pending interrupts.
5816                 */
5817                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("{");
5818                 ncr_exception (np);
5819                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("}");
5820         }
5821 #endif /* SCSI_NCR_BROKEN_INTR */
5822 }
5823
5824 /*==========================================================
5825 **
5826 **      log message for real hard errors
5827 **
5828 **      "ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc)."
5829 **      "             reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
5830 **
5831 **      exception register:
5832 **              ds:     dstat
5833 **              si:     sist
5834 **
5835 **      SCSI bus lines:
5836 **              so:     control lines as driver by NCR.
5837 **              si:     control lines as seen by NCR.
5838 **              sd:     scsi data lines as seen by NCR.
5839 **
5840 **      wide/fastmode:
5841 **              sxfer:  (see the manual)
5842 **              scntl3: (see the manual)
5843 **
5844 **      current script command:
5845 **              dsp:    script address (relative to start of script).
5846 **              dbc:    first word of script command.
5847 **
5848 **      First 16 register of the chip:
5849 **              r0..rf
5850 **
5851 **==========================================================
5852 */
5853
5854 static void ncr_log_hard_error(struct ncb *np, u16 sist, u_char dstat)
5855 {
5856         u32     dsp;
5857         int     script_ofs;
5858         int     script_size;
5859         char    *script_name;
5860         u_char  *script_base;
5861         int     i;
5862
5863         dsp     = INL (nc_dsp);
5864
5865         if (dsp > np->p_script && dsp <= np->p_script + sizeof(struct script)) {
5866                 script_ofs      = dsp - np->p_script;
5867                 script_size     = sizeof(struct script);
5868                 script_base     = (u_char *) np->script0;
5869                 script_name     = "script";
5870         }
5871         else if (np->p_scripth < dsp && 
5872                  dsp <= np->p_scripth + sizeof(struct scripth)) {
5873                 script_ofs      = dsp - np->p_scripth;
5874                 script_size     = sizeof(struct scripth);
5875                 script_base     = (u_char *) np->scripth0;
5876                 script_name     = "scripth";
5877         } else {
5878                 script_ofs      = dsp;
5879                 script_size     = 0;
5880                 script_base     = NULL;
5881                 script_name     = "mem";
5882         }
5883
5884         printk ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
5885                 ncr_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
5886                 (unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl), (unsigned)INB (nc_sbdl),
5887                 (unsigned)INB (nc_sxfer),(unsigned)INB (nc_scntl3), script_name, script_ofs,
5888                 (unsigned)INL (nc_dbc));
5889
5890         if (((script_ofs & 3) == 0) &&
5891             (unsigned)script_ofs < script_size) {
5892                 printk ("%s: script cmd = %08x\n", ncr_name(np),
5893                         scr_to_cpu((int) *(ncrcmd *)(script_base + script_ofs)));
5894         }
5895
5896         printk ("%s: regdump:", ncr_name(np));
5897         for (i=0; i<16;i++)
5898             printk (" %02x", (unsigned)INB_OFF(i));
5899         printk (".\n");
5900 }
5901
5902 /*============================================================
5903 **
5904 **      ncr chip exception handler.
5905 **
5906 **============================================================
5907 **
5908 **      In normal cases, interrupt conditions occur one at a 
5909 **      time. The ncr is able to stack in some extra registers 
5910 **      other interrupts that will occurs after the first one.
5911 **      But severall interrupts may occur at the same time.
5912 **
5913 **      We probably should only try to deal with the normal 
5914 **      case, but it seems that multiple interrupts occur in 
5915 **      some cases that are not abnormal at all.
5916 **
5917 **      The most frequent interrupt condition is Phase Mismatch.
5918 **      We should want to service this interrupt quickly.
5919 **      A SCSI parity error may be delivered at the same time.
5920 **      The SIR interrupt is not very frequent in this driver, 
5921 **      since the INTFLY is likely used for command completion 
5922 **      signaling.
5923 **      The Selection Timeout interrupt may be triggered with 
5924 **      IID and/or UDC.
5925 **      The SBMC interrupt (SCSI Bus Mode Change) may probably 
5926 **      occur at any time.
5927 **
5928 **      This handler try to deal as cleverly as possible with all
5929 **      the above.
5930 **
5931 **============================================================
5932 */
5933
5934 void ncr_exception (struct ncb *np)
5935 {
5936         u_char  istat, dstat;
5937         u16     sist;
5938         int     i;
5939
5940         /*
5941         **      interrupt on the fly ?
5942         **      Since the global header may be copied back to a CCB 
5943         **      using a posted PCI memory write, the last operation on 
5944         **      the istat register is a READ in order to flush posted 
5945         **      PCI write commands.
5946         */
5947         istat = INB (nc_istat);
5948         if (istat & INTF) {
5949                 OUTB (nc_istat, (istat & SIGP) | INTF);
5950                 istat = INB (nc_istat);
5951                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("F ");
5952                 ncr_wakeup_done (np);
5953         }
5954
5955         if (!(istat & (SIP|DIP)))
5956                 return;
5957
5958         if (istat & CABRT)
5959                 OUTB (nc_istat, CABRT);
5960
5961         /*
5962         **      Steinbach's Guideline for Systems Programming:
5963         **      Never test for an error condition you don't know how to handle.
5964         */
5965
5966         sist  = (istat & SIP) ? INW (nc_sist)  : 0;
5967         dstat = (istat & DIP) ? INB (nc_dstat) : 0;
5968
5969         if (DEBUG_FLAGS & DEBUG_TINY)
5970                 printk ("<%d|%x:%x|%x:%x>",
5971                         (int)INB(nc_scr0),
5972                         dstat,sist,
5973                         (unsigned)INL(nc_dsp),
5974                         (unsigned)INL(nc_dbc));
5975
5976         /*========================================================
5977         **      First, interrupts we want to service cleanly.
5978         **
5979         **      Phase mismatch is the most frequent interrupt, and 
5980         **      so we have to service it as quickly and as cleanly 
5981         **      as possible.
5982         **      Programmed interrupts are rarely used in this driver,
5983         **      but we must handle them cleanly anyway.
5984         **      We try to deal with PAR and SBMC combined with 
5985         **      some other interrupt(s).
5986         **=========================================================
5987         */
5988
5989         if (!(sist  & (STO|GEN|HTH|SGE|UDC|RST)) &&
5990             !(dstat & (MDPE|BF|ABRT|IID))) {
5991                 if ((sist & SBMC) && ncr_int_sbmc (np))
5992                         return;
5993                 if ((sist & PAR)  && ncr_int_par  (np))
5994                         return;
5995                 if (sist & MA) {
5996                         ncr_int_ma (np);
5997                         return;
5998                 }
5999                 if (dstat & SIR) {
6000                         ncr_int_sir (np);
6001                         return;
6002                 }
6003                 /*
6004                 **  DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 2.
6005                 */
6006                 if (!(sist & (SBMC|PAR)) && !(dstat & SSI)) {
6007                         printk( "%s: unknown interrupt(s) ignored, "
6008                                 "ISTAT=%x DSTAT=%x SIST=%x\n",
6009                                 ncr_name(np), istat, dstat, sist);
6010                         return;
6011                 }
6012                 OUTONB_STD ();
6013                 return;
6014         }
6015
6016         /*========================================================
6017         **      Now, interrupts that need some fixing up.
6018         **      Order and multiple interrupts is so less important.
6019         **
6020         **      If SRST has been asserted, we just reset the chip.
6021         **
6022         **      Selection is intirely handled by the chip. If the 
6023         **      chip says STO, we trust it. Seems some other 
6024         **      interrupts may occur at the same time (UDC, IID), so 
6025         **      we ignore them. In any case we do enough fix-up 
6026         **      in the service routine.
6027         **      We just exclude some fatal dma errors.
6028         **=========================================================
6029         */
6030
6031         if (sist & RST) {
6032                 ncr_init (np, 1, bootverbose ? "scsi reset" : NULL, HS_RESET);
6033                 return;
6034         }
6035
6036         if ((sist & STO) &&
6037                 !(dstat & (MDPE|BF|ABRT))) {
6038         /*
6039         **      DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 1.
6040         */
6041                 OUTONB (nc_ctest3, CLF);
6042
6043                 ncr_int_sto (np);
6044                 return;
6045         }
6046
6047         /*=========================================================
6048         **      Now, interrupts we are not able to recover cleanly.
6049         **      (At least for the moment).
6050         **
6051         **      Do the register dump.
6052         **      Log message for real hard errors.
6053         **      Clear all fifos.
6054         **      For MDPE, BF, ABORT, IID, SGE and HTH we reset the 
6055         **      BUS and the chip.
6056         **      We are more soft for UDC.
6057         **=========================================================
6058         */
6059
6060         if (time_after(jiffies, np->regtime)) {
6061                 np->regtime = jiffies + 10*HZ;
6062                 for (i = 0; i<sizeof(np->regdump); i++)
6063                         ((char*)&np->regdump)[i] = INB_OFF(i);
6064                 np->regdump.nc_dstat = dstat;
6065                 np->regdump.nc_sist  = sist;
6066         }
6067
6068         ncr_log_hard_error(np, sist, dstat);
6069
6070         printk ("%s: have to clear fifos.\n", ncr_name (np));
6071         OUTB (nc_stest3, TE|CSF);
6072         OUTONB (nc_ctest3, CLF);
6073
6074         if ((sist & (SGE)) ||
6075                 (dstat & (MDPE|BF|ABRT|IID))) {
6076                 ncr_start_reset(np);
6077                 return;
6078         }
6079
6080         if (sist & HTH) {
6081                 printk ("%s: handshake timeout\n", ncr_name(np));
6082                 ncr_start_reset(np);
6083                 return;
6084         }
6085
6086         if (sist & UDC) {
6087                 printk ("%s: unexpected disconnect\n", ncr_name(np));
6088                 OUTB (HS_PRT, HS_UNEXPECTED);
6089                 OUTL_DSP (NCB_SCRIPT_PHYS (np, cleanup));
6090                 return;
6091         }
6092
6093         /*=========================================================
6094         **      We just miss the cause of the interrupt. :(
6095         **      Print a message. The timeout will do the real work.
6096         **=========================================================
6097         */
6098         printk ("%s: unknown interrupt\n", ncr_name(np));
6099 }
6100
6101 /*==========================================================
6102 **
6103 **      ncr chip exception handler for selection timeout
6104 **
6105 **==========================================================
6106 **
6107 **      There seems to be a bug in the 53c810.
6108 **      Although a STO-Interrupt is pending,
6109 **      it continues executing script commands.
6110 **      But it will fail and interrupt (IID) on
6111 **      the next instruction where it's looking
6112 **      for a valid phase.
6113 **
6114 **----------------------------------------------------------
6115 */
6116
6117 void ncr_int_sto (struct ncb *np)
6118 {
6119         u_long dsa;
6120         struct ccb *cp;
6121         if (DEBUG_FLAGS & DEBUG_TINY) printk ("T");
6122
6123         /*
6124         **      look for ccb and set the status.
6125         */
6126
6127         dsa = INL (nc_dsa);
6128         cp = np->ccb;
6129         while (cp && (CCB_PHYS (cp, phys) != dsa))
6130                 cp = cp->link_ccb;
6131
6132         if (cp) {
6133                 cp-> host_status = HS_SEL_TIMEOUT;
6134                 ncr_complete (np, cp);
6135         }
6136
6137         /*
6138         **      repair start queue and jump to start point.
6139         */
6140
6141         OUTL_DSP (NCB_SCRIPTH_PHYS (np, sto_restart));
6142         return;
6143 }
6144
6145 /*==========================================================
6146 **
6147 **      ncr chip exception handler for SCSI bus mode change
6148 **
6149 **==========================================================
6150 **
6151 **      spi2-r12 11.2.3 says a transceiver mode change must 
6152 **      generate a reset event and a device that detects a reset 
6153 **      event shall initiate a hard reset. It says also that a
6154 **      device that detects a mode change shall set data transfer 
6155 **      mode to eight bit asynchronous, etc...
6156 **      So, just resetting should be enough.
6157 **       
6158 **
6159 **----------------------------------------------------------
6160 */
6161
6162 static int ncr_int_sbmc (struct ncb *np)
6163 {
6164         u_char scsi_mode = INB (nc_stest4) & SMODE;
6165
6166         if (scsi_mode != np->scsi_mode) {
6167                 printk("%s: SCSI bus mode change from %x to %x.\n",
6168                         ncr_name(np), np->scsi_mode, scsi_mode);
6169
6170                 np->scsi_mode = scsi_mode;
6171
6172
6173                 /*
6174                 **      Suspend command processing for 1 second and 
6175                 **      reinitialize all except the chip.
6176                 */
6177                 np->settle_time = jiffies + HZ;
6178                 ncr_init (np, 0, bootverbose ? "scsi mode change" : NULL, HS_RESET);
6179                 return 1;
6180         }
6181         return 0;
6182 }
6183
6184 /*==========================================================
6185 **
6186 **      ncr chip exception handler for SCSI parity error.
6187 **
6188 **==========================================================
6189 **
6190 **
6191 **----------------------------------------------------------
6192 */
6193
6194 static int ncr_int_par (struct ncb *np)
6195 {
6196         u_char  hsts    = INB (HS_PRT);
6197         u32     dbc     = INL (nc_dbc);
6198         u_char  sstat1  = INB (nc_sstat1);
6199         int phase       = -1;
6200         int msg         = -1;
6201         u32 jmp;
6202
6203         printk("%s: SCSI parity error detected: SCR1=%d DBC=%x SSTAT1=%x\n",
6204                 ncr_name(np), hsts, dbc, sstat1);
6205
6206         /*
6207          *      Ignore the interrupt if the NCR is not connected 
6208          *      to the SCSI bus, since the right work should have  
6209          *      been done on unexpected disconnection handling.
6210          */
6211         if (!(INB (nc_scntl1) & ISCON))
6212                 return 0;
6213
6214         /*
6215          *      If the nexus is not clearly identified, reset the bus.
6216          *      We will try to do better later.
6217          */
6218         if (hsts & HS_INVALMASK)
6219                 goto reset_all;
6220
6221         /*
6222          *      If the SCSI parity error occurs in MSG IN phase, prepare a 
6223          *      MSG PARITY message. Otherwise, prepare a INITIATOR DETECTED 
6224          *      ERROR message and let the device decide to retry the command 
6225          *      or to terminate with check condition. If we were in MSG IN 
6226          *      phase waiting for the response of a negotiation, we will 
6227          *      get SIR_NEGO_FAILED at dispatch.
6228          */
6229         if (!(dbc & 0xc0000000))
6230                 phase = (dbc >> 24) & 7;
6231         if (phase == 7)
6232                 msg = M_PARITY;
6233         else
6234                 msg = M_ID_ERROR;
6235
6236
6237         /*
6238          *      If the NCR stopped on a MOVE ^ DATA_IN, we jump to a 
6239          *      script that will ignore all data in bytes until phase 
6240          *      change, since we are not sure the chip will wait the phase 
6241          *      change prior to delivering the interrupt.
6242          */
6243         if (phase == 1)
6244                 jmp = NCB_SCRIPTH_PHYS (np, par_err_data_in);
6245         else
6246                 jmp = NCB_SCRIPTH_PHYS (np, par_err_other);
6247
6248         OUTONB (nc_ctest3, CLF );       /* clear dma fifo  */
6249         OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
6250
6251         np->msgout[0] = msg;
6252         OUTL_DSP (jmp);
6253         return 1;
6254
6255 reset_all:
6256         ncr_start_reset(np);
6257         return 1;
6258 }
6259
6260 /*==========================================================
6261 **
6262 **
6263 **      ncr chip exception handler for phase errors.
6264 **
6265 **
6266 **==========================================================
6267 **
6268 **      We have to construct a new transfer descriptor,
6269 **      to transfer the rest of the current block.
6270 **
6271 **----------------------------------------------------------
6272 */
6273
6274 static void ncr_int_ma (struct ncb *np)
6275 {
6276         u32     dbc;
6277         u32     rest;
6278         u32     dsp;
6279         u32     dsa;
6280         u32     nxtdsp;
6281         u32     newtmp;
6282         u32     *vdsp;
6283         u32     oadr, olen;
6284         u32     *tblp;
6285         ncrcmd *newcmd;
6286         u_char  cmd, sbcl;
6287         struct ccb *cp;
6288
6289         dsp     = INL (nc_dsp);
6290         dbc     = INL (nc_dbc);
6291         sbcl    = INB (nc_sbcl);
6292
6293         cmd     = dbc >> 24;
6294         rest    = dbc & 0xffffff;
6295
6296         /*
6297         **      Take into account dma fifo and various buffers and latches,
6298         **      only if the interrupted phase is an OUTPUT phase.
6299         */
6300
6301         if ((cmd & 1) == 0) {
6302                 u_char  ctest5, ss0, ss2;
6303                 u16     delta;
6304
6305                 ctest5 = (np->rv_ctest5 & DFS) ? INB (nc_ctest5) : 0;
6306                 if (ctest5 & DFS)
6307                         delta=(((ctest5 << 8) | (INB (nc_dfifo) & 0xff)) - rest) & 0x3ff;
6308                 else
6309                         delta=(INB (nc_dfifo) - rest) & 0x7f;
6310
6311                 /*
6312                 **      The data in the dma fifo has not been transferred to
6313                 **      the target -> add the amount to the rest
6314                 **      and clear the data.
6315                 **      Check the sstat2 register in case of wide transfer.
6316                 */
6317
6318                 rest += delta;
6319                 ss0  = INB (nc_sstat0);
6320                 if (ss0 & OLF) rest++;
6321                 if (ss0 & ORF) rest++;
6322                 if (INB(nc_scntl3) & EWS) {
6323                         ss2 = INB (nc_sstat2);
6324                         if (ss2 & OLF1) rest++;
6325                         if (ss2 & ORF1) rest++;
6326                 }
6327
6328                 if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6329                         printk ("P%x%x RL=%d D=%d SS0=%x ", cmd&7, sbcl&7,
6330                                 (unsigned) rest, (unsigned) delta, ss0);
6331
6332         } else  {
6333                 if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6334                         printk ("P%x%x RL=%d ", cmd&7, sbcl&7, rest);
6335         }
6336
6337         /*
6338         **      Clear fifos.
6339         */
6340         OUTONB (nc_ctest3, CLF );       /* clear dma fifo  */
6341         OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
6342
6343         /*
6344         **      locate matching cp.
6345         **      if the interrupted phase is DATA IN or DATA OUT,
6346         **      trust the global header.
6347         */
6348         dsa = INL (nc_dsa);
6349         if (!(cmd & 6)) {
6350                 cp = np->header.cp;
6351                 if (CCB_PHYS(cp, phys) != dsa)
6352                         cp = NULL;
6353         } else {
6354                 cp  = np->ccb;
6355                 while (cp && (CCB_PHYS (cp, phys) != dsa))
6356                         cp = cp->link_ccb;
6357         }
6358
6359         /*
6360         **      try to find the interrupted script command,
6361         **      and the address at which to continue.
6362         */
6363         vdsp    = NULL;
6364         nxtdsp  = 0;
6365         if      (dsp >  np->p_script &&
6366                  dsp <= np->p_script + sizeof(struct script)) {
6367                 vdsp = (u32 *)((char*)np->script0 + (dsp-np->p_script-8));
6368                 nxtdsp = dsp;
6369         }
6370         else if (dsp >  np->p_scripth &&
6371                  dsp <= np->p_scripth + sizeof(struct scripth)) {
6372                 vdsp = (u32 *)((char*)np->scripth0 + (dsp-np->p_scripth-8));
6373                 nxtdsp = dsp;
6374         }
6375         else if (cp) {
6376                 if      (dsp == CCB_PHYS (cp, patch[2])) {
6377                         vdsp = &cp->patch[0];
6378                         nxtdsp = scr_to_cpu(vdsp[3]);
6379                 }
6380                 else if (dsp == CCB_PHYS (cp, patch[6])) {
6381                         vdsp = &cp->patch[4];
6382                         nxtdsp = scr_to_cpu(vdsp[3]);
6383                 }
6384         }
6385
6386         /*
6387         **      log the information
6388         */
6389
6390         if (DEBUG_FLAGS & DEBUG_PHASE) {
6391                 printk ("\nCP=%p CP2=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
6392                         cp, np->header.cp,
6393                         (unsigned)dsp,
6394                         (unsigned)nxtdsp, vdsp, cmd);
6395         }
6396
6397         /*
6398         **      cp=0 means that the DSA does not point to a valid control 
6399         **      block. This should not happen since we donnot use multi-byte 
6400         **      move while we are being reselected ot after command complete.
6401         **      We are not able to recover from such a phase error.
6402         */
6403         if (!cp) {
6404                 printk ("%s: SCSI phase error fixup: "
6405                         "CCB already dequeued (0x%08lx)\n", 
6406                         ncr_name (np), (u_long) np->header.cp);
6407                 goto reset_all;
6408         }
6409
6410         /*
6411         **      get old startaddress and old length.
6412         */
6413
6414         oadr = scr_to_cpu(vdsp[1]);
6415
6416         if (cmd & 0x10) {       /* Table indirect */
6417                 tblp = (u32 *) ((char*) &cp->phys + oadr);
6418                 olen = scr_to_cpu(tblp[0]);
6419                 oadr = scr_to_cpu(tblp[1]);
6420         } else {
6421                 tblp = (u32 *) 0;
6422                 olen = scr_to_cpu(vdsp[0]) & 0xffffff;
6423         }
6424
6425         if (DEBUG_FLAGS & DEBUG_PHASE) {
6426                 printk ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
6427                         (unsigned) (scr_to_cpu(vdsp[0]) >> 24),
6428                         tblp,
6429                         (unsigned) olen,
6430                         (unsigned) oadr);
6431         }
6432
6433         /*
6434         **      check cmd against assumed interrupted script command.
6435         */
6436
6437         if (cmd != (scr_to_cpu(vdsp[0]) >> 24)) {
6438                 PRINT_ADDR(cp->cmd, "internal error: cmd=%02x != %02x=(vdsp[0] "
6439                                 ">> 24)\n", cmd, scr_to_cpu(vdsp[0]) >> 24);
6440
6441                 goto reset_all;
6442         }
6443
6444         /*
6445         **      cp != np->header.cp means that the header of the CCB 
6446         **      currently being processed has not yet been copied to 
6447         **      the global header area. That may happen if the device did 
6448         **      not accept all our messages after having been selected.
6449         */
6450         if (cp != np->header.cp) {
6451                 printk ("%s: SCSI phase error fixup: "
6452                         "CCB address mismatch (0x%08lx != 0x%08lx)\n", 
6453                         ncr_name (np), (u_long) cp, (u_long) np->header.cp);
6454         }
6455
6456         /*
6457         **      if old phase not dataphase, leave here.
6458         */
6459
6460         if (cmd & 0x06) {
6461                 PRINT_ADDR(cp->cmd, "phase change %x-%x %d@%08x resid=%d.\n",
6462                         cmd&7, sbcl&7, (unsigned)olen,
6463                         (unsigned)oadr, (unsigned)rest);
6464                 goto unexpected_phase;
6465         }
6466
6467         /*
6468         **      choose the correct patch area.
6469         **      if savep points to one, choose the other.
6470         */
6471
6472         newcmd = cp->patch;
6473         newtmp = CCB_PHYS (cp, patch);
6474         if (newtmp == scr_to_cpu(cp->phys.header.savep)) {
6475                 newcmd = &cp->patch[4];
6476                 newtmp = CCB_PHYS (cp, patch[4]);
6477         }
6478
6479         /*
6480         **      fillin the commands
6481         */
6482
6483         newcmd[0] = cpu_to_scr(((cmd & 0x0f) << 24) | rest);
6484         newcmd[1] = cpu_to_scr(oadr + olen - rest);
6485         newcmd[2] = cpu_to_scr(SCR_JUMP);
6486         newcmd[3] = cpu_to_scr(nxtdsp);
6487
6488         if (DEBUG_FLAGS & DEBUG_PHASE) {
6489                 PRINT_ADDR(cp->cmd, "newcmd[%d] %x %x %x %x.\n",
6490                         (int) (newcmd - cp->patch),
6491                         (unsigned)scr_to_cpu(newcmd[0]),
6492                         (unsigned)scr_to_cpu(newcmd[1]),
6493                         (unsigned)scr_to_cpu(newcmd[2]),
6494                         (unsigned)scr_to_cpu(newcmd[3]));
6495         }
6496         /*
6497         **      fake the return address (to the patch).
6498         **      and restart script processor at dispatcher.
6499         */
6500         OUTL (nc_temp, newtmp);
6501         OUTL_DSP (NCB_SCRIPT_PHYS (np, dispatch));
6502         return;
6503
6504         /*
6505         **      Unexpected phase changes that occurs when the current phase 
6506         **      is not a DATA IN or DATA OUT phase are due to error conditions.
6507         **      Such event may only happen when the SCRIPTS is using a 
6508         **      multibyte SCSI MOVE.
6509         **
6510         **      Phase change            Some possible cause
6511         **
6512         **      COMMAND  --> MSG IN     SCSI parity error detected by target.
6513         **      COMMAND  --> STATUS     Bad command or refused by target.
6514         **      MSG OUT  --> MSG IN     Message rejected by target.
6515         **      MSG OUT  --> COMMAND    Bogus target that discards extended
6516         **                              negotiation messages.
6517         **
6518         **      The code below does not care of the new phase and so 
6519         **      trusts the target. Why to annoy it ?
6520         **      If the interrupted phase is COMMAND phase, we restart at
6521         **      dispatcher.
6522         **      If a target does not get all the messages after selection, 
6523         **      the code assumes blindly that the target discards extended 
6524         **      messages and clears the negotiation status.
6525         **      If the target does not want all our response to negotiation,
6526         **      we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids 
6527         **      bloat for such a should_not_happen situation).
6528         **      In all other situation, we reset the BUS.
6529         **      Are these assumptions reasonnable ? (Wait and see ...)
6530         */
6531 unexpected_phase:
6532         dsp -= 8;
6533         nxtdsp = 0;
6534
6535         switch (cmd & 7) {
6536         case 2: /* COMMAND phase */
6537                 nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
6538                 break;
6539 #if 0
6540         case 3: /* STATUS  phase */
6541                 nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
6542                 break;
6543 #endif
6544         case 6: /* MSG OUT phase */
6545                 np->scripth->nxtdsp_go_on[0] = cpu_to_scr(dsp + 8);
6546                 if      (dsp == NCB_SCRIPT_PHYS (np, send_ident)) {
6547                         cp->host_status = HS_BUSY;
6548                         nxtdsp = NCB_SCRIPTH_PHYS (np, clratn_go_on);
6549                 }
6550                 else if (dsp == NCB_SCRIPTH_PHYS (np, send_wdtr) ||
6551                          dsp == NCB_SCRIPTH_PHYS (np, send_sdtr)) {
6552                         nxtdsp = NCB_SCRIPTH_PHYS (np, nego_bad_phase);
6553                 }
6554                 break;
6555 #if 0
6556         case 7: /* MSG IN  phase */
6557                 nxtdsp = NCB_SCRIPT_PHYS (np, clrack);
6558                 break;
6559 #endif
6560         }
6561
6562         if (nxtdsp) {
6563                 OUTL_DSP (nxtdsp);
6564                 return;
6565         }
6566
6567 reset_all:
6568         ncr_start_reset(np);
6569 }
6570
6571
6572 static void ncr_sir_to_redo(struct ncb *np, int num, struct ccb *cp)
6573 {
6574         struct scsi_cmnd *cmd   = cp->cmd;
6575         struct tcb *tp  = &np->target[cmd->device->id];
6576         struct lcb *lp  = tp->lp[cmd->device->lun];
6577         struct list_head *qp;
6578         struct ccb *    cp2;
6579         int             disc_cnt = 0;
6580         int             busy_cnt = 0;
6581         u32             startp;
6582         u_char          s_status = INB (SS_PRT);
6583
6584         /*
6585         **      Let the SCRIPTS processor skip all not yet started CCBs,
6586         **      and count disconnected CCBs. Since the busy queue is in 
6587         **      the same order as the chip start queue, disconnected CCBs 
6588         **      are before cp and busy ones after.
6589         */
6590         if (lp) {
6591                 qp = lp->busy_ccbq.prev;
6592                 while (qp != &lp->busy_ccbq) {
6593                         cp2 = list_entry(qp, struct ccb, link_ccbq);
6594                         qp  = qp->prev;
6595                         ++busy_cnt;
6596                         if (cp2 == cp)
6597                                 break;
6598                         cp2->start.schedule.l_paddr =
6599                         cpu_to_scr(NCB_SCRIPTH_PHYS (np, skip));
6600                 }
6601                 lp->held_ccb = cp;      /* Requeue when this one completes */
6602                 disc_cnt = lp->queuedccbs - busy_cnt;
6603         }
6604
6605         switch(s_status) {
6606         default:        /* Just for safety, should never happen */
6607         case S_QUEUE_FULL:
6608                 /*
6609                 **      Decrease number of tags to the number of 
6610                 **      disconnected commands.
6611                 */
6612                 if (!lp)
6613                         goto out;
6614                 if (bootverbose >= 1) {
6615                         PRINT_ADDR(cmd, "QUEUE FULL! %d busy, %d disconnected "
6616                                         "CCBs\n", busy_cnt, disc_cnt);
6617                 }
6618                 if (disc_cnt < lp->numtags) {
6619                         lp->numtags     = disc_cnt > 2 ? disc_cnt : 2;
6620                         lp->num_good    = 0;
6621                         ncr_setup_tags (np, cmd->device);
6622                 }
6623                 /*
6624                 **      Requeue the command to the start queue.
6625                 **      If any disconnected commands,
6626                 **              Clear SIGP.
6627                 **              Jump to reselect.
6628                 */
6629                 cp->phys.header.savep = cp->startp;
6630                 cp->host_status = HS_BUSY;
6631                 cp->scsi_status = S_ILLEGAL;
6632
6633                 ncr_put_start_queue(np, cp);
6634                 if (disc_cnt)
6635                         INB (nc_ctest2);                /* Clear SIGP */
6636                 OUTL_DSP (NCB_SCRIPT_PHYS (np, reselect));
6637                 return;
6638         case S_TERMINATED:
6639         case S_CHECK_COND:
6640                 /*
6641                 **      If we were requesting sense, give up.
6642                 */
6643                 if (cp->auto_sense)
6644                         goto out;
6645
6646                 /*
6647                 **      Device returned CHECK CONDITION status.
6648                 **      Prepare all needed data strutures for getting 
6649                 **      sense data.
6650                 **
6651                 **      identify message
6652                 */
6653                 cp->scsi_smsg2[0]       = IDENTIFY(0, cmd->device->lun);
6654                 cp->phys.smsg.addr      = cpu_to_scr(CCB_PHYS (cp, scsi_smsg2));
6655                 cp->phys.smsg.size      = cpu_to_scr(1);
6656
6657                 /*
6658                 **      sense command
6659                 */
6660                 cp->phys.cmd.addr       = cpu_to_scr(CCB_PHYS (cp, sensecmd));
6661                 cp->phys.cmd.size       = cpu_to_scr(6);
6662
6663                 /*
6664                 **      patch requested size into sense command
6665                 */
6666                 cp->sensecmd[0]         = 0x03;
6667                 cp->sensecmd[1]         = cmd->device->lun << 5;
6668                 cp->sensecmd[4]         = sizeof(cp->sense_buf);
6669
6670                 /*
6671                 **      sense data
6672                 */
6673                 memset(cp->sense_buf, 0, sizeof(cp->sense_buf));
6674                 cp->phys.sense.addr     = cpu_to_scr(CCB_PHYS(cp,sense_buf[0]));
6675                 cp->phys.sense.size     = cpu_to_scr(sizeof(cp->sense_buf));
6676
6677                 /*
6678                 **      requeue the command.
6679                 */
6680                 startp = cpu_to_scr(NCB_SCRIPTH_PHYS (np, sdata_in));
6681
6682                 cp->phys.header.savep   = startp;
6683                 cp->phys.header.goalp   = startp + 24;
6684                 cp->phys.header.lastp   = startp;
6685                 cp->phys.header.wgoalp  = startp + 24;
6686                 cp->phys.header.wlastp  = startp;
6687
6688                 cp->host_status = HS_BUSY;
6689                 cp->scsi_status = S_ILLEGAL;
6690                 cp->auto_sense  = s_status;
6691
6692                 cp->start.schedule.l_paddr =
6693                         cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
6694
6695                 /*
6696                 **      Select without ATN for quirky devices.
6697                 */
6698                 if (cmd->device->select_no_atn)
6699                         cp->start.schedule.l_paddr =
6700                         cpu_to_scr(NCB_SCRIPTH_PHYS (np, select_no_atn));
6701
6702                 ncr_put_start_queue(np, cp);
6703
6704                 OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
6705                 return;
6706         }
6707
6708 out:
6709         OUTONB_STD ();
6710         return;
6711 }
6712
6713
6714 /*==========================================================
6715 **
6716 **
6717 **      ncr chip exception handler for programmed interrupts.
6718 **
6719 **
6720 **==========================================================
6721 */
6722
6723 void ncr_int_sir (struct ncb *np)
6724 {
6725         u_char scntl3;
6726         u_char chg, ofs, per, fak, wide;
6727         u_char num = INB (nc_dsps);
6728         struct ccb *cp=NULL;
6729         u_long  dsa    = INL (nc_dsa);
6730         u_char  target = INB (nc_sdid) & 0x0f;
6731         struct tcb *tp     = &np->target[target];
6732         struct scsi_target *starget = tp->starget;
6733
6734         if (DEBUG_FLAGS & DEBUG_TINY) printk ("I#%d", num);
6735
6736         switch (num) {
6737         case SIR_INTFLY:
6738                 /*
6739                 **      This is used for HP Zalon/53c720 where INTFLY
6740                 **      operation is currently broken.
6741                 */
6742                 ncr_wakeup_done(np);
6743 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
6744                 OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, done_end) + 8);
6745 #else
6746                 OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, start));
6747 #endif
6748                 return;
6749         case SIR_RESEL_NO_MSG_IN:
6750         case SIR_RESEL_NO_IDENTIFY:
6751                 /*
6752                 **      If devices reselecting without sending an IDENTIFY 
6753                 **      message still exist, this should help.
6754                 **      We just assume lun=0, 1 CCB, no tag.
6755                 */
6756                 if (tp->lp[0]) { 
6757                         OUTL_DSP (scr_to_cpu(tp->lp[0]->jump_ccb[0]));
6758                         return;
6759                 }
6760         case SIR_RESEL_BAD_TARGET:      /* Will send a TARGET RESET message */
6761         case SIR_RESEL_BAD_LUN:         /* Will send a TARGET RESET message */
6762         case SIR_RESEL_BAD_I_T_L_Q:     /* Will send an ABORT TAG message   */
6763         case SIR_RESEL_BAD_I_T_L:       /* Will send an ABORT message       */
6764                 printk ("%s:%d: SIR %d, "
6765                         "incorrect nexus identification on reselection\n",
6766                         ncr_name (np), target, num);
6767                 goto out;
6768         case SIR_DONE_OVERFLOW:
6769                 printk ("%s:%d: SIR %d, "
6770                         "CCB done queue overflow\n",
6771                         ncr_name (np), target, num);
6772                 goto out;
6773         case SIR_BAD_STATUS:
6774                 cp = np->header.cp;
6775                 if (!cp || CCB_PHYS (cp, phys) != dsa)
6776                         goto out;
6777                 ncr_sir_to_redo(np, num, cp);
6778                 return;
6779         default:
6780                 /*
6781                 **      lookup the ccb
6782                 */
6783                 cp = np->ccb;
6784                 while (cp && (CCB_PHYS (cp, phys) != dsa))
6785                         cp = cp->link_ccb;
6786
6787                 BUG_ON(!cp);
6788                 BUG_ON(cp != np->header.cp);
6789
6790                 if (!cp || cp != np->header.cp)
6791                         goto out;
6792         }
6793
6794         switch (num) {
6795 /*-----------------------------------------------------------------------------
6796 **
6797 **      Was Sie schon immer ueber transfermode negotiation wissen wollten ...
6798 **
6799 **      We try to negotiate sync and wide transfer only after
6800 **      a successful inquire command. We look at byte 7 of the
6801 **      inquire data to determine the capabilities of the target.
6802 **
6803 **      When we try to negotiate, we append the negotiation message
6804 **      to the identify and (maybe) simple tag message.
6805 **      The host status field is set to HS_NEGOTIATE to mark this
6806 **      situation.
6807 **
6808 **      If the target doesn't answer this message immidiately
6809 **      (as required by the standard), the SIR_NEGO_FAIL interrupt
6810 **      will be raised eventually.
6811 **      The handler removes the HS_NEGOTIATE status, and sets the
6812 **      negotiated value to the default (async / nowide).
6813 **
6814 **      If we receive a matching answer immediately, we check it
6815 **      for validity, and set the values.
6816 **
6817 **      If we receive a Reject message immediately, we assume the
6818 **      negotiation has failed, and fall back to standard values.
6819 **
6820 **      If we receive a negotiation message while not in HS_NEGOTIATE
6821 **      state, it's a target initiated negotiation. We prepare a
6822 **      (hopefully) valid answer, set our parameters, and send back 
6823 **      this answer to the target.
6824 **
6825 **      If the target doesn't fetch the answer (no message out phase),
6826 **      we assume the negotiation has failed, and fall back to default
6827 **      settings.
6828 **
6829 **      When we set the values, we adjust them in all ccbs belonging 
6830 **      to this target, in the controller's register, and in the "phys"
6831 **      field of the controller's struct ncb.
6832 **
6833 **      Possible cases:            hs  sir   msg_in value  send   goto
6834 **      We try to negotiate:
6835 **      -> target doesn't msgin    NEG FAIL  noop   defa.  -      dispatch
6836 **      -> target rejected our msg NEG FAIL  reject defa.  -      dispatch
6837 **      -> target answered  (ok)   NEG SYNC  sdtr   set    -      clrack
6838 **      -> target answered (!ok)   NEG SYNC  sdtr   defa.  REJ--->msg_bad
6839 **      -> target answered  (ok)   NEG WIDE  wdtr   set    -      clrack
6840 **      -> target answered (!ok)   NEG WIDE  wdtr   defa.  REJ--->msg_bad
6841 **      -> any other msgin         NEG FAIL  noop   defa.  -      dispatch
6842 **
6843 **      Target tries to negotiate:
6844 **      -> incoming message        --- SYNC  sdtr   set    SDTR   -
6845 **      -> incoming message        --- WIDE  wdtr   set    WDTR   -
6846 **      We sent our answer:
6847 **      -> target doesn't msgout   --- PROTO ?      defa.  -      dispatch
6848 **
6849 **-----------------------------------------------------------------------------
6850 */
6851
6852         case SIR_NEGO_FAILED:
6853                 /*-------------------------------------------------------
6854                 **
6855                 **      Negotiation failed.
6856                 **      Target doesn't send an answer message,
6857                 **      or target rejected our message.
6858                 **
6859                 **      Remove negotiation request.
6860                 **
6861                 **-------------------------------------------------------
6862                 */
6863                 OUTB (HS_PRT, HS_BUSY);
6864
6865                 /* fall through */
6866
6867         case SIR_NEGO_PROTO:
6868                 /*-------------------------------------------------------
6869                 **
6870                 **      Negotiation failed.
6871                 **      Target doesn't fetch the answer message.
6872                 **
6873                 **-------------------------------------------------------
6874                 */
6875
6876                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6877                         PRINT_ADDR(cp->cmd, "negotiation failed sir=%x "
6878                                         "status=%x.\n", num, cp->nego_status);
6879                 }
6880
6881                 /*
6882                 **      any error in negotiation:
6883                 **      fall back to default mode.
6884                 */
6885                 switch (cp->nego_status) {
6886
6887                 case NS_SYNC:
6888                         spi_period(starget) = 0;
6889                         spi_offset(starget) = 0;
6890                         ncr_setsync (np, cp, 0, 0xe0);
6891                         break;
6892
6893                 case NS_WIDE:
6894                         spi_width(starget) = 0;
6895                         ncr_setwide (np, cp, 0, 0);
6896                         break;
6897
6898                 }
6899                 np->msgin [0] = M_NOOP;
6900                 np->msgout[0] = M_NOOP;
6901                 cp->nego_status = 0;
6902                 break;
6903
6904         case SIR_NEGO_SYNC:
6905                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6906                         ncr_print_msg(cp, "sync msgin", np->msgin);
6907                 }
6908
6909                 chg = 0;
6910                 per = np->msgin[3];
6911                 ofs = np->msgin[4];
6912                 if (ofs==0) per=255;
6913
6914                 /*
6915                 **      if target sends SDTR message,
6916                 **            it CAN transfer synch.
6917                 */
6918
6919                 if (ofs && starget)
6920                         spi_support_sync(starget) = 1;
6921
6922                 /*
6923                 **      check values against driver limits.
6924                 */
6925
6926                 if (per < np->minsync)
6927                         {chg = 1; per = np->minsync;}
6928                 if (per < tp->minsync)
6929                         {chg = 1; per = tp->minsync;}
6930                 if (ofs > tp->maxoffs)
6931                         {chg = 1; ofs = tp->maxoffs;}
6932
6933                 /*
6934                 **      Check against controller limits.
6935                 */
6936                 fak     = 7;
6937                 scntl3  = 0;
6938                 if (ofs != 0) {
6939                         ncr_getsync(np, per, &fak, &scntl3);
6940                         if (fak > 7) {
6941                                 chg = 1;
6942                                 ofs = 0;
6943                         }
6944                 }
6945                 if (ofs == 0) {
6946                         fak     = 7;
6947                         per     = 0;
6948                         scntl3  = 0;
6949                         tp->minsync = 0;
6950                 }
6951
6952                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6953                         PRINT_ADDR(cp->cmd, "sync: per=%d scntl3=0x%x ofs=%d "
6954                                 "fak=%d chg=%d.\n", per, scntl3, ofs, fak, chg);
6955                 }
6956
6957                 if (INB (HS_PRT) == HS_NEGOTIATE) {
6958                         OUTB (HS_PRT, HS_BUSY);
6959                         switch (cp->nego_status) {
6960
6961                         case NS_SYNC:
6962                                 /* This was an answer message */
6963                                 if (chg) {
6964                                         /* Answer wasn't acceptable.  */
6965                                         spi_period(starget) = 0;
6966                                         spi_offset(starget) = 0;
6967                                         ncr_setsync(np, cp, 0, 0xe0);
6968                                         OUTL_DSP(NCB_SCRIPT_PHYS (np, msg_bad));
6969                                 } else {
6970                                         /* Answer is ok.  */
6971                                         spi_period(starget) = per;
6972                                         spi_offset(starget) = ofs;
6973                                         ncr_setsync(np, cp, scntl3, (fak<<5)|ofs);
6974                                         OUTL_DSP(NCB_SCRIPT_PHYS (np, clrack));
6975                                 }
6976                                 return;
6977
6978                         case NS_WIDE:
6979                                 spi_width(starget) = 0;
6980                                 ncr_setwide(np, cp, 0, 0);
6981                                 break;
6982                         }
6983                 }
6984
6985                 /*
6986                 **      It was a request. Set value and
6987                 **      prepare an answer message
6988                 */
6989
6990                 spi_period(starget) = per;
6991                 spi_offset(starget) = ofs;
6992                 ncr_setsync(np, cp, scntl3, (fak<<5)|ofs);
6993
6994                 np->msgout[0] = M_EXTENDED;
6995                 np->msgout[1] = 3;
6996                 np->msgout[2] = M_X_SYNC_REQ;
6997                 np->msgout[3] = per;
6998                 np->msgout[4] = ofs;
6999
7000                 cp->nego_status = NS_SYNC;
7001
7002                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7003                         ncr_print_msg(cp, "sync msgout", np->msgout);
7004                 }
7005
7006                 if (!ofs) {
7007                         OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7008                         return;
7009                 }
7010                 np->msgin [0] = M_NOOP;
7011
7012                 break;
7013
7014         case SIR_NEGO_WIDE:
7015                 /*
7016                 **      Wide request message received.
7017                 */
7018                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7019                         ncr_print_msg(cp, "wide msgin", np->msgin);
7020                 }
7021
7022                 /*
7023                 **      get requested values.
7024                 */
7025
7026                 chg  = 0;
7027                 wide = np->msgin[3];
7028
7029                 /*
7030                 **      if target sends WDTR message,
7031                 **            it CAN transfer wide.
7032                 */
7033
7034                 if (wide && starget)
7035                         spi_support_wide(starget) = 1;
7036
7037                 /*
7038                 **      check values against driver limits.
7039                 */
7040
7041                 if (wide > tp->usrwide)
7042                         {chg = 1; wide = tp->usrwide;}
7043
7044                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7045                         PRINT_ADDR(cp->cmd, "wide: wide=%d chg=%d.\n", wide,
7046                                         chg);
7047                 }
7048
7049                 if (INB (HS_PRT) == HS_NEGOTIATE) {
7050                         OUTB (HS_PRT, HS_BUSY);
7051                         switch (cp->nego_status) {
7052
7053                         case NS_WIDE:
7054                                 /*
7055                                 **      This was an answer message
7056                                 */
7057                                 if (chg) {
7058                                         /* Answer wasn't acceptable.  */
7059                                         spi_width(starget) = 0;
7060                                         ncr_setwide(np, cp, 0, 1);
7061                                         OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7062                                 } else {
7063                                         /* Answer is ok.  */
7064                                         spi_width(starget) = wide;
7065                                         ncr_setwide(np, cp, wide, 1);
7066                                         OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
7067                                 }
7068                                 return;
7069
7070                         case NS_SYNC:
7071                                 spi_period(starget) = 0;
7072                                 spi_offset(starget) = 0;
7073                                 ncr_setsync(np, cp, 0, 0xe0);
7074                                 break;
7075                         }
7076                 }
7077
7078                 /*
7079                 **      It was a request, set value and
7080                 **      prepare an answer message
7081                 */
7082
7083                 spi_width(starget) = wide;
7084                 ncr_setwide(np, cp, wide, 1);
7085
7086                 np->msgout[0] = M_EXTENDED;
7087                 np->msgout[1] = 2;
7088                 np->msgout[2] = M_X_WIDE_REQ;
7089                 np->msgout[3] = wide;
7090
7091                 np->msgin [0] = M_NOOP;
7092
7093                 cp->nego_status = NS_WIDE;
7094
7095                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7096                         ncr_print_msg(cp, "wide msgout", np->msgin);
7097                 }
7098                 break;
7099
7100 /*--------------------------------------------------------------------
7101 **
7102 **      Processing of special messages
7103 **
7104 **--------------------------------------------------------------------
7105 */
7106
7107         case SIR_REJECT_RECEIVED:
7108                 /*-----------------------------------------------
7109                 **
7110                 **      We received a M_REJECT message.
7111                 **
7112                 **-----------------------------------------------
7113                 */
7114
7115                 PRINT_ADDR(cp->cmd, "M_REJECT received (%x:%x).\n",
7116                         (unsigned)scr_to_cpu(np->lastmsg), np->msgout[0]);
7117                 break;
7118
7119         case SIR_REJECT_SENT:
7120                 /*-----------------------------------------------
7121                 **
7122                 **      We received an unknown message
7123                 **
7124                 **-----------------------------------------------
7125                 */
7126
7127                 ncr_print_msg(cp, "M_REJECT sent for", np->msgin);
7128                 break;
7129
7130 /*--------------------------------------------------------------------
7131 **
7132 **      Processing of special messages
7133 **
7134 **--------------------------------------------------------------------
7135 */
7136
7137         case SIR_IGN_RESIDUE:
7138                 /*-----------------------------------------------
7139                 **
7140                 **      We received an IGNORE RESIDUE message,
7141                 **      which couldn't be handled by the script.
7142                 **
7143                 **-----------------------------------------------
7144                 */
7145
7146                 PRINT_ADDR(cp->cmd, "M_IGN_RESIDUE received, but not yet "
7147                                 "implemented.\n");
7148                 break;
7149 #if 0
7150         case SIR_MISSING_SAVE:
7151                 /*-----------------------------------------------
7152                 **
7153                 **      We received an DISCONNECT message,
7154                 **      but the datapointer wasn't saved before.
7155                 **
7156                 **-----------------------------------------------
7157                 */
7158
7159                 PRINT_ADDR(cp->cmd, "M_DISCONNECT received, but datapointer "
7160                                 "not saved: data=%x save=%x goal=%x.\n",
7161                         (unsigned) INL (nc_temp),
7162                         (unsigned) scr_to_cpu(np->header.savep),
7163                         (unsigned) scr_to_cpu(np->header.goalp));
7164                 break;
7165 #endif
7166         }
7167
7168 out:
7169         OUTONB_STD ();
7170 }
7171
7172 /*==========================================================
7173 **
7174 **
7175 **      Acquire a control block
7176 **
7177 **
7178 **==========================================================
7179 */
7180
7181 static struct ccb *ncr_get_ccb(struct ncb *np, struct scsi_cmnd *cmd)
7182 {
7183         u_char tn = cmd->device->id;
7184         u_char ln = cmd->device->lun;
7185         struct tcb *tp = &np->target[tn];
7186         struct lcb *lp = tp->lp[ln];
7187         u_char tag = NO_TAG;
7188         struct ccb *cp = NULL;
7189
7190         /*
7191         **      Lun structure available ?
7192         */
7193         if (lp) {
7194                 struct list_head *qp;
7195                 /*
7196                 **      Keep from using more tags than we can handle.
7197                 */
7198                 if (lp->usetags && lp->busyccbs >= lp->maxnxs)
7199                         return NULL;
7200
7201                 /*
7202                 **      Allocate a new CCB if needed.
7203                 */
7204                 if (list_empty(&lp->free_ccbq))
7205                         ncr_alloc_ccb(np, tn, ln);
7206
7207                 /*
7208                 **      Look for free CCB
7209                 */
7210                 qp = ncr_list_pop(&lp->free_ccbq);
7211                 if (qp) {
7212                         cp = list_entry(qp, struct ccb, link_ccbq);
7213                         if (cp->magic) {
7214                                 PRINT_ADDR(cmd, "ccb free list corrupted "
7215                                                 "(@%p)\n", cp);
7216                                 cp = NULL;
7217                         } else {
7218                                 list_add_tail(qp, &lp->wait_ccbq);
7219                                 ++lp->busyccbs;
7220                         }
7221                 }
7222
7223                 /*
7224                 **      If a CCB is available,
7225                 **      Get a tag for this nexus if required.
7226                 */
7227                 if (cp) {
7228                         if (lp->usetags)
7229                                 tag = lp->cb_tags[lp->ia_tag];
7230                 }
7231                 else if (lp->actccbs > 0)
7232                         return NULL;
7233         }
7234
7235         /*
7236         **      if nothing available, take the default.
7237         */
7238         if (!cp)
7239                 cp = np->ccb;
7240
7241         /*
7242         **      Wait until available.
7243         */
7244 #if 0
7245         while (cp->magic) {
7246                 if (flags & SCSI_NOSLEEP) break;
7247                 if (tsleep ((caddr_t)cp, PRIBIO|PCATCH, "ncr", 0))
7248                         break;
7249         }
7250 #endif
7251
7252         if (cp->magic)
7253                 return NULL;
7254
7255         cp->magic = 1;
7256
7257         /*
7258         **      Move to next available tag if tag used.
7259         */
7260         if (lp) {
7261                 if (tag != NO_TAG) {
7262                         ++lp->ia_tag;
7263                         if (lp->ia_tag == MAX_TAGS)
7264                                 lp->ia_tag = 0;
7265                         lp->tags_umap |= (((tagmap_t) 1) << tag);
7266                 }
7267         }
7268
7269         /*
7270         **      Remember all informations needed to free this CCB.
7271         */
7272         cp->tag    = tag;
7273         cp->target = tn;
7274         cp->lun    = ln;
7275
7276         if (DEBUG_FLAGS & DEBUG_TAGS) {
7277                 PRINT_ADDR(cmd, "ccb @%p using tag %d.\n", cp, tag);
7278         }
7279
7280         return cp;
7281 }
7282
7283 /*==========================================================
7284 **
7285 **
7286 **      Release one control block
7287 **
7288 **
7289 **==========================================================
7290 */
7291
7292 static void ncr_free_ccb (struct ncb *np, struct ccb *cp)
7293 {
7294         struct tcb *tp = &np->target[cp->target];
7295         struct lcb *lp = tp->lp[cp->lun];
7296
7297         if (DEBUG_FLAGS & DEBUG_TAGS) {
7298                 PRINT_ADDR(cp->cmd, "ccb @%p freeing tag %d.\n", cp, cp->tag);
7299         }
7300
7301         /*
7302         **      If lun control block available,
7303         **      decrement active commands and increment credit, 
7304         **      free the tag if any and remove the JUMP for reselect.
7305         */
7306         if (lp) {
7307                 if (cp->tag != NO_TAG) {
7308                         lp->cb_tags[lp->if_tag++] = cp->tag;
7309                         if (lp->if_tag == MAX_TAGS)
7310                                 lp->if_tag = 0;
7311                         lp->tags_umap &= ~(((tagmap_t) 1) << cp->tag);
7312                         lp->tags_smap &= lp->tags_umap;
7313                         lp->jump_ccb[cp->tag] =
7314                                 cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l_q));
7315                 } else {
7316                         lp->jump_ccb[0] =
7317                                 cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l));
7318                 }
7319         }
7320
7321         /*
7322         **      Make this CCB available.
7323         */
7324
7325         if (lp) {
7326                 if (cp != np->ccb)
7327                         list_move(&cp->link_ccbq, &lp->free_ccbq);
7328                 --lp->busyccbs;
7329                 if (cp->queued) {
7330                         --lp->queuedccbs;
7331                 }
7332         }
7333         cp -> host_status = HS_IDLE;
7334         cp -> magic = 0;
7335         if (cp->queued) {
7336                 --np->queuedccbs;
7337                 cp->queued = 0;
7338         }
7339
7340 #if 0
7341         if (cp == np->ccb)
7342                 wakeup ((caddr_t) cp);
7343 #endif
7344 }
7345
7346
7347 #define ncr_reg_bus_addr(r) (np->paddr + offsetof (struct ncr_reg, r))
7348
7349 /*------------------------------------------------------------------------
7350 **      Initialize the fixed part of a CCB structure.
7351 **------------------------------------------------------------------------
7352 **------------------------------------------------------------------------
7353 */
7354 static void ncr_init_ccb(struct ncb *np, struct ccb *cp)
7355 {
7356         ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
7357
7358         /*
7359         **      Remember virtual and bus address of this ccb.
7360         */
7361         cp->p_ccb          = vtobus(cp);
7362         cp->phys.header.cp = cp;
7363
7364         /*
7365         **      This allows list_del to work for the default ccb.
7366         */
7367         INIT_LIST_HEAD(&cp->link_ccbq);
7368
7369         /*
7370         **      Initialyze the start and restart launch script.
7371         **
7372         **      COPY(4) @(...p_phys), @(dsa)
7373         **      JUMP @(sched_point)
7374         */
7375         cp->start.setup_dsa[0]   = cpu_to_scr(copy_4);
7376         cp->start.setup_dsa[1]   = cpu_to_scr(CCB_PHYS(cp, start.p_phys));
7377         cp->start.setup_dsa[2]   = cpu_to_scr(ncr_reg_bus_addr(nc_dsa));
7378         cp->start.schedule.l_cmd = cpu_to_scr(SCR_JUMP);
7379         cp->start.p_phys         = cpu_to_scr(CCB_PHYS(cp, phys));
7380
7381         memcpy(&cp->restart, &cp->start, sizeof(cp->restart));
7382
7383         cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
7384         cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
7385 }
7386
7387
7388 /*------------------------------------------------------------------------
7389 **      Allocate a CCB and initialize its fixed part.
7390 **------------------------------------------------------------------------
7391 **------------------------------------------------------------------------
7392 */
7393 static void ncr_alloc_ccb(struct ncb *np, u_char tn, u_char ln)
7394 {
7395         struct tcb *tp = &np->target[tn];
7396         struct lcb *lp = tp->lp[ln];
7397         struct ccb *cp = NULL;
7398
7399         /*
7400         **      Allocate memory for this CCB.
7401         */
7402         cp = m_calloc_dma(sizeof(struct ccb), "CCB");
7403         if (!cp)
7404                 return;
7405
7406         /*
7407         **      Count it and initialyze it.
7408         */
7409         lp->actccbs++;
7410         np->actccbs++;
7411         memset(cp, 0, sizeof (*cp));
7412         ncr_init_ccb(np, cp);
7413
7414         /*
7415         **      Chain into wakeup list and free ccb queue and take it 
7416         **      into account for tagged commands.
7417         */
7418         cp->link_ccb      = np->ccb->link_ccb;
7419         np->ccb->link_ccb = cp;
7420
7421         list_add(&cp->link_ccbq, &lp->free_ccbq);
7422 }
7423
7424 /*==========================================================
7425 **
7426 **
7427 **      Allocation of resources for Targets/Luns/Tags.
7428 **
7429 **
7430 **==========================================================
7431 */
7432
7433
7434 /*------------------------------------------------------------------------
7435 **      Target control block initialisation.
7436 **------------------------------------------------------------------------
7437 **      This data structure is fully initialized after a SCSI command 
7438 **      has been successfully completed for this target.
7439 **      It contains a SCRIPT that is called on target reselection.
7440 **------------------------------------------------------------------------
7441 */
7442 static void ncr_init_tcb (struct ncb *np, u_char tn)
7443 {
7444         struct tcb *tp = &np->target[tn];
7445         ncrcmd copy_1 = np->features & FE_PFEN ? SCR_COPY(1) : SCR_COPY_F(1);
7446         int th = tn & 3;
7447         int i;
7448
7449         /*
7450         **      Jump to next tcb if SFBR does not match this target.
7451         **      JUMP  IF (SFBR != #target#), @(next tcb)
7452         */
7453         tp->jump_tcb.l_cmd   =
7454                 cpu_to_scr((SCR_JUMP ^ IFFALSE (DATA (0x80 + tn))));
7455         tp->jump_tcb.l_paddr = np->jump_tcb[th].l_paddr;
7456
7457         /*
7458         **      Load the synchronous transfer register.
7459         **      COPY @(tp->sval), @(sxfer)
7460         */
7461         tp->getscr[0] = cpu_to_scr(copy_1);
7462         tp->getscr[1] = cpu_to_scr(vtobus (&tp->sval));
7463 #ifdef SCSI_NCR_BIG_ENDIAN
7464         tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer) ^ 3);
7465 #else
7466         tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer));
7467 #endif
7468
7469         /*
7470         **      Load the timing register.
7471         **      COPY @(tp->wval), @(scntl3)
7472         */
7473         tp->getscr[3] = cpu_to_scr(copy_1);
7474         tp->getscr[4] = cpu_to_scr(vtobus (&tp->wval));
7475 #ifdef SCSI_NCR_BIG_ENDIAN
7476         tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3) ^ 3);
7477 #else
7478         tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3));
7479 #endif
7480
7481         /*
7482         **      Get the IDENTIFY message and the lun.
7483         **      CALL @script(resel_lun)
7484         */
7485         tp->call_lun.l_cmd   = cpu_to_scr(SCR_CALL);
7486         tp->call_lun.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_lun));
7487
7488         /*
7489         **      Look for the lun control block of this nexus.
7490         **      For i = 0 to 3
7491         **              JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
7492         */
7493         for (i = 0 ; i < 4 ; i++) {
7494                 tp->jump_lcb[i].l_cmd   =
7495                                 cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
7496                 tp->jump_lcb[i].l_paddr =
7497                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_identify));
7498         }
7499
7500         /*
7501         **      Link this target control block to the JUMP chain.
7502         */
7503         np->jump_tcb[th].l_paddr = cpu_to_scr(vtobus (&tp->jump_tcb));
7504
7505         /*
7506         **      These assert's should be moved at driver initialisations.
7507         */
7508 #ifdef SCSI_NCR_BIG_ENDIAN
7509         BUG_ON(((offsetof(struct ncr_reg, nc_sxfer) ^
7510                  offsetof(struct tcb    , sval    )) &3) != 3);
7511         BUG_ON(((offsetof(struct ncr_reg, nc_scntl3) ^
7512                  offsetof(struct tcb    , wval    )) &3) != 3);
7513 #else
7514         BUG_ON(((offsetof(struct ncr_reg, nc_sxfer) ^
7515                  offsetof(struct tcb    , sval    )) &3) != 0);
7516         BUG_ON(((offsetof(struct ncr_reg, nc_scntl3) ^
7517                  offsetof(struct tcb    , wval    )) &3) != 0);
7518 #endif
7519 }
7520
7521
7522 /*------------------------------------------------------------------------
7523 **      Lun control block allocation and initialization.
7524 **------------------------------------------------------------------------
7525 **      This data structure is allocated and initialized after a SCSI 
7526 **      command has been successfully completed for this target/lun.
7527 **------------------------------------------------------------------------
7528 */
7529 static struct lcb *ncr_alloc_lcb (struct ncb *np, u_char tn, u_char ln)
7530 {
7531         struct tcb *tp = &np->target[tn];
7532         struct lcb *lp = tp->lp[ln];
7533         ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
7534         int lh = ln & 3;
7535
7536         /*
7537         **      Already done, return.
7538         */
7539         if (lp)
7540                 return lp;
7541
7542         /*
7543         **      Allocate the lcb.
7544         */
7545         lp = m_calloc_dma(sizeof(struct lcb), "LCB");
7546         if (!lp)
7547                 goto fail;
7548         memset(lp, 0, sizeof(*lp));
7549         tp->lp[ln] = lp;
7550
7551         /*
7552         **      Initialize the target control block if not yet.
7553         */
7554         if (!tp->jump_tcb.l_cmd)
7555                 ncr_init_tcb(np, tn);
7556
7557         /*
7558         **      Initialize the CCB queue headers.
7559         */
7560         INIT_LIST_HEAD(&lp->free_ccbq);
7561         INIT_LIST_HEAD(&lp->busy_ccbq);
7562         INIT_LIST_HEAD(&lp->wait_ccbq);
7563         INIT_LIST_HEAD(&lp->skip_ccbq);
7564
7565         /*
7566         **      Set max CCBs to 1 and use the default 1 entry 
7567         **      jump table by default.
7568         */
7569         lp->maxnxs      = 1;
7570         lp->jump_ccb    = &lp->jump_ccb_0;
7571         lp->p_jump_ccb  = cpu_to_scr(vtobus(lp->jump_ccb));
7572
7573         /*
7574         **      Initilialyze the reselect script:
7575         **
7576         **      Jump to next lcb if SFBR does not match this lun.
7577         **      Load TEMP with the CCB direct jump table bus address.
7578         **      Get the SIMPLE TAG message and the tag.
7579         **
7580         **      JUMP  IF (SFBR != #lun#), @(next lcb)
7581         **      COPY @(lp->p_jump_ccb),   @(temp)
7582         **      JUMP @script(resel_notag)
7583         */
7584         lp->jump_lcb.l_cmd   =
7585                 cpu_to_scr((SCR_JUMP ^ IFFALSE (MASK (0x80+ln, 0xff))));
7586         lp->jump_lcb.l_paddr = tp->jump_lcb[lh].l_paddr;
7587
7588         lp->load_jump_ccb[0] = cpu_to_scr(copy_4);
7589         lp->load_jump_ccb[1] = cpu_to_scr(vtobus (&lp->p_jump_ccb));
7590         lp->load_jump_ccb[2] = cpu_to_scr(ncr_reg_bus_addr(nc_temp));
7591
7592         lp->jump_tag.l_cmd   = cpu_to_scr(SCR_JUMP);
7593         lp->jump_tag.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_notag));
7594
7595         /*
7596         **      Link this lun control block to the JUMP chain.
7597         */
7598         tp->jump_lcb[lh].l_paddr = cpu_to_scr(vtobus (&lp->jump_lcb));
7599
7600         /*
7601         **      Initialize command queuing control.
7602         */
7603         lp->busyccbs    = 1;
7604         lp->queuedccbs  = 1;
7605         lp->queuedepth  = 1;
7606 fail:
7607         return lp;
7608 }
7609
7610
7611 /*------------------------------------------------------------------------
7612 **      Lun control block setup on INQUIRY data received.
7613 **------------------------------------------------------------------------
7614 **      We only support WIDE, SYNC for targets and CMDQ for logical units.
7615 **      This setup is done on each INQUIRY since we are expecting user 
7616 **      will play with CHANGE DEFINITION commands. :-)
7617 **------------------------------------------------------------------------
7618 */
7619 static struct lcb *ncr_setup_lcb (struct ncb *np, struct scsi_device *sdev)
7620 {
7621         unsigned char tn = sdev->id, ln = sdev->lun;
7622         struct tcb *tp = &np->target[tn];
7623         struct lcb *lp = tp->lp[ln];
7624
7625         /* If no lcb, try to allocate it.  */
7626         if (!lp && !(lp = ncr_alloc_lcb(np, tn, ln)))
7627                 goto fail;
7628
7629         /*
7630         **      If unit supports tagged commands, allocate the 
7631         **      CCB JUMP table if not yet.
7632         */
7633         if (sdev->tagged_supported && lp->jump_ccb == &lp->jump_ccb_0) {
7634                 int i;
7635                 lp->jump_ccb = m_calloc_dma(256, "JUMP_CCB");
7636                 if (!lp->jump_ccb) {
7637                         lp->jump_ccb = &lp->jump_ccb_0;
7638                         goto fail;
7639                 }
7640                 lp->p_jump_ccb = cpu_to_scr(vtobus(lp->jump_ccb));
7641                 for (i = 0 ; i < 64 ; i++)
7642                         lp->jump_ccb[i] =
7643                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_i_t_l_q));
7644                 for (i = 0 ; i < MAX_TAGS ; i++)
7645                         lp->cb_tags[i] = i;
7646                 lp->maxnxs = MAX_TAGS;
7647                 lp->tags_stime = jiffies + 3*HZ;
7648                 ncr_setup_tags (np, sdev);
7649         }
7650
7651
7652 fail:
7653         return lp;
7654 }
7655
7656 /*==========================================================
7657 **
7658 **
7659 **      Build Scatter Gather Block
7660 **
7661 **
7662 **==========================================================
7663 **
7664 **      The transfer area may be scattered among
7665 **      several non adjacent physical pages.
7666 **
7667 **      We may use MAX_SCATTER blocks.
7668 **
7669 **----------------------------------------------------------
7670 */
7671
7672 /*
7673 **      We try to reduce the number of interrupts caused
7674 **      by unexpected phase changes due to disconnects.
7675 **      A typical harddisk may disconnect before ANY block.
7676 **      If we wanted to avoid unexpected phase changes at all
7677 **      we had to use a break point every 512 bytes.
7678 **      Of course the number of scatter/gather blocks is
7679 **      limited.
7680 **      Under Linux, the scatter/gatter blocks are provided by 
7681 **      the generic driver. We just have to copy addresses and 
7682 **      sizes to the data segment array.
7683 */
7684
7685 static int ncr_scatter_no_sglist(struct ncb *np, struct ccb *cp, struct scsi_cmnd *cmd)
7686 {
7687         struct scr_tblmove *data = &cp->phys.data[MAX_SCATTER - 1];
7688         int segment;
7689
7690         cp->data_len = cmd->request_bufflen;
7691
7692         if (cmd->request_bufflen) {
7693                 dma_addr_t baddr = map_scsi_single_data(np, cmd);
7694                 if (baddr) {
7695                         ncr_build_sge(np, data, baddr, cmd->request_bufflen);
7696                         segment = 1;
7697                 } else {
7698                         segment = -2;
7699                 }
7700         } else {
7701                 segment = 0;
7702         }
7703
7704         return segment;
7705 }
7706
7707 static int ncr_scatter(struct ncb *np, struct ccb *cp, struct scsi_cmnd *cmd)
7708 {
7709         int segment     = 0;
7710         int use_sg      = (int) cmd->use_sg;
7711
7712         cp->data_len    = 0;
7713
7714         if (!use_sg)
7715                 segment = ncr_scatter_no_sglist(np, cp, cmd);
7716         else if ((use_sg = map_scsi_sg_data(np, cmd)) > 0) {
7717                 struct scatterlist *scatter = (struct scatterlist *)cmd->buffer;
7718                 struct scr_tblmove *data;
7719
7720                 if (use_sg > MAX_SCATTER) {
7721                         unmap_scsi_data(np, cmd);
7722                         return -1;
7723                 }
7724
7725                 data = &cp->phys.data[MAX_SCATTER - use_sg];
7726
7727                 for (segment = 0; segment < use_sg; segment++) {
7728                         dma_addr_t baddr = sg_dma_address(&scatter[segment]);
7729                         unsigned int len = sg_dma_len(&scatter[segment]);
7730
7731                         ncr_build_sge(np, &data[segment], baddr, len);
7732                         cp->data_len += len;
7733                 }
7734         } else {
7735                 segment = -2;
7736         }
7737
7738         return segment;
7739 }
7740
7741 /*==========================================================
7742 **
7743 **
7744 **      Test the bus snoop logic :-(
7745 **
7746 **      Has to be called with interrupts disabled.
7747 **
7748 **
7749 **==========================================================
7750 */
7751
7752 static int __init ncr_regtest (struct ncb* np)
7753 {
7754         register volatile u32 data;
7755         /*
7756         **      ncr registers may NOT be cached.
7757         **      write 0xffffffff to a read only register area,
7758         **      and try to read it back.
7759         */
7760         data = 0xffffffff;
7761         OUTL_OFF(offsetof(struct ncr_reg, nc_dstat), data);
7762         data = INL_OFF(offsetof(struct ncr_reg, nc_dstat));
7763 #if 1
7764         if (data == 0xffffffff) {
7765 #else
7766         if ((data & 0xe2f0fffd) != 0x02000080) {
7767 #endif
7768                 printk ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
7769                         (unsigned) data);
7770                 return (0x10);
7771         }
7772         return (0);
7773 }
7774
7775 static int __init ncr_snooptest (struct ncb* np)
7776 {
7777         u32     ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc;
7778         int     i, err=0;
7779         if (np->reg) {
7780                 err |= ncr_regtest (np);
7781                 if (err)
7782                         return (err);
7783         }
7784
7785         /* init */
7786         pc  = NCB_SCRIPTH_PHYS (np, snooptest);
7787         host_wr = 1;
7788         ncr_wr  = 2;
7789         /*
7790         **      Set memory and register.
7791         */
7792         np->ncr_cache = cpu_to_scr(host_wr);
7793         OUTL (nc_temp, ncr_wr);
7794         /*
7795         **      Start script (exchange values)
7796         */
7797         OUTL_DSP (pc);
7798         /*
7799         **      Wait 'til done (with timeout)
7800         */
7801         for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
7802                 if (INB(nc_istat) & (INTF|SIP|DIP))
7803                         break;
7804         /*
7805         **      Save termination position.
7806         */
7807         pc = INL (nc_dsp);
7808         /*
7809         **      Read memory and register.
7810         */
7811         host_rd = scr_to_cpu(np->ncr_cache);
7812         ncr_rd  = INL (nc_scratcha);
7813         ncr_bk  = INL (nc_temp);
7814         /*
7815         **      Reset ncr chip
7816         */
7817         ncr_chip_reset(np, 100);
7818         /*
7819         **      check for timeout
7820         */
7821         if (i>=NCR_SNOOP_TIMEOUT) {
7822                 printk ("CACHE TEST FAILED: timeout.\n");
7823                 return (0x20);
7824         }
7825         /*
7826         **      Check termination position.
7827         */
7828         if (pc != NCB_SCRIPTH_PHYS (np, snoopend)+8) {
7829                 printk ("CACHE TEST FAILED: script execution failed.\n");
7830                 printk ("start=%08lx, pc=%08lx, end=%08lx\n", 
7831                         (u_long) NCB_SCRIPTH_PHYS (np, snooptest), (u_long) pc,
7832                         (u_long) NCB_SCRIPTH_PHYS (np, snoopend) +8);
7833                 return (0x40);
7834         }
7835         /*
7836         **      Show results.
7837         */
7838         if (host_wr != ncr_rd) {
7839                 printk ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
7840                         (int) host_wr, (int) ncr_rd);
7841                 err |= 1;
7842         }
7843         if (host_rd != ncr_wr) {
7844                 printk ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
7845                         (int) ncr_wr, (int) host_rd);
7846                 err |= 2;
7847         }
7848         if (ncr_bk != ncr_wr) {
7849                 printk ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
7850                         (int) ncr_wr, (int) ncr_bk);
7851                 err |= 4;
7852         }
7853         return (err);
7854 }
7855
7856 /*==========================================================
7857 **
7858 **      Determine the ncr's clock frequency.
7859 **      This is essential for the negotiation
7860 **      of the synchronous transfer rate.
7861 **
7862 **==========================================================
7863 **
7864 **      Note: we have to return the correct value.
7865 **      THERE IS NO SAVE DEFAULT VALUE.
7866 **
7867 **      Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
7868 **      53C860 and 53C875 rev. 1 support fast20 transfers but 
7869 **      do not have a clock doubler and so are provided with a 
7870 **      80 MHz clock. All other fast20 boards incorporate a doubler 
7871 **      and so should be delivered with a 40 MHz clock.
7872 **      The future fast40 chips (895/895) use a 40 Mhz base clock 
7873 **      and provide a clock quadrupler (160 Mhz). The code below 
7874 **      tries to deal as cleverly as possible with all this stuff.
7875 **
7876 **----------------------------------------------------------
7877 */
7878
7879 /*
7880  *      Select NCR SCSI clock frequency
7881  */
7882 static void ncr_selectclock(struct ncb *np, u_char scntl3)
7883 {
7884         if (np->multiplier < 2) {
7885                 OUTB(nc_scntl3, scntl3);
7886                 return;
7887         }
7888
7889         if (bootverbose >= 2)
7890                 printk ("%s: enabling clock multiplier\n", ncr_name(np));
7891
7892         OUTB(nc_stest1, DBLEN);    /* Enable clock multiplier             */
7893         if (np->multiplier > 2) {  /* Poll bit 5 of stest4 for quadrupler */
7894                 int i = 20;
7895                 while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
7896                         udelay(20);
7897                 if (!i)
7898                         printk("%s: the chip cannot lock the frequency\n", ncr_name(np));
7899         } else                  /* Wait 20 micro-seconds for doubler    */
7900                 udelay(20);
7901         OUTB(nc_stest3, HSC);           /* Halt the scsi clock          */
7902         OUTB(nc_scntl3, scntl3);
7903         OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier      */
7904         OUTB(nc_stest3, 0x00);          /* Restart scsi clock           */
7905 }
7906
7907
7908 /*
7909  *      calculate NCR SCSI clock frequency (in KHz)
7910  */
7911 static unsigned __init ncrgetfreq (struct ncb *np, int gen)
7912 {
7913         unsigned ms = 0;
7914         char count = 0;
7915
7916         /*
7917          * Measure GEN timer delay in order 
7918          * to calculate SCSI clock frequency
7919          *
7920          * This code will never execute too
7921          * many loop iterations (if DELAY is 
7922          * reasonably correct). It could get
7923          * too low a delay (too high a freq.)
7924          * if the CPU is slow executing the 
7925          * loop for some reason (an NMI, for
7926          * example). For this reason we will
7927          * if multiple measurements are to be 
7928          * performed trust the higher delay 
7929          * (lower frequency returned).
7930          */
7931         OUTB (nc_stest1, 0);    /* make sure clock doubler is OFF */
7932         OUTW (nc_sien , 0);     /* mask all scsi interrupts */
7933         (void) INW (nc_sist);   /* clear pending scsi interrupt */
7934         OUTB (nc_dien , 0);     /* mask all dma interrupts */
7935         (void) INW (nc_sist);   /* another one, just to be sure :) */
7936         OUTB (nc_scntl3, 4);    /* set pre-scaler to divide by 3 */
7937         OUTB (nc_stime1, 0);    /* disable general purpose timer */
7938         OUTB (nc_stime1, gen);  /* set to nominal delay of 1<<gen * 125us */
7939         while (!(INW(nc_sist) & GEN) && ms++ < 100000) {
7940                 for (count = 0; count < 10; count ++)
7941                         udelay(100);    /* count ms */
7942         }
7943         OUTB (nc_stime1, 0);    /* disable general purpose timer */
7944         /*
7945          * set prescaler to divide by whatever 0 means
7946          * 0 ought to choose divide by 2, but appears
7947          * to set divide by 3.5 mode in my 53c810 ...
7948          */
7949         OUTB (nc_scntl3, 0);
7950
7951         if (bootverbose >= 2)
7952                 printk ("%s: Delay (GEN=%d): %u msec\n", ncr_name(np), gen, ms);
7953         /*
7954          * adjust for prescaler, and convert into KHz 
7955          */
7956         return ms ? ((1 << gen) * 4340) / ms : 0;
7957 }
7958
7959 /*
7960  *      Get/probe NCR SCSI clock frequency
7961  */
7962 static void __init ncr_getclock (struct ncb *np, int mult)
7963 {
7964         unsigned char scntl3 = INB(nc_scntl3);
7965         unsigned char stest1 = INB(nc_stest1);
7966         unsigned f1;
7967
7968         np->multiplier = 1;
7969         f1 = 40000;
7970
7971         /*
7972         **      True with 875 or 895 with clock multiplier selected
7973         */
7974         if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
7975                 if (bootverbose >= 2)
7976                         printk ("%s: clock multiplier found\n", ncr_name(np));
7977                 np->multiplier = mult;
7978         }
7979
7980         /*
7981         **      If multiplier not found or scntl3 not 7,5,3,
7982         **      reset chip and get frequency from general purpose timer.
7983         **      Otherwise trust scntl3 BIOS setting.
7984         */
7985         if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
7986                 unsigned f2;
7987
7988                 ncr_chip_reset(np, 5);
7989
7990                 (void) ncrgetfreq (np, 11);     /* throw away first result */
7991                 f1 = ncrgetfreq (np, 11);
7992                 f2 = ncrgetfreq (np, 11);
7993
7994                 if(bootverbose)
7995                         printk ("%s: NCR clock is %uKHz, %uKHz\n", ncr_name(np), f1, f2);
7996
7997                 if (f1 > f2) f1 = f2;           /* trust lower result   */
7998
7999                 if      (f1 <   45000)          f1 =  40000;
8000                 else if (f1 <   55000)          f1 =  50000;
8001                 else                            f1 =  80000;
8002
8003                 if (f1 < 80000 && mult > 1) {
8004                         if (bootverbose >= 2)
8005                                 printk ("%s: clock multiplier assumed\n", ncr_name(np));
8006                         np->multiplier  = mult;
8007                 }
8008         } else {
8009                 if      ((scntl3 & 7) == 3)     f1 =  40000;
8010                 else if ((scntl3 & 7) == 5)     f1 =  80000;
8011                 else                            f1 = 160000;
8012
8013                 f1 /= np->multiplier;
8014         }
8015
8016         /*
8017         **      Compute controller synchronous parameters.
8018         */
8019         f1              *= np->multiplier;
8020         np->clock_khz   = f1;
8021 }
8022
8023 /*===================== LINUX ENTRY POINTS SECTION ==========================*/
8024
8025 static int ncr53c8xx_slave_alloc(struct scsi_device *device)
8026 {
8027         struct Scsi_Host *host = device->host;
8028         struct ncb *np = ((struct host_data *) host->hostdata)->ncb;
8029         struct tcb *tp = &np->target[device->id];
8030         tp->starget = device->sdev_target;
8031
8032         return 0;
8033 }
8034
8035 static int ncr53c8xx_slave_configure(struct scsi_device *device)
8036 {
8037         struct Scsi_Host *host = device->host;
8038         struct ncb *np = ((struct host_data *) host->hostdata)->ncb;
8039         struct tcb *tp = &np->target[device->id];
8040         struct lcb *lp = tp->lp[device->lun];
8041         int numtags, depth_to_use;
8042
8043         ncr_setup_lcb(np, device);
8044
8045         /*
8046         **      Select queue depth from driver setup.
8047         **      Donnot use more than configured by user.
8048         **      Use at least 2.
8049         **      Donnot use more than our maximum.
8050         */
8051         numtags = device_queue_depth(np->unit, device->id, device->lun);
8052         if (numtags > tp->usrtags)
8053                 numtags = tp->usrtags;
8054         if (!device->tagged_supported)
8055                 numtags = 1;
8056         depth_to_use = numtags;
8057         if (depth_to_use < 2)
8058                 depth_to_use = 2;
8059         if (depth_to_use > MAX_TAGS)
8060                 depth_to_use = MAX_TAGS;
8061
8062         scsi_adjust_queue_depth(device,
8063                                 (device->tagged_supported ?
8064                                  MSG_SIMPLE_TAG : 0),
8065                                 depth_to_use);
8066
8067         /*
8068         **      Since the queue depth is not tunable under Linux,
8069         **      we need to know this value in order not to 
8070         **      announce stupid things to user.
8071         **
8072         **      XXX(hch): As of Linux 2.6 it certainly _is_ tunable..
8073         **                In fact we just tuned it, or did I miss
8074         **                something important? :)
8075         */
8076         if (lp) {
8077                 lp->numtags = lp->maxtags = numtags;
8078                 lp->scdev_depth = depth_to_use;
8079         }
8080         ncr_setup_tags (np, device);
8081
8082 #ifdef DEBUG_NCR53C8XX
8083         printk("ncr53c8xx_select_queue_depth: host=%d, id=%d, lun=%d, depth=%d\n",
8084                np->unit, device->id, device->lun, depth_to_use);
8085 #endif
8086
8087         if (spi_support_sync(device->sdev_target) &&
8088             !spi_initial_dv(device->sdev_target))
8089                 spi_dv_device(device);
8090         return 0;
8091 }
8092
8093 static int ncr53c8xx_queue_command (struct scsi_cmnd *cmd, void (* done)(struct scsi_cmnd *))
8094 {
8095      struct ncb *np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
8096      unsigned long flags;
8097      int sts;
8098
8099 #ifdef DEBUG_NCR53C8XX
8100 printk("ncr53c8xx_queue_command\n");
8101 #endif
8102
8103      cmd->scsi_done     = done;
8104      cmd->host_scribble = NULL;
8105      cmd->__data_mapped = 0;
8106      cmd->__data_mapping = 0;
8107
8108      spin_lock_irqsave(&np->smp_lock, flags);
8109
8110      if ((sts = ncr_queue_command(np, cmd)) != DID_OK) {
8111           cmd->result = ScsiResult(sts, 0);
8112 #ifdef DEBUG_NCR53C8XX
8113 printk("ncr53c8xx : command not queued - result=%d\n", sts);
8114 #endif
8115      }
8116 #ifdef DEBUG_NCR53C8XX
8117      else
8118 printk("ncr53c8xx : command successfully queued\n");
8119 #endif
8120
8121      spin_unlock_irqrestore(&np->smp_lock, flags);
8122
8123      if (sts != DID_OK) {
8124           unmap_scsi_data(np, cmd);
8125           done(cmd);
8126           sts = 0;
8127      }
8128
8129      return sts;
8130 }
8131
8132 irqreturn_t ncr53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs)
8133 {
8134      unsigned long flags;
8135      struct Scsi_Host *shost = (struct Scsi_Host *)dev_id;
8136      struct host_data *host_data = (struct host_data *)shost->hostdata;
8137      struct ncb *np = host_data->ncb;
8138      struct scsi_cmnd *done_list;
8139
8140 #ifdef DEBUG_NCR53C8XX
8141      printk("ncr53c8xx : interrupt received\n");
8142 #endif
8143
8144      if (DEBUG_FLAGS & DEBUG_TINY) printk ("[");
8145
8146      spin_lock_irqsave(&np->smp_lock, flags);
8147      ncr_exception(np);
8148      done_list     = np->done_list;
8149      np->done_list = NULL;
8150      spin_unlock_irqrestore(&np->smp_lock, flags);
8151
8152      if (DEBUG_FLAGS & DEBUG_TINY) printk ("]\n");
8153
8154      if (done_list)
8155              ncr_flush_done_cmds(done_list);
8156      return IRQ_HANDLED;
8157 }
8158
8159 static void ncr53c8xx_timeout(unsigned long npref)
8160 {
8161         struct ncb *np = (struct ncb *) npref;
8162         unsigned long flags;
8163         struct scsi_cmnd *done_list;
8164
8165         spin_lock_irqsave(&np->smp_lock, flags);
8166         ncr_timeout(np);
8167         done_list     = np->done_list;
8168         np->done_list = NULL;
8169         spin_unlock_irqrestore(&np->smp_lock, flags);
8170
8171         if (done_list)
8172                 ncr_flush_done_cmds(done_list);
8173 }
8174
8175 static int ncr53c8xx_bus_reset(struct scsi_cmnd *cmd)
8176 {
8177         struct ncb *np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
8178         int sts;
8179         unsigned long flags;
8180         struct scsi_cmnd *done_list;
8181
8182         /*
8183          * If the mid-level driver told us reset is synchronous, it seems 
8184          * that we must call the done() callback for the involved command, 
8185          * even if this command was not queued to the low-level driver, 
8186          * before returning SUCCESS.
8187          */
8188
8189         spin_lock_irqsave(&np->smp_lock, flags);
8190         sts = ncr_reset_bus(np, cmd, 1);
8191
8192         done_list     = np->done_list;
8193         np->done_list = NULL;
8194         spin_unlock_irqrestore(&np->smp_lock, flags);
8195
8196         ncr_flush_done_cmds(done_list);
8197
8198         return sts;
8199 }
8200
8201 #if 0 /* unused and broken */
8202 static int ncr53c8xx_abort(struct scsi_cmnd *cmd)
8203 {
8204         struct ncb *np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
8205         int sts;
8206         unsigned long flags;
8207         struct scsi_cmnd *done_list;
8208
8209 #if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8210         printk("ncr53c8xx_abort: pid=%lu serial_number=%ld\n",
8211                 cmd->pid, cmd->serial_number);
8212 #else
8213         printk("ncr53c8xx_abort: command pid %lu\n", cmd->pid);
8214 #endif
8215
8216         NCR_LOCK_NCB(np, flags);
8217
8218         sts = ncr_abort_command(np, cmd);
8219 out:
8220         done_list     = np->done_list;
8221         np->done_list = NULL;
8222         NCR_UNLOCK_NCB(np, flags);
8223
8224         ncr_flush_done_cmds(done_list);
8225
8226         return sts;
8227 }
8228 #endif
8229
8230
8231 /*
8232 **      Scsi command waiting list management.
8233 **
8234 **      It may happen that we cannot insert a scsi command into the start queue,
8235 **      in the following circumstances.
8236 **              Too few preallocated ccb(s), 
8237 **              maxtags < cmd_per_lun of the Linux host control block,
8238 **              etc...
8239 **      Such scsi commands are inserted into a waiting list.
8240 **      When a scsi command complete, we try to requeue the commands of the
8241 **      waiting list.
8242 */
8243
8244 #define next_wcmd host_scribble
8245
8246 static void insert_into_waiting_list(struct ncb *np, struct scsi_cmnd *cmd)
8247 {
8248         struct scsi_cmnd *wcmd;
8249
8250 #ifdef DEBUG_WAITING_LIST
8251         printk("%s: cmd %lx inserted into waiting list\n", ncr_name(np), (u_long) cmd);
8252 #endif
8253         cmd->next_wcmd = NULL;
8254         if (!(wcmd = np->waiting_list)) np->waiting_list = cmd;
8255         else {
8256                 while ((wcmd->next_wcmd) != 0)
8257                         wcmd = (struct scsi_cmnd *) wcmd->next_wcmd;
8258                 wcmd->next_wcmd = (char *) cmd;
8259         }
8260 }
8261
8262 static struct scsi_cmnd *retrieve_from_waiting_list(int to_remove, struct ncb *np, struct scsi_cmnd *cmd)
8263 {
8264         struct scsi_cmnd **pcmd = &np->waiting_list;
8265
8266         while (*pcmd) {
8267                 if (cmd == *pcmd) {
8268                         if (to_remove) {
8269                                 *pcmd = (struct scsi_cmnd *) cmd->next_wcmd;
8270                                 cmd->next_wcmd = NULL;
8271                         }
8272 #ifdef DEBUG_WAITING_LIST
8273         printk("%s: cmd %lx retrieved from waiting list\n", ncr_name(np), (u_long) cmd);
8274 #endif
8275                         return cmd;
8276                 }
8277                 pcmd = (struct scsi_cmnd **) &(*pcmd)->next_wcmd;
8278         }
8279         return NULL;
8280 }
8281
8282 static void process_waiting_list(struct ncb *np, int sts)
8283 {
8284         struct scsi_cmnd *waiting_list, *wcmd;
8285
8286         waiting_list = np->waiting_list;
8287         np->waiting_list = NULL;
8288
8289 #ifdef DEBUG_WAITING_LIST
8290         if (waiting_list) printk("%s: waiting_list=%lx processing sts=%d\n", ncr_name(np), (u_long) waiting_list, sts);
8291 #endif
8292         while ((wcmd = waiting_list) != 0) {
8293                 waiting_list = (struct scsi_cmnd *) wcmd->next_wcmd;
8294                 wcmd->next_wcmd = NULL;
8295                 if (sts == DID_OK) {
8296 #ifdef DEBUG_WAITING_LIST
8297         printk("%s: cmd %lx trying to requeue\n", ncr_name(np), (u_long) wcmd);
8298 #endif
8299                         sts = ncr_queue_command(np, wcmd);
8300                 }
8301                 if (sts != DID_OK) {
8302 #ifdef DEBUG_WAITING_LIST
8303         printk("%s: cmd %lx done forced sts=%d\n", ncr_name(np), (u_long) wcmd, sts);
8304 #endif
8305                         wcmd->result = ScsiResult(sts, 0);
8306                         ncr_queue_done_cmd(np, wcmd);
8307                 }
8308         }
8309 }
8310
8311 #undef next_wcmd
8312
8313 static ssize_t show_ncr53c8xx_revision(struct class_device *dev, char *buf)
8314 {
8315         struct Scsi_Host *host = class_to_shost(dev);
8316         struct host_data *host_data = (struct host_data *)host->hostdata;
8317   
8318         return snprintf(buf, 20, "0x%x\n", host_data->ncb->revision_id);
8319 }
8320   
8321 static struct class_device_attribute ncr53c8xx_revision_attr = {
8322         .attr   = { .name = "revision", .mode = S_IRUGO, },
8323         .show   = show_ncr53c8xx_revision,
8324 };
8325   
8326 static struct class_device_attribute *ncr53c8xx_host_attrs[] = {
8327         &ncr53c8xx_revision_attr,
8328         NULL
8329 };
8330
8331 /*==========================================================
8332 **
8333 **      Boot command line.
8334 **
8335 **==========================================================
8336 */
8337 #ifdef  MODULE
8338 char *ncr53c8xx;        /* command line passed by insmod */
8339 module_param(ncr53c8xx, charp, 0);
8340 #endif
8341
8342 static int __init ncr53c8xx_setup(char *str)
8343 {
8344         return sym53c8xx__setup(str);
8345 }
8346
8347 #ifndef MODULE
8348 __setup("ncr53c8xx=", ncr53c8xx_setup);
8349 #endif
8350
8351
8352 /*
8353  *      Host attach and initialisations.
8354  *
8355  *      Allocate host data and ncb structure.
8356  *      Request IO region and remap MMIO region.
8357  *      Do chip initialization.
8358  *      If all is OK, install interrupt handling and
8359  *      start the timer daemon.
8360  */
8361 struct Scsi_Host * __init ncr_attach(struct scsi_host_template *tpnt,
8362                                         int unit, struct ncr_device *device)
8363 {
8364         struct host_data *host_data;
8365         struct ncb *np = NULL;
8366         struct Scsi_Host *instance = NULL;
8367         u_long flags = 0;
8368         int i;
8369
8370         if (!tpnt->name)
8371                 tpnt->name      = SCSI_NCR_DRIVER_NAME;
8372         if (!tpnt->shost_attrs)
8373                 tpnt->shost_attrs = ncr53c8xx_host_attrs;
8374
8375         tpnt->queuecommand      = ncr53c8xx_queue_command;
8376         tpnt->slave_configure   = ncr53c8xx_slave_configure;
8377         tpnt->slave_alloc       = ncr53c8xx_slave_alloc;
8378         tpnt->eh_bus_reset_handler = ncr53c8xx_bus_reset;
8379         tpnt->can_queue         = SCSI_NCR_CAN_QUEUE;
8380         tpnt->this_id           = 7;
8381         tpnt->sg_tablesize      = SCSI_NCR_SG_TABLESIZE;
8382         tpnt->cmd_per_lun       = SCSI_NCR_CMD_PER_LUN;
8383         tpnt->use_clustering    = ENABLE_CLUSTERING;
8384
8385         if (device->differential)
8386                 driver_setup.diff_support = device->differential;
8387
8388         printk(KERN_INFO "ncr53c720-%d: rev 0x%x irq %d\n",
8389                 unit, device->chip.revision_id, device->slot.irq);
8390
8391         instance = scsi_host_alloc(tpnt, sizeof(*host_data));
8392         if (!instance)
8393                 goto attach_error;
8394         host_data = (struct host_data *) instance->hostdata;
8395
8396         np = __m_calloc_dma(device->dev, sizeof(struct ncb), "NCB");
8397         if (!np)
8398                 goto attach_error;
8399         spin_lock_init(&np->smp_lock);
8400         np->dev = device->dev;
8401         np->p_ncb = vtobus(np);
8402         host_data->ncb = np;
8403
8404         np->ccb = m_calloc_dma(sizeof(struct ccb), "CCB");
8405         if (!np->ccb)
8406                 goto attach_error;
8407
8408         /* Store input information in the host data structure.  */
8409         np->unit        = unit;
8410         np->verbose     = driver_setup.verbose;
8411         sprintf(np->inst_name, "ncr53c720-%d", np->unit);
8412         np->revision_id = device->chip.revision_id;
8413         np->features    = device->chip.features;
8414         np->clock_divn  = device->chip.nr_divisor;
8415         np->maxoffs     = device->chip.offset_max;
8416         np->maxburst    = device->chip.burst_max;
8417         np->myaddr      = device->host_id;
8418
8419         /* Allocate SCRIPTS areas.  */
8420         np->script0 = m_calloc_dma(sizeof(struct script), "SCRIPT");
8421         if (!np->script0)
8422                 goto attach_error;
8423         np->scripth0 = m_calloc_dma(sizeof(struct scripth), "SCRIPTH");
8424         if (!np->scripth0)
8425                 goto attach_error;
8426
8427         init_timer(&np->timer);
8428         np->timer.data     = (unsigned long) np;
8429         np->timer.function = ncr53c8xx_timeout;
8430
8431         /* Try to map the controller chip to virtual and physical memory. */
8432
8433         np->paddr       = device->slot.base;
8434         np->paddr2      = (np->features & FE_RAM) ? device->slot.base_2 : 0;
8435
8436         if (device->slot.base_v)
8437                 np->vaddr = device->slot.base_v;
8438         else
8439                 np->vaddr = ioremap(device->slot.base_c, 128);
8440
8441         if (!np->vaddr) {
8442                 printk(KERN_ERR
8443                         "%s: can't map memory mapped IO region\n",ncr_name(np));
8444                 goto attach_error;
8445         } else {
8446                 if (bootverbose > 1)
8447                         printk(KERN_INFO
8448                                 "%s: using memory mapped IO at virtual address 0x%lx\n", ncr_name(np), (u_long) np->vaddr);
8449         }
8450
8451         /* Make the controller's registers available.  Now the INB INW INL
8452          * OUTB OUTW OUTL macros can be used safely.
8453          */
8454
8455         np->reg = (struct ncr_reg __iomem *)np->vaddr;
8456
8457         /* Do chip dependent initialization.  */
8458         ncr_prepare_setting(np);
8459
8460         if (np->paddr2 && sizeof(struct script) > 4096) {
8461                 np->paddr2 = 0;
8462                 printk(KERN_WARNING "%s: script too large, NOT using on chip RAM.\n",
8463                         ncr_name(np));
8464         }
8465
8466         instance->max_channel   = 0;
8467         instance->this_id       = np->myaddr;
8468         instance->max_id        = np->maxwide ? 16 : 8;
8469         instance->max_lun       = SCSI_NCR_MAX_LUN;
8470         instance->base          = (unsigned long) np->reg;
8471         instance->irq           = device->slot.irq;
8472         instance->unique_id     = device->slot.base;
8473         instance->dma_channel   = 0;
8474         instance->cmd_per_lun   = MAX_TAGS;
8475         instance->can_queue     = (MAX_START-4);
8476         /* This can happen if you forget to call ncr53c8xx_init from
8477          * your module_init */
8478         BUG_ON(!ncr53c8xx_transport_template);
8479         instance->transportt    = ncr53c8xx_transport_template;
8480
8481         /* Patch script to physical addresses */
8482         ncr_script_fill(&script0, &scripth0);
8483
8484         np->scripth     = np->scripth0;
8485         np->p_scripth   = vtobus(np->scripth);
8486         np->p_script    = (np->paddr2) ?  np->paddr2 : vtobus(np->script0);
8487
8488         ncr_script_copy_and_bind(np, (ncrcmd *) &script0,
8489                         (ncrcmd *) np->script0, sizeof(struct script));
8490         ncr_script_copy_and_bind(np, (ncrcmd *) &scripth0,
8491                         (ncrcmd *) np->scripth0, sizeof(struct scripth));
8492         np->ccb->p_ccb  = vtobus (np->ccb);
8493
8494         /* Patch the script for LED support.  */
8495
8496         if (np->features & FE_LED0) {
8497                 np->script0->idle[0]  =
8498                                 cpu_to_scr(SCR_REG_REG(gpreg, SCR_OR,  0x01));
8499                 np->script0->reselected[0] =
8500                                 cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
8501                 np->script0->start[0] =
8502                                 cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
8503         }
8504
8505         /*
8506          * Look for the target control block of this nexus.
8507          * For i = 0 to 3
8508          *   JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
8509          */
8510         for (i = 0 ; i < 4 ; i++) {
8511                 np->jump_tcb[i].l_cmd   =
8512                                 cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
8513                 np->jump_tcb[i].l_paddr =
8514                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_target));
8515         }
8516
8517         ncr_chip_reset(np, 100);
8518
8519         /* Now check the cache handling of the chipset.  */
8520
8521         if (ncr_snooptest(np)) {
8522                 printk(KERN_ERR "CACHE INCORRECTLY CONFIGURED.\n");
8523                 goto attach_error;
8524         }
8525
8526         /* Install the interrupt handler.  */
8527         np->irq = device->slot.irq;
8528
8529         /* Initialize the fixed part of the default ccb.  */
8530         ncr_init_ccb(np, np->ccb);
8531
8532         /*
8533          * After SCSI devices have been opened, we cannot reset the bus
8534          * safely, so we do it here.  Interrupt handler does the real work.
8535          * Process the reset exception if interrupts are not enabled yet.
8536          * Then enable disconnects.
8537          */
8538         spin_lock_irqsave(&np->smp_lock, flags);
8539         if (ncr_reset_scsi_bus(np, 0, driver_setup.settle_delay) != 0) {
8540                 printk(KERN_ERR "%s: FATAL ERROR: CHECK SCSI BUS - CABLES, TERMINATION, DEVICE POWER etc.!\n", ncr_name(np));
8541
8542                 spin_unlock_irqrestore(&np->smp_lock, flags);
8543                 goto attach_error;
8544         }
8545         ncr_exception(np);
8546
8547         np->disc = 1;
8548
8549         /*
8550          * The middle-level SCSI driver does not wait for devices to settle.
8551          * Wait synchronously if more than 2 seconds.
8552          */
8553         if (driver_setup.settle_delay > 2) {
8554                 printk(KERN_INFO "%s: waiting %d seconds for scsi devices to settle...\n",
8555                         ncr_name(np), driver_setup.settle_delay);
8556                 mdelay(1000 * driver_setup.settle_delay);
8557         }
8558
8559         /* start the timeout daemon */
8560         np->lasttime=0;
8561         ncr_timeout (np);
8562
8563         /* use SIMPLE TAG messages by default */
8564 #ifdef SCSI_NCR_ALWAYS_SIMPLE_TAG
8565         np->order = M_SIMPLE_TAG;
8566 #endif
8567
8568         spin_unlock_irqrestore(&np->smp_lock, flags);
8569
8570         return instance;
8571
8572  attach_error:
8573         if (!instance)
8574                 return NULL;
8575         printk(KERN_INFO "%s: detaching...\n", ncr_name(np));
8576         if (!np)
8577                 goto unregister;
8578         if (np->scripth0)
8579                 m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
8580         if (np->script0)
8581                 m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
8582         if (np->ccb)
8583                 m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
8584         m_free_dma(np, sizeof(struct ncb), "NCB");
8585         host_data->ncb = NULL;
8586
8587  unregister:
8588         scsi_host_put(instance);
8589
8590         return NULL;
8591 }
8592
8593
8594 int ncr53c8xx_release(struct Scsi_Host *host)
8595 {
8596         struct host_data *host_data;
8597 #ifdef DEBUG_NCR53C8XX
8598         printk("ncr53c8xx: release\n");
8599 #endif
8600         if (!host)
8601                 return 1;
8602         host_data = (struct host_data *)host->hostdata;
8603         if (host_data && host_data->ncb)
8604                 ncr_detach(host_data->ncb);
8605         return 1;
8606 }
8607
8608 static void ncr53c8xx_set_period(struct scsi_target *starget, int period)
8609 {
8610         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
8611         struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8612         struct tcb *tp = &np->target[starget->id];
8613
8614         if (period > np->maxsync)
8615                 period = np->maxsync;
8616         else if (period < np->minsync)
8617                 period = np->minsync;
8618
8619         tp->usrsync = period;
8620
8621         ncr_negotiate(np, tp);
8622 }
8623
8624 static void ncr53c8xx_set_offset(struct scsi_target *starget, int offset)
8625 {
8626         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
8627         struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8628         struct tcb *tp = &np->target[starget->id];
8629
8630         if (offset > np->maxoffs)
8631                 offset = np->maxoffs;
8632         else if (offset < 0)
8633                 offset = 0;
8634
8635         tp->maxoffs = offset;
8636
8637         ncr_negotiate(np, tp);
8638 }
8639
8640 static void ncr53c8xx_set_width(struct scsi_target *starget, int width)
8641 {
8642         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
8643         struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8644         struct tcb *tp = &np->target[starget->id];
8645
8646         if (width > np->maxwide)
8647                 width = np->maxwide;
8648         else if (width < 0)
8649                 width = 0;
8650
8651         tp->usrwide = width;
8652
8653         ncr_negotiate(np, tp);
8654 }
8655
8656 static void ncr53c8xx_get_signalling(struct Scsi_Host *shost)
8657 {
8658         struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8659         enum spi_signal_type type;
8660
8661         switch (np->scsi_mode) {
8662         case SMODE_SE:
8663                 type = SPI_SIGNAL_SE;
8664                 break;
8665         case SMODE_HVD:
8666                 type = SPI_SIGNAL_HVD;
8667                 break;
8668         default:
8669                 type = SPI_SIGNAL_UNKNOWN;
8670                 break;
8671         }
8672         spi_signalling(shost) = type;
8673 }
8674
8675 static struct spi_function_template ncr53c8xx_transport_functions =  {
8676         .set_period     = ncr53c8xx_set_period,
8677         .show_period    = 1,
8678         .set_offset     = ncr53c8xx_set_offset,
8679         .show_offset    = 1,
8680         .set_width      = ncr53c8xx_set_width,
8681         .show_width     = 1,
8682         .get_signalling = ncr53c8xx_get_signalling,
8683 };
8684
8685 int __init ncr53c8xx_init(void)
8686 {
8687         ncr53c8xx_transport_template = spi_attach_transport(&ncr53c8xx_transport_functions);
8688         if (!ncr53c8xx_transport_template)
8689                 return -ENODEV;
8690         return 0;
8691 }
8692
8693 void ncr53c8xx_exit(void)
8694 {
8695         spi_release_transport(ncr53c8xx_transport_template);
8696 }