Fix arch headers.
[linux-flexiantxendom0-3.2.10.git] / drivers / scsi / sym53c8xx_2 / sym_glue.c
1 /*
2  * Device driver for the SYMBIOS/LSILOGIC 53C8XX and 53C1010 family 
3  * of PCI-SCSI IO processors.
4  *
5  * Copyright (C) 1999-2001  Gerard Roudier <groudier@free.fr>
6  *
7  * This driver is derived from the Linux sym53c8xx driver.
8  * Copyright (C) 1998-2000  Gerard Roudier
9  *
10  * The sym53c8xx driver is derived from the ncr53c8xx driver that had been 
11  * a port of the FreeBSD ncr driver to Linux-1.2.13.
12  *
13  * The original ncr driver has been written for 386bsd and FreeBSD by
14  *         Wolfgang Stanglmeier        <wolf@cologne.de>
15  *         Stefan Esser                <se@mi.Uni-Koeln.de>
16  * Copyright (C) 1994  Wolfgang Stanglmeier
17  *
18  * Other major contributions:
19  *
20  * NVRAM detection and reading.
21  * Copyright (C) 1997 Richard Waltham <dormouse@farsrobt.demon.co.uk>
22  *
23  *-----------------------------------------------------------------------------
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. The name of the author may not be used to endorse or promote products
31  *    derived from this software without specific prior written permission.
32  *
33  * Where this Software is combined with software released under the terms of 
34  * the GNU Public License ("GPL") and the terms of the GPL would require the 
35  * combined work to also be released under the terms of the GPL, the terms
36  * and conditions of this License will apply in addition to those of the
37  * GPL with the exception of any terms or conditions of this License that
38  * conflict with, or are expressly prohibited by, the GPL.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
44  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  */
52 #define SYM_GLUE_C
53
54 #include <linux/module.h>
55 #include "sym_glue.h"
56
57 #define NAME53C         "sym53c"
58 #define NAME53C8XX      "sym53c8xx"
59
60 /*
61  *  Simple Wrapper to kernel PCI bus interface.
62  */
63
64 typedef struct pci_dev *pcidev_t;
65 #define PCIDEV_NULL             (0)
66 #define PciBusNumber(d)         (d)->bus->number
67 #define PciDeviceFn(d)          (d)->devfn
68 #define PciVendorId(d)          (d)->vendor
69 #define PciDeviceId(d)          (d)->device
70 #define PciIrqLine(d)           (d)->irq
71
72 static u_long __init
73 pci_get_base_cookie(struct pci_dev *pdev, int index)
74 {
75         u_long base;
76
77 #if LINUX_VERSION_CODE > LinuxVersionCode(2,3,12)
78         base = pdev->resource[index].start;
79 #else
80         base = pdev->base_address[index];
81 #if BITS_PER_LONG > 32
82         if ((base & 0x7) == 0x4)
83                 base |= (((u_long)pdev->base_address[++index]) << 32);
84 #endif
85 #endif
86         return (base & ~0x7ul);
87 }
88
89 static int __init
90 pci_get_base_address(struct pci_dev *pdev, int index, u_long *base)
91 {
92         u32 tmp;
93 #define PCI_BAR_OFFSET(index) (PCI_BASE_ADDRESS_0 + (index<<2))
94
95         pci_read_config_dword(pdev, PCI_BAR_OFFSET(index), &tmp);
96         *base = tmp;
97         ++index;
98         if ((tmp & 0x7) == 0x4) {
99 #if BITS_PER_LONG > 32
100                 pci_read_config_dword(pdev, PCI_BAR_OFFSET(index), &tmp);
101                 *base |= (((u_long)tmp) << 32);
102 #endif
103                 ++index;
104         }
105         return index;
106 #undef PCI_BAR_OFFSET
107 }
108
109 #if LINUX_VERSION_CODE  < LinuxVersionCode(2,4,0)
110 #define pci_enable_device(pdev)         (0)
111 #endif
112
113 #if LINUX_VERSION_CODE  < LinuxVersionCode(2,4,4)
114 #define scsi_set_pci_device(inst, pdev) do { ;} while (0)
115 #endif
116
117 /*
118  *  Insert a delay in micro-seconds and milli-seconds.
119  */
120 void sym_udelay(int us) { udelay(us); }
121 void sym_mdelay(int ms) { mdelay(ms); }
122
123 /*
124  *  SMP threading.
125  *
126  *  The whole SCSI sub-system under Linux is basically single-threaded.
127  *  Everything, including low-level driver interrupt routine, happens 
128  *  with the `io_request_lock' held.
129  *  The sym53c8xx-1.x drivers series ran their interrupt code using a 
130  *  spin mutex per controller. This added complexity without improving 
131  *  scalability significantly. the sym-2 driver still use a spinlock 
132  *  per controller for safety, but basically runs with the damned 
133  *  io_request_lock held.
134  */
135
136 spinlock_t sym53c8xx_lock = SPIN_LOCK_UNLOCKED;
137
138 #define SYM_LOCK_DRIVER(flags)    spin_lock_irqsave(&sym53c8xx_lock, flags)
139 #define SYM_UNLOCK_DRIVER(flags)  spin_unlock_irqrestore(&sym53c8xx_lock,flags)
140
141 #define SYM_INIT_LOCK_HCB(np)           spin_lock_init((np)->s.host->host_lock);
142 #define SYM_LOCK_HCB(np, flags)         \
143                         spin_lock_irqsave((np)->s.host->host_lock, flags)
144 #define SYM_UNLOCK_HCB(np, flags)       \
145                         spin_unlock_irqrestore((np)->s.host->host_lock, flags)
146
147 /*
148  *  These simple macros limit expression involving 
149  *  kernel time values (jiffies) to some that have 
150  *  chance not to be too much incorrect. :-)
151  */
152 #define ktime_get(o)            (jiffies + (u_long) o)
153 #define ktime_exp(b)            ((long)(jiffies) - (long)(b) >= 0)
154 #define ktime_dif(a, b)         ((long)(a) - (long)(b))
155 #define ktime_add(a, o)         ((a) + (u_long)(o))
156 #define ktime_sub(a, o)         ((a) - (u_long)(o))
157
158 /*
159  *  Wrappers to the generic memory allocator.
160  */
161 void *sym_calloc(int size, char *name)
162 {
163         u_long flags;
164         void *m;
165         SYM_LOCK_DRIVER(flags);
166         m = sym_calloc_unlocked(size, name);
167         SYM_UNLOCK_DRIVER(flags);
168         return m;
169 }
170
171 void sym_mfree(void *m, int size, char *name)
172 {
173         u_long flags;
174         SYM_LOCK_DRIVER(flags);
175         sym_mfree_unlocked(m, size, name);
176         SYM_UNLOCK_DRIVER(flags);
177 }
178
179 #ifdef  SYM_LINUX_DYNAMIC_DMA_MAPPING
180
181 void *__sym_calloc_dma(m_pool_ident_t dev_dmat, int size, char *name)
182 {
183         u_long flags;
184         void *m;
185         SYM_LOCK_DRIVER(flags);
186         m = __sym_calloc_dma_unlocked(dev_dmat, size, name);
187         SYM_UNLOCK_DRIVER(flags);
188         return m;
189 }
190
191 void __sym_mfree_dma(m_pool_ident_t dev_dmat, void *m, int size, char *name)
192 {
193         u_long flags;
194         SYM_LOCK_DRIVER(flags);
195         __sym_mfree_dma_unlocked(dev_dmat, m, size, name);
196         SYM_UNLOCK_DRIVER(flags);
197 }
198
199 m_addr_t __vtobus(m_pool_ident_t dev_dmat, void *m)
200 {
201         u_long flags;
202         m_addr_t b;
203         SYM_LOCK_DRIVER(flags);
204         b = __vtobus_unlocked(dev_dmat, m);
205         SYM_UNLOCK_DRIVER(flags);
206         return b;
207 }
208
209 #endif  /* SYM_LINUX_DYNAMIC_DMA_MAPPING */
210
211
212 /*
213  *  Map/unmap a PCI memory window.
214  */
215 #ifndef SYM_OPT_NO_BUS_MEMORY_MAPPING
216 static u_long __init pci_map_mem(u_long base, u_long size)
217 {
218         u_long page_base        = ((u_long) base) & PAGE_MASK;
219         u_long page_offs        = ((u_long) base) - page_base;
220         u_long page_remapped    = (u_long) ioremap(page_base, page_offs+size);
221
222         return page_remapped? (page_remapped + page_offs) : 0UL;
223 }
224
225 static void __init pci_unmap_mem(u_long vaddr, u_long size)
226 {
227         if (vaddr)
228                 iounmap((void *) (vaddr & PAGE_MASK));
229 }
230 #endif
231
232 /*
233  *  Used to retrieve the host structure when the 
234  *  driver is called from the proc FS.
235  */
236 static struct Scsi_Host *first_host = NULL;
237
238 /*
239  *  /proc directory entry and proc_info.
240  */
241 #if LINUX_VERSION_CODE < LinuxVersionCode(2,3,27)
242 static struct proc_dir_entry proc_scsi_sym53c8xx = {
243     PROC_SCSI_SYM53C8XX, 9, NAME53C8XX,
244     S_IFDIR | S_IRUGO | S_IXUGO, 2
245 };
246 #endif
247
248 /*
249  *  Transfer direction
250  *
251  *  Until some linux kernel version near 2.3.40, low-level scsi 
252  *  drivers were not told about data transfer direction.
253  */
254 #if LINUX_VERSION_CODE > LinuxVersionCode(2, 3, 40)
255
256 #define scsi_data_direction(cmd)        (cmd->sc_data_direction)
257
258 #else
259
260 static __inline__ int scsi_data_direction(Scsi_Cmnd *cmd)
261 {
262         int direction;
263
264         switch((int) cmd->cmnd[0]) {
265         case 0x08:  /*  READ(6)                         08 */
266         case 0x28:  /*  READ(10)                        28 */
267         case 0xA8:  /*  READ(12)                        A8 */
268                 direction = SCSI_DATA_READ;
269                 break;
270         case 0x0A:  /*  WRITE(6)                        0A */
271         case 0x2A:  /*  WRITE(10)                       2A */
272         case 0xAA:  /*  WRITE(12)                       AA */
273                 direction = SCSI_DATA_WRITE;
274                 break;
275         default:
276                 direction = SCSI_DATA_UNKNOWN;
277                 break;
278         }
279
280         return direction;
281 }
282
283 #endif
284
285 /*
286  *  Driver host data structure.
287  */
288 struct host_data {
289      hcb_p ncb;
290 };
291
292 /*
293  * Some type that fit DMA addresses as seen from BUS.
294  */
295 #ifndef SYM_LINUX_DYNAMIC_DMA_MAPPING
296 typedef u_long          bus_addr_t;
297 #else
298 typedef dma_addr_t      bus_addr_t;
299 #endif
300
301 /*
302  *  Used by the eh thread to wait for command completion.
303  *  It is allocated on the eh thread stack.
304  */
305 struct sym_eh_wait {
306         struct semaphore sem;
307         struct timer_list timer;
308         void (*old_done)(Scsi_Cmnd *);
309         int to_do;
310         int timed_out;
311 };
312
313 /*
314  *  Driver private area in the SCSI command structure.
315  */
316 struct sym_ucmd {               /* Override the SCSI pointer structure */
317         SYM_QUEHEAD link_cmdq;  /* Must stay at offset ZERO */
318 #ifdef SYM_LINUX_DYNAMIC_DMA_MAPPING
319         bus_addr_t data_mapping;
320         u_char  data_mapped;
321 #endif
322         struct sym_eh_wait *eh_wait;
323 };
324
325 typedef struct sym_ucmd *ucmd_p;
326
327 #define SYM_UCMD_PTR(cmd)  ((ucmd_p)(&(cmd)->SCp))
328 #define SYM_SCMD_PTR(ucmd) sym_que_entry(ucmd, Scsi_Cmnd, SCp)
329 #define SYM_SOFTC_PTR(cmd) (((struct host_data *)cmd->device->host->hostdata)->ncb)
330
331 /*
332  *  Deal with DMA mapping/unmapping.
333  */
334
335 #ifndef SYM_LINUX_DYNAMIC_DMA_MAPPING
336
337 /* Linux versions prior to pci bus iommu kernel interface */
338
339 #define __unmap_scsi_data(pdev, cmd)    do {; } while (0)
340 #define __map_scsi_single_data(pdev, cmd) (__vtobus(pdev,(cmd)->request_buffer))
341 #define __map_scsi_sg_data(pdev, cmd)   ((cmd)->use_sg)
342 #define __sync_scsi_data(pdev, cmd)     do {; } while (0)
343
344 #define bus_sg_dma_address(sc)          vtobus((sc)->address)
345 #define bus_sg_dma_len(sc)              ((sc)->length)
346
347 #else /* Linux version with pci bus iommu kernel interface */
348
349 #define bus_unmap_sg(pdev, sgptr, sgcnt, dir)           \
350         pci_unmap_sg(pdev, sgptr, sgcnt, dir)
351
352 #define bus_unmap_single(pdev, mapping, bufptr, dir)    \
353         pci_unmap_single(pdev, mapping, bufptr, dir)
354
355 #define bus_map_single(pdev, bufptr, bufsiz, dir)       \
356         pci_map_single(pdev, bufptr, bufsiz, dir)
357  
358 #define bus_map_sg(pdev, sgptr, sgcnt, dir)             \
359         pci_map_sg(pdev, sgptr, sgcnt, dir)
360
361 #define bus_dma_sync_sg(pdev, sgptr, sgcnt, dir)        \
362         pci_dma_sync_sg(pdev, sgptr, sgcnt, dir)
363
364 #define bus_dma_sync_single(pdev, mapping, bufsiz, dir) \
365         pci_dma_sync_single(pdev, mapping, bufsiz, dir)
366
367 #define bus_sg_dma_address(sc)  sg_dma_address(sc)
368 #define bus_sg_dma_len(sc)      sg_dma_len(sc)
369
370 static void __unmap_scsi_data(pcidev_t pdev, Scsi_Cmnd *cmd)
371 {
372         int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
373
374         switch(SYM_UCMD_PTR(cmd)->data_mapped) {
375         case 2:
376                 bus_unmap_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
377                 break;
378         case 1:
379                 bus_unmap_single(pdev, SYM_UCMD_PTR(cmd)->data_mapping,
380                                  cmd->request_bufflen, dma_dir);
381                 break;
382         }
383         SYM_UCMD_PTR(cmd)->data_mapped = 0;
384 }
385
386 static bus_addr_t __map_scsi_single_data(pcidev_t pdev, Scsi_Cmnd *cmd)
387 {
388         bus_addr_t mapping;
389         int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
390
391         mapping = bus_map_single(pdev, cmd->request_buffer,
392                                  cmd->request_bufflen, dma_dir);
393         if (mapping) {
394                 SYM_UCMD_PTR(cmd)->data_mapped  = 1;
395                 SYM_UCMD_PTR(cmd)->data_mapping = mapping;
396         }
397
398         return mapping;
399 }
400
401 static int __map_scsi_sg_data(pcidev_t pdev, Scsi_Cmnd *cmd)
402 {
403         int use_sg;
404         int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
405
406         use_sg = bus_map_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
407         if (use_sg > 0) {
408                 SYM_UCMD_PTR(cmd)->data_mapped  = 2;
409                 SYM_UCMD_PTR(cmd)->data_mapping = use_sg;
410         }
411
412         return use_sg;
413 }
414
415 static void __sync_scsi_data(pcidev_t pdev, Scsi_Cmnd *cmd)
416 {
417         int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
418
419         switch(SYM_UCMD_PTR(cmd)->data_mapped) {
420         case 2:
421                 bus_dma_sync_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
422                 break;
423         case 1:
424                 bus_dma_sync_single(pdev, SYM_UCMD_PTR(cmd)->data_mapping,
425                                     cmd->request_bufflen, dma_dir);
426                 break;
427         }
428 }
429
430 #endif  /* SYM_LINUX_DYNAMIC_DMA_MAPPING */
431
432 #define unmap_scsi_data(np, cmd)        \
433                 __unmap_scsi_data(np->s.device, cmd)
434 #define map_scsi_single_data(np, cmd)   \
435                 __map_scsi_single_data(np->s.device, cmd)
436 #define map_scsi_sg_data(np, cmd)       \
437                 __map_scsi_sg_data(np->s.device, cmd)
438 #define sync_scsi_data(np, cmd)         \
439                 __sync_scsi_data(np->s.device, cmd)
440
441 /*
442  *  Complete a pending CAM CCB.
443  */
444 void sym_xpt_done(hcb_p np, Scsi_Cmnd *ccb)
445 {
446         sym_remque(&SYM_UCMD_PTR(ccb)->link_cmdq);
447         unmap_scsi_data(np, ccb);
448         ccb->scsi_done(ccb);
449 }
450
451 void sym_xpt_done2(hcb_p np, Scsi_Cmnd *ccb, int cam_status)
452 {
453         sym_set_cam_status(ccb, cam_status);
454         sym_xpt_done(np, ccb);
455 }
456
457
458 /*
459  *  Print something that identifies the IO.
460  */
461 void sym_print_addr (ccb_p cp)
462 {
463         Scsi_Cmnd *cmd = cp->cam_ccb;
464         if (cmd)
465                 printf("%s:%d:%d:", sym_name(SYM_SOFTC_PTR(cmd)),
466                        cmd->device->id,cmd->device->lun);
467 }
468
469 /*
470  *  Tell the SCSI layer about a BUS RESET.
471  */
472 void sym_xpt_async_bus_reset(hcb_p np)
473 {
474         printf_notice("%s: SCSI BUS has been reset.\n", sym_name(np));
475         np->s.settle_time = ktime_get(sym_driver_setup.settle_delay * HZ);
476         np->s.settle_time_valid = 1;
477         if (sym_verbose >= 2)
478                 printf_info("%s: command processing suspended for %d seconds\n",
479                             sym_name(np), sym_driver_setup.settle_delay);
480 }
481
482 /*
483  *  Tell the SCSI layer about a BUS DEVICE RESET message sent.
484  */
485 void sym_xpt_async_sent_bdr(hcb_p np, int target)
486 {
487         printf_notice("%s: TARGET %d has been reset.\n", sym_name(np), target);
488 }
489
490 /*
491  *  Tell the SCSI layer about the new transfer parameters.
492  */
493 void sym_xpt_async_nego_wide(hcb_p np, int target)
494 {
495         if (sym_verbose < 3)
496                 return;
497         sym_announce_transfer_rate(np, target);
498 }
499
500 /*
501  *  Choose the more appropriate CAM status if 
502  *  the IO encountered an extended error.
503  */
504 static int sym_xerr_cam_status(int cam_status, int x_status)
505 {
506         if (x_status) {
507                 if      (x_status & XE_PARITY_ERR)
508                         cam_status = DID_PARITY;
509                 else if (x_status &(XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN))
510                         cam_status = DID_ERROR;
511                 else if (x_status & XE_BAD_PHASE)
512                         cam_status = DID_ERROR;
513                 else
514                         cam_status = DID_ERROR;
515         }
516         return cam_status;
517 }
518
519 /*
520  *  Build CAM result for a failed or auto-sensed IO.
521  */
522 void sym_set_cam_result_error(hcb_p np, ccb_p cp, int resid)
523 {
524         Scsi_Cmnd *csio = cp->cam_ccb;
525         u_int cam_status, scsi_status, drv_status;
526
527         drv_status  = 0;
528         cam_status  = DID_OK;
529         scsi_status = cp->ssss_status;
530
531         if (cp->host_flags & HF_SENSE) {
532                 scsi_status = cp->sv_scsi_status;
533                 resid = cp->sv_resid;
534                 if (sym_verbose && cp->sv_xerr_status)
535                         sym_print_xerr(cp, cp->sv_xerr_status);
536                 if (cp->host_status == HS_COMPLETE &&
537                     cp->ssss_status == S_GOOD &&
538                     cp->xerr_status == 0) {
539                         cam_status = sym_xerr_cam_status(DID_OK,
540                                                          cp->sv_xerr_status);
541                         drv_status = DRIVER_SENSE;
542                         /*
543                          *  Bounce back the sense data to user.
544                          */
545                         bzero(&csio->sense_buffer, sizeof(csio->sense_buffer));
546                         bcopy(cp->sns_bbuf, csio->sense_buffer,
547                               MIN(sizeof(csio->sense_buffer),SYM_SNS_BBUF_LEN));
548 #if 0
549                         /*
550                          *  If the device reports a UNIT ATTENTION condition 
551                          *  due to a RESET condition, we should consider all 
552                          *  disconnect CCBs for this unit as aborted.
553                          */
554                         if (1) {
555                                 u_char *p;
556                                 p  = (u_char *) csio->sense_data;
557                                 if (p[0]==0x70 && p[2]==0x6 && p[12]==0x29)
558                                         sym_clear_tasks(np, DID_ABORT,
559                                                         cp->target,cp->lun, -1);
560                         }
561 #endif
562                 }
563                 else
564                         cam_status = DID_ERROR;
565         }
566         else if (cp->host_status == HS_COMPLETE)        /* Bad SCSI status */
567                 cam_status = DID_OK;
568         else if (cp->host_status == HS_SEL_TIMEOUT)     /* Selection timeout */
569                 cam_status = DID_NO_CONNECT;
570         else if (cp->host_status == HS_UNEXPECTED)      /* Unexpected BUS FREE*/
571                 cam_status = DID_ERROR;
572         else {                                          /* Extended error */
573                 if (sym_verbose) {
574                         PRINT_ADDR(cp);
575                         printf ("COMMAND FAILED (%x %x %x).\n",
576                                 cp->host_status, cp->ssss_status,
577                                 cp->xerr_status);
578                 }
579                 /*
580                  *  Set the most appropriate value for CAM status.
581                  */
582                 cam_status = sym_xerr_cam_status(DID_ERROR, cp->xerr_status);
583         }
584 #if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,99)
585         csio->resid = resid;
586 #endif
587         csio->result = (drv_status << 24) + (cam_status << 16) + scsi_status;
588 }
589
590
591 /*
592  *  Called on successfull INQUIRY response.
593  */
594 void sym_sniff_inquiry(hcb_p np, Scsi_Cmnd *cmd, int resid)
595 {
596         int retv;
597
598         if (!cmd || cmd->use_sg)
599                 return;
600
601         sync_scsi_data(np, cmd);
602         retv = __sym_sniff_inquiry(np, cmd->device->id, cmd->device->lun,
603                                    (u_char *) cmd->request_buffer,
604                                    cmd->request_bufflen - resid);
605         if (retv < 0)
606                 return;
607         else if (retv)
608                 sym_update_trans_settings(np, &np->target[cmd->device->id]);
609 }
610
611 /*
612  *  Build the scatter/gather array for an I/O.
613  */
614
615 static int sym_scatter_no_sglist(hcb_p np, ccb_p cp, Scsi_Cmnd *cmd)
616 {
617         struct sym_tblmove *data = &cp->phys.data[SYM_CONF_MAX_SG-1];
618         int segment;
619
620         cp->data_len = cmd->request_bufflen;
621
622         if (cmd->request_bufflen) {
623                 bus_addr_t baddr = map_scsi_single_data(np, cmd);
624                 if (baddr) {
625                         sym_build_sge(np, data, baddr, cmd->request_bufflen);
626                         segment = 1;
627                 }
628                 else
629                         segment = -2;
630         }
631         else
632                 segment = 0;
633
634         return segment;
635 }
636
637 static int sym_scatter(hcb_p np, ccb_p cp, Scsi_Cmnd *cmd)
638 {
639         int segment;
640         int use_sg = (int) cmd->use_sg;
641
642         cp->data_len = 0;
643
644         if (!use_sg)
645                 segment = sym_scatter_no_sglist(np, cp, cmd);
646         else if ((use_sg = map_scsi_sg_data(np, cmd)) > 0) {
647                 struct scatterlist *scatter = (struct scatterlist *)cmd->buffer;
648                 struct sym_tblmove *data;
649
650                 if (use_sg > SYM_CONF_MAX_SG) {
651                         unmap_scsi_data(np, cmd);
652                         return -1;
653                 }
654
655                 data = &cp->phys.data[SYM_CONF_MAX_SG - use_sg];
656
657                 for (segment = 0; segment < use_sg; segment++) {
658                         bus_addr_t baddr = bus_sg_dma_address(&scatter[segment]);
659                         unsigned int len = bus_sg_dma_len(&scatter[segment]);
660
661                         sym_build_sge(np, &data[segment], baddr, len);
662                         cp->data_len += len;
663                 }
664         }
665         else
666                 segment = -2;
667
668         return segment;
669 }
670
671 /*
672  *  Queue a SCSI command.
673  */
674 static int sym_queue_command(hcb_p np, Scsi_Cmnd *ccb)
675 {
676 /*      Scsi_Device        *device    = ccb->device; */
677         tcb_p   tp;
678         lcb_p   lp;
679         ccb_p   cp;
680         int     order;
681
682         /*
683          *  Minimal checkings, so that we will not 
684          *  go outside our tables.
685          */
686         if (ccb->device->id == np->myaddr ||
687             ccb->device->id >= SYM_CONF_MAX_TARGET ||
688             ccb->device->lun >= SYM_CONF_MAX_LUN) {
689                 sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
690                 return 0;
691         }
692
693         /*
694          *  Retreive the target descriptor.
695          */
696         tp = &np->target[ccb->device->id];
697
698         /*
699          *  Complete the 1st INQUIRY command with error 
700          *  condition if the device is flagged NOSCAN 
701          *  at BOOT in the NVRAM. This may speed up 
702          *  the boot and maintain coherency with BIOS 
703          *  device numbering. Clearing the flag allows 
704          *  user to rescan skipped devices later.
705          *  We also return error for devices not flagged 
706          *  for SCAN LUNS in the NVRAM since some mono-lun 
707          *  devices behave badly when asked for some non 
708          *  zero LUN. Btw, this is an absolute hack.:-)
709          */
710         if (ccb->cmnd[0] == 0x12 || ccb->cmnd[0] == 0x0) {
711                 if ((tp->usrflags & SYM_SCAN_BOOT_DISABLED) ||
712                     ((tp->usrflags & SYM_SCAN_LUNS_DISABLED) && 
713                      ccb->device->lun != 0)) {
714                         tp->usrflags &= ~SYM_SCAN_BOOT_DISABLED;
715                         sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
716                         return 0;
717                 }
718         }
719
720         /*
721          *  Select tagged/untagged.
722          */
723         lp = sym_lp(np, tp, ccb->device->lun);
724         order = (lp && lp->s.reqtags) ? M_SIMPLE_TAG : 0;
725
726         /*
727          *  Queue the SCSI IO.
728          */
729         cp = sym_get_ccb(np, ccb->device->id, ccb->device->lun, order);
730         if (!cp)
731                 return 1;       /* Means resource shortage */
732         (void) sym_queue_scsiio(np, ccb, cp);
733         return 0;
734 }
735
736 /*
737  *  Setup buffers and pointers that address the CDB.
738  */
739 static int __inline sym_setup_cdb(hcb_p np, Scsi_Cmnd *ccb, ccb_p cp)
740 {
741         u32     cmd_ba;
742         int     cmd_len;
743
744         /*
745          *  CDB is 16 bytes max.
746          */
747         if (ccb->cmd_len > sizeof(cp->cdb_buf)) {
748                 sym_set_cam_status(cp->cam_ccb, CAM_REQ_INVALID);
749                 return -1;
750         }
751
752         bcopy(ccb->cmnd, cp->cdb_buf, ccb->cmd_len);
753         cmd_ba  = CCB_BA (cp, cdb_buf[0]);
754         cmd_len = ccb->cmd_len;
755
756         cp->phys.cmd.addr       = cpu_to_scr(cmd_ba);
757         cp->phys.cmd.size       = cpu_to_scr(cmd_len);
758
759         return 0;
760 }
761
762 /*
763  *  Setup pointers that address the data and start the I/O.
764  */
765 int sym_setup_data_and_start(hcb_p np, Scsi_Cmnd *csio, ccb_p cp)
766 {
767         int dir;
768         tcb_p tp = &np->target[cp->target];
769         lcb_p lp = sym_lp(np, tp, cp->lun);
770
771         /*
772          *  Build the CDB.
773          */
774         if (sym_setup_cdb(np, csio, cp))
775                 goto out_abort;
776
777         /*
778          *  No direction means no data.
779          */
780         dir = scsi_data_direction(csio);
781         if (dir != SCSI_DATA_NONE) {
782                 cp->segments = sym_scatter (np, cp, csio);
783                 if (cp->segments < 0) {
784                         if (cp->segments == -2)
785                                 sym_set_cam_status(csio, CAM_RESRC_UNAVAIL);
786                         else
787                                 sym_set_cam_status(csio, CAM_REQ_TOO_BIG);
788                         goto out_abort;
789                 }
790         }
791         else {
792                 cp->data_len = 0;
793                 cp->segments = 0;
794         }
795
796         /*
797          *  Set data pointers.
798          */
799         sym_setup_data_pointers(np, cp, dir);
800
801         /*
802          *  When `#ifed 1', the code below makes the driver 
803          *  panic on the first attempt to write to a SCSI device.
804          *  It is the first test we want to do after a driver 
805          *  change that does not seem obviously safe. :)
806          */
807 #if 0
808         switch (cp->cdb_buf[0]) {
809         case 0x0A: case 0x2A: case 0xAA:
810                 panic("XXXXXXXXXXXXX WRITE NOT YET ALLOWED XXXXXXXXXXXXXX\n");
811                 MDELAY(10000);
812                 break;
813         default:
814                 break;
815         }
816 #endif
817
818         /*
819          *      activate this job.
820          */
821         if (lp)
822                 sym_start_next_ccbs(np, lp, 2);
823         else
824                 sym_put_start_queue(np, cp);
825         return 0;
826
827 out_abort:
828         sym_free_ccb(np, cp);
829         sym_xpt_done(np, csio);
830         return 0;
831 }
832
833
834 /*
835  *  timer daemon.
836  *
837  *  Misused to keep the driver running when
838  *  interrupts are not configured correctly.
839  */
840 static void sym_timer (hcb_p np)
841 {
842         u_long  thistime = ktime_get(0);
843
844 #if LINUX_VERSION_CODE < LinuxVersionCode(2, 4, 0)
845         /*
846          *  If release process in progress, let's go
847          *  Set the release stage from 1 to 2 to synchronize
848          *  with the release process.
849          */
850
851         if (np->s.release_stage) {
852                 if (np->s.release_stage == 1)
853                         np->s.release_stage = 2;
854                 return;
855         }
856 #endif
857
858         /*
859          *  Restart the timer.
860          */
861 #ifdef SYM_CONF_PCIQ_BROKEN_INTR
862         np->s.timer.expires = ktime_get((HZ+99)/100);
863 #else
864         np->s.timer.expires = ktime_get(SYM_CONF_TIMER_INTERVAL);
865 #endif
866         add_timer(&np->s.timer);
867
868         /*
869          *  If we are resetting the ncr, wait for settle_time before 
870          *  clearing it. Then command processing will be resumed.
871          */
872         if (np->s.settle_time_valid) {
873                 if (ktime_dif(np->s.settle_time, thistime) <= 0){
874                         if (sym_verbose >= 2 )
875                                 printk("%s: command processing resumed\n",
876                                        sym_name(np));
877                         np->s.settle_time_valid = 0;
878                 }
879                 return;
880         }
881
882         /*
883          *      Nothing to do for now, but that may come.
884          */
885         if (np->s.lasttime + 4*HZ < thistime) {
886                 np->s.lasttime = thistime;
887         }
888
889 #ifdef SYM_CONF_PCIQ_MAY_MISS_COMPLETIONS
890         /*
891          *  Some way-broken PCI bridges may lead to 
892          *  completions being lost when the clearing 
893          *  of the INTFLY flag by the CPU occurs 
894          *  concurrently with the chip raising this flag.
895          *  If this ever happen, lost completions will 
896          * be reaped here.
897          */
898         sym_wakeup_done(np);
899 #endif
900
901 #ifdef SYM_CONF_PCIQ_BROKEN_INTR
902         if (INB(nc_istat) & (INTF|SIP|DIP)) {
903
904                 /*
905                 **      Process pending interrupts.
906                 */
907                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("{");
908                 sym_interrupt(np);
909                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("}");
910         }
911 #endif /* SYM_CONF_PCIQ_BROKEN_INTR */
912 }
913
914
915 /*
916  *  PCI BUS error handler.
917  */
918 void sym_log_bus_error(hcb_p np)
919 {
920         u_short pci_sts;
921         pci_read_config_word(np->s.device, PCI_STATUS, &pci_sts);
922         if (pci_sts & 0xf900) {
923                 pci_write_config_word(np->s.device, PCI_STATUS,
924                                          pci_sts);
925                 printf("%s: PCI STATUS = 0x%04x\n",
926                         sym_name(np), pci_sts & 0xf900);
927         }
928 }
929
930
931 /*
932  *  Requeue awaiting commands.
933  */
934 static void sym_requeue_awaiting_cmds(hcb_p np)
935 {
936         Scsi_Cmnd *cmd;
937         ucmd_p ucp = SYM_UCMD_PTR(cmd);
938         SYM_QUEHEAD tmp_cmdq;
939         int sts;
940
941         sym_que_move(&np->s.wait_cmdq, &tmp_cmdq);
942
943         while ((ucp = (ucmd_p) sym_remque_head(&tmp_cmdq)) != 0) {
944                 sym_insque_tail(&ucp->link_cmdq, &np->s.busy_cmdq);
945                 cmd = SYM_SCMD_PTR(ucp);
946                 sts = sym_queue_command(np, cmd);
947                 if (sts) {
948                         sym_remque(&ucp->link_cmdq);
949                         sym_insque_head(&ucp->link_cmdq, &np->s.wait_cmdq);
950                 }
951         }
952 }
953
954 /*
955  *  Linux entry point of the queuecommand() function
956  */
957 int sym53c8xx_queue_command (Scsi_Cmnd *cmd, void (*done)(Scsi_Cmnd *))
958 {
959         hcb_p  np  = SYM_SOFTC_PTR(cmd);
960         ucmd_p ucp = SYM_UCMD_PTR(cmd);
961         int sts = 0;
962 #if 0
963         u_long flags;
964 #endif
965
966         cmd->scsi_done     = done;
967         cmd->host_scribble = NULL;
968         memset(ucp, 0, sizeof(*ucp));
969
970 #if 0
971         SYM_LOCK_HCB(np, flags);
972 #endif
973
974         /*
975          *  Shorten our settle_time if needed for 
976          *  this command not to time out.
977          */
978         if (np->s.settle_time_valid && cmd->timeout_per_command) {
979                 u_long tlimit = ktime_get(cmd->timeout_per_command);
980                 tlimit = ktime_sub(tlimit, SYM_CONF_TIMER_INTERVAL*2);
981                 if (ktime_dif(np->s.settle_time, tlimit) > 0) {
982                         np->s.settle_time = tlimit;
983                 }
984         }
985
986         if (np->s.settle_time_valid || !sym_que_empty(&np->s.wait_cmdq)) {
987                 sym_insque_tail(&ucp->link_cmdq, &np->s.wait_cmdq);
988                 goto out;
989         }
990
991         sym_insque_tail(&ucp->link_cmdq, &np->s.busy_cmdq);
992         sts = sym_queue_command(np, cmd);
993         if (sts) {
994                 sym_remque(&ucp->link_cmdq);
995                 sym_insque_tail(&ucp->link_cmdq, &np->s.wait_cmdq);
996         }
997 out:
998 #if 0
999         SYM_UNLOCK_HCB(np, flags);
1000 #endif
1001
1002         return 0;
1003 }
1004
1005 /*
1006  *  Linux entry point of the interrupt handler.
1007  */
1008 static irqreturn_t sym53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs)
1009 {
1010         unsigned long flags;
1011         hcb_p np = (hcb_p) dev_id;
1012
1013         if (DEBUG_FLAGS & DEBUG_TINY) printf_debug ("[");
1014
1015         SYM_LOCK_HCB(np, flags);
1016
1017         sym_interrupt(np);
1018
1019         /*
1020          * push queue walk-through to tasklet
1021          */
1022         if (!sym_que_empty(&np->s.wait_cmdq) && !np->s.settle_time_valid)
1023                 sym_requeue_awaiting_cmds(np);
1024
1025         SYM_UNLOCK_HCB(np, flags);
1026
1027         if (DEBUG_FLAGS & DEBUG_TINY) printf_debug ("]\n");
1028
1029         return IRQ_HANDLED;
1030 }
1031
1032 /*
1033  *  Linux entry point of the timer handler
1034  */
1035 static void sym53c8xx_timer(unsigned long npref)
1036 {
1037         hcb_p np = (hcb_p) npref;
1038         unsigned long flags;
1039
1040         SYM_LOCK_HCB(np, flags);
1041
1042         sym_timer(np);
1043
1044         if (!sym_que_empty(&np->s.wait_cmdq) && !np->s.settle_time_valid)
1045                 sym_requeue_awaiting_cmds(np);
1046
1047         SYM_UNLOCK_HCB(np, flags);
1048 }
1049
1050
1051 /*
1052  *  What the eh thread wants us to perform.
1053  */
1054 #define SYM_EH_ABORT            0
1055 #define SYM_EH_DEVICE_RESET     1
1056 #define SYM_EH_BUS_RESET        2
1057 #define SYM_EH_HOST_RESET       3
1058
1059 /*
1060  *  What we will do regarding the involved SCSI command.
1061  */
1062 #define SYM_EH_DO_IGNORE        0
1063 #define SYM_EH_DO_COMPLETE      1
1064 #define SYM_EH_DO_WAIT          2
1065
1066 /*
1067  *  Our general completion handler.
1068  */
1069 static void __sym_eh_done(Scsi_Cmnd *cmd, int timed_out)
1070 {
1071         struct sym_eh_wait *ep = SYM_UCMD_PTR(cmd)->eh_wait;
1072         if (!ep)
1073                 return;
1074
1075         /* Try to avoid a race here (not 100% safe) */
1076         if (!timed_out) {
1077                 ep->timed_out = 0;
1078                 if (ep->to_do == SYM_EH_DO_WAIT && !del_timer(&ep->timer))
1079                         return;
1080         }
1081
1082         /* Revert everything */
1083         SYM_UCMD_PTR(cmd)->eh_wait = 0;
1084         cmd->scsi_done = ep->old_done;
1085
1086         /* Wake up the eh thread if it wants to sleep */
1087         if (ep->to_do == SYM_EH_DO_WAIT)
1088                 up(&ep->sem);
1089 }
1090
1091 /*
1092  *  scsi_done() alias when error recovery is in progress. 
1093  */
1094 static void sym_eh_done(Scsi_Cmnd *cmd) { __sym_eh_done(cmd, 0); }
1095
1096 /*
1097  *  Some timeout handler to avoid waiting too long.
1098  */
1099 static void sym_eh_timeout(u_long p) { __sym_eh_done((Scsi_Cmnd *)p, 1); }
1100
1101 /*
1102  *  Generic method for our eh processing.
1103  *  The 'op' argument tells what we have to do.
1104  */
1105 static int sym_eh_handler(int op, char *opname, Scsi_Cmnd *cmd)
1106 {
1107         hcb_p np = SYM_SOFTC_PTR(cmd);
1108         SYM_QUEHEAD *qp;
1109         int to_do = SYM_EH_DO_IGNORE;
1110         int sts = -1;
1111         struct sym_eh_wait eh, *ep = &eh;
1112         char devname[20];
1113
1114         sprintf(devname, "%s:%d:%d", sym_name(np), cmd->device->id, cmd->device->lun);
1115
1116         printf_warning("%s: %s operation started.\n", devname, opname);
1117
1118 #if 0
1119         /* This one should be the result of some race, thus to ignore */
1120         if (cmd->serial_number != cmd->serial_number_at_timeout)
1121                 goto prepare;
1122 #endif
1123
1124         /* This one is not queued to the core driver -> to complete here */ 
1125         FOR_EACH_QUEUED_ELEMENT(&np->s.wait_cmdq, qp) {
1126                 if (SYM_SCMD_PTR(qp) == cmd) {
1127                         to_do = SYM_EH_DO_COMPLETE;
1128                         goto prepare;
1129                 }
1130         }
1131
1132         /* This one is queued in some place -> to wait for completion */
1133         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
1134                 ccb_p cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
1135                 if (cp->cam_ccb == cmd) {
1136                         to_do = SYM_EH_DO_WAIT;
1137                         goto prepare;
1138                 }
1139         }
1140
1141 prepare:
1142         /* Prepare stuff to either ignore, complete or wait for completion */
1143         switch(to_do) {
1144         default:
1145         case SYM_EH_DO_IGNORE:
1146                 goto finish;
1147                 break;
1148         case SYM_EH_DO_WAIT:
1149 #if LINUX_VERSION_CODE > LinuxVersionCode(2,3,0)
1150                 init_MUTEX_LOCKED(&ep->sem);
1151 #else
1152                 ep->sem = MUTEX_LOCKED;
1153 #endif
1154                 /* fall through */
1155         case SYM_EH_DO_COMPLETE:
1156                 ep->old_done = cmd->scsi_done;
1157                 cmd->scsi_done = sym_eh_done;
1158                 SYM_UCMD_PTR(cmd)->eh_wait = ep;
1159         }
1160
1161         /* Try to proceed the operation we have been asked for */
1162         sts = -1;
1163         switch(op) {
1164         case SYM_EH_ABORT:
1165                 sts = sym_abort_scsiio(np, cmd, 1);
1166                 break;
1167         case SYM_EH_DEVICE_RESET:
1168                 sts = sym_reset_scsi_target(np, cmd->device->id);
1169                 break;
1170         case SYM_EH_BUS_RESET:
1171                 sym_reset_scsi_bus(np, 1);
1172                 sts = 0;
1173                 break;
1174         case SYM_EH_HOST_RESET:
1175                 sym_reset_scsi_bus(np, 0);
1176                 sym_start_up (np, 1);
1177                 sts = 0;
1178                 break;
1179         default:
1180                 break;
1181         }
1182
1183         /* On error, restore everything and cross fingers :) */
1184         if (sts) {
1185                 SYM_UCMD_PTR(cmd)->eh_wait = 0;
1186                 cmd->scsi_done = ep->old_done;
1187                 to_do = SYM_EH_DO_IGNORE;
1188         }
1189
1190 finish:
1191         ep->to_do = to_do;
1192         /* Complete the command with locks held as required by the driver */
1193         if (to_do == SYM_EH_DO_COMPLETE)
1194                 sym_xpt_done2(np, cmd, CAM_REQ_ABORTED);
1195
1196         /* Wait for completion with locks released, as required by kernel */
1197         if (to_do == SYM_EH_DO_WAIT) {
1198                 init_timer(&ep->timer);
1199                 ep->timer.expires = jiffies + (5*HZ);
1200                 ep->timer.function = sym_eh_timeout;
1201                 ep->timer.data = (u_long)cmd;
1202                 ep->timed_out = 1;      /* Be pessimistic for once :) */
1203                 add_timer(&ep->timer);
1204                 down(&ep->sem);
1205                 if (ep->timed_out)
1206                         sts = -2;
1207         }
1208         printf_warning("%s: %s operation %s.\n", devname, opname,
1209                         sts==0?"complete":sts==-2?"timed-out":"failed");
1210         return sts? SCSI_FAILED : SCSI_SUCCESS;
1211 }
1212
1213
1214 /*
1215  * Error handlers called from the eh thread (one thread per HBA).
1216  */
1217 int sym53c8xx_eh_abort_handler(Scsi_Cmnd *cmd)
1218 {
1219         return sym_eh_handler(SYM_EH_ABORT, "ABORT", cmd);
1220 }
1221
1222 int sym53c8xx_eh_device_reset_handler(Scsi_Cmnd *cmd)
1223 {
1224         return sym_eh_handler(SYM_EH_DEVICE_RESET, "DEVICE RESET", cmd);
1225 }
1226
1227 int sym53c8xx_eh_bus_reset_handler(Scsi_Cmnd *cmd)
1228 {
1229         return sym_eh_handler(SYM_EH_BUS_RESET, "BUS RESET", cmd);
1230 }
1231
1232 int sym53c8xx_eh_host_reset_handler(Scsi_Cmnd *cmd)
1233 {
1234         return sym_eh_handler(SYM_EH_HOST_RESET, "HOST RESET", cmd);
1235 }
1236
1237 /*
1238  *  Tune device queuing depth, according to various limits.
1239  */
1240 static void 
1241 sym_tune_dev_queuing(hcb_p np, int target, int lun, u_short reqtags)
1242 {
1243         tcb_p   tp = &np->target[target];
1244         lcb_p   lp = sym_lp(np, tp, lun);
1245         u_short oldtags;
1246
1247         if (!lp)
1248                 return;
1249
1250         oldtags = lp->s.reqtags;
1251
1252         if (reqtags > lp->s.scdev_depth)
1253                 reqtags = lp->s.scdev_depth;
1254
1255         lp->started_limit = reqtags ? reqtags : 2;
1256         lp->started_max   = 1;
1257         lp->s.reqtags     = reqtags;
1258
1259         if (reqtags != oldtags) {
1260                 printf_info("%s:%d:%d: "
1261                          "tagged command queuing %s, command queue depth %d.\n",
1262                           sym_name(np), target, lun,
1263                           lp->s.reqtags ? "enabled" : "disabled",
1264                           lp->started_limit);
1265         }
1266 }
1267
1268 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
1269 /*
1270  *  Linux select queue depths function
1271  */
1272 #define DEF_DEPTH       (sym_driver_setup.max_tag)
1273 #define ALL_TARGETS     -2
1274 #define NO_TARGET       -1
1275 #define ALL_LUNS        -2
1276 #define NO_LUN          -1
1277
1278 static int device_queue_depth(hcb_p np, int target, int lun)
1279 {
1280         int c, h, t, u, v;
1281         char *p = sym_driver_setup.tag_ctrl;
1282         char *ep;
1283
1284         h = -1;
1285         t = NO_TARGET;
1286         u = NO_LUN;
1287         while ((c = *p++) != 0) {
1288                 v = simple_strtoul(p, &ep, 0);
1289                 switch(c) {
1290                 case '/':
1291                         ++h;
1292                         t = ALL_TARGETS;
1293                         u = ALL_LUNS;
1294                         break;
1295                 case 't':
1296                         if (t != target)
1297                                 t = (target == v) ? v : NO_TARGET;
1298                         u = ALL_LUNS;
1299                         break;
1300                 case 'u':
1301                         if (u != lun)
1302                                 u = (lun == v) ? v : NO_LUN;
1303                         break;
1304                 case 'q':
1305                         if (h == np->s.unit &&
1306                                 (t == ALL_TARGETS || t == target) &&
1307                                 (u == ALL_LUNS    || u == lun))
1308                                 return v;
1309                         break;
1310                 case '-':
1311                         t = ALL_TARGETS;
1312                         u = ALL_LUNS;
1313                         break;
1314                 default:
1315                         break;
1316                 }
1317                 p = ep;
1318         }
1319         return DEF_DEPTH;
1320 }
1321 #else
1322 #define device_queue_depth(np, t, l)    (sym_driver_setup.max_tag)
1323 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
1324
1325 /*
1326  * Linux entry point for device queue sizing.
1327  */
1328 int
1329 sym53c8xx_slave_configure(Scsi_Device *device)
1330 {
1331         struct Scsi_Host *host = device->host;
1332         hcb_p np;
1333         tcb_p tp;
1334         lcb_p lp;
1335         int reqtags, depth_to_use;
1336
1337         np = ((struct host_data *) host->hostdata)->ncb;
1338         tp = &np->target[device->id];
1339
1340         /*
1341          *  Get user settings for transfer parameters.
1342          */
1343         tp->inq_byte7_valid = (INQ7_SYNC|INQ7_WIDE16);
1344         sym_update_trans_settings(np, tp);
1345
1346         /*
1347          *  Allocate the LCB if not yet.
1348          *  If it fail, we may well be in the sh*t. :)
1349          */
1350         lp = sym_alloc_lcb(np, device->id, device->lun);
1351         if (!lp)
1352                 return -ENOMEM;
1353
1354         /*
1355          *  Get user flags.
1356          */
1357         lp->curr_flags = lp->user_flags;
1358
1359         /*
1360          *  Select queue depth from driver setup.
1361          *  Donnot use more than configured by user.
1362          *  Use at least 2.
1363          *  Donnot use more than our maximum.
1364          */
1365         reqtags = device_queue_depth(np, device->id, device->lun);
1366         if (reqtags > tp->usrtags)
1367                 reqtags = tp->usrtags;
1368         if (!device->tagged_supported)
1369                 reqtags = 0;
1370 #if 1 /* Avoid to locally queue commands for no good reasons */
1371         if (reqtags > SYM_CONF_MAX_TAG)
1372                 reqtags = SYM_CONF_MAX_TAG;
1373         depth_to_use = (reqtags ? reqtags : 2);
1374 #else
1375         depth_to_use = (reqtags ? SYM_CONF_MAX_TAG : 2);
1376 #endif
1377         scsi_adjust_queue_depth(device,
1378                                 (device->tagged_supported ?
1379                                  MSG_SIMPLE_TAG : 0),
1380                                 depth_to_use);
1381         lp->s.scdev_depth = depth_to_use;
1382         sym_tune_dev_queuing(np, device->id, device->lun, reqtags);
1383
1384         return 0;
1385 }
1386
1387 /*
1388  *  Linux entry point for info() function
1389  */
1390 const char *sym53c8xx_info (struct Scsi_Host *host)
1391 {
1392         return sym_driver_name();
1393 }
1394
1395
1396 #ifdef SYM_LINUX_PROC_INFO_SUPPORT
1397 /*
1398  *  Proc file system stuff
1399  *
1400  *  A read operation returns adapter information.
1401  *  A write operation is a control command.
1402  *  The string is parsed in the driver code and the command is passed 
1403  *  to the sym_usercmd() function.
1404  */
1405
1406 #ifdef SYM_LINUX_USER_COMMAND_SUPPORT
1407
1408 struct  sym_usrcmd {
1409         u_long  target;
1410         u_long  lun;
1411         u_long  data;
1412         u_long  cmd;
1413 };
1414
1415 #define UC_SETSYNC      10
1416 #define UC_SETTAGS      11
1417 #define UC_SETDEBUG     12
1418 #define UC_SETWIDE      14
1419 #define UC_SETFLAG      15
1420 #define UC_SETVERBOSE   17
1421 #define UC_RESETDEV     18
1422 #define UC_CLEARDEV     19
1423
1424 static void sym_exec_user_command (hcb_p np, struct sym_usrcmd *uc)
1425 {
1426         tcb_p tp;
1427         int t, l;
1428
1429         switch (uc->cmd) {
1430         case 0: return;
1431
1432 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1433         case UC_SETDEBUG:
1434                 sym_debug_flags = uc->data;
1435                 break;
1436 #endif
1437         case UC_SETVERBOSE:
1438                 np->verbose = uc->data;
1439                 break;
1440         default:
1441                 /*
1442                  * We assume that other commands apply to targets.
1443                  * This should always be the case and avoid the below 
1444                  * 4 lines to be repeated 6 times.
1445                  */
1446                 for (t = 0; t < SYM_CONF_MAX_TARGET; t++) {
1447                         if (!((uc->target >> t) & 1))
1448                                 continue;
1449                         tp = &np->target[t];
1450
1451                         switch (uc->cmd) {
1452
1453                         case UC_SETSYNC:
1454                                 if (!uc->data || uc->data >= 255) {
1455                                         tp->tinfo.goal.options = 0;
1456                                         tp->tinfo.goal.offset  = 0;
1457                                         break;
1458                                 }
1459                                 if (uc->data <= 9 && np->minsync_dt) {
1460                                         if (uc->data < np->minsync_dt)
1461                                                 uc->data = np->minsync_dt;
1462                                         tp->tinfo.goal.options = PPR_OPT_DT;
1463                                         tp->tinfo.goal.width   = 1;
1464                                         tp->tinfo.goal.period = uc->data;
1465                                         tp->tinfo.goal.offset = np->maxoffs_dt;
1466                                 }
1467                                 else {
1468                                         if (uc->data < np->minsync)
1469                                                 uc->data = np->minsync;
1470                                         tp->tinfo.goal.options = 0;
1471                                         tp->tinfo.goal.period = uc->data;
1472                                         tp->tinfo.goal.offset = np->maxoffs;
1473                                 }
1474                                 break;
1475                         case UC_SETWIDE:
1476                                 tp->tinfo.goal.width = uc->data ? 1 : 0;
1477                                 break;
1478                         case UC_SETTAGS:
1479                                 for (l = 0; l < SYM_CONF_MAX_LUN; l++)
1480                                         sym_tune_dev_queuing(np, t,l, uc->data);
1481                                 break;
1482                         case UC_RESETDEV:
1483                                 tp->to_reset = 1;
1484                                 np->istat_sem = SEM;
1485                                 OUTB (nc_istat, SIGP|SEM);
1486                                 break;
1487                         case UC_CLEARDEV:
1488                                 for (l = 0; l < SYM_CONF_MAX_LUN; l++) {
1489                                         lcb_p lp = sym_lp(np, tp, l);
1490                                         if (lp) lp->to_clear = 1;
1491                                 }
1492                                 np->istat_sem = SEM;
1493                                 OUTB (nc_istat, SIGP|SEM);
1494                                 break;
1495                         case UC_SETFLAG:
1496                                 tp->usrflags = uc->data;
1497                                 break;
1498                         }
1499                 }
1500                 break;
1501         }
1502 }
1503
1504 #define is_digit(c)     ((c) >= '0' && (c) <= '9')
1505 #define digit_to_bin(c) ((c) - '0')
1506 #define is_space(c)     ((c) == ' ' || (c) == '\t')
1507
1508 static int skip_spaces(char *ptr, int len)
1509 {
1510         int cnt, c;
1511
1512         for (cnt = len; cnt > 0 && (c = *ptr++) && is_space(c); cnt--);
1513
1514         return (len - cnt);
1515 }
1516
1517 static int get_int_arg(char *ptr, int len, u_long *pv)
1518 {
1519         int     cnt, c;
1520         u_long  v;
1521
1522         for (v = 0, cnt = len; cnt > 0 && (c = *ptr++) && is_digit(c); cnt--) {
1523                 v = (v * 10) + digit_to_bin(c);
1524         }
1525
1526         if (pv)
1527                 *pv = v;
1528
1529         return (len - cnt);
1530 }
1531
1532 static int is_keyword(char *ptr, int len, char *verb)
1533 {
1534         int verb_len = strlen(verb);
1535
1536         if (len >= strlen(verb) && !memcmp(verb, ptr, verb_len))
1537                 return verb_len;
1538         else
1539                 return 0;
1540
1541 }
1542
1543 #define SKIP_SPACES(min_spaces)                                         \
1544         if ((arg_len = skip_spaces(ptr, len)) < (min_spaces))           \
1545                 return -EINVAL;                                         \
1546         ptr += arg_len; len -= arg_len;
1547
1548 #define GET_INT_ARG(v)                                                  \
1549         if (!(arg_len = get_int_arg(ptr, len, &(v))))                   \
1550                 return -EINVAL;                                         \
1551         ptr += arg_len; len -= arg_len;
1552
1553
1554 /*
1555  * Parse a control command
1556  */
1557
1558 static int sym_user_command(hcb_p np, char *buffer, int length)
1559 {
1560         char *ptr       = buffer;
1561         int len         = length;
1562         struct sym_usrcmd cmd, *uc = &cmd;
1563         int             arg_len;
1564         u_long          target;
1565
1566         bzero(uc, sizeof(*uc));
1567
1568         if (len > 0 && ptr[len-1] == '\n')
1569                 --len;
1570
1571         if      ((arg_len = is_keyword(ptr, len, "setsync")) != 0)
1572                 uc->cmd = UC_SETSYNC;
1573         else if ((arg_len = is_keyword(ptr, len, "settags")) != 0)
1574                 uc->cmd = UC_SETTAGS;
1575         else if ((arg_len = is_keyword(ptr, len, "setverbose")) != 0)
1576                 uc->cmd = UC_SETVERBOSE;
1577         else if ((arg_len = is_keyword(ptr, len, "setwide")) != 0)
1578                 uc->cmd = UC_SETWIDE;
1579 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1580         else if ((arg_len = is_keyword(ptr, len, "setdebug")) != 0)
1581                 uc->cmd = UC_SETDEBUG;
1582 #endif
1583         else if ((arg_len = is_keyword(ptr, len, "setflag")) != 0)
1584                 uc->cmd = UC_SETFLAG;
1585         else if ((arg_len = is_keyword(ptr, len, "resetdev")) != 0)
1586                 uc->cmd = UC_RESETDEV;
1587         else if ((arg_len = is_keyword(ptr, len, "cleardev")) != 0)
1588                 uc->cmd = UC_CLEARDEV;
1589         else
1590                 arg_len = 0;
1591
1592 #ifdef DEBUG_PROC_INFO
1593 printk("sym_user_command: arg_len=%d, cmd=%ld\n", arg_len, uc->cmd);
1594 #endif
1595
1596         if (!arg_len)
1597                 return -EINVAL;
1598         ptr += arg_len; len -= arg_len;
1599
1600         switch(uc->cmd) {
1601         case UC_SETSYNC:
1602         case UC_SETTAGS:
1603         case UC_SETWIDE:
1604         case UC_SETFLAG:
1605         case UC_RESETDEV:
1606         case UC_CLEARDEV:
1607                 SKIP_SPACES(1);
1608                 if ((arg_len = is_keyword(ptr, len, "all")) != 0) {
1609                         ptr += arg_len; len -= arg_len;
1610                         uc->target = ~0;
1611                 } else {
1612                         GET_INT_ARG(target);
1613                         uc->target = (1<<target);
1614 #ifdef DEBUG_PROC_INFO
1615 printk("sym_user_command: target=%ld\n", target);
1616 #endif
1617                 }
1618                 break;
1619         }
1620
1621         switch(uc->cmd) {
1622         case UC_SETVERBOSE:
1623         case UC_SETSYNC:
1624         case UC_SETTAGS:
1625         case UC_SETWIDE:
1626                 SKIP_SPACES(1);
1627                 GET_INT_ARG(uc->data);
1628 #ifdef DEBUG_PROC_INFO
1629 printk("sym_user_command: data=%ld\n", uc->data);
1630 #endif
1631                 break;
1632 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1633         case UC_SETDEBUG:
1634                 while (len > 0) {
1635                         SKIP_SPACES(1);
1636                         if      ((arg_len = is_keyword(ptr, len, "alloc")))
1637                                 uc->data |= DEBUG_ALLOC;
1638                         else if ((arg_len = is_keyword(ptr, len, "phase")))
1639                                 uc->data |= DEBUG_PHASE;
1640                         else if ((arg_len = is_keyword(ptr, len, "queue")))
1641                                 uc->data |= DEBUG_QUEUE;
1642                         else if ((arg_len = is_keyword(ptr, len, "result")))
1643                                 uc->data |= DEBUG_RESULT;
1644                         else if ((arg_len = is_keyword(ptr, len, "scatter")))
1645                                 uc->data |= DEBUG_SCATTER;
1646                         else if ((arg_len = is_keyword(ptr, len, "script")))
1647                                 uc->data |= DEBUG_SCRIPT;
1648                         else if ((arg_len = is_keyword(ptr, len, "tiny")))
1649                                 uc->data |= DEBUG_TINY;
1650                         else if ((arg_len = is_keyword(ptr, len, "timing")))
1651                                 uc->data |= DEBUG_TIMING;
1652                         else if ((arg_len = is_keyword(ptr, len, "nego")))
1653                                 uc->data |= DEBUG_NEGO;
1654                         else if ((arg_len = is_keyword(ptr, len, "tags")))
1655                                 uc->data |= DEBUG_TAGS;
1656                         else if ((arg_len = is_keyword(ptr, len, "pointer")))
1657                                 uc->data |= DEBUG_POINTER;
1658                         else
1659                                 return -EINVAL;
1660                         ptr += arg_len; len -= arg_len;
1661                 }
1662 #ifdef DEBUG_PROC_INFO
1663 printk("sym_user_command: data=%ld\n", uc->data);
1664 #endif
1665                 break;
1666 #endif /* SYM_LINUX_DEBUG_CONTROL_SUPPORT */
1667         case UC_SETFLAG:
1668                 while (len > 0) {
1669                         SKIP_SPACES(1);
1670                         if      ((arg_len = is_keyword(ptr, len, "no_disc")))
1671                                 uc->data &= ~SYM_DISC_ENABLED;
1672                         else
1673                                 return -EINVAL;
1674                         ptr += arg_len; len -= arg_len;
1675                 }
1676                 break;
1677         default:
1678                 break;
1679         }
1680
1681         if (len)
1682                 return -EINVAL;
1683         else {
1684                 unsigned long flags;
1685
1686                 SYM_LOCK_HCB(np, flags);
1687                 sym_exec_user_command (np, uc);
1688                 SYM_UNLOCK_HCB(np, flags);
1689         }
1690         return length;
1691 }
1692
1693 #endif  /* SYM_LINUX_USER_COMMAND_SUPPORT */
1694
1695
1696 #ifdef SYM_LINUX_USER_INFO_SUPPORT
1697 /*
1698  *  Informations through the proc file system.
1699  */
1700 struct info_str {
1701         char *buffer;
1702         int length;
1703         int offset;
1704         int pos;
1705 };
1706
1707 static void copy_mem_info(struct info_str *info, char *data, int len)
1708 {
1709         if (info->pos + len > info->length)
1710                 len = info->length - info->pos;
1711
1712         if (info->pos + len < info->offset) {
1713                 info->pos += len;
1714                 return;
1715         }
1716         if (info->pos < info->offset) {
1717                 data += (info->offset - info->pos);
1718                 len  -= (info->offset - info->pos);
1719         }
1720
1721         if (len > 0) {
1722                 memcpy(info->buffer + info->pos, data, len);
1723                 info->pos += len;
1724         }
1725 }
1726
1727 static int copy_info(struct info_str *info, char *fmt, ...)
1728 {
1729         va_list args;
1730         char buf[81];
1731         int len;
1732
1733         va_start(args, fmt);
1734         len = vsprintf(buf, fmt, args);
1735         va_end(args);
1736
1737         copy_mem_info(info, buf, len);
1738         return len;
1739 }
1740
1741 /*
1742  *  Copy formatted information into the input buffer.
1743  */
1744 static int sym_host_info(hcb_p np, char *ptr, off_t offset, int len)
1745 {
1746         struct info_str info;
1747
1748         info.buffer     = ptr;
1749         info.length     = len;
1750         info.offset     = offset;
1751         info.pos        = 0;
1752
1753         copy_info(&info, "Chip " NAME53C "%s, device id 0x%x, "
1754                          "revision id 0x%x\n",
1755                          np->s.chip_name, np->device_id, np->revision_id);
1756         copy_info(&info, "On PCI bus %d, device %d, function %d, "
1757 #ifdef __sparc__
1758                 "IRQ %s\n",
1759 #else
1760                 "IRQ %d\n",
1761 #endif
1762                 np->s.bus, (np->s.device_fn & 0xf8) >> 3, np->s.device_fn & 7,
1763 #ifdef __sparc__
1764                 __irq_itoa(np->s.irq));
1765 #else
1766                 (int) np->s.irq);
1767 #endif
1768         copy_info(&info, "Min. period factor %d, %s SCSI BUS%s\n",
1769                          (int) (np->minsync_dt ? np->minsync_dt : np->minsync),
1770                          np->maxwide ? "Wide" : "Narrow",
1771                          np->minsync_dt ? ", DT capable" : "");
1772
1773         copy_info(&info, "Max. started commands %d, "
1774                          "max. commands per LUN %d\n",
1775                          SYM_CONF_MAX_START, SYM_CONF_MAX_TAG);
1776
1777         return info.pos > info.offset? info.pos - info.offset : 0;
1778 }
1779 #endif /* SYM_LINUX_USER_INFO_SUPPORT */
1780
1781 /*
1782  *  Entry point of the scsi proc fs of the driver.
1783  *  - func = 0 means read  (returns adapter infos)
1784  *  - func = 1 means write (not yet merget from sym53c8xx)
1785  */
1786 static int sym53c8xx_proc_info(char *buffer, char **start, off_t offset,
1787                         int length, int hostno, int func)
1788 {
1789         struct Scsi_Host *host;
1790         struct host_data *host_data;
1791         hcb_p np = 0;
1792         int retv;
1793
1794         host = scsi_host_hn_get(hostno);
1795         if (!host)
1796                 return -EINVAL;
1797
1798         host_data = (struct host_data *) host->hostdata;
1799         np = host_data->ncb;
1800         if (!np)
1801                 return -EINVAL;
1802
1803         if (func) {
1804 #ifdef  SYM_LINUX_USER_COMMAND_SUPPORT
1805                 retv = sym_user_command(np, buffer, length);
1806 #else
1807                 retv = -EINVAL;
1808 #endif
1809         }
1810         else {
1811                 if (start)
1812                         *start = buffer;
1813 #ifdef SYM_LINUX_USER_INFO_SUPPORT
1814                 retv = sym_host_info(np, buffer, offset, length);
1815 #else
1816                 retv = -EINVAL;
1817 #endif
1818         }
1819
1820         scsi_host_put(host);
1821         return retv;
1822 }
1823 #endif /* SYM_LINUX_PROC_INFO_SUPPORT */
1824
1825 /*
1826  *      Free controller resources.
1827  */
1828 static void sym_free_resources(hcb_p np)
1829 {
1830         /*
1831          *  Free O/S specific resources.
1832          */
1833         if (np->s.irq)
1834                 free_irq(np->s.irq, np);
1835         if (np->s.io_port)
1836                 release_region(np->s.io_port, np->s.io_ws);
1837 #ifndef SYM_OPT_NO_BUS_MEMORY_MAPPING
1838         if (np->s.mmio_va)
1839                 pci_unmap_mem(np->s.mmio_va, np->s.io_ws);
1840         if (np->s.ram_va)
1841                 pci_unmap_mem(np->s.ram_va, np->ram_ws);
1842 #endif
1843         /*
1844          *  Free O/S independent resources.
1845          */
1846         sym_hcb_free(np);
1847
1848         sym_mfree_dma(np, sizeof(*np), "HCB");
1849 }
1850
1851 /*
1852  *  Ask/tell the system about DMA addressing.
1853  */
1854 #ifdef SYM_LINUX_DYNAMIC_DMA_MAPPING
1855 static int sym_setup_bus_dma_mask(hcb_p np)
1856 {
1857 #if LINUX_VERSION_CODE < LinuxVersionCode(2,4,3)
1858         if (!pci_dma_supported(np->s.device, 0xffffffffUL))
1859                 goto out_err32;
1860 #else
1861 #if   SYM_CONF_DMA_ADDRESSING_MODE == 0
1862         if (pci_set_dma_mask(np->s.device, 0xffffffffUL))
1863                 goto out_err32;
1864 #else
1865 #if   SYM_CONF_DMA_ADDRESSING_MODE == 1
1866 #define PciDmaMask      0xffffffffff
1867 #elif SYM_CONF_DMA_ADDRESSING_MODE == 2
1868 #define PciDmaMask      0xffffffffffffffff
1869 #endif
1870         if (np->features & FE_DAC) {
1871                 if (!pci_set_dma_mask(np->s.device, PciDmaMask)) {
1872                         np->use_dac = 1;
1873                         printf_info("%s: using 64 bit DMA addressing\n",
1874                                         sym_name(np));
1875                 }
1876                 else {
1877                         if (pci_set_dma_mask(np->s.device, 0xffffffffUL))
1878                                 goto out_err32;
1879                 }
1880         }
1881 #undef  PciDmaMask
1882 #endif
1883 #endif
1884         return 0;
1885
1886 out_err32:
1887         printf_warning("%s: 32 BIT DMA ADDRESSING NOT SUPPORTED\n",
1888                         sym_name(np));
1889         return -1;
1890 }
1891 #endif /* SYM_LINUX_DYNAMIC_DMA_MAPPING */
1892
1893 /*
1894  *  Host attach and initialisations.
1895  *
1896  *  Allocate host data and ncb structure.
1897  *  Request IO region and remap MMIO region.
1898  *  Do chip initialization.
1899  *  If all is OK, install interrupt handling and
1900  *  start the timer daemon.
1901  */
1902 static int __init 
1903 sym_attach (Scsi_Host_Template *tpnt, int unit, sym_device *dev)
1904 {
1905         struct host_data *host_data;
1906         hcb_p np = 0;
1907         struct Scsi_Host *instance = 0;
1908         u_long flags = 0;
1909         sym_nvram *nvram = dev->nvram;
1910         struct sym_fw *fw;
1911
1912         printk(KERN_INFO
1913                 "sym%d: <%s> rev 0x%x on pci bus %d device %d function %d "
1914 #ifdef __sparc__
1915                 "irq %s\n",
1916 #else
1917                 "irq %d\n",
1918 #endif
1919                 unit, dev->chip.name, dev->chip.revision_id,
1920                 dev->s.bus, (dev->s.device_fn & 0xf8) >> 3,
1921                 dev->s.device_fn & 7,
1922 #ifdef __sparc__
1923                 __irq_itoa(dev->s.irq));
1924 #else
1925                 dev->s.irq);
1926 #endif
1927
1928         /*
1929          *  Get the firmware for this chip.
1930          */
1931         fw = sym_find_firmware(&dev->chip);
1932         if (!fw)
1933                 goto attach_failed;
1934
1935         /*
1936          *      Allocate host_data structure
1937          */
1938         if (!(instance = scsi_register(tpnt, sizeof(*host_data))))
1939                 goto attach_failed;
1940         host_data = (struct host_data *) instance->hostdata;
1941
1942         /*
1943          *  Allocate immediately the host control block, 
1944          *  since we are only expecting to succeed. :)
1945          *  We keep track in the HCB of all the resources that 
1946          *  are to be released on error.
1947          */
1948 #ifdef  SYM_LINUX_DYNAMIC_DMA_MAPPING
1949         np = __sym_calloc_dma(dev->pdev, sizeof(*np), "HCB");
1950         if (np) {
1951                 np->s.device = dev->pdev;
1952                 np->bus_dmat = dev->pdev; /* Result in 1 DMA pool per HBA */
1953         }
1954         else
1955                 goto attach_failed;
1956 #else
1957         np = sym_calloc_dma(sizeof(*np), "HCB");
1958         if (!np)
1959                 goto attach_failed;
1960 #endif
1961         host_data->ncb = np;
1962         np->s.host = instance;
1963
1964         SYM_INIT_LOCK_HCB(np);
1965
1966         /*
1967          *  Copy some useful infos to the HCB.
1968          */
1969         np->hcb_ba      = vtobus(np);
1970         np->verbose     = sym_driver_setup.verbose;
1971         np->s.device    = dev->pdev;
1972         np->s.unit      = unit;
1973         np->device_id   = dev->chip.device_id;
1974         np->revision_id = dev->chip.revision_id;
1975         np->s.bus       = dev->s.bus;
1976         np->s.device_fn = dev->s.device_fn;
1977         np->features    = dev->chip.features;
1978         np->clock_divn  = dev->chip.nr_divisor;
1979         np->maxoffs     = dev->chip.offset_max;
1980         np->maxburst    = dev->chip.burst_max;
1981         np->myaddr      = dev->host_id;
1982
1983         /*
1984          *  Edit its name.
1985          */
1986         strncpy(np->s.chip_name, dev->chip.name, sizeof(np->s.chip_name)-1);
1987         sprintf(np->s.inst_name, "sym%d", np->s.unit);
1988
1989         /*
1990          *  Ask/tell the system about DMA addressing.
1991          */
1992 #ifdef SYM_LINUX_DYNAMIC_DMA_MAPPING
1993         if (sym_setup_bus_dma_mask(np))
1994                 goto attach_failed;
1995 #endif
1996
1997         /*
1998          *  Try to map the controller chip to
1999          *  virtual and physical memory.
2000          */
2001         np->mmio_ba     = (u32)dev->s.base;
2002         np->s.io_ws     = (np->features & FE_IO256)? 256 : 128;
2003
2004 #ifndef SYM_CONF_IOMAPPED
2005         np->s.mmio_va = pci_map_mem(dev->s.base_c, np->s.io_ws);
2006         if (!np->s.mmio_va) {
2007                 printf_err("%s: can't map PCI MMIO region\n", sym_name(np));
2008                 goto attach_failed;
2009         }
2010         else if (sym_verbose > 1)
2011                 printf_info("%s: using memory mapped IO\n", sym_name(np));
2012 #endif /* !defined SYM_CONF_IOMAPPED */
2013
2014         /*
2015          *  Try to map the controller chip into iospace.
2016          */
2017         if (dev->s.io_port) {
2018                 request_region(dev->s.io_port, np->s.io_ws, NAME53C8XX);
2019                 np->s.io_port = dev->s.io_port;
2020         }
2021
2022         /*
2023          *  Map on-chip RAM if present and supported.
2024          */
2025         if (!(np->features & FE_RAM))
2026                 dev->s.base_2 = 0;
2027         if (dev->s.base_2) {
2028                 np->ram_ba = (u32)dev->s.base_2;
2029                 if (np->features & FE_RAM8K)
2030                         np->ram_ws = 8192;
2031                 else
2032                         np->ram_ws = 4096;
2033 #ifndef SYM_OPT_NO_BUS_MEMORY_MAPPING
2034                 np->s.ram_va = pci_map_mem(dev->s.base_2_c, np->ram_ws);
2035                 if (!np->s.ram_va) {
2036                         printf_err("%s: can't map PCI MEMORY region\n",
2037                                sym_name(np));
2038                         goto attach_failed;
2039                 }
2040 #endif
2041         }
2042
2043         /*
2044          *  Perform O/S independent stuff.
2045          */
2046         if (sym_hcb_attach(np, fw, nvram))
2047                 goto attach_failed;
2048
2049
2050         /*
2051          *  Install the interrupt handler.
2052          *  If we synchonize the C code with SCRIPTS on interrupt, 
2053          *  we donnot want to share the INTR line at all.
2054          */
2055         if (request_irq(dev->s.irq, sym53c8xx_intr, SA_SHIRQ,
2056                         NAME53C8XX, np)) {
2057                 printf_err("%s: request irq %d failure\n",
2058                         sym_name(np), dev->s.irq);
2059                 goto attach_failed;
2060         }
2061         np->s.irq = dev->s.irq;
2062
2063         /*
2064          *  After SCSI devices have been opened, we cannot
2065          *  reset the bus safely, so we do it here.
2066          */
2067         SYM_LOCK_HCB(np, flags);
2068         if (sym_reset_scsi_bus(np, 0)) {
2069                 printf_err("%s: FATAL ERROR: CHECK SCSI BUS - CABLES, "
2070                            "TERMINATION, DEVICE POWER etc.!\n", sym_name(np));
2071                 SYM_UNLOCK_HCB(np, flags);
2072                 goto attach_failed;
2073         }
2074
2075         /*
2076          *  Initialize some queue headers.
2077          */
2078         sym_que_init(&np->s.wait_cmdq);
2079         sym_que_init(&np->s.busy_cmdq);
2080
2081         /*
2082          *  Start the SCRIPTS.
2083          */
2084         sym_start_up (np, 1);
2085
2086         /*
2087          *  Start the timer daemon
2088          */
2089         init_timer(&np->s.timer);
2090         np->s.timer.data     = (unsigned long) np;
2091         np->s.timer.function = sym53c8xx_timer;
2092         np->s.lasttime=0;
2093         sym_timer (np);
2094
2095         /*
2096          *  Done.
2097          */
2098         if (!first_host)
2099                 first_host = instance;
2100
2101         /*
2102          *  Fill Linux host instance structure
2103          *  and return success.
2104          */
2105         instance->max_channel   = 0;
2106         instance->this_id       = np->myaddr;
2107         instance->max_id        = np->maxwide ? 16 : 8;
2108         instance->max_lun       = SYM_CONF_MAX_LUN;
2109 #ifndef SYM_CONF_IOMAPPED
2110 #if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,29)
2111         instance->base          = (unsigned long) np->s.mmio_va;
2112 #else
2113         instance->base          = (char *) np->s.mmio_va;
2114 #endif
2115 #endif
2116         instance->irq           = np->s.irq;
2117         instance->unique_id     = np->s.io_port;
2118         instance->io_port       = np->s.io_port;
2119         instance->n_io_port     = np->s.io_ws;
2120         instance->dma_channel   = 0;
2121         instance->cmd_per_lun   = SYM_CONF_MAX_TAG;
2122         instance->can_queue     = (SYM_CONF_MAX_START-2);
2123         instance->sg_tablesize  = SYM_CONF_MAX_SG;
2124 #if LINUX_VERSION_CODE >= LinuxVersionCode(2,4,0)
2125         instance->max_cmd_len   = 16;
2126 #endif
2127         instance->highmem_io    = 1;
2128
2129         SYM_UNLOCK_HCB(np, flags);
2130
2131         scsi_set_device(instance, &dev->pdev->dev);
2132
2133         /*
2134          *  Now let the generic SCSI driver
2135          *  look for the SCSI devices on the bus ..
2136          */
2137         return 0;
2138
2139 attach_failed:
2140         if (!instance) return -1;
2141         printf_info("%s: giving up ...\n", sym_name(np));
2142         if (np)
2143                 sym_free_resources(np);
2144         scsi_unregister(instance);
2145
2146         return -1;
2147  }
2148
2149
2150 /*
2151  *    Detect and try to read SYMBIOS and TEKRAM NVRAM.
2152  */
2153 #if SYM_CONF_NVRAM_SUPPORT
2154 static void __init sym_get_nvram(sym_device *devp, sym_nvram *nvp)
2155 {
2156         if (!nvp)
2157                 return;
2158
2159         devp->nvram = nvp;
2160         devp->device_id = devp->chip.device_id;
2161         nvp->type = 0;
2162
2163         /*
2164          *  Get access to chip IO registers
2165          */
2166 #ifdef SYM_CONF_IOMAPPED
2167         request_region(devp->s.io_port, 128, NAME53C8XX);
2168 #else
2169         devp->s.mmio_va = pci_map_mem(devp->s.base_c, 128);
2170         if (!devp->s.mmio_va)
2171                 return;
2172 #endif
2173
2174         /*
2175          *  Try to read SYMBIOS|TEKRAM nvram.
2176          */
2177         (void) sym_read_nvram(devp, nvp);
2178
2179         /*
2180          *  Release access to chip IO registers
2181          */
2182 #ifdef SYM_CONF_IOMAPPED
2183         release_region(devp->s.io_port, 128);
2184 #else
2185         pci_unmap_mem((u_long) devp->s.mmio_va, 128ul);
2186 #endif
2187 }
2188 #endif  /* SYM_CONF_NVRAM_SUPPORT */
2189
2190 /*
2191  *  Driver setup from the boot command line
2192  */
2193 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
2194
2195 static struct sym_driver_setup
2196         sym_driver_safe_setup __initdata = SYM_LINUX_DRIVER_SAFE_SETUP;
2197 #ifdef  MODULE
2198 char *sym53c8xx = 0;    /* command line passed by insmod */
2199 MODULE_PARM(sym53c8xx, "s");
2200 #endif
2201
2202 static void __init sym53c8xx_print_driver_setup(void)
2203 {
2204         printf_info (NAME53C8XX ": setup="
2205                 "mpar:%d,spar:%d,tags:%d,sync:%d,burst:%d,"
2206                 "led:%d,wide:%d,diff:%d,irqm:%d, buschk:%d\n",
2207                 sym_driver_setup.pci_parity,
2208                 sym_driver_setup.scsi_parity,
2209                 sym_driver_setup.max_tag,
2210                 sym_driver_setup.min_sync,
2211                 sym_driver_setup.burst_order,
2212                 sym_driver_setup.scsi_led,
2213                 sym_driver_setup.max_wide,
2214                 sym_driver_setup.scsi_diff,
2215                 sym_driver_setup.irq_mode,
2216                 sym_driver_setup.scsi_bus_check);
2217         printf_info (NAME53C8XX ": setup="
2218                 "hostid:%d,offs:%d,luns:%d,pcifix:%d,revprob:%d,"
2219                 "verb:%d,debug:0x%x,setlle_delay:%d\n",
2220                 sym_driver_setup.host_id,
2221                 sym_driver_setup.max_offs,
2222                 sym_driver_setup.max_lun,
2223                 sym_driver_setup.pci_fix_up,
2224                 sym_driver_setup.reverse_probe,
2225                 sym_driver_setup.verbose,
2226                 sym_driver_setup.debug,
2227                 sym_driver_setup.settle_delay);
2228 #ifdef DEBUG_2_0_X
2229 MDELAY(5000);
2230 #endif
2231 };
2232
2233 #define OPT_PCI_PARITY          1
2234 #define OPT_SCSI_PARITY         2
2235 #define OPT_MAX_TAG             3
2236 #define OPT_MIN_SYNC            4
2237 #define OPT_BURST_ORDER         5
2238 #define OPT_SCSI_LED            6
2239 #define OPT_MAX_WIDE            7
2240 #define OPT_SCSI_DIFF           8
2241 #define OPT_IRQ_MODE            9
2242 #define OPT_SCSI_BUS_CHECK      10
2243 #define OPT_HOST_ID             11
2244 #define OPT_MAX_OFFS            12
2245 #define OPT_MAX_LUN             13
2246 #define OPT_PCI_FIX_UP          14
2247
2248 #define OPT_REVERSE_PROBE       15
2249 #define OPT_VERBOSE             16
2250 #define OPT_DEBUG               17
2251 #define OPT_SETTLE_DELAY        18
2252 #define OPT_USE_NVRAM           19
2253 #define OPT_EXCLUDE             20
2254 #define OPT_SAFE_SETUP          21
2255
2256 static char setup_token[] __initdata =
2257         "mpar:"         "spar:"
2258         "tags:"         "sync:"
2259         "burst:"        "led:"
2260         "wide:"         "diff:"
2261         "irqm:"         "buschk:"
2262         "hostid:"       "offset:"
2263         "luns:"         "pcifix:"
2264         "revprob:"      "verb:"
2265         "debug:"        "settle:"
2266         "nvram:"        "excl:"
2267         "safe:"
2268         ;
2269
2270 #ifdef MODULE
2271 #define ARG_SEP ' '
2272 #else
2273 #define ARG_SEP ','
2274 #endif
2275
2276 static int __init get_setup_token(char *p)
2277 {
2278         char *cur = setup_token;
2279         char *pc;
2280         int i = 0;
2281
2282         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
2283                 ++pc;
2284                 ++i;
2285                 if (!strncmp(p, cur, pc - cur))
2286                         return i;
2287                 cur = pc;
2288         }
2289         return 0;
2290 }
2291 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
2292
2293 int __init sym53c8xx_setup(char *str)
2294 {
2295 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
2296         char *cur = str;
2297         char *pc, *pv;
2298         unsigned long val;
2299         int i,  c;
2300         int xi = 0;
2301
2302         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
2303                 char *pe;
2304
2305                 val = 0;
2306                 pv = pc;
2307                 c = *++pv;
2308
2309                 if      (c == 'n')
2310                         val = 0;
2311                 else if (c == 'y')
2312                         val = 1;
2313                 else
2314                         val = (int) simple_strtoul(pv, &pe, 0);
2315
2316                 switch (get_setup_token(cur)) {
2317                 case OPT_MAX_TAG:
2318                         sym_driver_setup.max_tag = val;
2319                         if (!(pe && *pe == '/'))
2320                                 break;
2321                         i = 0;
2322                         while (*pe && *pe != ARG_SEP && 
2323                                 i < sizeof(sym_driver_setup.tag_ctrl)-1) {
2324                                 sym_driver_setup.tag_ctrl[i++] = *pe++;
2325                         }
2326                         sym_driver_setup.tag_ctrl[i] = '\0';
2327                         break;
2328                 case OPT_SAFE_SETUP:
2329                         memcpy(&sym_driver_setup, &sym_driver_safe_setup,
2330                                 sizeof(sym_driver_setup));
2331                         break;
2332                 case OPT_EXCLUDE:
2333                         if (xi < 8)
2334                                 sym_driver_setup.excludes[xi++] = val;
2335                         break;
2336
2337 #define __SIMPLE_OPTION(NAME, name) \
2338                 case OPT_ ## NAME :             \
2339                         sym_driver_setup.name = val;\
2340                         break;
2341
2342                 __SIMPLE_OPTION(PCI_PARITY, pci_parity)
2343                 __SIMPLE_OPTION(SCSI_PARITY, scsi_parity)
2344                 __SIMPLE_OPTION(MIN_SYNC, min_sync)
2345                 __SIMPLE_OPTION(BURST_ORDER, burst_order)
2346                 __SIMPLE_OPTION(SCSI_LED, scsi_led)
2347                 __SIMPLE_OPTION(MAX_WIDE, max_wide)
2348                 __SIMPLE_OPTION(SCSI_DIFF, scsi_diff)
2349                 __SIMPLE_OPTION(IRQ_MODE, irq_mode)
2350                 __SIMPLE_OPTION(SCSI_BUS_CHECK, scsi_bus_check)
2351                 __SIMPLE_OPTION(HOST_ID, host_id)
2352                 __SIMPLE_OPTION(MAX_OFFS, max_offs)
2353                 __SIMPLE_OPTION(MAX_LUN, max_lun)
2354                 __SIMPLE_OPTION(PCI_FIX_UP, pci_fix_up)
2355                 __SIMPLE_OPTION(REVERSE_PROBE, reverse_probe)
2356                 __SIMPLE_OPTION(VERBOSE, verbose)
2357                 __SIMPLE_OPTION(DEBUG, debug)
2358                 __SIMPLE_OPTION(SETTLE_DELAY, settle_delay)
2359                 __SIMPLE_OPTION(USE_NVRAM, use_nvram)
2360
2361 #undef __SIMPLE_OPTION
2362
2363                 default:
2364                         printk("sym53c8xx_setup: unexpected boot option '%.*s' ignored\n", (int)(pc-cur+1), cur);
2365                         break;
2366                 }
2367
2368                 if ((cur = strchr(cur, ARG_SEP)) != NULL)
2369                         ++cur;
2370         }
2371 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
2372         return 1;
2373 }
2374
2375 #if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,13)
2376 #ifndef MODULE
2377 __setup("sym53c8xx=", sym53c8xx_setup);
2378 #endif
2379 #endif
2380
2381 #ifdef  SYM_CONF_PQS_PDS_SUPPORT
2382 /*
2383  *  Detect all NCR PQS/PDS boards and keep track of their bus nr.
2384  *
2385  *  The NCR PQS or PDS card is constructed as a DEC bridge
2386  *  behind which sit a proprietary NCR memory controller and
2387  *  four or two 53c875s as separate devices.  In its usual mode
2388  *  of operation, the 875s are slaved to the memory controller
2389  *  for all transfers.  We can tell if an 875 is part of a
2390  *  PQS/PDS or not since if it is, it will be on the same bus
2391  *  as the memory controller.  To operate with the Linux
2392  *  driver, the memory controller is disabled and the 875s
2393  *  freed to function independently.  The only wrinkle is that
2394  *  the preset SCSI ID (which may be zero) must be read in from
2395  *  a special configuration space register of the 875
2396  */
2397 #ifndef SYM_CONF_MAX_PQS_BUS
2398 #define SYM_CONF_MAX_PQS_BUS 16
2399 #endif
2400 static int pqs_bus[SYM_CONF_MAX_PQS_BUS] __initdata = { 0 };
2401
2402 static void __init sym_detect_pqs_pds(void)
2403 {
2404         short index;
2405         pcidev_t dev = PCIDEV_NULL;
2406
2407         for(index=0; index < SYM_CONF_MAX_PQS_BUS; index++) {
2408                 u_char tmp;
2409
2410                 dev = pci_find_device(0x101a, 0x0009, dev);
2411                 if (dev == PCIDEV_NULL) {
2412                         pqs_bus[index] = -1;
2413                         break;
2414                 }
2415                 printf_info(NAME53C8XX ": NCR PQS/PDS memory controller detected on bus %d\n", PciBusNumber(dev));
2416                 pci_read_config_byte(dev, 0x44, &tmp);
2417                 /* bit 1: allow individual 875 configuration */
2418                 tmp |= 0x2;
2419                 pci_write_config_byte(dev, 0x44, tmp);
2420                 pci_read_config_byte(dev, 0x45, &tmp);
2421                 /* bit 2: drive individual 875 interrupts to the bus */
2422                 tmp |= 0x4;
2423                 pci_write_config_byte(dev, 0x45, tmp);
2424
2425                 pqs_bus[index] = PciBusNumber(dev);
2426         }
2427 }
2428 #endif /* SYM_CONF_PQS_PDS_SUPPORT */
2429
2430 /*
2431  *  Read and check the PCI configuration for any detected NCR 
2432  *  boards and save data for attaching after all boards have 
2433  *  been detected.
2434  */
2435 static int __init
2436 sym53c8xx_pci_init(Scsi_Host_Template *tpnt, pcidev_t pdev, sym_device *device)
2437 {
2438         u_short vendor_id, device_id, command, status_reg;
2439         u_char cache_line_size;
2440         u_char suggested_cache_line_size = 0;
2441         u_char pci_fix_up = SYM_SETUP_PCI_FIX_UP;
2442         u_char revision;
2443         u_int irq;
2444         u_long base, base_2, base_io; 
2445         u_long base_c, base_2_c, io_port; 
2446         int i;
2447         sym_chip *chip;
2448
2449         /* Choose some short name for this device */
2450         sprintf(device->s.inst_name, "sym.%d.%d.%d",
2451                 PciBusNumber(pdev),
2452                 (int) (PciDeviceFn(pdev) & 0xf8) >> 3,
2453                 (int) (PciDeviceFn(pdev) & 7));
2454
2455         /*
2456          *  Read needed minimal info from the PCI config space.
2457          */
2458         vendor_id = PciVendorId(pdev);
2459         device_id = PciDeviceId(pdev);
2460         irq       = PciIrqLine(pdev);
2461
2462         i = pci_get_base_address(pdev, 0, &base_io);
2463         io_port = pci_get_base_cookie(pdev, 0);
2464
2465         base_c = pci_get_base_cookie(pdev, i);
2466         i = pci_get_base_address(pdev, i, &base);
2467
2468         base_2_c = pci_get_base_cookie(pdev, i);
2469         (void) pci_get_base_address(pdev, i, &base_2);
2470
2471         io_port &= PCI_BASE_ADDRESS_IO_MASK;
2472         base    &= PCI_BASE_ADDRESS_MEM_MASK;
2473         base_2  &= PCI_BASE_ADDRESS_MEM_MASK;
2474
2475         pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
2476
2477         /*
2478          *  If user excluded this chip, donnot initialize it.
2479          */
2480         if (base_io) {
2481                 for (i = 0 ; i < 8 ; i++) {
2482                         if (sym_driver_setup.excludes[i] == base_io)
2483                                 return -1;
2484                 }
2485         }
2486
2487         /*
2488          *  Leave here if another driver attached the chip.
2489          */
2490         if (io_port && check_region (io_port, 128)) {
2491                 printf_info("%s: IO region 0x%lx[0..127] is in use\n",
2492                             sym_name(device), (long) io_port);
2493                 return -1;
2494         }
2495
2496         /*
2497          *  Check if the chip is supported.
2498          */
2499         chip = sym_lookup_pci_chip_table(device_id, revision);
2500         if (!chip) {
2501                 printf_info("%s: device not supported\n", sym_name(device));
2502                 return -1;
2503         }
2504
2505         /*
2506          *  Check if the chip has been assigned resources we need.
2507          */
2508 #ifdef SYM_CONF_IOMAPPED
2509         if (!io_port) {
2510                 printf_info("%s: IO base address disabled.\n",
2511                             sym_name(device));
2512                 return -1;
2513         }
2514 #else
2515         if (!base) {
2516                 printf_info("%s: MMIO base address disabled.\n",
2517                             sym_name(device));
2518                 return -1;
2519         }
2520 #endif
2521
2522         /*
2523          *  Ignore Symbios chips controlled by various RAID controllers.
2524          *  These controllers set value 0x52414944 at RAM end - 16.
2525          */
2526 #if defined(__i386__) && !defined(SYM_OPT_NO_BUS_MEMORY_MAPPING)
2527         if (base_2_c) {
2528                 unsigned int ram_size, ram_val;
2529                 u_long ram_ptr;
2530
2531                 if (chip->features & FE_RAM8K)
2532                         ram_size = 8192;
2533                 else
2534                         ram_size = 4096;
2535
2536                 ram_ptr = pci_map_mem(base_2_c, ram_size);
2537                 if (ram_ptr) {
2538                         ram_val = readl_raw(ram_ptr + ram_size - 16);
2539                         pci_unmap_mem(ram_ptr, ram_size);
2540                         if (ram_val == 0x52414944) {
2541                                 printf_info("%s: not initializing, "
2542                                             "driven by RAID controller.\n",
2543                                             sym_name(device));
2544                                 return -1;
2545                         }
2546                 }
2547         }
2548 #endif /* i386 and PCI MEMORY accessible */
2549
2550         /*
2551          *  Copy the chip description to our device structure, 
2552          *  so we can make it match the actual device and options.
2553          */
2554         bcopy(chip, &device->chip, sizeof(device->chip));
2555         device->chip.revision_id = revision;
2556
2557         /*
2558          *  Read additionnal info from the configuration space.
2559          */
2560         pci_read_config_word(pdev, PCI_COMMAND,         &command);
2561         pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &cache_line_size);
2562
2563         /*
2564          * Enable missing capabilities in the PCI COMMAND register.
2565          */
2566 #ifdef SYM_CONF_IOMAPPED
2567 #define PCI_COMMAND_BITS_TO_ENABLE (PCI_COMMAND_IO | \
2568         PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_PARITY)
2569 #else
2570 #define PCI_COMMAND_BITS_TO_ENABLE \
2571         (PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_PARITY)
2572 #endif
2573         if ((command & PCI_COMMAND_BITS_TO_ENABLE)
2574                     != PCI_COMMAND_BITS_TO_ENABLE) {
2575                 printf_info("%s: setting%s%s%s%s...\n", sym_name(device),
2576                 (command & PCI_COMMAND_IO)     ? "" : " PCI_COMMAND_IO",
2577                 (command & PCI_COMMAND_MEMORY) ? "" : " PCI_COMMAND_MEMORY",
2578                 (command & PCI_COMMAND_MASTER) ? "" : " PCI_COMMAND_MASTER",
2579                 (command & PCI_COMMAND_PARITY) ? "" : " PCI_COMMAND_PARITY");
2580                 command |= PCI_COMMAND_BITS_TO_ENABLE;
2581                 pci_write_config_word(pdev, PCI_COMMAND, command);
2582         }
2583 #undef  PCI_COMMAND_BITS_TO_ENABLE
2584
2585         /*
2586          *  If cache line size is not configured, suggest
2587          *  a value for well known CPUs.
2588          */
2589 #if defined(__i386__) && !defined(MODULE)
2590         if (!cache_line_size && boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) {
2591                 switch(boot_cpu_data.x86) {
2592                 case 4: suggested_cache_line_size = 4;   break;
2593                 case 6: if (boot_cpu_data.x86_model > 8) break;
2594                 case 5: suggested_cache_line_size = 8;   break;
2595                 }
2596         }
2597 #endif  /* __i386__ */
2598
2599         /*
2600          *  Some features are required to be enabled in order to 
2601          *  work around some chip problems. :) ;)
2602          *  (ITEM 12 of a DEL about the 896 I haven't yet).
2603          *  We must ensure the chip will use WRITE AND INVALIDATE.
2604          *  The revision number limit is for now arbitrary.
2605          */
2606         if (device_id == PCI_DEVICE_ID_NCR_53C896 && revision < 0x4) {
2607                 chip->features  |= (FE_WRIE | FE_CLSE);
2608                 pci_fix_up      |=  3;  /* Force appropriate PCI fix-up */
2609         }
2610
2611 #ifdef  SYM_CONF_PCI_FIX_UP
2612         /*
2613          *  Try to fix up PCI config according to wished features.
2614          */
2615         if ((pci_fix_up & 1) && (chip->features & FE_CLSE) && 
2616             !cache_line_size && suggested_cache_line_size) {
2617                 cache_line_size = suggested_cache_line_size;
2618                 pci_write_config_byte(pdev,
2619                                       PCI_CACHE_LINE_SIZE, cache_line_size);
2620                 printf_info("%s: PCI_CACHE_LINE_SIZE set to %d.\n",
2621                             sym_name(device), cache_line_size);
2622         }
2623
2624         if ((pci_fix_up & 2) && cache_line_size &&
2625             (chip->features & FE_WRIE) && !(command & PCI_COMMAND_INVALIDATE)) {
2626                 printf_info("%s: setting PCI_COMMAND_INVALIDATE.\n",
2627                             sym_name(device));
2628                 command |= PCI_COMMAND_INVALIDATE;
2629                 pci_write_config_word(pdev, PCI_COMMAND, command);
2630         }
2631 #endif  /* SYM_CONF_PCI_FIX_UP */
2632
2633         /*
2634          *  Work around for errant bit in 895A. The 66Mhz
2635          *  capable bit is set erroneously. Clear this bit.
2636          *  (Item 1 DEL 533)
2637          *
2638          *  Make sure Config space and Features agree.
2639          *
2640          *  Recall: writes are not normal to status register -
2641          *  write a 1 to clear and a 0 to leave unchanged.
2642          *  Can only reset bits.
2643          */
2644         pci_read_config_word(pdev, PCI_STATUS, &status_reg);
2645         if (chip->features & FE_66MHZ) {
2646                 if (!(status_reg & PCI_STATUS_66MHZ))
2647                         chip->features &= ~FE_66MHZ;
2648         }
2649         else {
2650                 if (status_reg & PCI_STATUS_66MHZ) {
2651                         status_reg = PCI_STATUS_66MHZ;
2652                         pci_write_config_word(pdev, PCI_STATUS, status_reg);
2653                         pci_read_config_word(pdev, PCI_STATUS, &status_reg);
2654                 }
2655         }
2656
2657         /*
2658          *  Initialise device structure with items required by sym_attach.
2659          */
2660         device->pdev            = pdev;
2661         device->s.bus           = PciBusNumber(pdev);
2662         device->s.device_fn     = PciDeviceFn(pdev);
2663         device->s.base          = base;
2664         device->s.base_2        = base_2;
2665         device->s.base_c        = base_c;
2666         device->s.base_2_c      = base_2_c;
2667         device->s.io_port       = io_port;
2668         device->s.irq           = irq;
2669         device->attach_done     = 0;
2670
2671         return 0;
2672 }
2673
2674 /*
2675  *  List of supported NCR chip ids
2676  */
2677 static u_short sym_chip_ids[] __initdata        = {
2678         PCI_ID_SYM53C810,
2679         PCI_ID_SYM53C815,
2680         PCI_ID_SYM53C825,
2681         PCI_ID_SYM53C860,
2682         PCI_ID_SYM53C875,
2683         PCI_ID_SYM53C875_2,
2684         PCI_ID_SYM53C885,
2685         PCI_ID_SYM53C875A,
2686         PCI_ID_SYM53C895,
2687         PCI_ID_SYM53C896,
2688         PCI_ID_SYM53C895A,
2689         PCI_ID_LSI53C1510D,
2690         PCI_ID_LSI53C1010,
2691         PCI_ID_LSI53C1010_2
2692 };
2693
2694 /*
2695  *  Detect all 53c8xx hosts and then attach them.
2696  *
2697  *  If we are using NVRAM, once all hosts are detected, we need to 
2698  *  check any NVRAM for boot order in case detect and boot order 
2699  *  differ and attach them using the order in the NVRAM.
2700  *
2701  *  If no NVRAM is found or data appears invalid attach boards in 
2702  *  the order they are detected.
2703  */
2704 int __init sym53c8xx_detect(Scsi_Host_Template *tpnt)
2705 {
2706         pcidev_t pcidev;
2707         int i, j, chips, hosts, count;
2708         int attach_count = 0;
2709         sym_device *devtbl, *devp;
2710         sym_nvram  nvram;
2711 #if SYM_CONF_NVRAM_SUPPORT
2712         sym_nvram  nvram0, *nvp;
2713 #endif
2714
2715         /*
2716          *  PCI is required.
2717          */
2718         if (!pci_present())
2719                 return 0;
2720
2721         /*
2722          *    Initialize driver general stuff.
2723          */
2724 #ifdef SYM_LINUX_PROC_INFO_SUPPORT
2725 #if LINUX_VERSION_CODE < LinuxVersionCode(2,3,27)
2726      tpnt->proc_dir  = &proc_scsi_sym53c8xx;
2727 #else
2728      tpnt->proc_name = NAME53C8XX;
2729 #endif
2730      tpnt->proc_info = sym53c8xx_proc_info;
2731 #endif
2732
2733 #ifdef SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
2734 #ifdef MODULE
2735 if (sym53c8xx)
2736         sym53c8xx_setup(sym53c8xx);
2737 #endif
2738 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
2739         sym_debug_flags = sym_driver_setup.debug;
2740 #endif
2741         if (boot_verbose >= 2)
2742                 sym53c8xx_print_driver_setup();
2743 #endif /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
2744
2745         /*
2746          *  Allocate the device table since we donnot want to 
2747          *  overflow the kernel stack.
2748          *  1 x 4K PAGE is enough for more than 40 devices for i386.
2749          */
2750         devtbl = sym_calloc(PAGE_SIZE, "DEVTBL");
2751         if (!devtbl)
2752                 return 0;
2753
2754         /*
2755          *  Detect all NCR PQS/PDS memory controllers.
2756          */
2757 #ifdef  SYM_CONF_PQS_PDS_SUPPORT
2758         sym_detect_pqs_pds();
2759 #endif
2760
2761         /* 
2762          *  Detect all 53c8xx hosts.
2763          *  Save the first Symbios NVRAM content if any 
2764          *  for the boot order.
2765          */
2766         chips   = sizeof(sym_chip_ids)  / sizeof(sym_chip_ids[0]);
2767         hosts   = PAGE_SIZE             / sizeof(*devtbl);
2768 #if SYM_CONF_NVRAM_SUPPORT
2769         nvp = (sym_driver_setup.use_nvram & 0x1) ? &nvram0 : 0;
2770 #endif
2771         j = 0;
2772         count = 0;
2773         pcidev = PCIDEV_NULL;
2774         while (1) {
2775                 char *msg = "";
2776                 if (count >= hosts)
2777                         break;
2778                 if (j >= chips)
2779                         break;
2780                 i = sym_driver_setup.reverse_probe ? chips - 1 - j : j;
2781                 pcidev = pci_find_device(PCI_VENDOR_ID_NCR, sym_chip_ids[i],
2782                                          pcidev);
2783                 if (pcidev == PCIDEV_NULL) {
2784                         ++j;
2785                         continue;
2786                 }
2787                 /* This one is guaranteed by AC to do nothing :-) */
2788                 if (pci_enable_device(pcidev))
2789                         continue;
2790                 /* Some HW as the HP LH4 may report twice PCI devices */
2791                 for (i = 0; i < count ; i++) {
2792                         if (devtbl[i].s.bus       == PciBusNumber(pcidev) && 
2793                             devtbl[i].s.device_fn == PciDeviceFn(pcidev))
2794                                 break;
2795                 }
2796                 if (i != count) /* Ignore this device if we already have it */
2797                         continue;
2798                 devp = &devtbl[count];
2799                 devp->host_id = SYM_SETUP_HOST_ID;
2800                 devp->attach_done = 0;
2801                 if (sym53c8xx_pci_init(tpnt, pcidev, devp)) {
2802                         continue;
2803                 }
2804                 ++count;
2805 #if SYM_CONF_NVRAM_SUPPORT
2806                 if (nvp) {
2807                         sym_get_nvram(devp, nvp);
2808                         switch(nvp->type) {
2809                         case SYM_SYMBIOS_NVRAM:
2810                                 /*
2811                                  *   Switch to the other nvram buffer, so that 
2812                                  *   nvram0 will contain the first Symbios 
2813                                  *   format NVRAM content with boot order.
2814                                  */
2815                                 nvp = &nvram;
2816                                 msg = "with Symbios NVRAM";
2817                                 break;
2818                         case SYM_TEKRAM_NVRAM:
2819                                 msg = "with Tekram NVRAM";
2820                                 break;
2821                         }
2822                 }
2823 #endif
2824 #ifdef  SYM_CONF_PQS_PDS_SUPPORT
2825                 /*
2826                  *  Match the BUS number for PQS/PDS devices.
2827                  *  Read the SCSI ID from a special register mapped
2828                  *  into the configuration space of the individual
2829                  *  875s.  This register is set up by the PQS bios
2830                  */
2831                 for(i = 0; i < SYM_CONF_MAX_PQS_BUS && pqs_bus[i] != -1; i++) {
2832                         u_char tmp;
2833                         if (pqs_bus[i] == PciBusNumber(pcidev)) {
2834                                 pci_read_config_byte(pcidev, 0x84, &tmp);
2835                                 devp->pqs_pds = 1;
2836                                 devp->host_id = tmp;
2837                                 break;
2838                         }
2839                 }
2840                 if (devp->pqs_pds)
2841                         msg = "(NCR PQS/PDS)";
2842 #endif
2843                 if (boot_verbose)
2844                         printf_info("%s: 53c%s detected %s\n",
2845                                     sym_name(devp), devp->chip.name, msg);
2846         }
2847
2848         /*
2849          *  If we have found a SYMBIOS NVRAM, use first the NVRAM boot 
2850          *  sequence as device boot order.
2851          *  check devices in the boot record against devices detected. 
2852          *  attach devices if we find a match. boot table records that 
2853          *  do not match any detected devices will be ignored. 
2854          *  devices that do not match any boot table will not be attached
2855          *  here but will attempt to be attached during the device table 
2856          *  rescan.
2857          */
2858 #if SYM_CONF_NVRAM_SUPPORT
2859         if (!nvp || nvram0.type != SYM_SYMBIOS_NVRAM)
2860                 goto next;
2861         for (i = 0; i < 4; i++) {
2862                 Symbios_host *h = &nvram0.data.Symbios.host[i];
2863                 for (j = 0 ; j < count ; j++) {
2864                         devp = &devtbl[j];
2865                         if (h->device_fn != devp->s.device_fn ||
2866                             h->bus_nr    != devp->s.bus  ||
2867                             h->device_id != devp->chip.device_id)
2868                                 continue;
2869                         if (devp->attach_done)
2870                                 continue;
2871                         if (h->flags & SYMBIOS_INIT_SCAN_AT_BOOT) {
2872                                 sym_get_nvram(devp, nvp);
2873                                 if (!sym_attach (tpnt, attach_count, devp))
2874                                         attach_count++;
2875                         }
2876                         else if (!(sym_driver_setup.use_nvram & 0x80))
2877                                 printf_info(
2878                                       "%s: 53c%s state OFF thus not attached\n",
2879                                       sym_name(devp), devp->chip.name);
2880                         else
2881                                 continue;
2882
2883                         devp->attach_done = 1;
2884                         break;
2885                 }
2886         }
2887 next:
2888 #endif
2889
2890         /* 
2891          *  Rescan device list to make sure all boards attached.
2892          *  Devices without boot records will not be attached yet
2893          *  so try to attach them here.
2894          */
2895         for (i= 0; i < count; i++) {
2896                 devp = &devtbl[i];
2897                 if (!devp->attach_done) {
2898                         devp->nvram = &nvram;
2899                         nvram.type = 0;
2900 #if SYM_CONF_NVRAM_SUPPORT
2901                         sym_get_nvram(devp, nvp);
2902 #endif
2903                         if (!sym_attach (tpnt, attach_count, devp))
2904                                 attach_count++;
2905                 }
2906         }
2907
2908         sym_mfree(devtbl, PAGE_SIZE, "DEVTBL");
2909
2910         return attach_count;
2911 }
2912
2913
2914
2915 #ifdef MODULE
2916 /*
2917  *  Linux release module stuff.
2918  *
2919  *  Called before unloading the module.
2920  *  Detach the host.
2921  *  We have to free resources and halt the NCR chip.
2922  *
2923  */
2924 static int sym_detach(hcb_p np)
2925 {
2926         printk("%s: detaching ...\n", sym_name(np));
2927
2928         /*
2929          *  Try to delete the timer.
2930          *  In the unlikely situation where this failed,
2931          *  try to synchronize with the timer handler.
2932          */
2933 #if LINUX_VERSION_CODE < LinuxVersionCode(2, 4, 0)
2934         np->s.release_stage = 1;
2935         if (!del_timer(&np->s.timer)) {
2936                 int i = 1000;
2937                 int k = 1;
2938                 while (1) {
2939                         u_long flags;
2940                         SYM_LOCK_HCB(np, flags);
2941                         k = np->s.release_stage;
2942                         SYM_UNLOCK_HCB(np, flags);
2943                         if (k == 2 || !--i)
2944                                 break;
2945                         MDELAY(5);
2946                 }
2947                 if (!i)
2948                         printk("%s: failed to kill timer!\n", sym_name(np));
2949         }
2950         np->s.release_stage = 2;
2951 #else
2952         (void)del_timer_sync(&np->s.timer);
2953 #endif
2954
2955         /*
2956          *  Reset NCR chip.
2957          *  We should use sym_soft_reset(), but we donnot want to do 
2958          *  so, since we may not be safe if interrupts occur.
2959          */
2960         printk("%s: resetting chip\n", sym_name(np));
2961         OUTB (nc_istat, SRST);
2962         UDELAY (10);
2963         OUTB (nc_istat, 0);
2964
2965         /*
2966          *  Free host resources
2967          */
2968         sym_free_resources(np);
2969
2970         return 1;
2971 }
2972
2973 int sym53c8xx_release(struct Scsi_Host *host)
2974 {
2975      sym_detach(((struct host_data *) host->hostdata)->ncb);
2976
2977      return 0;
2978 }
2979 #endif /* MODULE */
2980
2981 /*
2982  * For bigots to keep silent. :)
2983  */
2984 #ifdef MODULE_LICENSE
2985 MODULE_LICENSE("Dual BSD/GPL");
2986 #endif
2987
2988 /*
2989  * Driver host template.
2990  */
2991 #if LINUX_VERSION_CODE >= LinuxVersionCode(2,4,0)
2992 static
2993 #endif
2994 #if LINUX_VERSION_CODE >= LinuxVersionCode(2,4,0) || defined(MODULE)
2995 Scsi_Host_Template driver_template = SYM53C8XX;
2996 #include "../scsi_module.c"
2997 #endif