This commit was manufactured by cvs2svn to create tag
[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         if (!spi_initial_dv(device->sdev_target))
1100                 spi_dv_device(device);
1101
1102         return 0;
1103 }
1104
1105 /*
1106  *  Linux entry point for info() function
1107  */
1108 static const char *sym53c8xx_info (struct Scsi_Host *host)
1109 {
1110         return sym_driver_name();
1111 }
1112
1113
1114 #ifdef SYM_LINUX_PROC_INFO_SUPPORT
1115 /*
1116  *  Proc file system stuff
1117  *
1118  *  A read operation returns adapter information.
1119  *  A write operation is a control command.
1120  *  The string is parsed in the driver code and the command is passed 
1121  *  to the sym_usercmd() function.
1122  */
1123
1124 #ifdef SYM_LINUX_USER_COMMAND_SUPPORT
1125
1126 struct  sym_usrcmd {
1127         u_long  target;
1128         u_long  lun;
1129         u_long  data;
1130         u_long  cmd;
1131 };
1132
1133 #define UC_SETSYNC      10
1134 #define UC_SETTAGS      11
1135 #define UC_SETDEBUG     12
1136 #define UC_SETWIDE      14
1137 #define UC_SETFLAG      15
1138 #define UC_SETVERBOSE   17
1139 #define UC_RESETDEV     18
1140 #define UC_CLEARDEV     19
1141
1142 static void sym_exec_user_command (struct sym_hcb *np, struct sym_usrcmd *uc)
1143 {
1144         struct sym_tcb *tp;
1145         int t, l;
1146
1147         switch (uc->cmd) {
1148         case 0: return;
1149
1150 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1151         case UC_SETDEBUG:
1152                 sym_debug_flags = uc->data;
1153                 break;
1154 #endif
1155         case UC_SETVERBOSE:
1156                 np->verbose = uc->data;
1157                 break;
1158         default:
1159                 /*
1160                  * We assume that other commands apply to targets.
1161                  * This should always be the case and avoid the below 
1162                  * 4 lines to be repeated 6 times.
1163                  */
1164                 for (t = 0; t < SYM_CONF_MAX_TARGET; t++) {
1165                         if (!((uc->target >> t) & 1))
1166                                 continue;
1167                         tp = &np->target[t];
1168
1169                         switch (uc->cmd) {
1170
1171                         case UC_SETSYNC:
1172                                 if (!uc->data || uc->data >= 255) {
1173                                         tp->tinfo.goal.options = 0;
1174                                         tp->tinfo.goal.offset  = 0;
1175                                         break;
1176                                 }
1177                                 if (uc->data <= 9 && np->minsync_dt) {
1178                                         if (uc->data < np->minsync_dt)
1179                                                 uc->data = np->minsync_dt;
1180                                         tp->tinfo.goal.options = PPR_OPT_DT;
1181                                         tp->tinfo.goal.width   = 1;
1182                                         tp->tinfo.goal.period = uc->data;
1183                                         tp->tinfo.goal.offset = np->maxoffs_dt;
1184                                 } else {
1185                                         if (uc->data < np->minsync)
1186                                                 uc->data = np->minsync;
1187                                         tp->tinfo.goal.options = 0;
1188                                         tp->tinfo.goal.period = uc->data;
1189                                         tp->tinfo.goal.offset = np->maxoffs;
1190                                 }
1191                                 break;
1192                         case UC_SETWIDE:
1193                                 tp->tinfo.goal.width = uc->data ? 1 : 0;
1194                                 break;
1195                         case UC_SETTAGS:
1196                                 for (l = 0; l < SYM_CONF_MAX_LUN; l++)
1197                                         sym_tune_dev_queuing(np, t,l, uc->data);
1198                                 break;
1199                         case UC_RESETDEV:
1200                                 tp->to_reset = 1;
1201                                 np->istat_sem = SEM;
1202                                 OUTB (nc_istat, SIGP|SEM);
1203                                 break;
1204                         case UC_CLEARDEV:
1205                                 for (l = 0; l < SYM_CONF_MAX_LUN; l++) {
1206                                         struct sym_lcb *lp = sym_lp(np, tp, l);
1207                                         if (lp) lp->to_clear = 1;
1208                                 }
1209                                 np->istat_sem = SEM;
1210                                 OUTB (nc_istat, SIGP|SEM);
1211                                 break;
1212                         case UC_SETFLAG:
1213                                 tp->usrflags = uc->data;
1214                                 break;
1215                         }
1216                 }
1217                 break;
1218         }
1219 }
1220
1221 #define digit_to_bin(c) ((c) - '0')
1222
1223 static int skip_spaces(char *ptr, int len)
1224 {
1225         int cnt, c;
1226
1227         for (cnt = len; cnt > 0 && (c = *ptr++) && isspace(c); cnt--);
1228
1229         return (len - cnt);
1230 }
1231
1232 static int get_int_arg(char *ptr, int len, u_long *pv)
1233 {
1234         int     cnt, c;
1235         u_long  v;
1236
1237         for (v = 0, cnt = len; cnt > 0 && (c = *ptr++) && isdigit(c); cnt--) {
1238                 v = (v * 10) + digit_to_bin(c);
1239         }
1240
1241         if (pv)
1242                 *pv = v;
1243
1244         return (len - cnt);
1245 }
1246
1247 static int is_keyword(char *ptr, int len, char *verb)
1248 {
1249         int verb_len = strlen(verb);
1250
1251         if (len >= verb_len && !memcmp(verb, ptr, verb_len))
1252                 return verb_len;
1253         else
1254                 return 0;
1255
1256 }
1257
1258 #define SKIP_SPACES(min_spaces)                                         \
1259         if ((arg_len = skip_spaces(ptr, len)) < (min_spaces))           \
1260                 return -EINVAL;                                         \
1261         ptr += arg_len; len -= arg_len;
1262
1263 #define GET_INT_ARG(v)                                                  \
1264         if (!(arg_len = get_int_arg(ptr, len, &(v))))                   \
1265                 return -EINVAL;                                         \
1266         ptr += arg_len; len -= arg_len;
1267
1268
1269 /*
1270  * Parse a control command
1271  */
1272
1273 static int sym_user_command(struct sym_hcb *np, char *buffer, int length)
1274 {
1275         char *ptr       = buffer;
1276         int len         = length;
1277         struct sym_usrcmd cmd, *uc = &cmd;
1278         int             arg_len;
1279         u_long          target;
1280
1281         bzero(uc, sizeof(*uc));
1282
1283         if (len > 0 && ptr[len-1] == '\n')
1284                 --len;
1285
1286         if      ((arg_len = is_keyword(ptr, len, "setsync")) != 0)
1287                 uc->cmd = UC_SETSYNC;
1288         else if ((arg_len = is_keyword(ptr, len, "settags")) != 0)
1289                 uc->cmd = UC_SETTAGS;
1290         else if ((arg_len = is_keyword(ptr, len, "setverbose")) != 0)
1291                 uc->cmd = UC_SETVERBOSE;
1292         else if ((arg_len = is_keyword(ptr, len, "setwide")) != 0)
1293                 uc->cmd = UC_SETWIDE;
1294 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1295         else if ((arg_len = is_keyword(ptr, len, "setdebug")) != 0)
1296                 uc->cmd = UC_SETDEBUG;
1297 #endif
1298         else if ((arg_len = is_keyword(ptr, len, "setflag")) != 0)
1299                 uc->cmd = UC_SETFLAG;
1300         else if ((arg_len = is_keyword(ptr, len, "resetdev")) != 0)
1301                 uc->cmd = UC_RESETDEV;
1302         else if ((arg_len = is_keyword(ptr, len, "cleardev")) != 0)
1303                 uc->cmd = UC_CLEARDEV;
1304         else
1305                 arg_len = 0;
1306
1307 #ifdef DEBUG_PROC_INFO
1308 printk("sym_user_command: arg_len=%d, cmd=%ld\n", arg_len, uc->cmd);
1309 #endif
1310
1311         if (!arg_len)
1312                 return -EINVAL;
1313         ptr += arg_len; len -= arg_len;
1314
1315         switch(uc->cmd) {
1316         case UC_SETSYNC:
1317         case UC_SETTAGS:
1318         case UC_SETWIDE:
1319         case UC_SETFLAG:
1320         case UC_RESETDEV:
1321         case UC_CLEARDEV:
1322                 SKIP_SPACES(1);
1323                 if ((arg_len = is_keyword(ptr, len, "all")) != 0) {
1324                         ptr += arg_len; len -= arg_len;
1325                         uc->target = ~0;
1326                 } else {
1327                         GET_INT_ARG(target);
1328                         uc->target = (1<<target);
1329 #ifdef DEBUG_PROC_INFO
1330 printk("sym_user_command: target=%ld\n", target);
1331 #endif
1332                 }
1333                 break;
1334         }
1335
1336         switch(uc->cmd) {
1337         case UC_SETVERBOSE:
1338         case UC_SETSYNC:
1339         case UC_SETTAGS:
1340         case UC_SETWIDE:
1341                 SKIP_SPACES(1);
1342                 GET_INT_ARG(uc->data);
1343 #ifdef DEBUG_PROC_INFO
1344 printk("sym_user_command: data=%ld\n", uc->data);
1345 #endif
1346                 break;
1347 #ifdef SYM_LINUX_DEBUG_CONTROL_SUPPORT
1348         case UC_SETDEBUG:
1349                 while (len > 0) {
1350                         SKIP_SPACES(1);
1351                         if      ((arg_len = is_keyword(ptr, len, "alloc")))
1352                                 uc->data |= DEBUG_ALLOC;
1353                         else if ((arg_len = is_keyword(ptr, len, "phase")))
1354                                 uc->data |= DEBUG_PHASE;
1355                         else if ((arg_len = is_keyword(ptr, len, "queue")))
1356                                 uc->data |= DEBUG_QUEUE;
1357                         else if ((arg_len = is_keyword(ptr, len, "result")))
1358                                 uc->data |= DEBUG_RESULT;
1359                         else if ((arg_len = is_keyword(ptr, len, "scatter")))
1360                                 uc->data |= DEBUG_SCATTER;
1361                         else if ((arg_len = is_keyword(ptr, len, "script")))
1362                                 uc->data |= DEBUG_SCRIPT;
1363                         else if ((arg_len = is_keyword(ptr, len, "tiny")))
1364                                 uc->data |= DEBUG_TINY;
1365                         else if ((arg_len = is_keyword(ptr, len, "timing")))
1366                                 uc->data |= DEBUG_TIMING;
1367                         else if ((arg_len = is_keyword(ptr, len, "nego")))
1368                                 uc->data |= DEBUG_NEGO;
1369                         else if ((arg_len = is_keyword(ptr, len, "tags")))
1370                                 uc->data |= DEBUG_TAGS;
1371                         else if ((arg_len = is_keyword(ptr, len, "pointer")))
1372                                 uc->data |= DEBUG_POINTER;
1373                         else
1374                                 return -EINVAL;
1375                         ptr += arg_len; len -= arg_len;
1376                 }
1377 #ifdef DEBUG_PROC_INFO
1378 printk("sym_user_command: data=%ld\n", uc->data);
1379 #endif
1380                 break;
1381 #endif /* SYM_LINUX_DEBUG_CONTROL_SUPPORT */
1382         case UC_SETFLAG:
1383                 while (len > 0) {
1384                         SKIP_SPACES(1);
1385                         if      ((arg_len = is_keyword(ptr, len, "no_disc")))
1386                                 uc->data &= ~SYM_DISC_ENABLED;
1387                         else
1388                                 return -EINVAL;
1389                         ptr += arg_len; len -= arg_len;
1390                 }
1391                 break;
1392         default:
1393                 break;
1394         }
1395
1396         if (len)
1397                 return -EINVAL;
1398         else {
1399                 unsigned long flags;
1400
1401                 spin_lock_irqsave(np->s.host->host_lock, flags);
1402                 sym_exec_user_command (np, uc);
1403                 spin_unlock_irqrestore(np->s.host->host_lock, flags);
1404         }
1405         return length;
1406 }
1407
1408 #endif  /* SYM_LINUX_USER_COMMAND_SUPPORT */
1409
1410
1411 #ifdef SYM_LINUX_USER_INFO_SUPPORT
1412 /*
1413  *  Informations through the proc file system.
1414  */
1415 struct info_str {
1416         char *buffer;
1417         int length;
1418         int offset;
1419         int pos;
1420 };
1421
1422 static void copy_mem_info(struct info_str *info, char *data, int len)
1423 {
1424         if (info->pos + len > info->length)
1425                 len = info->length - info->pos;
1426
1427         if (info->pos + len < info->offset) {
1428                 info->pos += len;
1429                 return;
1430         }
1431         if (info->pos < info->offset) {
1432                 data += (info->offset - info->pos);
1433                 len  -= (info->offset - info->pos);
1434         }
1435
1436         if (len > 0) {
1437                 memcpy(info->buffer + info->pos, data, len);
1438                 info->pos += len;
1439         }
1440 }
1441
1442 static int copy_info(struct info_str *info, char *fmt, ...)
1443 {
1444         va_list args;
1445         char buf[81];
1446         int len;
1447
1448         va_start(args, fmt);
1449         len = vsprintf(buf, fmt, args);
1450         va_end(args);
1451
1452         copy_mem_info(info, buf, len);
1453         return len;
1454 }
1455
1456 /*
1457  *  Copy formatted information into the input buffer.
1458  */
1459 static int sym_host_info(struct sym_hcb *np, char *ptr, off_t offset, int len)
1460 {
1461         struct info_str info;
1462
1463         info.buffer     = ptr;
1464         info.length     = len;
1465         info.offset     = offset;
1466         info.pos        = 0;
1467
1468         copy_info(&info, "Chip " NAME53C "%s, device id 0x%x, "
1469                          "revision id 0x%x\n",
1470                          np->s.chip_name, np->device_id, np->revision_id);
1471         copy_info(&info, "At PCI address %s, "
1472 #ifdef __sparc__
1473                 "IRQ %s\n",
1474 #else
1475                 "IRQ %d\n",
1476 #endif
1477                 pci_name(np->s.device),
1478 #ifdef __sparc__
1479                 __irq_itoa(np->s.irq));
1480 #else
1481                 (int) np->s.irq);
1482 #endif
1483         copy_info(&info, "Min. period factor %d, %s SCSI BUS%s\n",
1484                          (int) (np->minsync_dt ? np->minsync_dt : np->minsync),
1485                          np->maxwide ? "Wide" : "Narrow",
1486                          np->minsync_dt ? ", DT capable" : "");
1487
1488         copy_info(&info, "Max. started commands %d, "
1489                          "max. commands per LUN %d\n",
1490                          SYM_CONF_MAX_START, SYM_CONF_MAX_TAG);
1491
1492         return info.pos > info.offset? info.pos - info.offset : 0;
1493 }
1494 #endif /* SYM_LINUX_USER_INFO_SUPPORT */
1495
1496 /*
1497  *  Entry point of the scsi proc fs of the driver.
1498  *  - func = 0 means read  (returns adapter infos)
1499  *  - func = 1 means write (not yet merget from sym53c8xx)
1500  */
1501 static int sym53c8xx_proc_info(struct Scsi_Host *host, char *buffer,
1502                         char **start, off_t offset, int length, int func)
1503 {
1504         struct host_data *host_data;
1505         struct sym_hcb *np = NULL;
1506         int retv;
1507
1508         host_data = (struct host_data *) host->hostdata;
1509         np = host_data->ncb;
1510         if (!np)
1511                 return -EINVAL;
1512
1513         if (func) {
1514 #ifdef  SYM_LINUX_USER_COMMAND_SUPPORT
1515                 retv = sym_user_command(np, buffer, length);
1516 #else
1517                 retv = -EINVAL;
1518 #endif
1519         } else {
1520                 if (start)
1521                         *start = buffer;
1522 #ifdef SYM_LINUX_USER_INFO_SUPPORT
1523                 retv = sym_host_info(np, buffer, offset, length);
1524 #else
1525                 retv = -EINVAL;
1526 #endif
1527         }
1528
1529         return retv;
1530 }
1531 #endif /* SYM_LINUX_PROC_INFO_SUPPORT */
1532
1533 /*
1534  *      Free controller resources.
1535  */
1536 static void sym_free_resources(struct sym_hcb *np)
1537 {
1538         /*
1539          *  Free O/S specific resources.
1540          */
1541         if (np->s.irq)
1542                 free_irq(np->s.irq, np);
1543 #ifndef SYM_CONF_IOMAPPED
1544         if (np->s.mmio_va)
1545                 iounmap(np->s.mmio_va);
1546 #endif
1547         if (np->s.ram_va)
1548                 iounmap(np->s.ram_va);
1549         /*
1550          *  Free O/S independent resources.
1551          */
1552         sym_hcb_free(np);
1553
1554         sym_mfree_dma(np, sizeof(*np), "HCB");
1555 }
1556
1557 /*
1558  *  Ask/tell the system about DMA addressing.
1559  */
1560 static int sym_setup_bus_dma_mask(struct sym_hcb *np)
1561 {
1562 #if   SYM_CONF_DMA_ADDRESSING_MODE == 0
1563         if (pci_set_dma_mask(np->s.device, 0xffffffffUL))
1564                 goto out_err32;
1565 #else
1566 #if   SYM_CONF_DMA_ADDRESSING_MODE == 1
1567 #define PciDmaMask      0xffffffffffULL
1568 #elif SYM_CONF_DMA_ADDRESSING_MODE == 2
1569 #define PciDmaMask      0xffffffffffffffffULL
1570 #endif
1571         if (np->features & FE_DAC) {
1572                 if (!pci_set_dma_mask(np->s.device, PciDmaMask)) {
1573                         np->use_dac = 1;
1574                         printf_info("%s: using 64 bit DMA addressing\n",
1575                                         sym_name(np));
1576                 } else {
1577                         if (pci_set_dma_mask(np->s.device, 0xffffffffUL))
1578                                 goto out_err32;
1579                 }
1580         }
1581 #undef  PciDmaMask
1582 #endif
1583         return 0;
1584
1585 out_err32:
1586         printf_warning("%s: 32 BIT DMA ADDRESSING NOT SUPPORTED\n",
1587                         sym_name(np));
1588         return -1;
1589 }
1590
1591 /*
1592  *  Host attach and initialisations.
1593  *
1594  *  Allocate host data and ncb structure.
1595  *  Remap MMIO region.
1596  *  Do chip initialization.
1597  *  If all is OK, install interrupt handling and
1598  *  start the timer daemon.
1599  */
1600 static struct Scsi_Host * __devinit sym_attach(struct scsi_host_template *tpnt,
1601                 int unit, struct sym_device *dev)
1602 {
1603         struct host_data *host_data;
1604         struct sym_hcb *np = NULL;
1605         struct Scsi_Host *instance = NULL;
1606         unsigned long flags;
1607         struct sym_fw *fw;
1608
1609         printk(KERN_INFO
1610                 "sym%d: <%s> rev 0x%x at pci %s "
1611 #ifdef __sparc__
1612                 "irq %s\n",
1613 #else
1614                 "irq %d\n",
1615 #endif
1616                 unit, dev->chip.name, dev->chip.revision_id,
1617                 pci_name(dev->pdev),
1618 #ifdef __sparc__
1619                 __irq_itoa(dev->s.irq));
1620 #else
1621                 dev->s.irq);
1622 #endif
1623
1624         /*
1625          *  Get the firmware for this chip.
1626          */
1627         fw = sym_find_firmware(&dev->chip);
1628         if (!fw)
1629                 goto attach_failed;
1630
1631         /*
1632          *      Allocate host_data structure
1633          */
1634         instance = scsi_host_alloc(tpnt, sizeof(*host_data));
1635         if (!instance)
1636                 goto attach_failed;
1637         host_data = (struct host_data *) instance->hostdata;
1638
1639         /*
1640          *  Allocate immediately the host control block, 
1641          *  since we are only expecting to succeed. :)
1642          *  We keep track in the HCB of all the resources that 
1643          *  are to be released on error.
1644          */
1645         np = __sym_calloc_dma(dev->pdev, sizeof(*np), "HCB");
1646         if (!np)
1647                 goto attach_failed;
1648         np->s.device = dev->pdev;
1649         np->bus_dmat = dev->pdev; /* Result in 1 DMA pool per HBA */
1650         host_data->ncb = np;
1651         np->s.host = instance;
1652
1653         pci_set_drvdata(dev->pdev, np);
1654
1655         /*
1656          *  Copy some useful infos to the HCB.
1657          */
1658         np->hcb_ba      = vtobus(np);
1659         np->verbose     = sym_driver_setup.verbose;
1660         np->s.device    = dev->pdev;
1661         np->s.unit      = unit;
1662         np->device_id   = dev->chip.device_id;
1663         np->revision_id = dev->chip.revision_id;
1664         np->features    = dev->chip.features;
1665         np->clock_divn  = dev->chip.nr_divisor;
1666         np->maxoffs     = dev->chip.offset_max;
1667         np->maxburst    = dev->chip.burst_max;
1668         np->myaddr      = dev->host_id;
1669
1670         /*
1671          *  Edit its name.
1672          */
1673         strlcpy(np->s.chip_name, dev->chip.name, sizeof(np->s.chip_name));
1674         sprintf(np->s.inst_name, "sym%d", np->s.unit);
1675
1676         /*
1677          *  Ask/tell the system about DMA addressing.
1678          */
1679         if (sym_setup_bus_dma_mask(np))
1680                 goto attach_failed;
1681
1682         /*
1683          *  Try to map the controller chip to
1684          *  virtual and physical memory.
1685          */
1686         np->mmio_ba     = (u32)dev->s.base;
1687         np->s.io_ws     = (np->features & FE_IO256)? 256 : 128;
1688
1689 #ifndef SYM_CONF_IOMAPPED
1690         np->s.mmio_va = ioremap(dev->s.base_c, np->s.io_ws);
1691         if (!np->s.mmio_va) {
1692                 printf_err("%s: can't map PCI MMIO region\n", sym_name(np));
1693                 goto attach_failed;
1694         } else if (sym_verbose > 1)
1695                 printf_info("%s: using memory mapped IO\n", sym_name(np));
1696 #endif /* !defined SYM_CONF_IOMAPPED */
1697
1698         np->s.io_port = dev->s.io_port;
1699
1700         /*
1701          *  Map on-chip RAM if present and supported.
1702          */
1703         if (!(np->features & FE_RAM))
1704                 dev->s.base_2 = 0;
1705         if (dev->s.base_2) {
1706                 np->ram_ba = (u32)dev->s.base_2;
1707                 if (np->features & FE_RAM8K)
1708                         np->ram_ws = 8192;
1709                 else
1710                         np->ram_ws = 4096;
1711                 np->s.ram_va = ioremap(dev->s.base_2_c, np->ram_ws);
1712                 if (!np->s.ram_va) {
1713                         printf_err("%s: can't map PCI MEMORY region\n",
1714                                 sym_name(np));
1715                         goto attach_failed;
1716                 }
1717         }
1718
1719         /*
1720          *  Perform O/S independent stuff.
1721          */
1722         if (sym_hcb_attach(np, fw, dev->nvram))
1723                 goto attach_failed;
1724
1725
1726         /*
1727          *  Install the interrupt handler.
1728          *  If we synchonize the C code with SCRIPTS on interrupt, 
1729          *  we donnot want to share the INTR line at all.
1730          */
1731         if (request_irq(dev->s.irq, sym53c8xx_intr, SA_SHIRQ,
1732                         NAME53C8XX, np)) {
1733                 printf_err("%s: request irq %d failure\n",
1734                         sym_name(np), dev->s.irq);
1735                 goto attach_failed;
1736         }
1737         np->s.irq = dev->s.irq;
1738
1739         /*
1740          *  After SCSI devices have been opened, we cannot
1741          *  reset the bus safely, so we do it here.
1742          */
1743         spin_lock_irqsave(instance->host_lock, flags);
1744         if (sym_reset_scsi_bus(np, 0))
1745                 goto reset_failed;
1746
1747         /*
1748          *  Initialize some queue headers.
1749          */
1750         sym_que_init(&np->s.wait_cmdq);
1751         sym_que_init(&np->s.busy_cmdq);
1752
1753         /*
1754          *  Start the SCRIPTS.
1755          */
1756         sym_start_up (np, 1);
1757
1758         /*
1759          *  Start the timer daemon
1760          */
1761         init_timer(&np->s.timer);
1762         np->s.timer.data     = (unsigned long) np;
1763         np->s.timer.function = sym53c8xx_timer;
1764         np->s.lasttime=0;
1765         sym_timer (np);
1766
1767         /*
1768          *  Fill Linux host instance structure
1769          *  and return success.
1770          */
1771         instance->max_channel   = 0;
1772         instance->this_id       = np->myaddr;
1773         instance->max_id        = np->maxwide ? 16 : 8;
1774         instance->max_lun       = SYM_CONF_MAX_LUN;
1775 #ifndef SYM_CONF_IOMAPPED
1776         instance->base          = (unsigned long) np->s.mmio_va;
1777 #endif
1778         instance->irq           = np->s.irq;
1779         instance->unique_id     = np->s.io_port;
1780         instance->io_port       = np->s.io_port;
1781         instance->n_io_port     = np->s.io_ws;
1782         instance->dma_channel   = 0;
1783         instance->cmd_per_lun   = SYM_CONF_MAX_TAG;
1784         instance->can_queue     = (SYM_CONF_MAX_START-2);
1785         instance->sg_tablesize  = SYM_CONF_MAX_SG;
1786         instance->max_cmd_len   = 16;
1787         BUG_ON(sym2_transport_template == NULL);
1788         instance->transportt    = sym2_transport_template;
1789
1790         spin_unlock_irqrestore(instance->host_lock, flags);
1791
1792         return instance;
1793
1794  reset_failed:
1795         printf_err("%s: FATAL ERROR: CHECK SCSI BUS - CABLES, "
1796                    "TERMINATION, DEVICE POWER etc.!\n", sym_name(np));
1797         spin_unlock_irqrestore(instance->host_lock, flags);
1798  attach_failed:
1799         if (!instance)
1800                 return NULL;
1801         printf_info("%s: giving up ...\n", sym_name(np));
1802         if (np)
1803                 sym_free_resources(np);
1804         scsi_host_put(instance);
1805
1806         return NULL;
1807  }
1808
1809
1810 /*
1811  *    Detect and try to read SYMBIOS and TEKRAM NVRAM.
1812  */
1813 #if SYM_CONF_NVRAM_SUPPORT
1814 static void __devinit sym_get_nvram(struct sym_device *devp, struct sym_nvram *nvp)
1815 {
1816         devp->nvram = nvp;
1817         devp->device_id = devp->chip.device_id;
1818         nvp->type = 0;
1819
1820         /*
1821          *  Get access to chip IO registers
1822          */
1823 #ifndef SYM_CONF_IOMAPPED
1824         devp->s.mmio_va = ioremap(devp->s.base_c, 128);
1825         if (!devp->s.mmio_va)
1826                 return;
1827 #endif
1828
1829         sym_read_nvram(devp, nvp);
1830
1831         /*
1832          *  Release access to chip IO registers
1833          */
1834 #ifndef SYM_CONF_IOMAPPED
1835         iounmap(devp->s.mmio_va);
1836 #endif
1837 }
1838 #else
1839 static inline void sym_get_nvram(struct sym_device *devp, struct sym_nvram *nvp)
1840 {
1841 }
1842 #endif  /* SYM_CONF_NVRAM_SUPPORT */
1843
1844 /*
1845  *  Driver setup from the boot command line
1846  */
1847 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
1848
1849 static struct sym_driver_setup
1850         sym_driver_safe_setup __initdata = SYM_LINUX_DRIVER_SAFE_SETUP;
1851 #ifdef  MODULE
1852 char *sym53c8xx;        /* command line passed by insmod */
1853 MODULE_PARM(sym53c8xx, "s");
1854 #endif
1855
1856 #define OPT_MAX_TAG             1
1857 #define OPT_BURST_ORDER         2
1858 #define OPT_SCSI_LED            3
1859 #define OPT_SCSI_DIFF           4
1860 #define OPT_IRQ_MODE            5
1861 #define OPT_SCSI_BUS_CHECK      6
1862 #define OPT_HOST_ID             7
1863 #define OPT_REVERSE_PROBE       8
1864 #define OPT_VERBOSE             9
1865 #define OPT_DEBUG               10
1866 #define OPT_SETTLE_DELAY        11
1867 #define OPT_USE_NVRAM           12
1868 #define OPT_EXCLUDE             13
1869 #define OPT_SAFE_SETUP          14
1870
1871 static char setup_token[] __initdata =
1872         "tags:"         "burst:"
1873         "led:"          "diff:"
1874         "irqm:"         "buschk:"
1875         "hostid:"       "revprob:"
1876         "verb:"         "debug:"
1877         "settle:"       "nvram:"
1878         "excl:"         "safe:"
1879         ;
1880
1881 #ifdef MODULE
1882 #define ARG_SEP ' '
1883 #else
1884 #define ARG_SEP ','
1885 #endif
1886
1887 static int __init get_setup_token(char *p)
1888 {
1889         char *cur = setup_token;
1890         char *pc;
1891         int i = 0;
1892
1893         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
1894                 ++pc;
1895                 ++i;
1896                 if (!strncmp(p, cur, pc - cur))
1897                         return i;
1898                 cur = pc;
1899         }
1900         return 0;
1901 }
1902 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
1903
1904 int __init sym53c8xx_setup(char *str)
1905 {
1906 #ifdef  SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT
1907         char *cur = str;
1908         char *pc, *pv;
1909         unsigned long val;
1910         unsigned int i,  c;
1911         int xi = 0;
1912
1913         while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
1914                 char *pe;
1915
1916                 val = 0;
1917                 pv = pc;
1918                 c = *++pv;
1919
1920                 if      (c == 'n')
1921                         val = 0;
1922                 else if (c == 'y')
1923                         val = 1;
1924                 else
1925                         val = (int) simple_strtoul(pv, &pe, 0);
1926
1927                 switch (get_setup_token(cur)) {
1928                 case OPT_MAX_TAG:
1929                         sym_driver_setup.max_tag = val;
1930                         if (!(pe && *pe == '/'))
1931                                 break;
1932                         i = 0;
1933                         while (*pe && *pe != ARG_SEP && 
1934                                 i < sizeof(sym_driver_setup.tag_ctrl)-1) {
1935                                 sym_driver_setup.tag_ctrl[i++] = *pe++;
1936                         }
1937                         sym_driver_setup.tag_ctrl[i] = '\0';
1938                         break;
1939                 case OPT_SAFE_SETUP:
1940                         memcpy(&sym_driver_setup, &sym_driver_safe_setup,
1941                                 sizeof(sym_driver_setup));
1942                         break;
1943                 case OPT_EXCLUDE:
1944                         if (xi < 8)
1945                                 sym_driver_setup.excludes[xi++] = val;
1946                         break;
1947
1948 #define __SIMPLE_OPTION(NAME, name) \
1949                 case OPT_ ## NAME :             \
1950                         sym_driver_setup.name = val;\
1951                         break;
1952
1953                 __SIMPLE_OPTION(BURST_ORDER, burst_order)
1954                 __SIMPLE_OPTION(SCSI_LED, scsi_led)
1955                 __SIMPLE_OPTION(SCSI_DIFF, scsi_diff)
1956                 __SIMPLE_OPTION(IRQ_MODE, irq_mode)
1957                 __SIMPLE_OPTION(SCSI_BUS_CHECK, scsi_bus_check)
1958                 __SIMPLE_OPTION(HOST_ID, host_id)
1959                 __SIMPLE_OPTION(REVERSE_PROBE, reverse_probe)
1960                 __SIMPLE_OPTION(VERBOSE, verbose)
1961                 __SIMPLE_OPTION(DEBUG, debug)
1962                 __SIMPLE_OPTION(SETTLE_DELAY, settle_delay)
1963                 __SIMPLE_OPTION(USE_NVRAM, use_nvram)
1964
1965 #undef __SIMPLE_OPTION
1966
1967                 default:
1968                         printk("sym53c8xx_setup: unexpected boot option '%.*s' ignored\n", (int)(pc-cur+1), cur);
1969                         break;
1970                 }
1971
1972                 if ((cur = strchr(cur, ARG_SEP)) != NULL)
1973                         ++cur;
1974         }
1975 #endif  /* SYM_LINUX_BOOT_COMMAND_LINE_SUPPORT */
1976         return 1;
1977 }
1978
1979 #ifndef MODULE
1980 __setup("sym53c8xx=", sym53c8xx_setup);
1981 #endif
1982
1983 /*
1984  *  Read and check the PCI configuration for any detected NCR 
1985  *  boards and save data for attaching after all boards have 
1986  *  been detected.
1987  */
1988 static int __devinit
1989 sym53c8xx_pci_init(struct pci_dev *pdev, struct sym_device *device)
1990 {
1991         struct sym_pci_chip *chip;
1992         u_long base, base_2; 
1993         u_long base_c, base_2_c, io_port; 
1994         int i;
1995         u_short device_id, status_reg;
1996         u_char revision;
1997
1998         /* Choose some short name for this device */
1999         sprintf(device->s.inst_name, "sym.%d.%d.%d", pdev->bus->number,
2000                         PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
2001
2002         device_id = pdev->device;
2003
2004         io_port = pdev->resource[0].start;
2005
2006         base_c = pdev->resource[1].start;
2007         i = pci_get_base_address(pdev, 1, &base);
2008
2009         base_2_c = pdev->resource[i].start;
2010         pci_get_base_address(pdev, i, &base_2);
2011
2012         base    &= PCI_BASE_ADDRESS_MEM_MASK;
2013         base_2  &= PCI_BASE_ADDRESS_MEM_MASK;
2014
2015         pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
2016
2017         /*
2018          *  If user excluded this chip, do not initialize it.
2019          */
2020         if (io_port) {
2021                 for (i = 0 ; i < 8 ; i++) {
2022                         if (sym_driver_setup.excludes[i] == io_port)
2023                                 return -1;
2024                 }
2025         }
2026
2027         /*
2028          *  Check if the chip is supported.
2029          */
2030         chip = sym_lookup_pci_chip_table(device_id, revision);
2031         if (!chip) {
2032                 printf_info("%s: device not supported\n", sym_name(device));
2033                 return -1;
2034         }
2035
2036         /*
2037          *  Check if the chip has been assigned resources we need.
2038          *  XXX: can this still happen with Linux 2.6's PCI layer?
2039          */
2040 #ifdef SYM_CONF_IOMAPPED
2041         if (!io_port) {
2042                 printf_info("%s: IO base address disabled.\n",
2043                             sym_name(device));
2044                 return -1;
2045         }
2046 #else
2047         if (!base) {
2048                 printf_info("%s: MMIO base address disabled.\n",
2049                             sym_name(device));
2050                 return -1;
2051         }
2052 #endif
2053
2054         /*
2055          *  Ignore Symbios chips controlled by various RAID controllers.
2056          *  These controllers set value 0x52414944 at RAM end - 16.
2057          */
2058 #if defined(__i386__)
2059         if (base_2_c) {
2060                 unsigned int ram_size, ram_val;
2061                 void *ram_ptr;
2062
2063                 if (chip->features & FE_RAM8K)
2064                         ram_size = 8192;
2065                 else
2066                         ram_size = 4096;
2067
2068                 ram_ptr = ioremap(base_2_c, ram_size);
2069                 if (ram_ptr) {
2070                         ram_val = readl_raw(ram_ptr + ram_size - 16);
2071                         iounmap(ram_ptr);
2072                         if (ram_val == 0x52414944) {
2073                                 printf_info("%s: not initializing, "
2074                                             "driven by RAID controller.\n",
2075                                             sym_name(device));
2076                                 return -1;
2077                         }
2078                 }
2079         }
2080 #endif /* i386 and PCI MEMORY accessible */
2081
2082         /*
2083          *  Copy the chip description to our device structure, 
2084          *  so we can make it match the actual device and options.
2085          */
2086         memcpy(&device->chip, chip, sizeof(device->chip));
2087         device->chip.revision_id = revision;
2088
2089         /*
2090          *  Some features are required to be enabled in order to 
2091          *  work around some chip problems. :) ;)
2092          *  (ITEM 12 of a DEL about the 896 I haven't yet).
2093          *  We must ensure the chip will use WRITE AND INVALIDATE.
2094          *  The revision number limit is for now arbitrary.
2095          */
2096         if (device_id == PCI_DEVICE_ID_NCR_53C896 && revision < 0x4) {
2097                 chip->features  |= (FE_WRIE | FE_CLSE);
2098         }
2099
2100         /* If the chip can do Memory Write Invalidate, enable it */
2101         if (chip->features & FE_WRIE) {
2102                 if (pci_set_mwi(pdev))
2103                         return -1;
2104         }
2105
2106         /*
2107          *  Work around for errant bit in 895A. The 66Mhz
2108          *  capable bit is set erroneously. Clear this bit.
2109          *  (Item 1 DEL 533)
2110          *
2111          *  Make sure Config space and Features agree.
2112          *
2113          *  Recall: writes are not normal to status register -
2114          *  write a 1 to clear and a 0 to leave unchanged.
2115          *  Can only reset bits.
2116          */
2117         pci_read_config_word(pdev, PCI_STATUS, &status_reg);
2118         if (chip->features & FE_66MHZ) {
2119                 if (!(status_reg & PCI_STATUS_66MHZ))
2120                         chip->features &= ~FE_66MHZ;
2121         } else {
2122                 if (status_reg & PCI_STATUS_66MHZ) {
2123                         status_reg = PCI_STATUS_66MHZ;
2124                         pci_write_config_word(pdev, PCI_STATUS, status_reg);
2125                         pci_read_config_word(pdev, PCI_STATUS, &status_reg);
2126                 }
2127         }
2128
2129         /*
2130          *  Initialise device structure with items required by sym_attach.
2131          */
2132         device->pdev            = pdev;
2133         device->s.base          = base;
2134         device->s.base_2        = base_2;
2135         device->s.base_c        = base_c;
2136         device->s.base_2_c      = base_2_c;
2137         device->s.io_port       = io_port;
2138         device->s.irq           = pdev->irq;
2139
2140         return 0;
2141 }
2142
2143 /*
2144  * The NCR PQS and PDS cards are constructed as a DEC bridge
2145  * behind which sits a proprietary NCR memory controller and
2146  * either four or two 53c875s as separate devices.  We can tell
2147  * if an 875 is part of a PQS/PDS or not since if it is, it will
2148  * be on the same bus as the memory controller.  In its usual
2149  * mode of operation, the 875s are slaved to the memory
2150  * controller for all transfers.  To operate with the Linux
2151  * driver, the memory controller is disabled and the 875s
2152  * freed to function independently.  The only wrinkle is that
2153  * the preset SCSI ID (which may be zero) must be read in from
2154  * a special configuration space register of the 875.
2155  */
2156 void sym_config_pqs(struct pci_dev *pdev, struct sym_device *sym_dev)
2157 {
2158         int slot;
2159
2160         for (slot = 0; slot < 256; slot++) {
2161                 u8 tmp;
2162                 struct pci_dev *memc = pci_get_slot(pdev->bus, slot);
2163
2164                 if (!memc || memc->vendor != 0x101a || memc->device == 0x0009) {
2165                         pci_dev_put(memc);
2166                         continue;
2167                 }
2168
2169                 /*
2170                  * We set these bits in the memory controller once per 875.
2171                  * This isn't a problem in practice.
2172                  */
2173
2174                 /* bit 1: allow individual 875 configuration */
2175                 pci_read_config_byte(memc, 0x44, &tmp);
2176                 tmp |= 0x2;
2177                 pci_write_config_byte(memc, 0x44, tmp);
2178
2179                 /* bit 2: drive individual 875 interrupts to the bus */
2180                 pci_read_config_byte(memc, 0x45, &tmp);
2181                 tmp |= 0x4;
2182                 pci_write_config_byte(memc, 0x45, tmp);
2183
2184                 pci_read_config_byte(pdev, 0x84, &tmp);
2185                 sym_dev->host_id = tmp;
2186
2187                 pci_dev_put(memc);
2188
2189                 break;
2190         }
2191 }
2192
2193 /*
2194  *  Called before unloading the module.
2195  *  Detach the host.
2196  *  We have to free resources and halt the NCR chip.
2197  */
2198 static int sym_detach(struct sym_hcb *np)
2199 {
2200         printk("%s: detaching ...\n", sym_name(np));
2201
2202         del_timer_sync(&np->s.timer);
2203
2204         /*
2205          * Reset NCR chip.
2206          * We should use sym_soft_reset(), but we don't want to do 
2207          * so, since we may not be safe if interrupts occur.
2208          */
2209         printk("%s: resetting chip\n", sym_name(np));
2210         OUTB (nc_istat, SRST);
2211         UDELAY (10);
2212         OUTB (nc_istat, 0);
2213
2214         sym_free_resources(np);
2215
2216         return 1;
2217 }
2218
2219 MODULE_LICENSE("Dual BSD/GPL");
2220 MODULE_VERSION(SYM_VERSION);
2221
2222 /*
2223  * Driver host template.
2224  */
2225 static struct scsi_host_template sym2_template = {
2226         .module                 = THIS_MODULE,
2227         .name                   = "sym53c8xx",
2228         .info                   = sym53c8xx_info, 
2229         .queuecommand           = sym53c8xx_queue_command,
2230         .slave_configure        = sym53c8xx_slave_configure,
2231         .eh_abort_handler       = sym53c8xx_eh_abort_handler,
2232         .eh_device_reset_handler = sym53c8xx_eh_device_reset_handler,
2233         .eh_bus_reset_handler   = sym53c8xx_eh_bus_reset_handler,
2234         .eh_host_reset_handler  = sym53c8xx_eh_host_reset_handler,
2235         .this_id                = 7,
2236         .use_clustering         = DISABLE_CLUSTERING,
2237 #ifdef SYM_LINUX_PROC_INFO_SUPPORT
2238         .proc_info              = sym53c8xx_proc_info,
2239         .proc_name              = NAME53C8XX,
2240 #endif
2241 };
2242
2243 static int attach_count;
2244
2245 static int __devinit sym2_probe(struct pci_dev *pdev,
2246                                 const struct pci_device_id *ent)
2247 {
2248         struct sym_device sym_dev;
2249         struct sym_nvram nvram;
2250         struct Scsi_Host *instance;
2251
2252         memset(&sym_dev, 0, sizeof(sym_dev));
2253         memset(&nvram, 0, sizeof(nvram));
2254
2255         if (pci_enable_device(pdev))
2256                 return -ENODEV;
2257
2258         pci_set_master(pdev);
2259
2260         if (pci_request_regions(pdev, NAME53C8XX))
2261                 goto disable;
2262
2263         sym_dev.host_id = SYM_SETUP_HOST_ID;
2264         if (sym53c8xx_pci_init(pdev, &sym_dev))
2265                 goto free;
2266
2267         sym_config_pqs(pdev, &sym_dev);
2268
2269         sym_get_nvram(&sym_dev, &nvram);
2270
2271         instance = sym_attach(&sym2_template, attach_count, &sym_dev);
2272         if (!instance)
2273                 goto free;
2274
2275         if (scsi_add_host(instance, &pdev->dev))
2276                 goto detach;
2277         scsi_scan_host(instance);
2278
2279         attach_count++;
2280
2281         return 0;
2282
2283  detach:
2284         sym_detach(pci_get_drvdata(pdev));
2285  free:
2286         pci_release_regions(pdev);
2287  disable:
2288         pci_disable_device(pdev);
2289         return -ENODEV;
2290 }
2291
2292 static void __devexit sym2_remove(struct pci_dev *pdev)
2293 {
2294         struct sym_hcb *np = pci_get_drvdata(pdev);
2295         struct Scsi_Host *host = np->s.host;
2296
2297         scsi_remove_host(host);
2298         scsi_host_put(host);
2299
2300         sym_detach(np);
2301
2302         pci_release_regions(pdev);
2303         pci_disable_device(pdev);
2304
2305         attach_count--;
2306 }
2307
2308 static void sym2_get_signalling(struct Scsi_Host *shost)
2309 {
2310         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2311         enum spi_signal_type type;
2312
2313         switch (np->scsi_mode) {
2314         case SMODE_SE:
2315                 type =  SPI_SIGNAL_SE;
2316                 break;
2317         case SMODE_LVD:
2318                 type = SPI_SIGNAL_LVD;
2319                 break;
2320         case SMODE_HVD:
2321                 type = SPI_SIGNAL_HVD;
2322                 break;
2323         default:
2324                 type = SPI_SIGNAL_UNKNOWN;
2325                 break;
2326         }
2327         spi_signalling(shost) = type;
2328 }
2329
2330 static void sym2_get_offset(struct scsi_target *starget)
2331 {
2332         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2333         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2334         struct sym_tcb *tp = &np->target[starget->id];
2335
2336         spi_offset(starget) = tp->tinfo.curr.offset;
2337 }
2338
2339 static void sym2_set_offset(struct scsi_target *starget, int offset)
2340 {
2341         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2342         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2343         struct sym_tcb *tp = &np->target[starget->id];
2344
2345         tp->tinfo.goal.offset = offset;
2346 }
2347
2348
2349 static void sym2_get_period(struct scsi_target *starget)
2350 {
2351         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2352         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2353         struct sym_tcb *tp = &np->target[starget->id];
2354
2355         spi_period(starget) = tp->tinfo.curr.period;
2356 }
2357
2358 static void sym2_set_period(struct scsi_target *starget, int period)
2359 {
2360         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2361         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2362         struct sym_tcb *tp = &np->target[starget->id];
2363
2364         /* have to have DT for these transfers */
2365         if (period <= np->minsync)
2366                 tp->tinfo.goal.options |= PPR_OPT_DT;
2367
2368         tp->tinfo.goal.period = period;
2369 }
2370
2371 static void sym2_get_width(struct scsi_target *starget)
2372 {
2373         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2374         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2375         struct sym_tcb *tp = &np->target[starget->id];
2376
2377         spi_width(starget) = tp->tinfo.curr.width ? 1 : 0;
2378 }
2379
2380 static void sym2_set_width(struct scsi_target *starget, int width)
2381 {
2382         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2383         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2384         struct sym_tcb *tp = &np->target[starget->id];
2385
2386         /* It is illegal to have DT set on narrow transfers */
2387         if (width == 0)
2388                 tp->tinfo.goal.options &= ~PPR_OPT_DT;
2389
2390         tp->tinfo.goal.width = width;
2391 }
2392
2393 static void sym2_get_dt(struct scsi_target *starget)
2394 {
2395         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2396         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2397         struct sym_tcb *tp = &np->target[starget->id];
2398
2399         spi_dt(starget) = (tp->tinfo.curr.options & PPR_OPT_DT) ? 1 : 0;
2400 }
2401
2402 static void sym2_set_dt(struct scsi_target *starget, int dt)
2403 {
2404         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2405         struct sym_hcb *np = ((struct host_data *)shost->hostdata)->ncb;
2406         struct sym_tcb *tp = &np->target[starget->id];
2407
2408         if (dt)
2409                 tp->tinfo.goal.options |= PPR_OPT_DT;
2410         else
2411                 tp->tinfo.goal.options &= ~PPR_OPT_DT;
2412 }
2413         
2414
2415 static struct spi_function_template sym2_transport_functions = {
2416         .set_offset     = sym2_set_offset,
2417         .get_offset     = sym2_get_offset,
2418         .show_offset    = 1,
2419         .set_period     = sym2_set_period,
2420         .get_period     = sym2_get_period,
2421         .show_period    = 1,
2422         .set_width      = sym2_set_width,
2423         .get_width      = sym2_get_width,
2424         .show_width     = 1,
2425         .get_dt         = sym2_get_dt,
2426         .set_dt         = sym2_set_dt,
2427         .show_dt        = 1,
2428         .get_signalling = sym2_get_signalling,
2429 };
2430
2431 static struct pci_device_id sym2_id_table[] __devinitdata = {
2432         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C810,
2433           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2434         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C820,
2435           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, /* new */
2436         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C825,
2437           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2438         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C815,
2439           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2440         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C810AP,
2441           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, /* new */
2442         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C860,
2443           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2444         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C1510,
2445           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2446         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C896,
2447           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2448         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C895,
2449           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2450         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C885,
2451           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2452         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C875,
2453           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2454         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C1510,
2455           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, /* new */
2456         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C895A,
2457           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2458         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C875A,
2459           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2460         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C1010_33,
2461           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2462         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C1010_66,
2463           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2464         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_NCR_53C875J,
2465           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
2466         { 0, }
2467 };
2468
2469 MODULE_DEVICE_TABLE(pci, sym2_id_table);
2470
2471 static struct pci_driver sym2_driver = {
2472         .name           = NAME53C8XX,
2473         .id_table       = sym2_id_table,
2474         .probe          = sym2_probe,
2475         .remove         = __devexit_p(sym2_remove),
2476 };
2477
2478 static int __init sym2_init(void)
2479 {
2480         sym2_transport_template = spi_attach_transport(&sym2_transport_functions);
2481         if (!sym2_transport_template)
2482                 return -ENODEV;
2483
2484         pci_register_driver(&sym2_driver);
2485         return 0;
2486 }
2487
2488 static void __exit sym2_exit(void)
2489 {
2490         pci_unregister_driver(&sym2_driver);
2491         spi_release_transport(sym2_transport_template);
2492 }
2493
2494 module_init(sym2_init);
2495 module_exit(sym2_exit);