vserver 1.9.3
[linux-2.6.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/ctype.h>
55 #include <linux/init.h>
56 #include <linux/interrupt.h>
57 #include <linux/module.h>
58 #include <linux/spinlock.h>
59 #include <scsi/scsi.h>
60 #include <scsi/scsi_tcq.h>
61 #include <scsi/scsi_device.h>
62 #include <scsi/scsi_transport.h>
63 #include <scsi/scsi_transport_spi.h>
64
65 #include "sym_glue.h"
66 #include "sym_nvram.h"
67
68 #define NAME53C         "sym53c"
69 #define NAME53C8XX      "sym53c8xx"
70
71 static int __devinit
72 pci_get_base_address(struct pci_dev *pdev, int index, u_long *base)
73 {
74         u32 tmp;
75 #define PCI_BAR_OFFSET(index) (PCI_BASE_ADDRESS_0 + (index<<2))
76
77         pci_read_config_dword(pdev, PCI_BAR_OFFSET(index), &tmp);
78         *base = tmp;
79         ++index;
80         if ((tmp & 0x7) == PCI_BASE_ADDRESS_MEM_TYPE_64) {
81 #if BITS_PER_LONG > 32
82                 pci_read_config_dword(pdev, PCI_BAR_OFFSET(index), &tmp);
83                 *base |= (((u_long)tmp) << 32);
84 #endif
85                 ++index;
86         }
87         return index;
88 #undef PCI_BAR_OFFSET
89 }
90
91 /* This lock protects only the memory allocation/free.  */
92 spinlock_t sym53c8xx_lock = SPIN_LOCK_UNLOCKED;
93
94 static struct scsi_transport_template *sym2_transport_template = NULL;
95
96 /*
97  *  Wrappers to the generic memory allocator.
98  */
99 void *sym_calloc(int size, char *name)
100 {
101         unsigned long flags;
102         void *m;
103         spin_lock_irqsave(&sym53c8xx_lock, flags);
104         m = sym_calloc_unlocked(size, name);
105         spin_unlock_irqrestore(&sym53c8xx_lock, flags);
106         return m;
107 }
108
109 void sym_mfree(void *m, int size, char *name)
110 {
111         unsigned long flags;
112         spin_lock_irqsave(&sym53c8xx_lock, flags);
113         sym_mfree_unlocked(m, size, name);
114         spin_unlock_irqrestore(&sym53c8xx_lock, flags);
115 }
116
117 void *__sym_calloc_dma(m_pool_ident_t dev_dmat, int size, char *name)
118 {
119         unsigned long flags;
120         void *m;
121         spin_lock_irqsave(&sym53c8xx_lock, flags);
122         m = __sym_calloc_dma_unlocked(dev_dmat, size, name);
123         spin_unlock_irqrestore(&sym53c8xx_lock, flags);
124         return m;
125 }
126
127 void __sym_mfree_dma(m_pool_ident_t dev_dmat, void *m, int size, char *name)
128 {
129         unsigned long flags;
130         spin_lock_irqsave(&sym53c8xx_lock, flags);
131         __sym_mfree_dma_unlocked(dev_dmat, m, size, name);
132         spin_unlock_irqrestore(&sym53c8xx_lock, flags);
133 }
134
135 m_addr_t __vtobus(m_pool_ident_t dev_dmat, void *m)
136 {
137         unsigned long flags;
138         m_addr_t b;
139         spin_lock_irqsave(&sym53c8xx_lock, flags);
140         b = __vtobus_unlocked(dev_dmat, m);
141         spin_unlock_irqrestore(&sym53c8xx_lock, flags);
142         return b;
143 }
144
145 /*
146  *  Used by the eh thread to wait for command completion.
147  *  It is allocated on the eh thread stack.
148  */
149 struct sym_eh_wait {
150         struct semaphore sem;
151         struct timer_list timer;
152         void (*old_done)(struct scsi_cmnd *);
153         int to_do;
154         int timed_out;
155 };
156
157 /*
158  *  Driver private area in the SCSI command structure.
159  */
160 struct sym_ucmd {               /* Override the SCSI pointer structure */
161         SYM_QUEHEAD link_cmdq;  /* Must stay at offset ZERO */
162         dma_addr_t data_mapping;
163         u_char  data_mapped;
164         struct sym_eh_wait *eh_wait;
165 };
166
167 #define SYM_UCMD_PTR(cmd)  ((struct sym_ucmd *)(&(cmd)->SCp))
168 #define SYM_SCMD_PTR(ucmd) sym_que_entry(ucmd, struct scsi_cmnd, SCp)
169 #define SYM_SOFTC_PTR(cmd) (((struct host_data *)cmd->device->host->hostdata)->ncb)
170
171 static void __unmap_scsi_data(struct pci_dev *pdev, struct scsi_cmnd *cmd)
172 {
173         int dma_dir = cmd->sc_data_direction;
174
175         switch(SYM_UCMD_PTR(cmd)->data_mapped) {
176         case 2:
177                 pci_unmap_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
178                 break;
179         case 1:
180                 pci_unmap_single(pdev, SYM_UCMD_PTR(cmd)->data_mapping,
181                                  cmd->request_bufflen, dma_dir);
182                 break;
183         }
184         SYM_UCMD_PTR(cmd)->data_mapped = 0;
185 }
186
187 static dma_addr_t __map_scsi_single_data(struct pci_dev *pdev, struct scsi_cmnd *cmd)
188 {
189         dma_addr_t mapping;
190         int dma_dir = cmd->sc_data_direction;
191
192         mapping = pci_map_single(pdev, cmd->request_buffer,
193                                  cmd->request_bufflen, dma_dir);
194         if (mapping) {
195                 SYM_UCMD_PTR(cmd)->data_mapped  = 1;
196                 SYM_UCMD_PTR(cmd)->data_mapping = mapping;
197         }
198
199         return mapping;
200 }
201
202 static int __map_scsi_sg_data(struct pci_dev *pdev, struct scsi_cmnd *cmd)
203 {
204         int use_sg;
205         int dma_dir = cmd->sc_data_direction;
206
207         use_sg = pci_map_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
208         if (use_sg > 0) {
209                 SYM_UCMD_PTR(cmd)->data_mapped  = 2;
210                 SYM_UCMD_PTR(cmd)->data_mapping = use_sg;
211         }
212
213         return use_sg;
214 }
215
216 #define unmap_scsi_data(np, cmd)        \
217                 __unmap_scsi_data(np->s.device, cmd)
218 #define map_scsi_single_data(np, cmd)   \
219                 __map_scsi_single_data(np->s.device, cmd)
220 #define map_scsi_sg_data(np, cmd)       \
221                 __map_scsi_sg_data(np->s.device, cmd)
222 /*
223  *  Complete a pending CAM CCB.
224  */
225 void sym_xpt_done(struct sym_hcb *np, struct scsi_cmnd *ccb)
226 {
227         sym_remque(&SYM_UCMD_PTR(ccb)->link_cmdq);
228         unmap_scsi_data(np, ccb);
229         ccb->scsi_done(ccb);
230 }
231
232 void sym_xpt_done2(struct sym_hcb *np, struct scsi_cmnd *ccb, int cam_status)
233 {
234         sym_set_cam_status(ccb, cam_status);
235         sym_xpt_done(np, ccb);
236 }
237
238
239 /*
240  *  Print something that identifies the IO.
241  */
242 void sym_print_addr(struct sym_ccb *cp)
243 {
244         struct scsi_cmnd *cmd = cp->cam_ccb;
245         if (cmd)
246                 printf("%s:%d:%d:", sym_name(SYM_SOFTC_PTR(cmd)),
247                                 cmd->device->id, cmd->device->lun);
248 }
249
250 /*
251  *  Tell the SCSI layer about a BUS RESET.
252  */
253 void sym_xpt_async_bus_reset(struct sym_hcb *np)
254 {
255         printf_notice("%s: SCSI BUS has been reset.\n", sym_name(np));
256         np->s.settle_time = jiffies + sym_driver_setup.settle_delay * HZ;
257         np->s.settle_time_valid = 1;
258         if (sym_verbose >= 2)
259                 printf_info("%s: command processing suspended for %d seconds\n",
260                             sym_name(np), sym_driver_setup.settle_delay);
261 }
262
263 /*
264  *  Tell the SCSI layer about a BUS DEVICE RESET message sent.
265  */
266 void sym_xpt_async_sent_bdr(struct sym_hcb *np, int target)
267 {
268         printf_notice("%s: TARGET %d has been reset.\n", sym_name(np), target);
269 }
270
271 /*
272  *  Tell the SCSI layer about the new transfer parameters.
273  */
274 void sym_xpt_async_nego_wide(struct sym_hcb *np, int target)
275 {
276         if (sym_verbose < 3)
277                 return;
278         sym_announce_transfer_rate(np, target);
279 }
280
281 /*
282  *  Choose the more appropriate CAM status if 
283  *  the IO encountered an extended error.
284  */
285 static int sym_xerr_cam_status(int cam_status, int x_status)
286 {
287         if (x_status) {
288                 if      (x_status & XE_PARITY_ERR)
289                         cam_status = DID_PARITY;
290                 else if (x_status &(XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN))
291                         cam_status = DID_ERROR;
292                 else if (x_status & XE_BAD_PHASE)
293                         cam_status = DID_ERROR;
294                 else
295                         cam_status = DID_ERROR;
296         }
297         return cam_status;
298 }
299
300 /*
301  *  Build CAM result for a failed or auto-sensed IO.
302  */
303 void sym_set_cam_result_error(struct sym_hcb *np, struct sym_ccb *cp, int resid)
304 {
305         struct scsi_cmnd *csio = cp->cam_ccb;
306         u_int cam_status, scsi_status, drv_status;
307
308         drv_status  = 0;
309         cam_status  = DID_OK;
310         scsi_status = cp->ssss_status;
311
312         if (cp->host_flags & HF_SENSE) {
313                 scsi_status = cp->sv_scsi_status;
314                 resid = cp->sv_resid;
315                 if (sym_verbose && cp->sv_xerr_status)
316                         sym_print_xerr(cp, cp->sv_xerr_status);
317                 if (cp->host_status == HS_COMPLETE &&
318                     cp->ssss_status == S_GOOD &&
319                     cp->xerr_status == 0) {
320                         cam_status = sym_xerr_cam_status(DID_OK,
321                                                          cp->sv_xerr_status);
322                         drv_status = DRIVER_SENSE;
323                         /*
324                          *  Bounce back the sense data to user.
325                          */
326                         bzero(&csio->sense_buffer, sizeof(csio->sense_buffer));
327                         memcpy(csio->sense_buffer, cp->sns_bbuf,
328                               min(sizeof(csio->sense_buffer),
329                                   (size_t)SYM_SNS_BBUF_LEN));
330 #if 0
331                         /*
332                          *  If the device reports a UNIT ATTENTION condition 
333                          *  due to a RESET condition, we should consider all 
334                          *  disconnect CCBs for this unit as aborted.
335                          */
336                         if (1) {
337                                 u_char *p;
338                                 p  = (u_char *) csio->sense_data;
339                                 if (p[0]==0x70 && p[2]==0x6 && p[12]==0x29)
340                                         sym_clear_tasks(np, DID_ABORT,
341                                                         cp->target,cp->lun, -1);
342                         }
343 #endif
344                 } else {
345                         /*
346                          * Error return from our internal request sense.  This
347                          * is bad: we must clear the contingent allegiance
348                          * condition otherwise the device will always return
349                          * BUSY.  Use a big stick.
350                          */
351                         sym_reset_scsi_target(np, csio->device->id);
352                         cam_status = DID_ERROR;
353                 }
354         } else if (cp->host_status == HS_COMPLETE)      /* Bad SCSI status */
355                 cam_status = DID_OK;
356         else if (cp->host_status == HS_SEL_TIMEOUT)     /* Selection timeout */
357                 cam_status = DID_NO_CONNECT;
358         else if (cp->host_status == HS_UNEXPECTED)      /* Unexpected BUS FREE*/
359                 cam_status = DID_ERROR;
360         else {                                          /* Extended error */
361                 if (sym_verbose) {
362                         PRINT_ADDR(cp);
363                         printf ("COMMAND FAILED (%x %x %x).\n",
364                                 cp->host_status, cp->ssss_status,
365                                 cp->xerr_status);
366                 }
367                 /*
368                  *  Set the most appropriate value for CAM status.
369                  */
370                 cam_status = sym_xerr_cam_status(DID_ERROR, cp->xerr_status);
371         }
372         csio->resid = resid;
373         csio->result = (drv_status << 24) + (cam_status << 16) + scsi_status;
374 }
375
376
377 /*
378  *  Build the scatter/gather array for an I/O.
379  */
380
381 static int sym_scatter_no_sglist(struct sym_hcb *np, struct sym_ccb *cp, struct scsi_cmnd *cmd)
382 {
383         struct sym_tblmove *data = &cp->phys.data[SYM_CONF_MAX_SG-1];
384         int segment;
385
386         cp->data_len = cmd->request_bufflen;
387
388         if (cmd->request_bufflen) {
389                 dma_addr_t baddr = map_scsi_single_data(np, cmd);
390                 if (baddr) {
391                         sym_build_sge(np, data, baddr, cmd->request_bufflen);
392                         segment = 1;
393                 } else {
394                         segment = -2;
395                 }
396         } else {
397                 segment = 0;
398         }
399
400         return segment;
401 }
402
403 static int sym_scatter(struct sym_hcb *np, struct sym_ccb *cp, struct scsi_cmnd *cmd)
404 {
405         int segment;
406         int use_sg = (int) cmd->use_sg;
407
408         cp->data_len = 0;
409
410         if (!use_sg)
411                 segment = sym_scatter_no_sglist(np, cp, cmd);
412         else if ((use_sg = map_scsi_sg_data(np, cmd)) > 0) {
413                 struct scatterlist *scatter = (struct scatterlist *)cmd->buffer;
414                 struct sym_tblmove *data;
415
416                 if (use_sg > SYM_CONF_MAX_SG) {
417                         unmap_scsi_data(np, cmd);
418                         return -1;
419                 }
420
421                 data = &cp->phys.data[SYM_CONF_MAX_SG - use_sg];
422
423                 for (segment = 0; segment < use_sg; segment++) {
424                         dma_addr_t baddr = sg_dma_address(&scatter[segment]);
425                         unsigned int len = sg_dma_len(&scatter[segment]);
426
427                         sym_build_sge(np, &data[segment], baddr, len);
428                         cp->data_len += len;
429                 }
430         } else {
431                 segment = -2;
432         }
433
434         return segment;
435 }
436
437 /*
438  *  Queue a SCSI command.
439  */
440 static int sym_queue_command(struct sym_hcb *np, struct scsi_cmnd *ccb)
441 {
442 /*      struct scsi_device        *device    = ccb->device; */
443         struct sym_tcb *tp;
444         struct sym_lcb *lp;
445         struct sym_ccb *cp;
446         int     order;
447
448         /*
449          *  Minimal checkings, so that we will not 
450          *  go outside our tables.
451          */
452         if (ccb->device->id == np->myaddr ||
453             ccb->device->id >= SYM_CONF_MAX_TARGET ||
454             ccb->device->lun >= SYM_CONF_MAX_LUN) {
455                 sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
456                 return 0;
457         }
458
459         /*
460          *  Retreive the target descriptor.
461          */
462         tp = &np->target[ccb->device->id];
463
464         /*
465          *  Complete the 1st INQUIRY command with error 
466          *  condition if the device is flagged NOSCAN 
467          *  at BOOT in the NVRAM. This may speed up 
468          *  the boot and maintain coherency with BIOS 
469          *  device numbering. Clearing the flag allows 
470          *  user to rescan skipped devices later.
471          *  We also return error for devices not flagged 
472          *  for SCAN LUNS in the NVRAM since some mono-lun 
473          *  devices behave badly when asked for some non 
474          *  zero LUN. Btw, this is an absolute hack.:-)
475          */
476         if (ccb->cmnd[0] == 0x12 || ccb->cmnd[0] == 0x0) {
477                 if ((tp->usrflags & SYM_SCAN_BOOT_DISABLED) ||
478                     ((tp->usrflags & SYM_SCAN_LUNS_DISABLED) && 
479                      ccb->device->lun != 0)) {
480                         tp->usrflags &= ~SYM_SCAN_BOOT_DISABLED;
481                         sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
482                         return 0;
483                 }
484         }
485
486         /*
487          *  Select tagged/untagged.
488          */
489         lp = sym_lp(np, tp, ccb->device->lun);
490         order = (lp && lp->s.reqtags) ? M_SIMPLE_TAG : 0;
491
492         /*
493          *  Queue the SCSI IO.
494          */
495         cp = sym_get_ccb(np, ccb->device->id, ccb->device->lun, order);
496         if (!cp)
497                 return 1;       /* Means resource shortage */
498         sym_queue_scsiio(np, ccb, cp);
499         return 0;
500 }
501
502 /*
503  *  Setup buffers and pointers that address the CDB.
504  */
505 static inline int sym_setup_cdb(struct sym_hcb *np, struct scsi_cmnd *ccb, struct sym_ccb *cp)
506 {
507         u32     cmd_ba;
508         int     cmd_len;
509
510         /*
511          *  CDB is 16 bytes max.
512          */
513         if (ccb->cmd_len > sizeof(cp->cdb_buf)) {
514                 sym_set_cam_status(cp->cam_ccb, CAM_REQ_INVALID);
515                 return -1;
516         }
517
518         memcpy(cp->cdb_buf, ccb->cmnd, ccb->cmd_len);
519         cmd_ba  = CCB_BA (cp, cdb_buf[0]);
520         cmd_len = ccb->cmd_len;
521
522         cp->phys.cmd.addr       = cpu_to_scr(cmd_ba);
523         cp->phys.cmd.size       = cpu_to_scr(cmd_len);
524
525         return 0;
526 }
527
528 /*
529  *  Setup pointers that address the data and start the I/O.
530  */
531 int sym_setup_data_and_start(struct sym_hcb *np, struct scsi_cmnd *csio, struct sym_ccb *cp)
532 {
533         int dir;
534         struct sym_tcb *tp = &np->target[cp->target];
535         struct sym_lcb *lp = sym_lp(np, tp, cp->lun);
536
537         /*
538          *  Build the CDB.
539          */
540         if (sym_setup_cdb(np, csio, cp))
541                 goto out_abort;
542
543         /*
544          *  No direction means no data.
545          */
546         dir = csio->sc_data_direction;
547         if (dir != DMA_NONE) {
548                 cp->segments = sym_scatter(np, cp, csio);
549                 if (cp->segments < 0) {
550                         if (cp->segments == -2)
551                                 sym_set_cam_status(csio, CAM_RESRC_UNAVAIL);
552                         else
553                                 sym_set_cam_status(csio, CAM_REQ_TOO_BIG);
554                         goto out_abort;
555                 }
556         } else {
557                 cp->data_len = 0;
558                 cp->segments = 0;
559         }
560
561         /*
562          *  Set data pointers.
563          */
564         sym_setup_data_pointers(np, cp, dir);
565
566         /*
567          *  When `#ifed 1', the code below makes the driver 
568          *  panic on the first attempt to write to a SCSI device.
569          *  It is the first test we want to do after a driver 
570          *  change that does not seem obviously safe. :)
571          */
572 #if 0
573         switch (cp->cdb_buf[0]) {
574         case 0x0A: case 0x2A: case 0xAA:
575                 panic("XXXXXXXXXXXXX WRITE NOT YET ALLOWED XXXXXXXXXXXXXX\n");
576                 MDELAY(10000);
577                 break;
578         default:
579                 break;
580         }
581 #endif
582
583         /*
584          *      activate this job.
585          */
586         if (lp)
587                 sym_start_next_ccbs(np, lp, 2);
588         else
589                 sym_put_start_queue(np, cp);
590         return 0;
591
592 out_abort:
593         sym_free_ccb(np, cp);
594         sym_xpt_done(np, csio);
595         return 0;
596 }
597
598
599 /*
600  *  timer daemon.
601  *
602  *  Misused to keep the driver running when
603  *  interrupts are not configured correctly.
604  */
605 static void sym_timer(struct sym_hcb *np)
606 {
607         unsigned long thistime = jiffies;
608
609         /*
610          *  Restart the timer.
611          */
612         np->s.timer.expires = thistime + SYM_CONF_TIMER_INTERVAL;
613         add_timer(&np->s.timer);
614
615         /*
616          *  If we are resetting the ncr, wait for settle_time before 
617          *  clearing it. Then command processing will be resumed.
618          */
619         if (np->s.settle_time_valid) {
620                 if (time_before_eq(np->s.settle_time, thistime)) {
621                         if (sym_verbose >= 2 )
622                                 printk("%s: command processing resumed\n",
623                                        sym_name(np));
624                         np->s.settle_time_valid = 0;
625                 }
626                 return;
627         }
628
629         /*
630          *      Nothing to do for now, but that may come.
631          */
632         if (np->s.lasttime + 4*HZ < thistime) {
633                 np->s.lasttime = thistime;
634         }
635
636 #ifdef SYM_CONF_PCIQ_MAY_MISS_COMPLETIONS
637         /*
638          *  Some way-broken PCI bridges may lead to 
639          *  completions being lost when the clearing 
640          *  of the INTFLY flag by the CPU occurs 
641          *  concurrently with the chip raising this flag.
642          *  If this ever happen, lost completions will 
643          * be reaped here.
644          */
645         sym_wakeup_done(np);
646 #endif
647 }
648
649
650 /*
651  *  PCI BUS error handler.
652  */
653 void sym_log_bus_error(struct sym_hcb *np)
654 {
655         u_short pci_sts;
656         pci_read_config_word(np->s.device, PCI_STATUS, &pci_sts);
657         if (pci_sts & 0xf900) {
658                 pci_write_config_word(np->s.device, PCI_STATUS, pci_sts);
659                 printf("%s: PCI STATUS = 0x%04x\n",
660                         sym_name(np), pci_sts & 0xf900);
661         }
662 }
663
664
665 /*
666  *  Requeue awaiting commands.
667  */
668 static void sym_requeue_awaiting_cmds(struct sym_hcb *np)
669 {
670         struct sym_ucmd *ucp;
671         SYM_QUEHEAD tmp_cmdq;
672         int sts;
673
674         sym_que_move(&np->s.wait_cmdq, &tmp_cmdq);
675
676         while ((ucp = (struct sym_ucmd *) sym_remque_head(&tmp_cmdq)) != 0) {
677                 struct scsi_cmnd *cmd;
678
679                 sym_insque_tail(&ucp->link_cmdq, &np->s.busy_cmdq);
680                 cmd = SYM_SCMD_PTR(ucp);
681                 sts = sym_queue_command(np, cmd);
682                 if (sts) {
683                         sym_remque(&ucp->link_cmdq);
684                         sym_insque_head(&ucp->link_cmdq, &np->s.wait_cmdq);
685                 }
686         }
687 }
688
689 /*
690  * queuecommand method.  Entered with the host adapter lock held and
691  * interrupts disabled.
692  */
693 static int sym53c8xx_queue_command(struct scsi_cmnd *cmd,
694                                         void (*done)(struct scsi_cmnd *))
695 {
696         struct sym_hcb *np = SYM_SOFTC_PTR(cmd);
697         struct sym_ucmd *ucp = SYM_UCMD_PTR(cmd);
698         int sts = 0;
699
700         cmd->scsi_done     = done;
701         cmd->host_scribble = NULL;
702         memset(ucp, 0, sizeof(*ucp));
703
704         /*
705          *  Shorten our settle_time if needed for 
706          *  this command not to time out.
707          */
708         if (np->s.settle_time_valid && cmd->timeout_per_command) {
709                 unsigned long tlimit = jiffies + cmd->timeout_per_command;
710                 tlimit -= SYM_CONF_TIMER_INTERVAL*2;
711                 if (time_after(np->s.settle_time, tlimit)) {
712                         np->s.settle_time = tlimit;
713                 }
714         }
715
716         if (np->s.settle_time_valid || !sym_que_empty(&np->s.wait_cmdq)) {
717                 sym_insque_tail(&ucp->link_cmdq, &np->s.wait_cmdq);
718                 goto out;
719         }
720
721         sym_insque_tail(&ucp->link_cmdq, &np->s.busy_cmdq);
722         sts = sym_queue_command(np, cmd);
723         if (sts) {
724                 sym_remque(&ucp->link_cmdq);
725                 sym_insque_tail(&ucp->link_cmdq, &np->s.wait_cmdq);
726         }
727 out:
728         return 0;
729 }
730
731 /*
732  *  Linux entry point of the interrupt handler.
733  */
734 static irqreturn_t sym53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs)
735 {
736         unsigned long flags;
737         struct sym_hcb *np = (struct sym_hcb *)dev_id;
738
739         if (DEBUG_FLAGS & DEBUG_TINY) printf_debug ("[");
740
741         spin_lock_irqsave(np->s.host->host_lock, flags);
742
743         sym_interrupt(np);
744
745         /*
746          * push queue walk-through to tasklet
747          */
748         if (!sym_que_empty(&np->s.wait_cmdq) && !np->s.settle_time_valid)
749                 sym_requeue_awaiting_cmds(np);
750
751         spin_unlock_irqrestore(np->s.host->host_lock, flags);
752
753         if (DEBUG_FLAGS & DEBUG_TINY) printf_debug ("]\n");
754
755         return IRQ_HANDLED;
756 }
757
758 /*
759  *  Linux entry point of the timer handler
760  */
761 static void sym53c8xx_timer(unsigned long npref)
762 {
763         struct sym_hcb *np = (struct sym_hcb *)npref;
764         unsigned long flags;
765
766         spin_lock_irqsave(np->s.host->host_lock, flags);
767
768         sym_timer(np);
769
770         if (!sym_que_empty(&np->s.wait_cmdq) && !np->s.settle_time_valid)
771                 sym_requeue_awaiting_cmds(np);
772
773         spin_unlock_irqrestore(np->s.host->host_lock, flags);
774 }
775
776
777 /*
778  *  What the eh thread wants us to perform.
779  */
780 #define SYM_EH_ABORT            0
781 #define SYM_EH_DEVICE_RESET     1
782 #define SYM_EH_BUS_RESET        2
783 #define SYM_EH_HOST_RESET       3
784
785 /*
786  *  What we will do regarding the involved SCSI command.
787  */
788 #define SYM_EH_DO_IGNORE        0
789 #define SYM_EH_DO_COMPLETE      1
790 #define SYM_EH_DO_WAIT          2
791
792 /*
793  *  Our general completion handler.
794  */
795 static void __sym_eh_done(struct scsi_cmnd *cmd, int timed_out)
796 {
797         struct sym_eh_wait *ep = SYM_UCMD_PTR(cmd)->eh_wait;
798         if (!ep)
799                 return;
800
801         /* Try to avoid a race here (not 100% safe) */
802         if (!timed_out) {
803                 ep->timed_out = 0;
804                 if (ep->to_do == SYM_EH_DO_WAIT && !del_timer(&ep->timer))
805                         return;
806         }
807
808         /* Revert everything */
809         SYM_UCMD_PTR(cmd)->eh_wait = NULL;
810         cmd->scsi_done = ep->old_done;
811
812         /* Wake up the eh thread if it wants to sleep */
813         if (ep->to_do == SYM_EH_DO_WAIT)
814                 up(&ep->sem);
815 }
816
817 /*
818  *  scsi_done() alias when error recovery is in progress. 
819  */
820 static void sym_eh_done(struct scsi_cmnd *cmd) { __sym_eh_done(cmd, 0); }
821
822 /*
823  *  Some timeout handler to avoid waiting too long.
824  */
825 static void sym_eh_timeout(u_long p) { __sym_eh_done((struct scsi_cmnd *)p, 1); }
826
827 /*
828  *  Generic method for our eh processing.
829  *  The 'op' argument tells what we have to do.
830  */
831 static int sym_eh_handler(int op, char *opname, struct scsi_cmnd *cmd)
832 {
833         struct sym_hcb *np = SYM_SOFTC_PTR(cmd);
834         SYM_QUEHEAD *qp;
835         int to_do = SYM_EH_DO_IGNORE;
836         int sts = -1;
837         struct sym_eh_wait eh, *ep = &eh;
838         char devname[20];
839
840         sprintf(devname, "%s:%d:%d", sym_name(np), cmd->device->id, cmd->device->lun);
841
842         printf_warning("%s: %s operation started.\n", devname, opname);
843
844 #if 0
845         /* This one should be the result of some race, thus to ignore */
846         if (cmd->serial_number != cmd->serial_number_at_timeout)
847                 goto prepare;
848 #endif
849
850         /* This one is not queued to the core driver -> to complete here */ 
851         FOR_EACH_QUEUED_ELEMENT(&np->s.wait_cmdq, qp) {
852                 if (SYM_SCMD_PTR(qp) == cmd) {
853                         to_do = SYM_EH_DO_COMPLETE;
854                         goto prepare;
855                 }
856         }
857
858         /* This one is queued in some place -> to wait for completion */
859         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
860                 struct sym_ccb *cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
861                 if (cp->cam_ccb == cmd) {
862                         to_do = SYM_EH_DO_WAIT;
863                         goto prepare;
864                 }
865         }
866
867 prepare:
868         /* Prepare stuff to either ignore, complete or wait for completion */
869         switch(to_do) {
870         default:
871         case SYM_EH_DO_IGNORE:
872                 break;
873         case SYM_EH_DO_WAIT:
874                 init_MUTEX_LOCKED(&ep->sem);
875                 /* fall through */
876         case SYM_EH_DO_COMPLETE:
877                 ep->old_done = cmd->scsi_done;
878                 cmd->scsi_done = sym_eh_done;
879                 SYM_UCMD_PTR(cmd)->eh_wait = ep;
880         }
881
882         /* Try to proceed the operation we have been asked for */
883         sts = -1;
884         switch(op) {
885         case SYM_EH_ABORT:
886                 sts = sym_abort_scsiio(np, cmd, 1);
887                 break;
888         case SYM_EH_DEVICE_RESET:
889                 sts = sym_reset_scsi_target(np, cmd->device->id);
890                 break;
891         case SYM_EH_BUS_RESET:
892                 sym_reset_scsi_bus(np, 1);
893                 sts = 0;
894                 break;
895         case SYM_EH_HOST_RESET:
896                 sym_reset_scsi_bus(np, 0);
897                 sym_start_up (np, 1);
898                 sts = 0;
899                 break;
900         default:
901                 break;
902         }
903
904         /* On error, restore everything and cross fingers :) */
905         if (sts) {
906                 SYM_UCMD_PTR(cmd)->eh_wait = NULL;
907                 cmd->scsi_done = ep->old_done;
908                 to_do = SYM_EH_DO_IGNORE;
909         }
910
911         ep->to_do = to_do;
912         /* Complete the command with locks held as required by the driver */
913         if (to_do == SYM_EH_DO_COMPLETE)
914                 sym_xpt_done2(np, cmd, CAM_REQ_ABORTED);
915
916         /* Wait for completion with locks released, as required by kernel */
917         if (to_do == SYM_EH_DO_WAIT) {
918                 init_timer(&ep->timer);
919                 ep->timer.expires = jiffies + (5*HZ);
920                 ep->timer.function = sym_eh_timeout;
921                 ep->timer.data = (u_long)cmd;
922                 ep->timed_out = 1;      /* Be pessimistic for once :) */
923                 add_timer(&ep->timer);
924                 spin_unlock_irq(np->s.host->host_lock);
925                 down(&ep->sem);
926                 spin_lock_irq(np->s.host->host_lock);
927                 if (ep->timed_out)
928                         sts = -2;
929         }
930         printf_warning("%s: %s operation %s.\n", devname, opname,
931                         sts==0?"complete":sts==-2?"timed-out":"failed");
932         return sts? SCSI_FAILED : SCSI_SUCCESS;
933 }
934
935
936 /*
937  * Error handlers called from the eh thread (one thread per HBA).
938  */
939 static int sym53c8xx_eh_abort_handler(struct scsi_cmnd *cmd)
940 {
941         return sym_eh_handler(SYM_EH_ABORT, "ABORT", cmd);
942 }
943
944 static int sym53c8xx_eh_device_reset_handler(struct scsi_cmnd *cmd)
945 {
946         return sym_eh_handler(SYM_EH_DEVICE_RESET, "DEVICE RESET", cmd);
947 }
948
949 static int sym53c8xx_eh_bus_reset_handler(struct scsi_cmnd *cmd)
950 {
951         return sym_eh_handler(SYM_EH_BUS_RESET, "BUS RESET", cmd);
952 }
953
954 static int sym53c8xx_eh_host_reset_handler(struct scsi_cmnd *cmd)
955 {
956         return sym_eh_handler(SYM_EH_HOST_RESET, "HOST RESET", cmd);
957 }
958
959 /*
960  *  Tune device queuing depth, according to various limits.
961  */
962 static void sym_tune_dev_queuing(struct sym_hcb *np, int target, int lun, u_short reqtags)
963 {
964         struct sym_tcb *tp = &np->target[target];
965         struct sym_lcb *lp = sym_lp(np, tp, lun);
966         u_short oldtags;
967
968         if (!lp)
969                 return;
970
971         oldtags = lp->s.reqtags;
972
973         if (reqtags > lp->s.scdev_depth)
974                 reqtags = lp->s.scdev_depth;
975
976         lp->started_limit = reqtags ? reqtags : 2;
977         lp->started_max   = 1;
978         lp->s.reqtags     = reqtags;
979
980         if (reqtags != oldtags) {
981                 printf_info("%s:%d:%d: "
982                          "tagged command queuing %s, command queue depth %d.\n",
983                           sym_name(np), target, lun,
984                           lp->s.reqtags ? "enabled" : "disabled",
985                           lp->started_limit);
986         }
987 }
988
989 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
990 /*
991  *  Linux select queue depths function
992  */
993 #define DEF_DEPTH       (sym_driver_setup.max_tag)
994 #define ALL_TARGETS     -2
995 #define NO_TARGET       -1
996 #define ALL_LUNS        -2
997 #define NO_LUN          -1
998
999 static int device_queue_depth(struct sym_hcb *np, int target, int lun)
1000 {
1001         int c, h, t, u, v;
1002         char *p = sym_driver_setup.tag_ctrl;
1003         char *ep;
1004
1005         h = -1;
1006         t = NO_TARGET;
1007         u = NO_LUN;
1008         while ((c = *p++) != 0) {
1009                 v = simple_strtoul(p, &ep, 0);
1010                 switch(c) {
1011                 case '/':
1012                         ++h;
1013                         t = ALL_TARGETS;
1014                         u = ALL_LUNS;
1015                         break;
1016                 case 't':
1017                         if (t != target)
1018                                 t = (target == v) ? v : NO_TARGET;
1019                         u = ALL_LUNS;
1020                         break;
1021                 case 'u':
1022                         if (u != lun)
1023                                 u = (lun == v) ? v : NO_LUN;
1024                         break;
1025                 case 'q':
1026                         if (h == np->s.unit &&
1027                                 (t == ALL_TARGETS || t == target) &&
1028                                 (u == ALL_LUNS    || u == lun))
1029                                 return v;
1030                         break;
1031                 case '-':
1032                         t = ALL_TARGETS;
1033                         u = ALL_LUNS;
1034                         break;
1035                 default:
1036                         break;
1037                 }
1038                 p = ep;
1039         }
1040         return DEF_DEPTH;
1041 }
1042 #else
1043 #define device_queue_depth(np, t, l)    (sym_driver_setup.max_tag)
1044 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
1045
1046 /*
1047  * Linux entry point for device queue sizing.
1048  */
1049 static int sym53c8xx_slave_configure(struct scsi_device *device)
1050 {
1051         struct Scsi_Host *host = device->host;
1052         struct sym_hcb *np;
1053         struct sym_tcb *tp;
1054         struct sym_lcb *lp;
1055         int reqtags, depth_to_use;
1056
1057         np = ((struct host_data *) host->hostdata)->ncb;
1058         tp = &np->target[device->id];
1059         tp->sdev = device;
1060
1061         /*
1062          *  Allocate the LCB if not yet.
1063          *  If it fail, we may well be in the sh*t. :)
1064          */
1065         lp = sym_alloc_lcb(np, device->id, device->lun);
1066         if (!lp)
1067                 return -ENOMEM;
1068
1069         /*
1070          *  Get user flags.
1071          */
1072         lp->curr_flags = lp->user_flags;
1073
1074         /*
1075          *  Select queue depth from driver setup.
1076          *  Donnot use more than configured by user.
1077          *  Use at least 2.
1078          *  Donnot use more than our maximum.
1079          */
1080         reqtags = device_queue_depth(np, device->id, device->lun);
1081         if (reqtags > tp->usrtags)
1082                 reqtags = tp->usrtags;
1083         if (!device->tagged_supported)
1084                 reqtags = 0;
1085 #if 1 /* Avoid to locally queue commands for no good reasons */
1086         if (reqtags > SYM_CONF_MAX_TAG)
1087                 reqtags = SYM_CONF_MAX_TAG;
1088         depth_to_use = (reqtags ? reqtags : 2);
1089 #else
1090         depth_to_use = (reqtags ? SYM_CONF_MAX_TAG : 2);
1091 #endif
1092         scsi_adjust_queue_depth(device,
1093                                 (device->tagged_supported ?
1094                                  MSG_SIMPLE_TAG : 0),
1095                                 depth_to_use);
1096         lp->s.scdev_depth = depth_to_use;
1097         sym_tune_dev_queuing(np, device->id, device->lun, reqtags);
1098
1099         spi_dv_device(device);
1100
1101         return 0;
1102 }
1103
1104 /*
1105  *  Linux entry point for info() function
1106  */
1107 static const char *sym53c8xx_info (struct Scsi_Host *host)
1108 {
1109         return sym_driver_name();
1110 }
1111
1112
1113 #ifdef SYM_LINUX_PROC_INFO_SUPPORT
1114 /*
1115  *  Proc file system stuff
1116  *
1117  *  A read operation returns adapter information.
1118  *  A write operation is a control command.
1119  *  The string is parsed in the driver code and the command is passed 
1120  *  to the sym_usercmd() function.
1121  */
1122
1123 #ifdef SYM_LINUX_USER_COMMAND_SUPPORT
1124
1125 struct  sym_usrcmd {
1126         u_long  target;
1127         u_long  lun;
1128         u_long  data;
1129         u_long  cmd;
1130 };
1131
1132 #define UC_SETSYNC      10
1133 #define UC_SETTAGS      11
1134 #define UC_SETDEBUG     12
1135 #define UC_SETWIDE      14
1136 #define UC_SETFLAG      15
1137 #define UC_SETVERBOSE   17
1138 #define UC_RESETDEV     18
1139 #define UC_CLEARDEV     19
1140
1141 static void sym_exec_user_command (struct sym_hcb *np, struct sym_usrcmd *uc)
1142 {
1143         struct sym_tcb *tp;
1144         int t, l;
1145
1146         switch (uc->cmd) {
1147         case 0: return;
1148
1149 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1150         case UC_SETDEBUG:
1151                 sym_debug_flags = uc->data;
1152                 break;
1153 #endif
1154         case UC_SETVERBOSE:
1155                 np->verbose = uc->data;
1156                 break;
1157         default:
1158                 /*
1159                  * We assume that other commands apply to targets.
1160                  * This should always be the case and avoid the below 
1161                  * 4 lines to be repeated 6 times.
1162                  */
1163                 for (t = 0; t < SYM_CONF_MAX_TARGET; t++) {
1164                         if (!((uc->target >> t) & 1))
1165                                 continue;
1166                         tp = &np->target[t];
1167
1168                         switch (uc->cmd) {
1169
1170                         case UC_SETSYNC:
1171                                 if (!uc->data || uc->data >= 255) {
1172                                         tp->tinfo.goal.options = 0;
1173                                         tp->tinfo.goal.offset  = 0;
1174                                         break;
1175                                 }
1176                                 if (uc->data <= 9 && np->minsync_dt) {
1177                                         if (uc->data < np->minsync_dt)
1178                                                 uc->data = np->minsync_dt;
1179                                         tp->tinfo.goal.options = PPR_OPT_DT;
1180                                         tp->tinfo.goal.width   = 1;
1181                                         tp->tinfo.goal.period = uc->data;
1182                                         tp->tinfo.goal.offset = np->maxoffs_dt;
1183                                 } else {
1184                                         if (uc->data < np->minsync)
1185                                                 uc->data = np->minsync;
1186                                         tp->tinfo.goal.options = 0;
1187                                         tp->tinfo.goal.period = uc->data;
1188                                         tp->tinfo.goal.offset = np->maxoffs;
1189                                 }
1190                                 break;
1191                         case UC_SETWIDE:
1192                                 tp->tinfo.goal.width = uc->data ? 1 : 0;
1193                                 break;
1194                         case UC_SETTAGS:
1195                                 for (l = 0; l < SYM_CONF_MAX_LUN; l++)
1196                                         sym_tune_dev_queuing(np, t,l, uc->data);
1197                                 break;
1198                         case UC_RESETDEV:
1199                                 tp->to_reset = 1;
1200                                 np->istat_sem = SEM;
1201                                 OUTB (nc_istat, SIGP|SEM);
1202                                 break;
1203                         case UC_CLEARDEV:
1204                                 for (l = 0; l < SYM_CONF_MAX_LUN; l++) {
1205                                         struct sym_lcb *lp = sym_lp(np, tp, l);
1206                                         if (lp) lp->to_clear = 1;
1207                                 }
1208                                 np->istat_sem = SEM;
1209                                 OUTB (nc_istat, SIGP|SEM);
1210                                 break;
1211                         case UC_SETFLAG:
1212                                 tp->usrflags = uc->data;
1213                                 break;
1214                         }
1215                 }
1216                 break;
1217         }
1218 }
1219
1220 #define digit_to_bin(c) ((c) - '0')
1221
1222 static int skip_spaces(char *ptr, int len)
1223 {
1224         int cnt, c;
1225
1226         for (cnt = len; cnt > 0 && (c = *ptr++) && isspace(c); cnt--);
1227
1228         return (len - cnt);
1229 }
1230
1231 static int get_int_arg(char *ptr, int len, u_long *pv)
1232 {
1233         int     cnt, c;
1234         u_long  v;
1235
1236         for (v = 0, cnt = len; cnt > 0 && (c = *ptr++) && isdigit(c); cnt--) {
1237                 v = (v * 10) + digit_to_bin(c);
1238         }
1239
1240         if (pv)
1241                 *pv = v;
1242
1243         return (len - cnt);
1244 }
1245
1246 static int is_keyword(char *ptr, int len, char *verb)
1247 {
1248         int verb_len = strlen(verb);
1249
1250         if (len >= verb_len && !memcmp(verb, ptr, verb_len))
1251                 return verb_len;
1252         else
1253                 return 0;
1254
1255 }
1256
1257 #define SKIP_SPACES(min_spaces)                                         \
1258         if ((arg_len = skip_spaces(ptr, len)) < (min_spaces))           \
1259                 return -EINVAL;                                         \
1260         ptr += arg_len; len -= arg_len;
1261
1262 #define GET_INT_ARG(v)                                                  \
1263         if (!(arg_len = get_int_arg(ptr, len, &(v))))                   \
1264                 return -EINVAL;                                         \
1265         ptr += arg_len; len -= arg_len;
1266
1267
1268 /*
1269  * Parse a control command
1270  */
1271
1272 static int sym_user_command(struct sym_hcb *np, char *buffer, int length)
1273 {
1274         char *ptr       = buffer;
1275         int len         = length;
1276         struct sym_usrcmd cmd, *uc = &cmd;
1277         int             arg_len;
1278         u_long          target;
1279
1280         bzero(uc, sizeof(*uc));
1281
1282         if (len > 0 && ptr[len-1] == '\n')
1283                 --len;
1284
1285         if      ((arg_len = is_keyword(ptr, len, "setsync")) != 0)
1286                 uc->cmd = UC_SETSYNC;
1287         else if ((arg_len = is_keyword(ptr, len, "settags")) != 0)
1288                 uc->cmd = UC_SETTAGS;
1289         else if ((arg_len = is_keyword(ptr, len, "setverbose")) != 0)
1290                 uc->cmd = UC_SETVERBOSE;
1291         else if ((arg_len = is_keyword(ptr, len, "setwide")) != 0)
1292                 uc->cmd = UC_SETWIDE;
1293 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1294         else if ((arg_len = is_keyword(ptr, len, "setdebug")) != 0)
1295                 uc->cmd = UC_SETDEBUG;
1296 #endif
1297         else if ((arg_len = is_keyword(ptr, len, "setflag")) != 0)
1298                 uc->cmd = UC_SETFLAG;
1299         else if ((arg_len = is_keyword(ptr, len, "resetdev")) != 0)
1300                 uc->cmd = UC_RESETDEV;
1301         else if ((arg_len = is_keyword(ptr, len, "cleardev")) != 0)
1302                 uc->cmd = UC_CLEARDEV;
1303         else
1304                 arg_len = 0;
1305
1306 #ifdef DEBUG_PROC_INFO
1307 printk("sym_user_command: arg_len=%d, cmd=%ld\n", arg_len, uc->cmd);
1308 #endif
1309
1310         if (!arg_len)
1311                 return -EINVAL;
1312         ptr += arg_len; len -= arg_len;
1313
1314         switch(uc->cmd) {
1315         case UC_SETSYNC:
1316         case UC_SETTAGS:
1317         case UC_SETWIDE:
1318         case UC_SETFLAG:
1319         case UC_RESETDEV:
1320         case UC_CLEARDEV:
1321                 SKIP_SPACES(1);
1322                 if ((arg_len = is_keyword(ptr, len, "all")) != 0) {
1323                         ptr += arg_len; len -= arg_len;
1324                         uc->target = ~0;
1325                 } else {
1326                         GET_INT_ARG(target);
1327                         uc->target = (1<<target);
1328 #ifdef DEBUG_PROC_INFO
1329 printk("sym_user_command: target=%ld\n", target);
1330 #endif
1331                 }
1332                 break;
1333         }
1334
1335         switch(uc->cmd) {
1336         case UC_SETVERBOSE:
1337         case UC_SETSYNC:
1338         case UC_SETTAGS:
1339         case UC_SETWIDE:
1340                 SKIP_SPACES(1);
1341                 GET_INT_ARG(uc->data);
1342 #ifdef DEBUG_PROC_INFO
1343 printk("sym_user_command: data=%ld\n", uc->data);
1344 #endif
1345                 break;
1346 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1347         case UC_SETDEBUG:
1348                 while (len > 0) {
1349                         SKIP_SPACES(1);
1350                         if      ((arg_len = is_keyword(ptr, len, "alloc")))
1351                                 uc->data |= DEBUG_ALLOC;
1352                         else if ((arg_len = is_keyword(ptr, len, "phase")))
1353                                 uc->data |= DEBUG_PHASE;
1354                         else if ((arg_len = is_keyword(ptr, len, "queue")))
1355                                 uc->data |= DEBUG_QUEUE;
1356                         else if ((arg_len = is_keyword(ptr, len, "result")))
1357                                 uc->data |= DEBUG_RESULT;
1358                         else if ((arg_len = is_keyword(ptr, len, "scatter")))
1359                                 uc->data |= DEBUG_SCATTER;
1360                         else if ((arg_len = is_keyword(ptr, len, "script")))
1361                                 uc->data |= DEBUG_SCRIPT;
1362                         else if ((arg_len = is_keyword(ptr, len, "tiny")))
1363                                 uc->data |= DEBUG_TINY;
1364                         else if ((arg_len = is_keyword(ptr, len, "timing")))
1365                                 uc->data |= DEBUG_TIMING;
1366                         else if ((arg_len = is_keyword(ptr, len, "nego")))
1367                                 uc->data |= DEBUG_NEGO;
1368                         else if ((arg_len = is_keyword(ptr, len, "tags")))
1369                                 uc->data |= DEBUG_TAGS;
1370                         else if ((arg_len = is_keyword(ptr, len, "pointer")))
1371                                 uc->data |= DEBUG_POINTER;
1372                         else
1373                                 return -EINVAL;
1374                         ptr += arg_len; len -= arg_len;
1375                 }
1376 #ifdef DEBUG_PROC_INFO
1377 printk("sym_user_command: data=%ld\n", uc->data);
1378 #endif
1379                 break;
1380 #endif /* SYM_LINUX_DEBUG_CONTROL_SUPPORT */
1381         case UC_SETFLAG:
1382                 while (len > 0) {
1383                         SKIP_SPACES(1);
1384                         if      ((arg_len = is_keyword(ptr, len, "no_disc")))
1385                                 uc->data &= ~SYM_DISC_ENABLED;
1386                         else
1387                                 return -EINVAL;
1388                         ptr += arg_len; len -= arg_len;
1389                 }
1390                 break;
1391         default:
1392                 break;
1393         }
1394
1395         if (len)
1396                 return -EINVAL;
1397         else {
1398                 unsigned long flags;
1399
1400                 spin_lock_irqsave(np->s.host->host_lock, flags);
1401                 sym_exec_user_command (np, uc);
1402                 spin_unlock_irqrestore(np->s.host->host_lock, flags);
1403         }
1404         return length;
1405 }
1406
1407 #endif  /* SYM_LINUX_USER_COMMAND_SUPPORT */
1408
1409
1410 #ifdef SYM_LINUX_USER_INFO_SUPPORT
1411 /*
1412  *  Informations through the proc file system.
1413  */
1414 struct info_str {
1415         char *buffer;
1416         int length;
1417         int offset;
1418         int pos;
1419 };
1420
1421 static void copy_mem_info(struct info_str *info, char *data, int len)
1422 {
1423         if (info->pos + len > info->length)
1424                 len = info->length - info->pos;
1425
1426         if (info->pos + len < info->offset) {
1427                 info->pos += len;
1428                 return;
1429         }
1430         if (info->pos < info->offset) {
1431                 data += (info->offset - info->pos);
1432                 len  -= (info->offset - info->pos);
1433         }
1434
1435         if (len > 0) {
1436                 memcpy(info->buffer + info->pos, data, len);
1437                 info->pos += len;
1438         }
1439 }
1440
1441 static int copy_info(struct info_str *info, char *fmt, ...)
1442 {
1443         va_list args;
1444         char buf[81];
1445         int len;
1446
1447         va_start(args, fmt);
1448         len = vsprintf(buf, fmt, args);
1449         va_end(args);
1450
1451         copy_mem_info(info, buf, len);
1452         return len;
1453 }
1454
1455 /*
1456  *  Copy formatted information into the input buffer.
1457  */
1458 static int sym_host_info(struct sym_hcb *np, char *ptr, off_t offset, int len)
1459 {
1460         struct info_str info;
1461
1462         info.buffer     = ptr;
1463         info.length     = len;
1464         info.offset     = offset;
1465         info.pos        = 0;
1466
1467         copy_info(&info, "Chip " NAME53C "%s, device id 0x%x, "
1468                          "revision id 0x%x\n",
1469                          np->s.chip_name, np->device_id, np->revision_id);
1470         copy_info(&info, "At PCI address %s, "
1471 #ifdef __sparc__
1472                 "IRQ %s\n",
1473 #else
1474                 "IRQ %d\n",
1475 #endif
1476                 pci_name(np->s.device),
1477 #ifdef __sparc__
1478                 __irq_itoa(np->s.irq));
1479 #else
1480                 (int) np->s.irq);
1481 #endif
1482         copy_info(&info, "Min. period factor %d, %s SCSI BUS%s\n",
1483                          (int) (np->minsync_dt ? np->minsync_dt : np->minsync),
1484                          np->maxwide ? "Wide" : "Narrow",
1485                          np->minsync_dt ? ", DT capable" : "");
1486
1487         copy_info(&info, "Max. started commands %d, "
1488                          "max. commands per LUN %d\n",
1489                          SYM_CONF_MAX_START, SYM_CONF_MAX_TAG);
1490
1491         return info.pos > info.offset? info.pos - info.offset : 0;
1492 }
1493 #endif /* SYM_LINUX_USER_INFO_SUPPORT */
1494
1495 /*
1496  *  Entry point of the scsi proc fs of the driver.
1497  *  - func = 0 means read  (returns adapter infos)
1498  *  - func = 1 means write (not yet merget from sym53c8xx)
1499  */
1500 static int sym53c8xx_proc_info(struct Scsi_Host *host, char *buffer,
1501                         char **start, off_t offset, int length, int func)
1502 {
1503         struct host_data *host_data;
1504         struct sym_hcb *np = NULL;
1505         int retv;
1506
1507         host_data = (struct host_data *) host->hostdata;
1508         np = host_data->ncb;
1509         if (!np)
1510                 return -EINVAL;
1511
1512         if (func) {
1513 #ifdef  SYM_LINUX_USER_COMMAND_SUPPORT
1514                 retv = sym_user_command(np, buffer, length);
1515 #else
1516                 retv = -EINVAL;
1517 #endif
1518         } else {
1519                 if (start)
1520                         *start = buffer;
1521 #ifdef SYM_LINUX_USER_INFO_SUPPORT
1522                 retv = sym_host_info(np, buffer, offset, length);
1523 #else
1524                 retv = -EINVAL;
1525 #endif
1526         }
1527
1528         return retv;
1529 }
1530 #endif /* SYM_LINUX_PROC_INFO_SUPPORT */
1531
1532 /*
1533  *      Free controller resources.
1534  */
1535 static void sym_free_resources(struct sym_hcb *np)
1536 {
1537         /*
1538          *  Free O/S specific resources.
1539          */
1540         if (np->s.irq)
1541                 free_irq(np->s.irq, np);
1542 #ifndef SYM_CONF_IOMAPPED
1543         if (np->s.mmio_va)
1544                 iounmap(np->s.mmio_va);
1545 #endif
1546         if (np->s.ram_va)
1547                 iounmap(np->s.ram_va);
1548         /*
1549          *  Free O/S independent resources.
1550          */
1551         sym_hcb_free(np);
1552
1553         sym_mfree_dma(np, sizeof(*np), "HCB");
1554 }
1555
1556 /*
1557  *  Ask/tell the system about DMA addressing.
1558  */
1559 static int sym_setup_bus_dma_mask(struct sym_hcb *np)
1560 {
1561 #if   SYM_CONF_DMA_ADDRESSING_MODE == 0
1562         if (pci_set_dma_mask(np->s.device, 0xffffffffUL))
1563                 goto out_err32;
1564 #else
1565 #if   SYM_CONF_DMA_ADDRESSING_MODE == 1
1566 #define PciDmaMask      0xffffffffffULL
1567 #elif SYM_CONF_DMA_ADDRESSING_MODE == 2
1568 #define PciDmaMask      0xffffffffffffffffULL
1569 #endif
1570         if (np->features & FE_DAC) {
1571                 if (!pci_set_dma_mask(np->s.device, PciDmaMask)) {
1572                         np->use_dac = 1;
1573                         printf_info("%s: using 64 bit DMA addressing\n",
1574                                         sym_name(np));
1575                 } else {
1576                         if (pci_set_dma_mask(np->s.device, 0xffffffffUL))
1577                                 goto out_err32;
1578                 }
1579         }
1580 #undef  PciDmaMask
1581 #endif
1582         return 0;
1583
1584 out_err32:
1585         printf_warning("%s: 32 BIT DMA ADDRESSING NOT SUPPORTED\n",
1586                         sym_name(np));
1587         return -1;
1588 }
1589
1590 /*
1591  *  Host attach and initialisations.
1592  *
1593  *  Allocate host data and ncb structure.
1594  *  Remap MMIO region.
1595  *  Do chip initialization.
1596  *  If all is OK, install interrupt handling and
1597  *  start the timer daemon.
1598  */
1599 static struct Scsi_Host * __devinit sym_attach(struct scsi_host_template *tpnt,
1600                 int unit, struct sym_device *dev)
1601 {
1602         struct host_data *host_data;
1603         struct sym_hcb *np = NULL;
1604         struct Scsi_Host *instance = NULL;
1605         unsigned long flags;
1606         struct sym_fw *fw;
1607
1608         printk(KERN_INFO
1609                 "sym%d: <%s> rev 0x%x at pci %s "
1610 #ifdef __sparc__
1611                 "irq %s\n",
1612 #else
1613                 "irq %d\n",
1614 #endif
1615                 unit, dev->chip.name, dev->chip.revision_id,
1616                 pci_name(dev->pdev),
1617 #ifdef __sparc__
1618                 __irq_itoa(dev->s.irq));
1619 #else
1620                 dev->s.irq);
1621 #endif
1622
1623         /*
1624          *  Get the firmware for this chip.
1625          */
1626         fw = sym_find_firmware(&dev->chip);
1627         if (!fw)
1628                 goto attach_failed;
1629
1630         /*
1631          *      Allocate host_data structure
1632          */
1633         instance = scsi_host_alloc(tpnt, sizeof(*host_data));
1634         if (!instance)
1635                 goto attach_failed;
1636         host_data = (struct host_data *) instance->hostdata;
1637
1638         /*
1639          *  Allocate immediately the host control block, 
1640          *  since we are only expecting to succeed. :)
1641          *  We keep track in the HCB of all the resources that 
1642          *  are to be released on error.
1643          */
1644         np = __sym_calloc_dma(dev->pdev, sizeof(*np), "HCB");
1645         if (!np)
1646                 goto attach_failed;
1647         np->s.device = dev->pdev;
1648         np->bus_dmat = dev->pdev; /* Result in 1 DMA pool per HBA */
1649         host_data->ncb = np;
1650         np->s.host = instance;
1651
1652         pci_set_drvdata(dev->pdev, np);
1653
1654         /*
1655          *  Copy some useful infos to the HCB.
1656          */
1657         np->hcb_ba      = vtobus(np);
1658         np->verbose     = sym_driver_setup.verbose;
1659         np->s.device    = dev->pdev;
1660         np->s.unit      = unit;
1661         np->device_id   = dev->chip.device_id;
1662         np->revision_id = dev->chip.revision_id;
1663         np->features    = dev->chip.features;
1664         np->clock_divn  = dev->chip.nr_divisor;
1665         np->maxoffs     = dev->chip.offset_max;
1666         np->maxburst    = dev->chip.burst_max;
1667         np->myaddr      = dev->host_id;
1668
1669         /*
1670          *  Edit its name.
1671          */
1672         strlcpy(np->s.chip_name, dev->chip.name, sizeof(np->s.chip_name));
1673         sprintf(np->s.inst_name, "sym%d", np->s.unit);
1674
1675         /*
1676          *  Ask/tell the system about DMA addressing.
1677          */
1678         if (sym_setup_bus_dma_mask(np))
1679                 goto attach_failed;
1680
1681         /*
1682          *  Try to map the controller chip to
1683          *  virtual and physical memory.
1684          */
1685         np->mmio_ba     = (u32)dev->s.base;
1686         np->s.io_ws     = (np->features & FE_IO256)? 256 : 128;
1687
1688 #ifndef SYM_CONF_IOMAPPED
1689         np->s.mmio_va = ioremap(dev->s.base_c, np->s.io_ws);
1690         if (!np->s.mmio_va) {
1691                 printf_err("%s: can't map PCI MMIO region\n", sym_name(np));
1692                 goto attach_failed;
1693         } else if (sym_verbose > 1)
1694                 printf_info("%s: using memory mapped IO\n", sym_name(np));
1695 #endif /* !defined SYM_CONF_IOMAPPED */
1696
1697         np->s.io_port = dev->s.io_port;
1698
1699         /*
1700          *  Map on-chip RAM if present and supported.
1701          */
1702         if (!(np->features & FE_RAM))
1703                 dev->s.base_2 = 0;
1704         if (dev->s.base_2) {
1705                 np->ram_ba = (u32)dev->s.base_2;
1706                 if (np->features & FE_RAM8K)
1707                         np->ram_ws = 8192;
1708                 else
1709                         np->ram_ws = 4096;
1710                 np->s.ram_va = ioremap(dev->s.base_2_c, np->ram_ws);
1711                 if (!np->s.ram_va) {
1712                         printf_err("%s: can't map PCI MEMORY region\n",
1713                                 sym_name(np));
1714                         goto attach_failed;
1715                 }
1716         }
1717
1718         /*
1719          *  Perform O/S independent stuff.
1720          */
1721         if (sym_hcb_attach(np, fw, dev->nvram))
1722                 goto attach_failed;
1723
1724
1725         /*
1726          *  Install the interrupt handler.
1727          *  If we synchonize the C code with SCRIPTS on interrupt, 
1728          *  we donnot want to share the INTR line at all.
1729          */
1730         if (request_irq(dev->s.irq, sym53c8xx_intr, SA_SHIRQ,
1731                         NAME53C8XX, np)) {
1732                 printf_err("%s: request irq %d failure\n",
1733                         sym_name(np), dev->s.irq);
1734                 goto attach_failed;
1735         }
1736         np->s.irq = dev->s.irq;
1737
1738         /*
1739          *  After SCSI devices have been opened, we cannot
1740          *  reset the bus safely, so we do it here.
1741          */
1742         spin_lock_irqsave(instance->host_lock, flags);
1743         if (sym_reset_scsi_bus(np, 0))
1744                 goto reset_failed;
1745
1746         /*
1747          *  Initialize some queue headers.
1748          */
1749         sym_que_init(&np->s.wait_cmdq);
1750         sym_que_init(&np->s.busy_cmdq);
1751
1752         /*
1753          *  Start the SCRIPTS.
1754          */
1755         sym_start_up (np, 1);
1756
1757         /*
1758          *  Start the timer daemon
1759          */
1760         init_timer(&np->s.timer);
1761         np->s.timer.data     = (unsigned long) np;
1762         np->s.timer.function = sym53c8xx_timer;
1763         np->s.lasttime=0;
1764         sym_timer (np);
1765
1766         /*
1767          *  Fill Linux host instance structure
1768          *  and return success.
1769          */
1770         instance->max_channel   = 0;
1771         instance->this_id       = np->myaddr;
1772         instance->max_id        = np->maxwide ? 16 : 8;
1773         instance->max_lun       = SYM_CONF_MAX_LUN;
1774 #ifndef SYM_CONF_IOMAPPED
1775         instance->base          = (unsigned long) np->s.mmio_va;
1776 #endif
1777         instance->irq           = np->s.irq;
1778         instance->unique_id     = np->s.io_port;
1779         instance->io_port       = np->s.io_port;
1780         instance->n_io_port     = np->s.io_ws;
1781         instance->dma_channel   = 0;
1782         instance->cmd_per_lun   = SYM_CONF_MAX_TAG;
1783         instance->can_queue     = (SYM_CONF_MAX_START-2);
1784         instance->sg_tablesize  = SYM_CONF_MAX_SG;
1785         instance->max_cmd_len   = 16;
1786         BUG_ON(sym2_transport_template == NULL);
1787         instance->transportt    = sym2_transport_template;
1788
1789         spin_unlock_irqrestore(instance->host_lock, flags);
1790
1791         return instance;
1792
1793  reset_failed:
1794         printf_err("%s: FATAL ERROR: CHECK SCSI BUS - CABLES, "
1795                    "TERMINATION, DEVICE POWER etc.!\n", sym_name(np));
1796         spin_unlock_irqrestore(instance->host_lock, flags);
1797  attach_failed:
1798         if (!instance)
1799                 return NULL;
1800         printf_info("%s: giving up ...\n", sym_name(np));
1801         if (np)
1802                 sym_free_resources(np);
1803         scsi_host_put(instance);
1804
1805         return NULL;
1806  }
1807
1808
1809 /*
1810  *    Detect and try to read SYMBIOS and TEKRAM NVRAM.
1811  */
1812 #if SYM_CONF_NVRAM_SUPPORT
1813 static void __devinit sym_get_nvram(struct sym_device *devp, struct sym_nvram *nvp)
1814 {
1815         devp->nvram = nvp;
1816         devp->device_id = devp->chip.device_id;
1817         nvp->type = 0;
1818
1819         /*
1820          *  Get access to chip IO registers
1821          */
1822 #ifndef SYM_CONF_IOMAPPED
1823         devp->s.mmio_va = ioremap(devp->s.base_c, 128);
1824         if (!devp->s.mmio_va)
1825                 return;
1826 #endif
1827
1828         sym_read_nvram(devp, nvp);
1829
1830         /*
1831          *  Release access to chip IO registers
1832          */
1833 #ifndef SYM_CONF_IOMAPPED
1834         iounmap(devp->s.mmio_va);
1835 #endif
1836 }
1837 #else
1838 static inline void sym_get_nvram(struct sym_device *devp, struct sym_nvram *nvp)
1839 {
1840 }
1841 #endif  /* SYM_CONF_NVRAM_SUPPORT */
1842
1843 /*
1844  *  Driver setup from the boot command line
1845  */
1846 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
1847
1848 static struct sym_driver_setup
1849         sym_driver_safe_setup __initdata = SYM_LINUX_DRIVER_SAFE_SETUP;
1850 #ifdef  MODULE
1851 char *sym53c8xx;        /* command line passed by insmod */
1852 MODULE_PARM(sym53c8xx, "s");
1853 #endif
1854
1855 #define OPT_MAX_TAG             1
1856 #define OPT_BURST_ORDER         2
1857 #define OPT_SCSI_LED            3
1858 #define OPT_SCSI_DIFF           4
1859 #define OPT_IRQ_MODE            5
1860 #define OPT_SCSI_BUS_CHECK      6
1861 #define OPT_HOST_ID             7
1862 #define OPT_REVERSE_PROBE       8
1863 #define OPT_VERBOSE             9
1864 #define OPT_DEBUG               10
1865 #define OPT_SETTLE_DELAY        11
1866 #define OPT_USE_NVRAM           12
1867 #define OPT_EXCLUDE             13
1868 #define OPT_SAFE_SETUP          14
1869
1870 static char setup_token[] __initdata =
1871         "tags:"         "burst:"
1872         "led:"          "diff:"
1873         "irqm:"         "buschk:"
1874         "hostid:"       "revprob:"
1875         "verb:"         "debug:"
1876         "settle:"       "nvram:"
1877         "excl:"         "safe:"
1878         ;
1879
1880 #ifdef MODULE
1881 #define ARG_SEP ' '
1882 #else
1883 #define ARG_SEP ','
1884 #endif
1885
1886 static int __init get_setup_token(char *p)
1887 {
1888         char *cur = setup_token;
1889         char *pc;
1890         int i = 0;
1891
1892         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
1893                 ++pc;
1894                 ++i;
1895                 if (!strncmp(p, cur, pc - cur))
1896                         return i;
1897                 cur = pc;
1898         }
1899         return 0;
1900 }
1901 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
1902
1903 int __init sym53c8xx_setup(char *str)
1904 {
1905 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
1906         char *cur = str;
1907         char *pc, *pv;
1908         unsigned long val;
1909         unsigned int i,  c;
1910         int xi = 0;
1911
1912         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
1913                 char *pe;
1914
1915                 val = 0;
1916                 pv = pc;
1917                 c = *++pv;
1918
1919                 if      (c == 'n')
1920                         val = 0;
1921                 else if (c == 'y')
1922                         val = 1;
1923                 else
1924                         val = (int) simple_strtoul(pv, &pe, 0);
1925
1926                 switch (get_setup_token(cur)) {
1927                 case OPT_MAX_TAG:
1928                         sym_driver_setup.max_tag = val;
1929                         if (!(pe && *pe == '/'))
1930                                 break;
1931                         i = 0;
1932                         while (*pe && *pe != ARG_SEP && 
1933                                 i < sizeof(sym_driver_setup.tag_ctrl)-1) {
1934                                 sym_driver_setup.tag_ctrl[i++] = *pe++;
1935                         }
1936                         sym_driver_setup.tag_ctrl[i] = '\0';
1937                         break;
1938                 case OPT_SAFE_SETUP:
1939                         memcpy(&sym_driver_setup, &sym_driver_safe_setup,
1940                                 sizeof(sym_driver_setup));
1941                         break;
1942                 case OPT_EXCLUDE:
1943                         if (xi < 8)
1944                                 sym_driver_setup.excludes[xi++] = val;
1945                         break;
1946
1947 #define __SIMPLE_OPTION(NAME, name) \
1948                 case OPT_ ## NAME :             \
1949                         sym_driver_setup.name = val;\
1950                         break;
1951
1952                 __SIMPLE_OPTION(BURST_ORDER, burst_order)
1953                 __SIMPLE_OPTION(SCSI_LED, scsi_led)
1954                 __SIMPLE_OPTION(SCSI_DIFF, scsi_diff)
1955                 __SIMPLE_OPTION(IRQ_MODE, irq_mode)
1956                 __SIMPLE_OPTION(SCSI_BUS_CHECK, scsi_bus_check)
1957                 __SIMPLE_OPTION(HOST_ID, host_id)
1958                 __SIMPLE_OPTION(REVERSE_PROBE, reverse_probe)
1959                 __SIMPLE_OPTION(VERBOSE, verbose)
1960                 __SIMPLE_OPTION(DEBUG, debug)
1961                 __SIMPLE_OPTION(SETTLE_DELAY, settle_delay)
1962                 __SIMPLE_OPTION(USE_NVRAM, use_nvram)
1963
1964 #undef __SIMPLE_OPTION
1965
1966                 default:
1967                         printk("sym53c8xx_setup: unexpected boot option '%.*s' ignored\n", (int)(pc-cur+1), cur);
1968                         break;
1969                 }
1970
1971                 if ((cur = strchr(cur, ARG_SEP)) != NULL)
1972                         ++cur;
1973         }
1974 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
1975         return 1;
1976 }
1977
1978 #ifndef MODULE
1979 __setup("sym53c8xx=", sym53c8xx_setup);
1980 #endif
1981
1982 /*
1983  *  Read and check the PCI configuration for any detected NCR 
1984  *  boards and save data for attaching after all boards have 
1985  *  been detected.
1986  */
1987 static int __devinit
1988 sym53c8xx_pci_init(struct pci_dev *pdev, struct sym_device *device)
1989 {
1990         struct sym_pci_chip *chip;
1991         u_long base, base_2; 
1992         u_long base_c, base_2_c, io_port; 
1993         int i;
1994         u_short device_id, status_reg;
1995         u_char revision;
1996
1997         /* Choose some short name for this device */
1998         sprintf(device->s.inst_name, "sym.%d.%d.%d", pdev->bus->number,
1999                         PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
2000
2001         device_id = pdev->device;
2002
2003         io_port = pdev->resource[0].start;
2004
2005         base_c = pdev->resource[1].start;
2006         i = pci_get_base_address(pdev, 1, &base);
2007
2008         base_2_c = pdev->resource[i].start;
2009         pci_get_base_address(pdev, i, &base_2);
2010
2011         base    &= PCI_BASE_ADDRESS_MEM_MASK;
2012         base_2  &= PCI_BASE_ADDRESS_MEM_MASK;
2013
2014         pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
2015
2016         /*
2017          *  If user excluded this chip, do not initialize it.
2018          */
2019         if (io_port) {
2020                 for (i = 0 ; i < 8 ; i++) {
2021                         if (sym_driver_setup.excludes[i] == io_port)
2022                                 return -1;
2023                 }
2024         }
2025
2026         /*
2027          *  Check if the chip is supported.
2028          */
2029         chip = sym_lookup_pci_chip_table(device_id, revision);
2030         if (!chip) {
2031                 printf_info("%s: device not supported\n", sym_name(device));
2032                 return -1;
2033         }
2034
2035         /*
2036          *  Check if the chip has been assigned resources we need.
2037          *  XXX: can this still happen with Linux 2.6's PCI layer?
2038          */
2039 #ifdef SYM_CONF_IOMAPPED
2040         if (!io_port) {
2041                 printf_info("%s: IO base address disabled.\n",
2042                             sym_name(device));
2043                 return -1;
2044         }
2045 #else
2046         if (!base) {
2047                 printf_info("%s: MMIO base address disabled.\n",
2048                             sym_name(device));
2049                 return -1;
2050         }
2051 #endif
2052
2053         /*
2054          *  Ignore Symbios chips controlled by various RAID controllers.
2055          *  These controllers set value 0x52414944 at RAM end - 16.
2056          */
2057 #if defined(__i386__)
2058         if (base_2_c) {
2059                 unsigned int ram_size, ram_val;
2060                 void *ram_ptr;
2061
2062                 if (chip->features & FE_RAM8K)
2063                         ram_size = 8192;
2064                 else
2065                         ram_size = 4096;
2066
2067                 ram_ptr = ioremap(base_2_c, ram_size);
2068                 if (ram_ptr) {
2069                         ram_val = readl_raw(ram_ptr + ram_size - 16);
2070                         iounmap(ram_ptr);
2071                         if (ram_val == 0x52414944) {
2072                                 printf_info("%s: not initializing, "
2073                                             "driven by RAID controller.\n",
2074                                             sym_name(device));
2075                                 return -1;
2076                         }
2077                 }
2078         }
2079 #endif /* i386 and PCI MEMORY accessible */
2080
2081         /*
2082          *  Copy the chip description to our device structure, 
2083          *  so we can make it match the actual device and options.
2084          */
2085         memcpy(&device->chip, chip, sizeof(device->chip));
2086         device->chip.revision_id = revision;
2087
2088         /*
2089          *  Some features are required to be enabled in order to 
2090          *  work around some chip problems. :) ;)
2091          *  (ITEM 12 of a DEL about the 896 I haven't yet).
2092          *  We must ensure the chip will use WRITE AND INVALIDATE.
2093          *  The revision number limit is for now arbitrary.
2094          */
2095         if (device_id == PCI_DEVICE_ID_NCR_53C896 && revision < 0x4) {
2096                 chip->features  |= (FE_WRIE | FE_CLSE);
2097         }
2098
2099         /* If the chip can do Memory Write Invalidate, enable it */
2100         if (chip->features & FE_WRIE) {
2101                 if (pci_set_mwi(pdev))
2102                         return -1;
2103         }
2104
2105         /*
2106          *  Work around for errant bit in 895A. The 66Mhz
2107          *  capable bit is set erroneously. Clear this bit.
2108          *  (Item 1 DEL 533)
2109          *
2110          *  Make sure Config space and Features agree.
2111          *
2112          *  Recall: writes are not normal to status register -
2113          *  write a 1 to clear and a 0 to leave unchanged.
2114          *  Can only reset bits.
2115          */
2116         pci_read_config_word(pdev, PCI_STATUS, &status_reg);
2117         if (chip->features & FE_66MHZ) {
2118                 if (!(status_reg & PCI_STATUS_66MHZ))
2119                         chip->features &= ~FE_66MHZ;
2120         } else {
2121                 if (status_reg & PCI_STATUS_66MHZ) {
2122                         status_reg = PCI_STATUS_66MHZ;
2123                         pci_write_config_word(pdev, PCI_STATUS, status_reg);
2124                         pci_read_config_word(pdev, PCI_STATUS, &status_reg);
2125                 }
2126         }
2127
2128         /*
2129          *  Initialise device structure with items required by sym_attach.
2130          */
2131         device->pdev            = pdev;
2132         device->s.base          = base;
2133         device->s.base_2        = base_2;
2134         device->s.base_c        = base_c;
2135         device->s.base_2_c      = base_2_c;
2136         device->s.io_port       = io_port;
2137         device->s.irq           = pdev->irq;
2138
2139         return 0;
2140 }
2141
2142 /*
2143  * The NCR PQS and PDS cards are constructed as a DEC bridge
2144  * behind which sits a proprietary NCR memory controller and
2145  * either four or two 53c875s as separate devices.  We can tell
2146  * if an 875 is part of a PQS/PDS or not since if it is, it will
2147  * be on the same bus as the memory controller.  In its usual
2148  * mode of operation, the 875s are slaved to the memory
2149  * controller for all transfers.  To operate with the Linux
2150  * driver, the memory controller is disabled and the 875s
2151  * freed to function independently.  The only wrinkle is that
2152  * the preset SCSI ID (which may be zero) must be read in from
2153  * a special configuration space register of the 875.
2154  */
2155 void sym_config_pqs(struct pci_dev *pdev, struct sym_device *sym_dev)
2156 {
2157         int slot;
2158
2159         for (slot = 0; slot < 256; slot++) {
2160                 u8 tmp;
2161                 struct pci_dev *memc = pci_get_slot(pdev->bus, slot);
2162
2163                 if (!memc || memc->vendor != 0x101a || memc->device == 0x0009) {
2164                         pci_dev_put(memc);
2165                         continue;
2166                 }
2167
2168                 /*
2169                  * We set these bits in the memory controller once per 875.
2170                  * This isn't a problem in practice.
2171                  */
2172
2173                 /* bit 1: allow individual 875 configuration */
2174                 pci_read_config_byte(memc, 0x44, &tmp);
2175                 tmp |= 0x2;
2176                 pci_write_config_byte(memc, 0x44, tmp);
2177
2178                 /* bit 2: drive individual 875 interrupts to the bus */
2179                 pci_read_config_byte(memc, 0x45, &tmp);
2180                 tmp |= 0x4;
2181                 pci_write_config_byte(memc, 0x45, tmp);
2182
2183                 pci_read_config_byte(pdev, 0x84, &tmp);
2184                 sym_dev->host_id = tmp;
2185
2186                 pci_dev_put(memc);
2187
2188                 break;
2189         }
2190 }
2191
2192 /*
2193  *  Called before unloading the module.
2194  *  Detach the host.
2195  *  We have to free resources and halt the NCR chip.
2196  */
2197 static int sym_detach(struct sym_hcb *np)
2198 {
2199         printk("%s: detaching ...\n", sym_name(np));
2200
2201         del_timer_sync(&np->s.timer);
2202
2203         /*
2204          * Reset NCR chip.
2205          * We should use sym_soft_reset(), but we don't want to do 
2206          * so, since we may not be safe if interrupts occur.
2207          */
2208         printk("%s: resetting chip\n", sym_name(np));
2209         OUTB (nc_istat, SRST);
2210         UDELAY (10);
2211         OUTB (nc_istat, 0);
2212
2213         sym_free_resources(np);
2214
2215         return 1;
2216 }
2217
2218 MODULE_LICENSE("Dual BSD/GPL");
2219 MODULE_VERSION(SYM_VERSION);
2220
2221 /*
2222  * Driver host template.
2223  */
2224 static struct scsi_host_template sym2_template = {
2225         .module                 = THIS_MODULE,
2226         .name                   = "sym53c8xx",
2227         .info                   = sym53c8xx_info, 
2228         .queuecommand           = sym53c8xx_queue_command,
2229         .slave_configure        = sym53c8xx_slave_configure,
2230         .eh_abort_handler       = sym53c8xx_eh_abort_handler,
2231         .eh_device_reset_handler = sym53c8xx_eh_device_reset_handler,
2232         .eh_bus_reset_handler   = sym53c8xx_eh_bus_reset_handler,
2233         .eh_host_reset_handler  = sym53c8xx_eh_host_reset_handler,
2234         .this_id                = 7,
2235         .use_clustering         = DISABLE_CLUSTERING,
2236 #ifdef SYM_LINUX_PROC_INFO_SUPPORT
2237         .proc_info              = sym53c8xx_proc_info,
2238         .proc_name              = NAME53C8XX,
2239 #endif
2240 };
2241
2242 static int attach_count;
2243
2244 static int __devinit sym2_probe(struct pci_dev *pdev,
2245                                 const struct pci_device_id *ent)
2246 {
2247         struct sym_device sym_dev;
2248         struct sym_nvram nvram;
2249         struct Scsi_Host *instance;
2250
2251         memset(&sym_dev, 0, sizeof(sym_dev));
2252         memset(&nvram, 0, sizeof(nvram));
2253
2254         if (pci_enable_device(pdev))
2255                 return -ENODEV;
2256
2257         pci_set_master(pdev);
2258
2259         if (pci_request_regions(pdev, NAME53C8XX))
2260                 goto disable;
2261
2262         sym_dev.host_id = SYM_SETUP_HOST_ID;
2263         if (sym53c8xx_pci_init(pdev, &sym_dev))
2264                 goto free;
2265
2266         sym_config_pqs(pdev, &sym_dev);
2267
2268         sym_get_nvram(&sym_dev, &nvram);
2269
2270         instance = sym_attach(&sym2_template, attach_count, &sym_dev);
2271         if (!instance)
2272                 goto free;
2273
2274         if (scsi_add_host(instance, &pdev->dev))
2275                 goto detach;
2276         scsi_scan_host(instance);
2277
2278         attach_count++;
2279
2280         return 0;
2281
2282  detach:
2283         sym_detach(pci_get_drvdata(pdev));
2284  free:
2285         pci_release_regions(pdev);
2286  disable:
2287         pci_disable_device(pdev);
2288         return -ENODEV;
2289 }
2290
2291 static void __devexit sym2_remove(struct pci_dev *pdev)
2292 {
2293         struct sym_hcb *np = pci_get_drvdata(pdev);
2294         struct Scsi_Host *host = np->s.host;
2295
2296         scsi_remove_host(host);
2297         scsi_host_put(host);
2298
2299         sym_detach(np);
2300
2301         pci_release_regions(pdev);
2302         pci_disable_device(pdev);
2303
2304         attach_count--;
2305 }
2306
2307 static void sym2_get_offset(struct scsi_device *sdev)
2308 {
2309         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2310         struct sym_tcb *tp = &np->target[sdev->id];
2311
2312         spi_offset(sdev) = tp->tinfo.curr.offset;
2313 }
2314
2315 static void sym2_set_offset(struct scsi_device *sdev, int offset)
2316 {
2317         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2318         struct sym_tcb *tp = &np->target[sdev->id];
2319
2320         tp->tinfo.goal.offset = offset;
2321 }
2322
2323
2324 static void sym2_get_period(struct scsi_device *sdev)
2325 {
2326         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2327         struct sym_tcb *tp = &np->target[sdev->id];
2328
2329         spi_period(sdev) = tp->tinfo.curr.period;
2330 }
2331
2332 static void sym2_set_period(struct scsi_device *sdev, int period)
2333 {
2334         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2335         struct sym_tcb *tp = &np->target[sdev->id];
2336
2337         /* have to have DT for these transfers */
2338         if (period <= np->minsync)
2339                 tp->tinfo.goal.options |= PPR_OPT_DT;
2340
2341         tp->tinfo.goal.period = period;
2342 }
2343
2344 static void sym2_get_width(struct scsi_device *sdev)
2345 {
2346         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2347         struct sym_tcb *tp = &np->target[sdev->id];
2348
2349         spi_width(sdev) = tp->tinfo.curr.width ? 1 : 0;
2350 }
2351
2352 static void sym2_set_width(struct scsi_device *sdev, int width)
2353 {
2354         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2355         struct sym_tcb *tp = &np->target[sdev->id];
2356
2357         /* It is illegal to have DT set on narrow transfers */
2358         if (width == 0)
2359                 tp->tinfo.goal.options &= ~PPR_OPT_DT;
2360
2361         tp->tinfo.goal.width = width;
2362 }
2363
2364 static void sym2_get_dt(struct scsi_device *sdev)
2365 {
2366         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2367         struct sym_tcb *tp = &np->target[sdev->id];
2368
2369         spi_dt(sdev) = (tp->tinfo.curr.options & PPR_OPT_DT) ? 1 : 0;
2370 }
2371
2372 static void sym2_set_dt(struct scsi_device *sdev, int dt)
2373 {
2374         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
2375         struct sym_tcb *tp = &np->target[sdev->id];
2376
2377         if (dt)
2378                 tp->tinfo.goal.options |= PPR_OPT_DT;
2379         else
2380                 tp->tinfo.goal.options &= ~PPR_OPT_DT;
2381 }
2382         
2383
2384 static struct spi_function_template sym2_transport_functions = {
2385         .set_offset     = sym2_set_offset,
2386         .get_offset     = sym2_get_offset,
2387         .show_offset    = 1,
2388         .set_period     = sym2_set_period,
2389         .get_period     = sym2_get_period,
2390         .show_period    = 1,
2391         .set_width      = sym2_set_width,
2392         .get_width      = sym2_get_width,
2393         .show_width     = 1,
2394         .get_dt         = sym2_get_dt,
2395         .set_dt         = sym2_set_dt,
2396         .show_dt        = 1,
2397 };
2398
2399 static struct pci_device_id sym2_id_table[] __devinitdata = {
2400         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C810,
2401           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2402         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C820,
2403           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, /* new */
2404         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C825,
2405           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2406         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C815,
2407           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2408         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C810AP,
2409           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, /* new */
2410         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C860,
2411           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2412         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C1510,
2413           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2414         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C896,
2415           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2416         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C895,
2417           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2418         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C885,
2419           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2420         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C875,
2421           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2422         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C1510,
2423           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, /* new */
2424         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C895A,
2425           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2426         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C875A,
2427           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2428         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C1010_33,
2429           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2430         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C1010_66,
2431           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2432         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C875J,
2433           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2434         { 0, }
2435 };
2436
2437 MODULE_DEVICE_TABLE(pci, sym2_id_table);
2438
2439 static struct pci_driver sym2_driver = {
2440         .name           = NAME53C8XX,
2441         .id_table       = sym2_id_table,
2442         .probe          = sym2_probe,
2443         .remove         = __devexit_p(sym2_remove),
2444 };
2445
2446 static int __init sym2_init(void)
2447 {
2448         sym2_transport_template = spi_attach_transport(&sym2_transport_functions);
2449         if (!sym2_transport_template)
2450                 return -ENODEV;
2451
2452         pci_register_driver(&sym2_driver);
2453         return 0;
2454 }
2455
2456 static void __exit sym2_exit(void)
2457 {
2458         pci_unregister_driver(&sym2_driver);
2459         spi_release_transport(sym2_transport_template);
2460 }
2461
2462 module_init(sym2_init);
2463 module_exit(sym2_exit);