]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/dev/asr/asr.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / dev / asr / asr.c
1 /*-
2  * Copyright (c) 1996-2000 Distributed Processing Technology Corporation
3  * Copyright (c) 2000-2001 Adaptec Corporation
4  * All rights reserved.
5  *
6  * TERMS AND CONDITIONS OF USE
7  *
8  * Redistribution and use in source form, with or without modification, are
9  * permitted provided that redistributions of source code must retain the
10  * above copyright notice, this list of conditions and the following disclaimer.
11  *
12  * This software is provided `as is' by Adaptec and any express or implied
13  * warranties, including, but not limited to, the implied warranties of
14  * merchantability and fitness for a particular purpose, are disclaimed. In no
15  * event shall Adaptec be liable for any direct, indirect, incidental, special,
16  * exemplary or consequential damages (including, but not limited to,
17  * procurement of substitute goods or services; loss of use, data, or profits;
18  * or business interruptions) however caused and on any theory of liability,
19  * whether in contract, strict liability, or tort (including negligence or
20  * otherwise) arising in any way out of the use of this driver software, even
21  * if advised of the possibility of such damage.
22  *
23  * SCSI I2O host adapter driver
24  *
25  *      V1.10 2004/05/05 scottl@freebsd.org
26  *              - Massive cleanup of the driver to remove dead code and
27  *                non-conformant style.
28  *              - Removed most i386-specific code to make it more portable.
29  *              - Converted to the bus_space API.
30  *      V1.08 2001/08/21 Mark_Salyzyn@adaptec.com
31  *              - The 2000S and 2005S do not initialize on some machines,
32  *                increased timeout to 255ms from 50ms for the StatusGet
33  *                command.
34  *      V1.07 2001/05/22 Mark_Salyzyn@adaptec.com
35  *              - I knew this one was too good to be true. The error return
36  *                on ioctl commands needs to be compared to CAM_REQ_CMP, not
37  *                to the bit masked status.
38  *      V1.06 2001/05/08 Mark_Salyzyn@adaptec.com
39  *              - The 2005S that was supported is affectionately called the
40  *                Conjoined BAR Firmware. In order to support RAID-5 in a
41  *                16MB low-cost configuration, Firmware was forced to go
42  *                to a Split BAR Firmware. This requires a separate IOP and
43  *                Messaging base address.
44  *      V1.05 2001/04/25 Mark_Salyzyn@adaptec.com
45  *              - Handle support for 2005S Zero Channel RAID solution.
46  *              - System locked up if the Adapter locked up. Do not try
47  *                to send other commands if the resetIOP command fails. The
48  *                fail outstanding command discovery loop was flawed as the
49  *                removal of the command from the list prevented discovering
50  *                all the commands.
51  *              - Comment changes to clarify driver.
52  *              - SysInfo searched for an EATA SmartROM, not an I2O SmartROM.
53  *              - We do not use the AC_FOUND_DEV event because of I2O.
54  *                Removed asr_async.
55  *      V1.04 2000/09/22 Mark_Salyzyn@adaptec.com, msmith@freebsd.org,
56  *                       lampa@fee.vutbr.cz and Scott_Long@adaptec.com.
57  *              - Removed support for PM1554, PM2554 and PM2654 in Mode-0
58  *                mode as this is confused with competitor adapters in run
59  *                mode.
60  *              - critical locking needed in ASR_ccbAdd and ASR_ccbRemove
61  *                to prevent operating system panic.
62  *              - moved default major number to 154 from 97.
63  *      V1.03 2000/07/12 Mark_Salyzyn@adaptec.com
64  *              - The controller is not actually an ASR (Adaptec SCSI RAID)
65  *                series that is visible, it's more of an internal code name.
66  *                remove any visible references within reason for now.
67  *              - bus_ptr->LUN was not correctly zeroed when initially
68  *                allocated causing a possible panic of the operating system
69  *                during boot.
70  *      V1.02 2000/06/26 Mark_Salyzyn@adaptec.com
71  *              - Code always fails for ASR_getTid affecting performance.
72  *              - initiated a set of changes that resulted from a formal
73  *                code inspection by Mark_Salyzyn@adaptec.com,
74  *                George_Dake@adaptec.com, Jeff_Zeak@adaptec.com,
75  *                Martin_Wilson@adaptec.com and Vincent_Trandoan@adaptec.com.
76  *                Their findings were focussed on the LCT & TID handler, and
77  *                all resulting changes were to improve code readability,
78  *                consistency or have a positive effect on performance.
79  *      V1.01 2000/06/14 Mark_Salyzyn@adaptec.com
80  *              - Passthrough returned an incorrect error.
81  *              - Passthrough did not migrate the intrinsic scsi layer wakeup
82  *                on command completion.
83  *              - generate control device nodes using make_dev and delete_dev.
84  *              - Performance affected by TID caching reallocing.
85  *              - Made suggested changes by Justin_Gibbs@adaptec.com
86  *                      - use splcam instead of splbio.
87  *                      - use cam_imask instead of bio_imask.
88  *                      - use u_int8_t instead of u_char.
89  *                      - use u_int16_t instead of u_short.
90  *                      - use u_int32_t instead of u_long where appropriate.
91  *                      - use 64 bit context handler instead of 32 bit.
92  *                      - create_ccb should only allocate the worst case
93  *                        requirements for the driver since CAM may evolve
94  *                        making union ccb much larger than needed here.
95  *                        renamed create_ccb to asr_alloc_ccb.
96  *                      - go nutz justifying all debug prints as macros
97  *                        defined at the top and remove unsightly ifdefs.
98  *                      - INLINE STATIC viewed as confusing. Historically
99  *                        utilized to affect code performance and debug
100  *                        issues in OS, Compiler or OEM specific situations.
101  *      V1.00 2000/05/31 Mark_Salyzyn@adaptec.com
102  *              - Ported from FreeBSD 2.2.X DPT I2O driver.
103  *                      changed struct scsi_xfer to union ccb/struct ccb_hdr
104  *                      changed variable name xs to ccb
105  *                      changed struct scsi_link to struct cam_path
106  *                      changed struct scsibus_data to struct cam_sim
107  *                      stopped using fordriver for holding on to the TID
108  *                      use proprietary packet creation instead of scsi_inquire
109  *                      CAM layer sends synchronize commands.
110  */
111
112 #include <sys/cdefs.h>
113 #include <sys/param.h>  /* TRUE=1 and FALSE=0 defined here */
114 #include <sys/kernel.h>
115 #include <sys/module.h>
116 #include <sys/systm.h>
117 #include <sys/malloc.h>
118 #include <sys/conf.h>
119 #include <sys/ioccom.h>
120 #include <sys/priv.h>
121 #include <sys/proc.h>
122 #include <sys/bus.h>
123 #include <machine/resource.h>
124 #include <machine/bus.h>
125 #include <sys/rman.h>
126 #include <sys/stat.h>
127 #include <sys/bus_dma.h>
128
129 #include <cam/cam.h>
130 #include <cam/cam_ccb.h>
131 #include <cam/cam_sim.h>
132 #include <cam/cam_xpt_sim.h>
133 #include <cam/cam_xpt_periph.h>
134
135 #include <cam/scsi/scsi_all.h>
136 #include <cam/scsi/scsi_message.h>
137
138 #include <vm/vm.h>
139 #include <vm/pmap.h>
140
141 #if defined(__i386__)
142 #include "opt_asr.h"
143 #include <i386/include/cputypes.h>
144
145 #ifndef BURN_BRIDGES
146 #if defined(ASR_COMPAT)
147 #define ASR_IOCTL_COMPAT
148 #endif /* ASR_COMPAT */
149 #endif /* !BURN_BRIDGES */
150 #endif
151 #include <machine/vmparam.h>
152
153 #include <dev/pci/pcivar.h>
154 #include <dev/pci/pcireg.h>
155
156 #define osdSwap4(x) ((u_long)ntohl((u_long)(x)))
157 #define KVTOPHYS(x) vtophys(x)
158 #include        <dev/asr/dptalign.h>
159 #include        <dev/asr/i2oexec.h>
160 #include        <dev/asr/i2obscsi.h>
161 #include        <dev/asr/i2odpt.h>
162 #include        <dev/asr/i2oadptr.h>
163
164 #include        <dev/asr/sys_info.h>
165
166 __FBSDID("$FreeBSD$");
167
168 #define ASR_VERSION     1
169 #define ASR_REVISION    '1'
170 #define ASR_SUBREVISION '0'
171 #define ASR_MONTH       5
172 #define ASR_DAY         5
173 #define ASR_YEAR        (2004 - 1980)
174
175 /*
176  *      Debug macros to reduce the unsightly ifdefs
177  */
178 #if (defined(DEBUG_ASR) || defined(DEBUG_ASR_USR_CMD) || defined(DEBUG_ASR_CMD))
179 static __inline void
180 debug_asr_message(PI2O_MESSAGE_FRAME message)
181 {
182         u_int32_t * pointer = (u_int32_t *)message;
183         u_int32_t   length = I2O_MESSAGE_FRAME_getMessageSize(message);
184         u_int32_t   counter = 0;
185
186         while (length--) {
187                 printf("%08lx%c", (u_long)*(pointer++),
188                   (((++counter & 7) == 0) || (length == 0)) ? '\n' : ' ');
189         }
190 }
191 #endif /* DEBUG_ASR || DEBUG_ASR_USR_CMD || DEBUG_ASR_CMD */
192
193 #ifdef DEBUG_ASR
194   /* Breaks on none STDC based compilers :-( */
195 #define debug_asr_printf(fmt,args...)   printf(fmt, ##args)
196 #define debug_asr_dump_message(message) debug_asr_message(message)
197 #define debug_asr_print_path(ccb)       xpt_print_path(ccb->ccb_h.path);
198 #else /* DEBUG_ASR */
199 #define debug_asr_printf(fmt,args...)
200 #define debug_asr_dump_message(message)
201 #define debug_asr_print_path(ccb)
202 #endif /* DEBUG_ASR */
203
204 /*
205  *      If DEBUG_ASR_CMD is defined:
206  *              0 - Display incoming SCSI commands
207  *              1 - add in a quick character before queueing.
208  *              2 - add in outgoing message frames.
209  */
210 #if (defined(DEBUG_ASR_CMD))
211 #define debug_asr_cmd_printf(fmt,args...)     printf(fmt,##args)
212 static __inline void
213 debug_asr_dump_ccb(union ccb *ccb)
214 {
215         u_int8_t        *cp = (unsigned char *)&(ccb->csio.cdb_io);
216         int             len = ccb->csio.cdb_len;
217
218         while (len) {
219                 debug_asr_cmd_printf (" %02x", *(cp++));
220                 --len;
221         }
222 }
223 #if (DEBUG_ASR_CMD > 0)
224 #define debug_asr_cmd1_printf                  debug_asr_cmd_printf
225 #else
226 #define debug_asr_cmd1_printf(fmt,args...)
227 #endif
228 #if (DEBUG_ASR_CMD > 1)
229 #define debug_asr_cmd2_printf                   debug_asr_cmd_printf
230 #define debug_asr_cmd2_dump_message(message)    debug_asr_message(message)
231 #else
232 #define debug_asr_cmd2_printf(fmt,args...)
233 #define debug_asr_cmd2_dump_message(message)
234 #endif
235 #else /* DEBUG_ASR_CMD */
236 #define debug_asr_cmd_printf(fmt,args...)
237 #define debug_asr_dump_ccb(ccb)
238 #define debug_asr_cmd1_printf(fmt,args...)
239 #define debug_asr_cmd2_printf(fmt,args...)
240 #define debug_asr_cmd2_dump_message(message)
241 #endif /* DEBUG_ASR_CMD */
242
243 #if (defined(DEBUG_ASR_USR_CMD))
244 #define debug_usr_cmd_printf(fmt,args...)   printf(fmt,##args)
245 #define debug_usr_cmd_dump_message(message) debug_usr_message(message)
246 #else /* DEBUG_ASR_USR_CMD */
247 #define debug_usr_cmd_printf(fmt,args...)
248 #define debug_usr_cmd_dump_message(message)
249 #endif /* DEBUG_ASR_USR_CMD */
250
251 #ifdef ASR_IOCTL_COMPAT
252 #define dsDescription_size 46   /* Snug as a bug in a rug */
253 #endif /* ASR_IOCTL_COMPAT */
254
255 #include "dev/asr/dptsig.h"
256
257 static dpt_sig_S ASR_sig = {
258         { 'd', 'P', 't', 'S', 'i', 'G'}, SIG_VERSION, PROC_INTEL,
259         PROC_386 | PROC_486 | PROC_PENTIUM | PROC_SEXIUM, FT_HBADRVR, 0,
260         OEM_DPT, OS_FREE_BSD, CAP_ABOVE16MB, DEV_ALL, ADF_ALL_SC5,
261         0, 0, ASR_VERSION, ASR_REVISION, ASR_SUBREVISION,
262         ASR_MONTH, ASR_DAY, ASR_YEAR,
263 /*       01234567890123456789012345678901234567890123456789     < 50 chars */
264         "Adaptec FreeBSD 4.0.0 Unix SCSI I2O HBA Driver"
265         /*               ^^^^^ asr_attach alters these to match OS */
266 };
267
268 /* Configuration Definitions */
269
270 #define SG_SIZE          58     /* Scatter Gather list Size              */
271 #define MAX_TARGET_ID    126    /* Maximum Target ID supported           */
272 #define MAX_LUN          255    /* Maximum LUN Supported                 */
273 #define MAX_CHANNEL      7      /* Maximum Channel # Supported by driver */
274 #define MAX_INBOUND      2000   /* Max CCBs, Also Max Queue Size         */
275 #define MAX_OUTBOUND     256    /* Maximum outbound frames/adapter       */
276 #define MAX_INBOUND_SIZE 512    /* Maximum inbound frame size            */
277 #define MAX_MAP          4194304L /* Maximum mapping size of IOP         */
278                                 /* Also serves as the minimum map for    */
279                                 /* the 2005S zero channel RAID product   */
280
281 /* I2O register set */
282 #define I2O_REG_STATUS          0x30
283 #define I2O_REG_MASK            0x34
284 #define I2O_REG_TOFIFO          0x40
285 #define I2O_REG_FROMFIFO        0x44
286
287 #define Mask_InterruptsDisabled 0x08
288
289 /*
290  * A MIX of performance and space considerations for TID lookups
291  */
292 typedef u_int16_t tid_t;
293
294 typedef struct {
295         u_int32_t size;         /* up to MAX_LUN    */
296         tid_t     TID[1];
297 } lun2tid_t;
298
299 typedef struct {
300         u_int32_t   size;       /* up to MAX_TARGET */
301         lun2tid_t * LUN[1];
302 } target2lun_t;
303
304 /*
305  *      To ensure that we only allocate and use the worst case ccb here, lets
306  *      make our own local ccb union. If asr_alloc_ccb is utilized for another
307  *      ccb type, ensure that you add the additional structures into our local
308  *      ccb union. To ensure strict type checking, we will utilize the local
309  *      ccb definition wherever possible.
310  */
311 union asr_ccb {
312         struct ccb_hdr      ccb_h;  /* For convenience */
313         struct ccb_scsiio   csio;
314         struct ccb_setasync csa;
315 };
316
317 struct Asr_status_mem {
318         I2O_EXEC_STATUS_GET_REPLY       status;
319         U32                             rstatus;
320 };
321
322 /**************************************************************************
323 ** ASR Host Adapter structure - One Structure For Each Host Adapter That **
324 **  Is Configured Into The System.  The Structure Supplies Configuration **
325 **  Information, Status Info, Queue Info And An Active CCB List Pointer. **
326 ***************************************************************************/
327
328 typedef struct Asr_softc {
329         device_t                ha_dev;
330         u_int16_t               ha_irq;
331         u_long                  ha_Base;       /* base port for each board */
332         bus_size_t              ha_blinkLED;
333         bus_space_handle_t      ha_i2o_bhandle;
334         bus_space_tag_t         ha_i2o_btag;
335         bus_space_handle_t      ha_frame_bhandle;
336         bus_space_tag_t         ha_frame_btag;
337         I2O_IOP_ENTRY           ha_SystemTable;
338         LIST_HEAD(,ccb_hdr)     ha_ccb;        /* ccbs in use              */
339
340         bus_dma_tag_t           ha_parent_dmat;
341         bus_dma_tag_t           ha_statusmem_dmat;
342         bus_dmamap_t            ha_statusmem_dmamap;
343         struct Asr_status_mem * ha_statusmem;
344         u_int32_t               ha_rstatus_phys;
345         u_int32_t               ha_status_phys;
346         struct cam_path       * ha_path[MAX_CHANNEL+1];
347         struct cam_sim        * ha_sim[MAX_CHANNEL+1];
348         struct resource       * ha_mem_res;
349         struct resource       * ha_mes_res;
350         struct resource       * ha_irq_res;
351         void                  * ha_intr;
352         PI2O_LCT                ha_LCT;        /* Complete list of devices */
353 #define le_type   IdentityTag[0]
354 #define I2O_BSA     0x20
355 #define I2O_FCA     0x40
356 #define I2O_SCSI    0x00
357 #define I2O_PORT    0x80
358 #define I2O_UNKNOWN 0x7F
359 #define le_bus    IdentityTag[1]
360 #define le_target IdentityTag[2]
361 #define le_lun    IdentityTag[3]
362         target2lun_t          * ha_targets[MAX_CHANNEL+1];
363         PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME ha_Msgs;
364         u_long                  ha_Msgs_Phys;
365
366         u_int8_t                ha_in_reset;
367 #define HA_OPERATIONAL      0
368 #define HA_IN_RESET         1
369 #define HA_OFF_LINE         2
370 #define HA_OFF_LINE_RECOVERY 3
371         /* Configuration information */
372         /* The target id maximums we take */
373         u_int8_t                ha_MaxBus;     /* Maximum bus */
374         u_int8_t                ha_MaxId;      /* Maximum target ID */
375         u_int8_t                ha_MaxLun;     /* Maximum target LUN */
376         u_int8_t                ha_SgSize;     /* Max SG elements */
377         u_int8_t                ha_pciBusNum;
378         u_int8_t                ha_pciDeviceNum;
379         u_int8_t                ha_adapter_target[MAX_CHANNEL+1];
380         u_int16_t               ha_QueueSize;  /* Max outstanding commands */
381         u_int16_t               ha_Msgs_Count;
382
383         /* Links into other parents and HBAs */
384         struct Asr_softc      * ha_next;       /* HBA list */
385         struct cdev *ha_devt;
386 } Asr_softc_t;
387
388 static Asr_softc_t *Asr_softc_list;
389
390 /*
391  *      Prototypes of the routines we have in this object.
392  */
393
394 /* I2O HDM interface */
395 static int      asr_probe(device_t dev);
396 static int      asr_attach(device_t dev);
397
398 static int      asr_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag,
399                           struct thread *td);
400 static int      asr_open(struct cdev *dev, int32_t flags, int32_t ifmt,
401                          struct thread *td);
402 static int      asr_close(struct cdev *dev, int flags, int ifmt, struct thread *td);
403 static int      asr_intr(Asr_softc_t *sc);
404 static void     asr_timeout(void *arg);
405 static int      ASR_init(Asr_softc_t *sc);
406 static int      ASR_acquireLct(Asr_softc_t *sc);
407 static int      ASR_acquireHrt(Asr_softc_t *sc);
408 static void     asr_action(struct cam_sim *sim, union ccb *ccb);
409 static void     asr_poll(struct cam_sim *sim);
410 static int      ASR_queue(Asr_softc_t *sc, PI2O_MESSAGE_FRAME Message);
411
412 /*
413  *      Here is the auto-probe structure used to nest our tests appropriately
414  *      during the startup phase of the operating system.
415  */
416 static device_method_t asr_methods[] = {
417         DEVMETHOD(device_probe,  asr_probe),
418         DEVMETHOD(device_attach, asr_attach),
419         { 0, 0 }
420 };
421
422 static driver_t asr_driver = {
423         "asr",
424         asr_methods,
425         sizeof(Asr_softc_t)
426 };
427
428 static devclass_t asr_devclass;
429 DRIVER_MODULE(asr, pci, asr_driver, asr_devclass, 0, 0);
430 MODULE_DEPEND(asr, pci, 1, 1, 1);
431 MODULE_DEPEND(asr, cam, 1, 1, 1);
432
433 /*
434  * devsw for asr hba driver
435  *
436  * only ioctl is used. the sd driver provides all other access.
437  */
438 static struct cdevsw asr_cdevsw = {
439         .d_version =    D_VERSION,
440         .d_flags =      D_NEEDGIANT,
441         .d_open =       asr_open,
442         .d_close =      asr_close,
443         .d_ioctl =      asr_ioctl,
444         .d_name =       "asr",
445 };
446
447 /* I2O support routines */
448
449 static __inline u_int32_t
450 asr_get_FromFIFO(Asr_softc_t *sc)
451 {
452         return (bus_space_read_4(sc->ha_i2o_btag, sc->ha_i2o_bhandle,
453                                  I2O_REG_FROMFIFO));
454 }
455
456 static __inline u_int32_t
457 asr_get_ToFIFO(Asr_softc_t *sc)
458 {
459         return (bus_space_read_4(sc->ha_i2o_btag, sc->ha_i2o_bhandle,
460                                  I2O_REG_TOFIFO));
461 }
462
463 static __inline u_int32_t
464 asr_get_intr(Asr_softc_t *sc)
465 {
466         return (bus_space_read_4(sc->ha_i2o_btag, sc->ha_i2o_bhandle,
467                                  I2O_REG_MASK));
468 }
469
470 static __inline u_int32_t
471 asr_get_status(Asr_softc_t *sc)
472 {
473         return (bus_space_read_4(sc->ha_i2o_btag, sc->ha_i2o_bhandle,
474                                  I2O_REG_STATUS));
475 }
476
477 static __inline void
478 asr_set_FromFIFO(Asr_softc_t *sc, u_int32_t val)
479 {
480         bus_space_write_4(sc->ha_i2o_btag, sc->ha_i2o_bhandle, I2O_REG_FROMFIFO,
481                           val);
482 }
483
484 static __inline void
485 asr_set_ToFIFO(Asr_softc_t *sc, u_int32_t val)
486 {
487         bus_space_write_4(sc->ha_i2o_btag, sc->ha_i2o_bhandle, I2O_REG_TOFIFO,
488                           val);
489 }
490
491 static __inline void
492 asr_set_intr(Asr_softc_t *sc, u_int32_t val)
493 {
494         bus_space_write_4(sc->ha_i2o_btag, sc->ha_i2o_bhandle, I2O_REG_MASK,
495                           val);
496 }
497
498 static __inline void
499 asr_set_frame(Asr_softc_t *sc, void *frame, u_int32_t offset, int len)
500 {
501         bus_space_write_region_4(sc->ha_frame_btag, sc->ha_frame_bhandle,
502                                  offset, (u_int32_t *)frame, len);
503 }
504
505 /*
506  *      Fill message with default.
507  */
508 static PI2O_MESSAGE_FRAME
509 ASR_fillMessage(void *Message, u_int16_t size)
510 {
511         PI2O_MESSAGE_FRAME Message_Ptr;
512
513         Message_Ptr = (I2O_MESSAGE_FRAME *)Message;
514         bzero(Message_Ptr, size);
515         I2O_MESSAGE_FRAME_setVersionOffset(Message_Ptr, I2O_VERSION_11);
516         I2O_MESSAGE_FRAME_setMessageSize(Message_Ptr,
517           (size + sizeof(U32) - 1) >> 2);
518         I2O_MESSAGE_FRAME_setInitiatorAddress (Message_Ptr, 1);
519         KASSERT(Message_Ptr != NULL, ("Message_Ptr == NULL"));
520         return (Message_Ptr);
521 } /* ASR_fillMessage */
522
523 #define EMPTY_QUEUE (0xffffffff)
524
525 static __inline U32
526 ASR_getMessage(Asr_softc_t *sc)
527 {
528         U32     MessageOffset;
529
530         MessageOffset = asr_get_ToFIFO(sc);
531         if (MessageOffset == EMPTY_QUEUE)
532                 MessageOffset = asr_get_ToFIFO(sc);
533
534         return (MessageOffset);
535 } /* ASR_getMessage */
536
537 /* Issue a polled command */
538 static U32
539 ASR_initiateCp(Asr_softc_t *sc, PI2O_MESSAGE_FRAME Message)
540 {
541         U32     Mask = 0xffffffff;
542         U32     MessageOffset;
543         u_int   Delay = 1500;
544
545         /*
546          * ASR_initiateCp is only used for synchronous commands and will
547          * be made more resiliant to adapter delays since commands like
548          * resetIOP can cause the adapter to be deaf for a little time.
549          */
550         while (((MessageOffset = ASR_getMessage(sc)) == EMPTY_QUEUE)
551          && (--Delay != 0)) {
552                 DELAY (10000);
553         }
554         if (MessageOffset != EMPTY_QUEUE) {
555                 asr_set_frame(sc, Message, MessageOffset,
556                               I2O_MESSAGE_FRAME_getMessageSize(Message));
557                 /*
558                  *      Disable the Interrupts
559                  */
560                 Mask = asr_get_intr(sc);
561                 asr_set_intr(sc, Mask | Mask_InterruptsDisabled);
562                 asr_set_ToFIFO(sc, MessageOffset);
563         }
564         return (Mask);
565 } /* ASR_initiateCp */
566
567 /*
568  *      Reset the adapter.
569  */
570 static U32
571 ASR_resetIOP(Asr_softc_t *sc)
572 {
573         I2O_EXEC_IOP_RESET_MESSAGE       Message;
574         PI2O_EXEC_IOP_RESET_MESSAGE      Message_Ptr;
575         U32                            * Reply_Ptr;
576         U32                              Old;
577
578         /*
579          *  Build up our copy of the Message.
580          */
581         Message_Ptr = (PI2O_EXEC_IOP_RESET_MESSAGE)ASR_fillMessage(&Message,
582           sizeof(I2O_EXEC_IOP_RESET_MESSAGE));
583         I2O_EXEC_IOP_RESET_MESSAGE_setFunction(Message_Ptr, I2O_EXEC_IOP_RESET);
584         /*
585          *  Reset the Reply Status
586          */
587         Reply_Ptr = &sc->ha_statusmem->rstatus;
588         *Reply_Ptr = 0;
589         I2O_EXEC_IOP_RESET_MESSAGE_setStatusWordLowAddress(Message_Ptr,
590             sc->ha_rstatus_phys);
591         /*
592          *      Send the Message out
593          */
594         if ((Old = ASR_initiateCp(sc, (PI2O_MESSAGE_FRAME)Message_Ptr)) !=
595              0xffffffff) {
596                 /*
597                  * Wait for a response (Poll), timeouts are dangerous if
598                  * the card is truly responsive. We assume response in 2s.
599                  */
600                 u_int8_t Delay = 200;
601
602                 while ((*Reply_Ptr == 0) && (--Delay != 0)) {
603                         DELAY (10000);
604                 }
605                 /*
606                  *      Re-enable the interrupts.
607                  */
608                 asr_set_intr(sc, Old);
609                 KASSERT(*Reply_Ptr != 0, ("*Reply_Ptr == 0"));
610                 return(*Reply_Ptr);
611         }
612         KASSERT(Old != 0xffffffff, ("Old == -1"));
613         return (0);
614 } /* ASR_resetIOP */
615
616 /*
617  *      Get the curent state of the adapter
618  */
619 static PI2O_EXEC_STATUS_GET_REPLY
620 ASR_getStatus(Asr_softc_t *sc)
621 {
622         I2O_EXEC_STATUS_GET_MESSAGE     Message;
623         PI2O_EXEC_STATUS_GET_MESSAGE    Message_Ptr;
624         PI2O_EXEC_STATUS_GET_REPLY      buffer;
625         U32                             Old;
626
627         /*
628          *  Build up our copy of the Message.
629          */
630         Message_Ptr = (PI2O_EXEC_STATUS_GET_MESSAGE)ASR_fillMessage(&Message,
631             sizeof(I2O_EXEC_STATUS_GET_MESSAGE));
632         I2O_EXEC_STATUS_GET_MESSAGE_setFunction(Message_Ptr,
633             I2O_EXEC_STATUS_GET);
634         I2O_EXEC_STATUS_GET_MESSAGE_setReplyBufferAddressLow(Message_Ptr,
635             sc->ha_status_phys);
636         /* This one is a Byte Count */
637         I2O_EXEC_STATUS_GET_MESSAGE_setReplyBufferLength(Message_Ptr,
638             sizeof(I2O_EXEC_STATUS_GET_REPLY));
639         /*
640          *  Reset the Reply Status
641          */
642         buffer = &sc->ha_statusmem->status;
643         bzero(buffer, sizeof(I2O_EXEC_STATUS_GET_REPLY));
644         /*
645          *      Send the Message out
646          */
647         if ((Old = ASR_initiateCp(sc, (PI2O_MESSAGE_FRAME)Message_Ptr)) != 
648             0xffffffff) {
649                 /*
650                  *      Wait for a response (Poll), timeouts are dangerous if
651                  * the card is truly responsive. We assume response in 50ms.
652                  */
653                 u_int8_t Delay = 255;
654
655                 while (*((U8 * volatile)&(buffer->SyncByte)) == 0) {
656                         if (--Delay == 0) {
657                                 buffer = NULL;
658                                 break;
659                         }
660                         DELAY (1000);
661                 }
662                 /*
663                  *      Re-enable the interrupts.
664                  */
665                 asr_set_intr(sc, Old);
666                 return (buffer);
667         }
668         return (NULL);
669 } /* ASR_getStatus */
670
671 /*
672  *      Check if the device is a SCSI I2O HBA, and add it to the list.
673  */
674
675 /*
676  * Probe for ASR controller.  If we find it, we will use it.
677  * virtual adapters.
678  */
679 static int
680 asr_probe(device_t dev)
681 {
682         u_int32_t id;
683
684         id = (pci_get_device(dev) << 16) | pci_get_vendor(dev);
685         if ((id == 0xA5011044) || (id == 0xA5111044)) {
686                 device_set_desc(dev, "Adaptec Caching SCSI RAID");
687                 return (BUS_PROBE_DEFAULT);
688         }
689         return (ENXIO);
690 } /* asr_probe */
691
692 static __inline union asr_ccb *
693 asr_alloc_ccb(Asr_softc_t *sc)
694 {
695         union asr_ccb *new_ccb;
696
697         if ((new_ccb = (union asr_ccb *)malloc(sizeof(*new_ccb),
698           M_DEVBUF, M_WAITOK | M_ZERO)) != NULL) {
699                 new_ccb->ccb_h.pinfo.priority = 1;
700                 new_ccb->ccb_h.pinfo.index = CAM_UNQUEUED_INDEX;
701                 new_ccb->ccb_h.spriv_ptr0 = sc;
702         }
703         return (new_ccb);
704 } /* asr_alloc_ccb */
705
706 static __inline void
707 asr_free_ccb(union asr_ccb *free_ccb)
708 {
709         free(free_ccb, M_DEVBUF);
710 } /* asr_free_ccb */
711
712 /*
713  *      Print inquiry data `carefully'
714  */
715 static void
716 ASR_prstring(u_int8_t *s, int len)
717 {
718         while ((--len >= 0) && (*s) && (*s != ' ') && (*s != '-')) {
719                 printf ("%c", *(s++));
720         }
721 } /* ASR_prstring */
722
723 /*
724  *      Send a message synchronously and without Interrupt to a ccb.
725  */
726 static int
727 ASR_queue_s(union asr_ccb *ccb, PI2O_MESSAGE_FRAME Message)
728 {
729         int             s;
730         U32             Mask;
731         Asr_softc_t     *sc = (Asr_softc_t *)(ccb->ccb_h.spriv_ptr0);
732
733         /*
734          * We do not need any (optional byteswapping) method access to
735          * the Initiator context field.
736          */
737         I2O_MESSAGE_FRAME_setInitiatorContext64(Message, (long)ccb);
738
739         /* Prevent interrupt service */
740         s = splcam ();
741         Mask = asr_get_intr(sc);
742         asr_set_intr(sc, Mask | Mask_InterruptsDisabled);
743
744         if (ASR_queue(sc, Message) == EMPTY_QUEUE) {
745                 ccb->ccb_h.status &= ~CAM_STATUS_MASK;
746                 ccb->ccb_h.status |= CAM_REQUEUE_REQ;
747         }
748
749         /*
750          * Wait for this board to report a finished instruction.
751          */
752         while ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
753                 (void)asr_intr (sc);
754         }
755
756         /* Re-enable Interrupts */
757         asr_set_intr(sc, Mask);
758         splx(s);
759
760         return (ccb->ccb_h.status);
761 } /* ASR_queue_s */
762
763 /*
764  *      Send a message synchronously to an Asr_softc_t.
765  */
766 static int
767 ASR_queue_c(Asr_softc_t *sc, PI2O_MESSAGE_FRAME Message)
768 {
769         union asr_ccb   *ccb;
770         int             status;
771
772         if ((ccb = asr_alloc_ccb (sc)) == NULL) {
773                 return (CAM_REQUEUE_REQ);
774         }
775
776         status = ASR_queue_s (ccb, Message);
777
778         asr_free_ccb(ccb);
779
780         return (status);
781 } /* ASR_queue_c */
782
783 /*
784  *      Add the specified ccb to the active queue
785  */
786 static __inline void
787 ASR_ccbAdd(Asr_softc_t *sc, union asr_ccb *ccb)
788 {
789         int s;
790
791         s = splcam();
792         LIST_INSERT_HEAD(&(sc->ha_ccb), &(ccb->ccb_h), sim_links.le);
793         if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
794                 if (ccb->ccb_h.timeout == CAM_TIME_DEFAULT) {
795                         /*
796                          * RAID systems can take considerable time to
797                          * complete some commands given the large cache
798                          * flashes switching from write back to write thru.
799                          */
800                         ccb->ccb_h.timeout = 6 * 60 * 1000;
801                 }
802                 ccb->ccb_h.timeout_ch = timeout(asr_timeout, (caddr_t)ccb,
803                   (ccb->ccb_h.timeout * hz) / 1000);
804         }
805         splx(s);
806 } /* ASR_ccbAdd */
807
808 /*
809  *      Remove the specified ccb from the active queue.
810  */
811 static __inline void
812 ASR_ccbRemove(Asr_softc_t *sc, union asr_ccb *ccb)
813 {
814         int s;
815
816         s = splcam();
817         untimeout(asr_timeout, (caddr_t)ccb, ccb->ccb_h.timeout_ch);
818         LIST_REMOVE(&(ccb->ccb_h), sim_links.le);
819         splx(s);
820 } /* ASR_ccbRemove */
821
822 /*
823  *      Fail all the active commands, so they get re-issued by the operating
824  *      system.
825  */
826 static void
827 ASR_failActiveCommands(Asr_softc_t *sc)
828 {
829         struct ccb_hdr  *ccb;
830         int             s;
831
832         s = splcam();
833         /*
834          *      We do not need to inform the CAM layer that we had a bus
835          * reset since we manage it on our own, this also prevents the
836          * SCSI_DELAY settling that would be required on other systems.
837          * The `SCSI_DELAY' has already been handled by the card via the
838          * acquisition of the LCT table while we are at CAM priority level.
839          *  for (int bus = 0; bus <= sc->ha_MaxBus; ++bus) {
840          *      xpt_async (AC_BUS_RESET, sc->ha_path[bus], NULL);
841          *  }
842          */
843         while ((ccb = LIST_FIRST(&(sc->ha_ccb))) != NULL) {
844                 ASR_ccbRemove (sc, (union asr_ccb *)ccb);
845
846                 ccb->status &= ~CAM_STATUS_MASK;
847                 ccb->status |= CAM_REQUEUE_REQ;
848                 /* Nothing Transfered */
849                 ((struct ccb_scsiio *)ccb)->resid
850                   = ((struct ccb_scsiio *)ccb)->dxfer_len;
851
852                 if (ccb->path) {
853                         xpt_done ((union ccb *)ccb);
854                 } else {
855                         wakeup (ccb);
856                 }
857         }
858         splx(s);
859 } /* ASR_failActiveCommands */
860
861 /*
862  *      The following command causes the HBA to reset the specific bus
863  */
864 static void
865 ASR_resetBus(Asr_softc_t *sc, int bus)
866 {
867         I2O_HBA_BUS_RESET_MESSAGE       Message;
868         I2O_HBA_BUS_RESET_MESSAGE       *Message_Ptr;
869         PI2O_LCT_ENTRY                  Device;
870
871         Message_Ptr = (I2O_HBA_BUS_RESET_MESSAGE *)ASR_fillMessage(&Message,
872           sizeof(I2O_HBA_BUS_RESET_MESSAGE));
873         I2O_MESSAGE_FRAME_setFunction(&Message_Ptr->StdMessageFrame,
874           I2O_HBA_BUS_RESET);
875         for (Device = sc->ha_LCT->LCTEntry; Device < (PI2O_LCT_ENTRY)
876           (((U32 *)sc->ha_LCT)+I2O_LCT_getTableSize(sc->ha_LCT));
877           ++Device) {
878                 if (((Device->le_type & I2O_PORT) != 0)
879                  && (Device->le_bus == bus)) {
880                         I2O_MESSAGE_FRAME_setTargetAddress(
881                           &Message_Ptr->StdMessageFrame,
882                           I2O_LCT_ENTRY_getLocalTID(Device));
883                         /* Asynchronous command, with no expectations */
884                         (void)ASR_queue(sc, (PI2O_MESSAGE_FRAME)Message_Ptr);
885                         break;
886                 }
887         }
888 } /* ASR_resetBus */
889
890 static __inline int
891 ASR_getBlinkLedCode(Asr_softc_t *sc)
892 {
893         U8      blink;
894
895         if (sc == NULL)
896                 return (0);
897
898         blink = bus_space_read_1(sc->ha_frame_btag,
899                                  sc->ha_frame_bhandle, sc->ha_blinkLED + 1);
900         if (blink != 0xBC)
901                 return (0);
902
903         blink = bus_space_read_1(sc->ha_frame_btag,
904                                  sc->ha_frame_bhandle, sc->ha_blinkLED);
905         return (blink);
906 } /* ASR_getBlinkCode */
907
908 /*
909  *      Determine the address of an TID lookup. Must be done at high priority
910  *      since the address can be changed by other threads of execution.
911  *
912  *      Returns NULL pointer if not indexible (but will attempt to generate
913  *      an index if `new_entry' flag is set to TRUE).
914  *
915  *      All addressible entries are to be guaranteed zero if never initialized.
916  */
917 static tid_t *
918 ASR_getTidAddress(Asr_softc_t *sc, int bus, int target, int lun, int new_entry)
919 {
920         target2lun_t    *bus_ptr;
921         lun2tid_t       *target_ptr;
922         unsigned        new_size;
923
924         /*
925          *      Validity checking of incoming parameters. More of a bound
926          * expansion limit than an issue with the code dealing with the
927          * values.
928          *
929          *      sc must be valid before it gets here, so that check could be
930          * dropped if speed a critical issue.
931          */
932         if ((sc == NULL)
933          || (bus > MAX_CHANNEL)
934          || (target > sc->ha_MaxId)
935          || (lun > sc->ha_MaxLun)) {
936                 debug_asr_printf("(%lx,%d,%d,%d) target out of range\n",
937                   (u_long)sc, bus, target, lun);
938                 return (NULL);
939         }
940         /*
941          *      See if there is an associated bus list.
942          *
943          *      for performance, allocate in size of BUS_CHUNK chunks.
944          *      BUS_CHUNK must be a power of two. This is to reduce
945          *      fragmentation effects on the allocations.
946          */
947 #define BUS_CHUNK 8
948         new_size = ((target + BUS_CHUNK - 1) & ~(BUS_CHUNK - 1));
949         if ((bus_ptr = sc->ha_targets[bus]) == NULL) {
950                 /*
951                  *      Allocate a new structure?
952                  *              Since one element in structure, the +1
953                  *              needed for size has been abstracted.
954                  */
955                 if ((new_entry == FALSE)
956                  || ((sc->ha_targets[bus] = bus_ptr = (target2lun_t *)malloc (
957                     sizeof(*bus_ptr) + (sizeof(bus_ptr->LUN) * new_size),
958                     M_TEMP, M_WAITOK | M_ZERO))
959                    == NULL)) {
960                         debug_asr_printf("failed to allocate bus list\n");
961                         return (NULL);
962                 }
963                 bus_ptr->size = new_size + 1;
964         } else if (bus_ptr->size <= new_size) {
965                 target2lun_t * new_bus_ptr;
966
967                 /*
968                  *      Reallocate a new structure?
969                  *              Since one element in structure, the +1
970                  *              needed for size has been abstracted.
971                  */
972                 if ((new_entry == FALSE)
973                  || ((new_bus_ptr = (target2lun_t *)malloc (
974                     sizeof(*bus_ptr) + (sizeof(bus_ptr->LUN) * new_size),
975                     M_TEMP, M_WAITOK | M_ZERO)) == NULL)) {
976                         debug_asr_printf("failed to reallocate bus list\n");
977                         return (NULL);
978                 }
979                 /*
980                  *      Copy the whole thing, safer, simpler coding
981                  * and not really performance critical at this point.
982                  */
983                 bcopy(bus_ptr, new_bus_ptr, sizeof(*bus_ptr)
984                     + (sizeof(bus_ptr->LUN) * (bus_ptr->size - 1)));
985                 sc->ha_targets[bus] = new_bus_ptr;
986                 free(bus_ptr, M_TEMP);
987                 bus_ptr = new_bus_ptr;
988                 bus_ptr->size = new_size + 1;
989         }
990         /*
991          *      We now have the bus list, lets get to the target list.
992          *      Since most systems have only *one* lun, we do not allocate
993          *      in chunks as above, here we allow one, then in chunk sizes.
994          *      TARGET_CHUNK must be a power of two. This is to reduce
995          *      fragmentation effects on the allocations.
996          */
997 #define TARGET_CHUNK 8
998         if ((new_size = lun) != 0) {
999                 new_size = ((lun + TARGET_CHUNK - 1) & ~(TARGET_CHUNK - 1));
1000         }
1001         if ((target_ptr = bus_ptr->LUN[target]) == NULL) {
1002                 /*
1003                  *      Allocate a new structure?
1004                  *              Since one element in structure, the +1
1005                  *              needed for size has been abstracted.
1006                  */
1007                 if ((new_entry == FALSE)
1008                  || ((bus_ptr->LUN[target] = target_ptr = (lun2tid_t *)malloc (
1009                     sizeof(*target_ptr) + (sizeof(target_ptr->TID) * new_size),
1010                     M_TEMP, M_WAITOK | M_ZERO)) == NULL)) {
1011                         debug_asr_printf("failed to allocate target list\n");
1012                         return (NULL);
1013                 }
1014                 target_ptr->size = new_size + 1;
1015         } else if (target_ptr->size <= new_size) {
1016                 lun2tid_t * new_target_ptr;
1017
1018                 /*
1019                  *      Reallocate a new structure?
1020                  *              Since one element in structure, the +1
1021                  *              needed for size has been abstracted.
1022                  */
1023                 if ((new_entry == FALSE)
1024                  || ((new_target_ptr = (lun2tid_t *)malloc (
1025                     sizeof(*target_ptr) + (sizeof(target_ptr->TID) * new_size),
1026                     M_TEMP, M_WAITOK | M_ZERO)) == NULL)) {
1027                         debug_asr_printf("failed to reallocate target list\n");
1028                         return (NULL);
1029                 }
1030                 /*
1031                  *      Copy the whole thing, safer, simpler coding
1032                  * and not really performance critical at this point.
1033                  */
1034                 bcopy(target_ptr, new_target_ptr, sizeof(*target_ptr)
1035                     + (sizeof(target_ptr->TID) * (target_ptr->size - 1)));
1036                 bus_ptr->LUN[target] = new_target_ptr;
1037                 free(target_ptr, M_TEMP);
1038                 target_ptr = new_target_ptr;
1039                 target_ptr->size = new_size + 1;
1040         }
1041         /*
1042          *      Now, acquire the TID address from the LUN indexed list.
1043          */
1044         return (&(target_ptr->TID[lun]));
1045 } /* ASR_getTidAddress */
1046
1047 /*
1048  *      Get a pre-existing TID relationship.
1049  *
1050  *      If the TID was never set, return (tid_t)-1.
1051  *
1052  *      should use mutex rather than spl.
1053  */
1054 static __inline tid_t
1055 ASR_getTid(Asr_softc_t *sc, int bus, int target, int lun)
1056 {
1057         tid_t   *tid_ptr;
1058         int     s;
1059         tid_t   retval;
1060
1061         s = splcam();
1062         if (((tid_ptr = ASR_getTidAddress(sc, bus, target, lun, FALSE)) == NULL)
1063         /* (tid_t)0 or (tid_t)-1 indicate no TID */
1064          || (*tid_ptr == (tid_t)0)) {
1065                 splx(s);
1066                 return ((tid_t)-1);
1067         }
1068         retval = *tid_ptr;
1069         splx(s);
1070         return (retval);
1071 } /* ASR_getTid */
1072
1073 /*
1074  *      Set a TID relationship.
1075  *
1076  *      If the TID was not set, return (tid_t)-1.
1077  *
1078  *      should use mutex rather than spl.
1079  */
1080 static __inline tid_t
1081 ASR_setTid(Asr_softc_t *sc, int bus, int target, int lun, tid_t TID)
1082 {
1083         tid_t   *tid_ptr;
1084         int     s;
1085
1086         if (TID != (tid_t)-1) {
1087                 if (TID == 0) {
1088                         return ((tid_t)-1);
1089                 }
1090                 s = splcam();
1091                 if ((tid_ptr = ASR_getTidAddress(sc, bus, target, lun, TRUE))
1092                  == NULL) {
1093                         splx(s);
1094                         return ((tid_t)-1);
1095                 }
1096                 *tid_ptr = TID;
1097                 splx(s);
1098         }
1099         return (TID);
1100 } /* ASR_setTid */
1101
1102 /*-------------------------------------------------------------------------*/
1103 /*                    Function ASR_rescan                                  */
1104 /*-------------------------------------------------------------------------*/
1105 /* The Parameters Passed To This Function Are :                            */
1106 /*     Asr_softc_t *     : HBA miniport driver's adapter data storage.     */
1107 /*                                                                         */
1108 /* This Function Will rescan the adapter and resynchronize any data        */
1109 /*                                                                         */
1110 /* Return : 0 For OK, Error Code Otherwise                                 */
1111 /*-------------------------------------------------------------------------*/
1112
1113 static int
1114 ASR_rescan(Asr_softc_t *sc)
1115 {
1116         int bus;
1117         int error;
1118
1119         /*
1120          * Re-acquire the LCT table and synchronize us to the adapter.
1121          */
1122         if ((error = ASR_acquireLct(sc)) == 0) {
1123                 error = ASR_acquireHrt(sc);
1124         }
1125
1126         if (error != 0) {
1127                 return error;
1128         }
1129
1130         bus = sc->ha_MaxBus;
1131         /* Reset all existing cached TID lookups */
1132         do {
1133                 int target, event = 0;
1134
1135                 /*
1136                  *      Scan for all targets on this bus to see if they
1137                  * got affected by the rescan.
1138                  */
1139                 for (target = 0; target <= sc->ha_MaxId; ++target) {
1140                         int lun;
1141
1142                         /* Stay away from the controller ID */
1143                         if (target == sc->ha_adapter_target[bus]) {
1144                                 continue;
1145                         }
1146                         for (lun = 0; lun <= sc->ha_MaxLun; ++lun) {
1147                                 PI2O_LCT_ENTRY Device;
1148                                 tid_t          TID = (tid_t)-1;
1149                                 tid_t          LastTID;
1150
1151                                 /*
1152                                  * See if the cached TID changed. Search for
1153                                  * the device in our new LCT.
1154                                  */
1155                                 for (Device = sc->ha_LCT->LCTEntry;
1156                                   Device < (PI2O_LCT_ENTRY)(((U32 *)sc->ha_LCT)
1157                                    + I2O_LCT_getTableSize(sc->ha_LCT));
1158                                   ++Device) {
1159                                         if ((Device->le_type != I2O_UNKNOWN)
1160                                          && (Device->le_bus == bus)
1161                                          && (Device->le_target == target)
1162                                          && (Device->le_lun == lun)
1163                                          && (I2O_LCT_ENTRY_getUserTID(Device)
1164                                           == 0xFFF)) {
1165                                                 TID = I2O_LCT_ENTRY_getLocalTID(
1166                                                   Device);
1167                                                 break;
1168                                         }
1169                                 }
1170                                 /*
1171                                  * Indicate to the OS that the label needs
1172                                  * to be recalculated, or that the specific
1173                                  * open device is no longer valid (Merde)
1174                                  * because the cached TID changed.
1175                                  */
1176                                 LastTID = ASR_getTid (sc, bus, target, lun);
1177                                 if (LastTID != TID) {
1178                                         struct cam_path * path;
1179
1180                                         if (xpt_create_path(&path,
1181                                           /*periph*/NULL,
1182                                           cam_sim_path(sc->ha_sim[bus]),
1183                                           target, lun) != CAM_REQ_CMP) {
1184                                                 if (TID == (tid_t)-1) {
1185                                                         event |= AC_LOST_DEVICE;
1186                                                 } else {
1187                                                         event |= AC_INQ_CHANGED
1188                                                                | AC_GETDEV_CHANGED;
1189                                                 }
1190                                         } else {
1191                                                 if (TID == (tid_t)-1) {
1192                                                         xpt_async(
1193                                                           AC_LOST_DEVICE,
1194                                                           path, NULL);
1195                                                 } else if (LastTID == (tid_t)-1) {
1196                                                         struct ccb_getdev ccb;
1197
1198                                                         xpt_setup_ccb(
1199                                                           &(ccb.ccb_h),
1200                                                           path, /*priority*/5);
1201                                                         xpt_async(
1202                                                           AC_FOUND_DEVICE,
1203                                                           path,
1204                                                           &ccb);
1205                                                 } else {
1206                                                         xpt_async(
1207                                                           AC_INQ_CHANGED,
1208                                                           path, NULL);
1209                                                         xpt_async(
1210                                                           AC_GETDEV_CHANGED,
1211                                                           path, NULL);
1212                                                 }
1213                                         }
1214                                 }
1215                                 /*
1216                                  *      We have the option of clearing the
1217                                  * cached TID for it to be rescanned, or to
1218                                  * set it now even if the device never got
1219                                  * accessed. We chose the later since we
1220                                  * currently do not use the condition that
1221                                  * the TID ever got cached.
1222                                  */
1223                                 ASR_setTid (sc, bus, target, lun, TID);
1224                         }
1225                 }
1226                 /*
1227                  *      The xpt layer can not handle multiple events at the
1228                  * same call.
1229                  */
1230                 if (event & AC_LOST_DEVICE) {
1231                         xpt_async(AC_LOST_DEVICE, sc->ha_path[bus], NULL);
1232                 }
1233                 if (event & AC_INQ_CHANGED) {
1234                         xpt_async(AC_INQ_CHANGED, sc->ha_path[bus], NULL);
1235                 }
1236                 if (event & AC_GETDEV_CHANGED) {
1237                         xpt_async(AC_GETDEV_CHANGED, sc->ha_path[bus], NULL);
1238                 }
1239         } while (--bus >= 0);
1240         return (error);
1241 } /* ASR_rescan */
1242
1243 /*-------------------------------------------------------------------------*/
1244 /*                    Function ASR_reset                                   */
1245 /*-------------------------------------------------------------------------*/
1246 /* The Parameters Passed To This Function Are :                            */
1247 /*     Asr_softc_t *      : HBA miniport driver's adapter data storage.    */
1248 /*                                                                         */
1249 /* This Function Will reset the adapter and resynchronize any data         */
1250 /*                                                                         */
1251 /* Return : None                                                           */
1252 /*-------------------------------------------------------------------------*/
1253
1254 static int
1255 ASR_reset(Asr_softc_t *sc)
1256 {
1257         int s, retVal;
1258
1259         s = splcam();
1260         if ((sc->ha_in_reset == HA_IN_RESET)
1261          || (sc->ha_in_reset == HA_OFF_LINE_RECOVERY)) {
1262                 splx (s);
1263                 return (EBUSY);
1264         }
1265         /*
1266          *      Promotes HA_OPERATIONAL to HA_IN_RESET,
1267          * or HA_OFF_LINE to HA_OFF_LINE_RECOVERY.
1268          */
1269         ++(sc->ha_in_reset);
1270         if (ASR_resetIOP(sc) == 0) {
1271                 debug_asr_printf ("ASR_resetIOP failed\n");
1272                 /*
1273                  *      We really need to take this card off-line, easier said
1274                  * than make sense. Better to keep retrying for now since if a
1275                  * UART cable is connected the blinkLEDs the adapter is now in
1276                  * a hard state requiring action from the monitor commands to
1277                  * the HBA to continue. For debugging waiting forever is a
1278                  * good thing. In a production system, however, one may wish
1279                  * to instead take the card off-line ...
1280                  */
1281                 /* Wait Forever */
1282                 while (ASR_resetIOP(sc) == 0);
1283         }
1284         retVal = ASR_init (sc);
1285         splx (s);
1286         if (retVal != 0) {
1287                 debug_asr_printf ("ASR_init failed\n");
1288                 sc->ha_in_reset = HA_OFF_LINE;
1289                 return (ENXIO);
1290         }
1291         if (ASR_rescan (sc) != 0) {
1292                 debug_asr_printf ("ASR_rescan failed\n");
1293         }
1294         ASR_failActiveCommands (sc);
1295         if (sc->ha_in_reset == HA_OFF_LINE_RECOVERY) {
1296                 printf ("asr%d: Brining adapter back on-line\n",
1297                   sc->ha_path[0]
1298                     ? cam_sim_unit(xpt_path_sim(sc->ha_path[0]))
1299                     : 0);
1300         }
1301         sc->ha_in_reset = HA_OPERATIONAL;
1302         return (0);
1303 } /* ASR_reset */
1304
1305 /*
1306  *      Device timeout handler.
1307  */
1308 static void
1309 asr_timeout(void *arg)
1310 {
1311         union asr_ccb   *ccb = (union asr_ccb *)arg;
1312         Asr_softc_t     *sc = (Asr_softc_t *)(ccb->ccb_h.spriv_ptr0);
1313         int             s;
1314
1315         debug_asr_print_path(ccb);
1316         debug_asr_printf("timed out");
1317
1318         /*
1319          *      Check if the adapter has locked up?
1320          */
1321         if ((s = ASR_getBlinkLedCode(sc)) != 0) {
1322                 /* Reset Adapter */
1323                 printf ("asr%d: Blink LED 0x%x resetting adapter\n",
1324                   cam_sim_unit(xpt_path_sim(ccb->ccb_h.path)), s);
1325                 if (ASR_reset (sc) == ENXIO) {
1326                         /* Try again later */
1327                         ccb->ccb_h.timeout_ch = timeout(asr_timeout,
1328                           (caddr_t)ccb,
1329                           (ccb->ccb_h.timeout * hz) / 1000);
1330                 }
1331                 return;
1332         }
1333         /*
1334          *      Abort does not function on the ASR card!!! Walking away from
1335          * the SCSI command is also *very* dangerous. A SCSI BUS reset is
1336          * our best bet, followed by a complete adapter reset if that fails.
1337          */
1338         s = splcam();
1339         /* Check if we already timed out once to raise the issue */
1340         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_CMD_TIMEOUT) {
1341                 debug_asr_printf (" AGAIN\nreinitializing adapter\n");
1342                 if (ASR_reset (sc) == ENXIO) {
1343                         ccb->ccb_h.timeout_ch = timeout(asr_timeout,
1344                           (caddr_t)ccb,
1345                           (ccb->ccb_h.timeout * hz) / 1000);
1346                 }
1347                 splx(s);
1348                 return;
1349         }
1350         debug_asr_printf ("\nresetting bus\n");
1351         /* If the BUS reset does not take, then an adapter reset is next! */
1352         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1353         ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1354         ccb->ccb_h.timeout_ch = timeout(asr_timeout, (caddr_t)ccb,
1355           (ccb->ccb_h.timeout * hz) / 1000);
1356         ASR_resetBus (sc, cam_sim_bus(xpt_path_sim(ccb->ccb_h.path)));
1357         xpt_async (AC_BUS_RESET, ccb->ccb_h.path, NULL);
1358         splx(s);
1359 } /* asr_timeout */
1360
1361 /*
1362  * send a message asynchronously
1363  */
1364 static int
1365 ASR_queue(Asr_softc_t *sc, PI2O_MESSAGE_FRAME Message)
1366 {
1367         U32             MessageOffset;
1368         union asr_ccb   *ccb;
1369
1370         debug_asr_printf("Host Command Dump:\n");
1371         debug_asr_dump_message(Message);
1372
1373         ccb = (union asr_ccb *)(long)
1374           I2O_MESSAGE_FRAME_getInitiatorContext64(Message);
1375
1376         if ((MessageOffset = ASR_getMessage(sc)) != EMPTY_QUEUE) {
1377                 asr_set_frame(sc, Message, MessageOffset,
1378                               I2O_MESSAGE_FRAME_getMessageSize(Message));
1379                 if (ccb) {
1380                         ASR_ccbAdd (sc, ccb);
1381                 }
1382                 /* Post the command */
1383                 asr_set_ToFIFO(sc, MessageOffset);
1384         } else {
1385                 if (ASR_getBlinkLedCode(sc)) {
1386                         /*
1387                          *      Unlikely we can do anything if we can't grab a
1388                          * message frame :-(, but lets give it a try.
1389                          */
1390                         (void)ASR_reset(sc);
1391                 }
1392         }
1393         return (MessageOffset);
1394 } /* ASR_queue */
1395
1396
1397 /* Simple Scatter Gather elements */
1398 #define SG(SGL,Index,Flags,Buffer,Size)                            \
1399         I2O_FLAGS_COUNT_setCount(                                  \
1400           &(((PI2O_SG_ELEMENT)(SGL))->u.Simple[Index].FlagsCount), \
1401           Size);                                                   \
1402         I2O_FLAGS_COUNT_setFlags(                                  \
1403           &(((PI2O_SG_ELEMENT)(SGL))->u.Simple[Index].FlagsCount), \
1404           I2O_SGL_FLAGS_SIMPLE_ADDRESS_ELEMENT | (Flags));         \
1405         I2O_SGE_SIMPLE_ELEMENT_setPhysicalAddress(                 \
1406           &(((PI2O_SG_ELEMENT)(SGL))->u.Simple[Index]),            \
1407           (Buffer == NULL) ? 0 : KVTOPHYS(Buffer))
1408
1409 /*
1410  *      Retrieve Parameter Group.
1411  */
1412 static void *
1413 ASR_getParams(Asr_softc_t *sc, tid_t TID, int Group, void *Buffer,
1414               unsigned BufferSize)
1415 {
1416         struct paramGetMessage {
1417                 I2O_UTIL_PARAMS_GET_MESSAGE M;
1418                 char
1419                    F[sizeof(I2O_SGE_SIMPLE_ELEMENT)*2 - sizeof(I2O_SG_ELEMENT)];
1420                 struct Operations {
1421                         I2O_PARAM_OPERATIONS_LIST_HEADER Header;
1422                         I2O_PARAM_OPERATION_ALL_TEMPLATE Template[1];
1423                 }                            O;
1424         }                               Message;
1425         struct Operations               *Operations_Ptr;
1426         I2O_UTIL_PARAMS_GET_MESSAGE     *Message_Ptr;
1427         struct ParamBuffer {
1428                 I2O_PARAM_RESULTS_LIST_HEADER       Header;
1429                 I2O_PARAM_READ_OPERATION_RESULT     Read;
1430                 char                                Info[1];
1431         }                               *Buffer_Ptr;
1432
1433         Message_Ptr = (I2O_UTIL_PARAMS_GET_MESSAGE *)ASR_fillMessage(&Message,
1434           sizeof(I2O_UTIL_PARAMS_GET_MESSAGE)
1435             + sizeof(I2O_SGE_SIMPLE_ELEMENT)*2 - sizeof(I2O_SG_ELEMENT));
1436         Operations_Ptr = (struct Operations *)((char *)Message_Ptr
1437           + sizeof(I2O_UTIL_PARAMS_GET_MESSAGE)
1438           + sizeof(I2O_SGE_SIMPLE_ELEMENT)*2 - sizeof(I2O_SG_ELEMENT));
1439         bzero(Operations_Ptr, sizeof(struct Operations));
1440         I2O_PARAM_OPERATIONS_LIST_HEADER_setOperationCount(
1441           &(Operations_Ptr->Header), 1);
1442         I2O_PARAM_OPERATION_ALL_TEMPLATE_setOperation(
1443           &(Operations_Ptr->Template[0]), I2O_PARAMS_OPERATION_FIELD_GET);
1444         I2O_PARAM_OPERATION_ALL_TEMPLATE_setFieldCount(
1445           &(Operations_Ptr->Template[0]), 0xFFFF);
1446         I2O_PARAM_OPERATION_ALL_TEMPLATE_setGroupNumber(
1447           &(Operations_Ptr->Template[0]), Group);
1448         Buffer_Ptr = (struct ParamBuffer *)Buffer;
1449         bzero(Buffer_Ptr, BufferSize);
1450
1451         I2O_MESSAGE_FRAME_setVersionOffset(&(Message_Ptr->StdMessageFrame),
1452           I2O_VERSION_11
1453           + (((sizeof(I2O_UTIL_PARAMS_GET_MESSAGE) - sizeof(I2O_SG_ELEMENT))
1454             / sizeof(U32)) << 4));
1455         I2O_MESSAGE_FRAME_setTargetAddress (&(Message_Ptr->StdMessageFrame),
1456           TID);
1457         I2O_MESSAGE_FRAME_setFunction (&(Message_Ptr->StdMessageFrame),
1458           I2O_UTIL_PARAMS_GET);
1459         /*
1460          *  Set up the buffers as scatter gather elements.
1461          */
1462         SG(&(Message_Ptr->SGL), 0,
1463           I2O_SGL_FLAGS_DIR | I2O_SGL_FLAGS_END_OF_BUFFER,
1464           Operations_Ptr, sizeof(struct Operations));
1465         SG(&(Message_Ptr->SGL), 1,
1466           I2O_SGL_FLAGS_LAST_ELEMENT | I2O_SGL_FLAGS_END_OF_BUFFER,
1467           Buffer_Ptr, BufferSize);
1468
1469         if ((ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr) == CAM_REQ_CMP)
1470          && (Buffer_Ptr->Header.ResultCount)) {
1471                 return ((void *)(Buffer_Ptr->Info));
1472         }
1473         return (NULL);
1474 } /* ASR_getParams */
1475
1476 /*
1477  *      Acquire the LCT information.
1478  */
1479 static int
1480 ASR_acquireLct(Asr_softc_t *sc)
1481 {
1482         PI2O_EXEC_LCT_NOTIFY_MESSAGE    Message_Ptr;
1483         PI2O_SGE_SIMPLE_ELEMENT         sg;
1484         int                             MessageSizeInBytes;
1485         caddr_t                         v;
1486         int                             len;
1487         I2O_LCT                         Table;
1488         PI2O_LCT_ENTRY                  Entry;
1489
1490         /*
1491          *      sc value assumed valid
1492          */
1493         MessageSizeInBytes = sizeof(I2O_EXEC_LCT_NOTIFY_MESSAGE) -
1494             sizeof(I2O_SG_ELEMENT) + sizeof(I2O_SGE_SIMPLE_ELEMENT);
1495         if ((Message_Ptr = (PI2O_EXEC_LCT_NOTIFY_MESSAGE)malloc(
1496             MessageSizeInBytes, M_TEMP, M_WAITOK)) == NULL) {
1497                 return (ENOMEM);
1498         }
1499         (void)ASR_fillMessage((void *)Message_Ptr, MessageSizeInBytes);
1500         I2O_MESSAGE_FRAME_setVersionOffset(&(Message_Ptr->StdMessageFrame),
1501             (I2O_VERSION_11 + (((sizeof(I2O_EXEC_LCT_NOTIFY_MESSAGE) -
1502             sizeof(I2O_SG_ELEMENT)) / sizeof(U32)) << 4)));
1503         I2O_MESSAGE_FRAME_setFunction(&(Message_Ptr->StdMessageFrame),
1504             I2O_EXEC_LCT_NOTIFY);
1505         I2O_EXEC_LCT_NOTIFY_MESSAGE_setClassIdentifier(Message_Ptr,
1506             I2O_CLASS_MATCH_ANYCLASS);
1507         /*
1508          *      Call the LCT table to determine the number of device entries
1509          * to reserve space for.
1510          */
1511         SG(&(Message_Ptr->SGL), 0,
1512           I2O_SGL_FLAGS_LAST_ELEMENT | I2O_SGL_FLAGS_END_OF_BUFFER, &Table,
1513           sizeof(I2O_LCT));
1514         /*
1515          *      since this code is reused in several systems, code efficiency
1516          * is greater by using a shift operation rather than a divide by
1517          * sizeof(u_int32_t).
1518          */
1519         I2O_LCT_setTableSize(&Table,
1520           (sizeof(I2O_LCT) - sizeof(I2O_LCT_ENTRY)) >> 2);
1521         (void)ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr);
1522         /*
1523          *      Determine the size of the LCT table.
1524          */
1525         if (sc->ha_LCT) {
1526                 free(sc->ha_LCT, M_TEMP);
1527         }
1528         /*
1529          *      malloc only generates contiguous memory when less than a
1530          * page is expected. We must break the request up into an SG list ...
1531          */
1532         if (((len = (I2O_LCT_getTableSize(&Table) << 2)) <=
1533           (sizeof(I2O_LCT) - sizeof(I2O_LCT_ENTRY)))
1534          || (len > (128 * 1024))) {     /* Arbitrary */
1535                 free(Message_Ptr, M_TEMP);
1536                 return (EINVAL);
1537         }
1538         if ((sc->ha_LCT = (PI2O_LCT)malloc (len, M_TEMP, M_WAITOK)) == NULL) {
1539                 free(Message_Ptr, M_TEMP);
1540                 return (ENOMEM);
1541         }
1542         /*
1543          *      since this code is reused in several systems, code efficiency
1544          * is greater by using a shift operation rather than a divide by
1545          * sizeof(u_int32_t).
1546          */
1547         I2O_LCT_setTableSize(sc->ha_LCT,
1548           (sizeof(I2O_LCT) - sizeof(I2O_LCT_ENTRY)) >> 2);
1549         /*
1550          *      Convert the access to the LCT table into a SG list.
1551          */
1552         sg = Message_Ptr->SGL.u.Simple;
1553         v = (caddr_t)(sc->ha_LCT);
1554         for (;;) {
1555                 int next, base, span;
1556
1557                 span = 0;
1558                 next = base = KVTOPHYS(v);
1559                 I2O_SGE_SIMPLE_ELEMENT_setPhysicalAddress(sg, base);
1560
1561                 /* How far can we go contiguously */
1562                 while ((len > 0) && (base == next)) {
1563                         int size;
1564
1565                         next = trunc_page(base) + PAGE_SIZE;
1566                         size = next - base;
1567                         if (size > len) {
1568                                 size = len;
1569                         }
1570                         span += size;
1571                         v += size;
1572                         len -= size;
1573                         base = KVTOPHYS(v);
1574                 }
1575
1576                 /* Construct the Flags */
1577                 I2O_FLAGS_COUNT_setCount(&(sg->FlagsCount), span);
1578                 {
1579                         int rw = I2O_SGL_FLAGS_SIMPLE_ADDRESS_ELEMENT;
1580                         if (len <= 0) {
1581                                 rw = (I2O_SGL_FLAGS_SIMPLE_ADDRESS_ELEMENT
1582                                     | I2O_SGL_FLAGS_LAST_ELEMENT
1583                                     | I2O_SGL_FLAGS_END_OF_BUFFER);
1584                         }
1585                         I2O_FLAGS_COUNT_setFlags(&(sg->FlagsCount), rw);
1586                 }
1587
1588                 if (len <= 0) {
1589                         break;
1590                 }
1591
1592                 /*
1593                  * Incrementing requires resizing of the packet.
1594                  */
1595                 ++sg;
1596                 MessageSizeInBytes += sizeof(*sg);
1597                 I2O_MESSAGE_FRAME_setMessageSize(
1598                   &(Message_Ptr->StdMessageFrame),
1599                   I2O_MESSAGE_FRAME_getMessageSize(
1600                     &(Message_Ptr->StdMessageFrame))
1601                   + (sizeof(*sg) / sizeof(U32)));
1602                 {
1603                         PI2O_EXEC_LCT_NOTIFY_MESSAGE NewMessage_Ptr;
1604
1605                         if ((NewMessage_Ptr = (PI2O_EXEC_LCT_NOTIFY_MESSAGE)
1606                             malloc(MessageSizeInBytes, M_TEMP, M_WAITOK))
1607                             == NULL) {
1608                                 free(sc->ha_LCT, M_TEMP);
1609                                 sc->ha_LCT = NULL;
1610                                 free(Message_Ptr, M_TEMP);
1611                                 return (ENOMEM);
1612                         }
1613                         span = ((caddr_t)sg) - (caddr_t)Message_Ptr;
1614                         bcopy(Message_Ptr, NewMessage_Ptr, span);
1615                         free(Message_Ptr, M_TEMP);
1616                         sg = (PI2O_SGE_SIMPLE_ELEMENT)
1617                           (((caddr_t)NewMessage_Ptr) + span);
1618                         Message_Ptr = NewMessage_Ptr;
1619                 }
1620         }
1621         {       int retval;
1622
1623                 retval = ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr);
1624                 free(Message_Ptr, M_TEMP);
1625                 if (retval != CAM_REQ_CMP) {
1626                         return (ENODEV);
1627                 }
1628         }
1629         /* If the LCT table grew, lets truncate accesses */
1630         if (I2O_LCT_getTableSize(&Table) < I2O_LCT_getTableSize(sc->ha_LCT)) {
1631                 I2O_LCT_setTableSize(sc->ha_LCT, I2O_LCT_getTableSize(&Table));
1632         }
1633         for (Entry = sc->ha_LCT->LCTEntry; Entry < (PI2O_LCT_ENTRY)
1634           (((U32 *)sc->ha_LCT)+I2O_LCT_getTableSize(sc->ha_LCT));
1635           ++Entry) {
1636                 Entry->le_type = I2O_UNKNOWN;
1637                 switch (I2O_CLASS_ID_getClass(&(Entry->ClassID))) {
1638
1639                 case I2O_CLASS_RANDOM_BLOCK_STORAGE:
1640                         Entry->le_type = I2O_BSA;
1641                         break;
1642
1643                 case I2O_CLASS_SCSI_PERIPHERAL:
1644                         Entry->le_type = I2O_SCSI;
1645                         break;
1646
1647                 case I2O_CLASS_FIBRE_CHANNEL_PERIPHERAL:
1648                         Entry->le_type = I2O_FCA;
1649                         break;
1650
1651                 case I2O_CLASS_BUS_ADAPTER_PORT:
1652                         Entry->le_type = I2O_PORT | I2O_SCSI;
1653                         /* FALLTHRU */
1654                 case I2O_CLASS_FIBRE_CHANNEL_PORT:
1655                         if (I2O_CLASS_ID_getClass(&(Entry->ClassID)) ==
1656                           I2O_CLASS_FIBRE_CHANNEL_PORT) {
1657                                 Entry->le_type = I2O_PORT | I2O_FCA;
1658                         }
1659                 {       struct ControllerInfo {
1660                                 I2O_PARAM_RESULTS_LIST_HEADER       Header;
1661                                 I2O_PARAM_READ_OPERATION_RESULT     Read;
1662                                 I2O_HBA_SCSI_CONTROLLER_INFO_SCALAR Info;
1663                         } Buffer;
1664                         PI2O_HBA_SCSI_CONTROLLER_INFO_SCALAR Info;
1665
1666                         Entry->le_bus = 0xff;
1667                         Entry->le_target = 0xff;
1668                         Entry->le_lun = 0xff;
1669
1670                         if ((Info = (PI2O_HBA_SCSI_CONTROLLER_INFO_SCALAR)
1671                           ASR_getParams(sc,
1672                             I2O_LCT_ENTRY_getLocalTID(Entry),
1673                             I2O_HBA_SCSI_CONTROLLER_INFO_GROUP_NO,
1674                             &Buffer, sizeof(struct ControllerInfo))) == NULL) {
1675                                 continue;
1676                         }
1677                         Entry->le_target
1678                           = I2O_HBA_SCSI_CONTROLLER_INFO_SCALAR_getInitiatorID(
1679                             Info);
1680                         Entry->le_lun = 0;
1681                 }       /* FALLTHRU */
1682                 default:
1683                         continue;
1684                 }
1685                 {       struct DeviceInfo {
1686                                 I2O_PARAM_RESULTS_LIST_HEADER   Header;
1687                                 I2O_PARAM_READ_OPERATION_RESULT Read;
1688                                 I2O_DPT_DEVICE_INFO_SCALAR      Info;
1689                         } Buffer;
1690                         PI2O_DPT_DEVICE_INFO_SCALAR      Info;
1691
1692                         Entry->le_bus = 0xff;
1693                         Entry->le_target = 0xff;
1694                         Entry->le_lun = 0xff;
1695
1696                         if ((Info = (PI2O_DPT_DEVICE_INFO_SCALAR)
1697                           ASR_getParams(sc,
1698                             I2O_LCT_ENTRY_getLocalTID(Entry),
1699                             I2O_DPT_DEVICE_INFO_GROUP_NO,
1700                             &Buffer, sizeof(struct DeviceInfo))) == NULL) {
1701                                 continue;
1702                         }
1703                         Entry->le_type
1704                           |= I2O_DPT_DEVICE_INFO_SCALAR_getDeviceType(Info);
1705                         Entry->le_bus
1706                           = I2O_DPT_DEVICE_INFO_SCALAR_getBus(Info);
1707                         if ((Entry->le_bus > sc->ha_MaxBus)
1708                          && (Entry->le_bus <= MAX_CHANNEL)) {
1709                                 sc->ha_MaxBus = Entry->le_bus;
1710                         }
1711                         Entry->le_target
1712                           = I2O_DPT_DEVICE_INFO_SCALAR_getIdentifier(Info);
1713                         Entry->le_lun
1714                           = I2O_DPT_DEVICE_INFO_SCALAR_getLunInfo(Info);
1715                 }
1716         }
1717         /*
1718          *      A zero return value indicates success.
1719          */
1720         return (0);
1721 } /* ASR_acquireLct */
1722
1723 /*
1724  * Initialize a message frame.
1725  * We assume that the CDB has already been set up, so all we do here is
1726  * generate the Scatter Gather list.
1727  */
1728 static PI2O_MESSAGE_FRAME
1729 ASR_init_message(union asr_ccb *ccb, PI2O_MESSAGE_FRAME Message)
1730 {
1731         PI2O_MESSAGE_FRAME      Message_Ptr;
1732         PI2O_SGE_SIMPLE_ELEMENT sg;
1733         Asr_softc_t             *sc = (Asr_softc_t *)(ccb->ccb_h.spriv_ptr0);
1734         vm_size_t               size, len;
1735         caddr_t                 v;
1736         U32                     MessageSize;
1737         int                     next, span, base, rw;
1738         int                     target = ccb->ccb_h.target_id;
1739         int                     lun = ccb->ccb_h.target_lun;
1740         int                     bus =cam_sim_bus(xpt_path_sim(ccb->ccb_h.path));
1741         tid_t                   TID;
1742
1743         /* We only need to zero out the PRIVATE_SCSI_SCB_EXECUTE_MESSAGE */
1744         Message_Ptr = (I2O_MESSAGE_FRAME *)Message;
1745         bzero(Message_Ptr, (sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE) -
1746               sizeof(I2O_SG_ELEMENT)));
1747
1748         if ((TID = ASR_getTid (sc, bus, target, lun)) == (tid_t)-1) {
1749                 PI2O_LCT_ENTRY Device;
1750
1751                 TID = 0;
1752                 for (Device = sc->ha_LCT->LCTEntry; Device < (PI2O_LCT_ENTRY)
1753                     (((U32 *)sc->ha_LCT) + I2O_LCT_getTableSize(sc->ha_LCT));
1754                     ++Device) {
1755                         if ((Device->le_type != I2O_UNKNOWN)
1756                          && (Device->le_bus == bus)
1757                          && (Device->le_target == target)
1758                          && (Device->le_lun == lun)
1759                          && (I2O_LCT_ENTRY_getUserTID(Device) == 0xFFF)) {
1760                                 TID = I2O_LCT_ENTRY_getLocalTID(Device);
1761                                 ASR_setTid(sc, Device->le_bus,
1762                                            Device->le_target, Device->le_lun,
1763                                            TID);
1764                                 break;
1765                         }
1766                 }
1767         }
1768         if (TID == (tid_t)0) {
1769                 return (NULL);
1770         }
1771         I2O_MESSAGE_FRAME_setTargetAddress(Message_Ptr, TID);
1772         PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setTID(
1773             (PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr, TID);
1774         I2O_MESSAGE_FRAME_setVersionOffset(Message_Ptr, I2O_VERSION_11 |
1775           (((sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE) - sizeof(I2O_SG_ELEMENT))
1776                 / sizeof(U32)) << 4));
1777         I2O_MESSAGE_FRAME_setMessageSize(Message_Ptr,
1778           (sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE)
1779           - sizeof(I2O_SG_ELEMENT)) / sizeof(U32));
1780         I2O_MESSAGE_FRAME_setInitiatorAddress (Message_Ptr, 1);
1781         I2O_MESSAGE_FRAME_setFunction(Message_Ptr, I2O_PRIVATE_MESSAGE);
1782         I2O_PRIVATE_MESSAGE_FRAME_setXFunctionCode (
1783           (PI2O_PRIVATE_MESSAGE_FRAME)Message_Ptr, I2O_SCSI_SCB_EXEC);
1784         PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setSCBFlags (
1785           (PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr,
1786             I2O_SCB_FLAG_ENABLE_DISCONNECT
1787           | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
1788           | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER);
1789         /*
1790          * We do not need any (optional byteswapping) method access to
1791          * the Initiator & Transaction context field.
1792          */
1793         I2O_MESSAGE_FRAME_setInitiatorContext64(Message, (long)ccb);
1794
1795         I2O_PRIVATE_MESSAGE_FRAME_setOrganizationID(
1796           (PI2O_PRIVATE_MESSAGE_FRAME)Message_Ptr, DPT_ORGANIZATION_ID);
1797         /*
1798          * copy the cdb over
1799          */
1800         PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setCDBLength(
1801             (PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr, ccb->csio.cdb_len);
1802         bcopy(&(ccb->csio.cdb_io),
1803             ((PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr)->CDB,
1804             ccb->csio.cdb_len);
1805
1806         /*
1807          * Given a buffer describing a transfer, set up a scatter/gather map
1808          * in a ccb to map that SCSI transfer.
1809          */
1810
1811         rw = (ccb->ccb_h.flags & CAM_DIR_IN) ? 0 : I2O_SGL_FLAGS_DIR;
1812
1813         PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setSCBFlags (
1814           (PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr,
1815           (ccb->csio.dxfer_len)
1816             ? ((rw) ? (I2O_SCB_FLAG_XFER_TO_DEVICE
1817                      | I2O_SCB_FLAG_ENABLE_DISCONNECT
1818                      | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
1819                      | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER)
1820                     : (I2O_SCB_FLAG_XFER_FROM_DEVICE
1821                      | I2O_SCB_FLAG_ENABLE_DISCONNECT
1822                      | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
1823                      | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER))
1824             :         (I2O_SCB_FLAG_ENABLE_DISCONNECT
1825                      | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
1826                      | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER));
1827
1828         /*
1829          * Given a transfer described by a `data', fill in the SG list.
1830          */
1831         sg = &((PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr)->SGL.u.Simple[0];
1832
1833         len = ccb->csio.dxfer_len;
1834         v = ccb->csio.data_ptr;
1835         KASSERT(ccb->csio.dxfer_len >= 0, ("csio.dxfer_len < 0"));
1836         MessageSize = I2O_MESSAGE_FRAME_getMessageSize(Message_Ptr);
1837         PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setByteCount(
1838           (PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr, len);
1839         while ((len > 0) && (sg < &((PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)
1840           Message_Ptr)->SGL.u.Simple[SG_SIZE])) {
1841                 span = 0;
1842                 next = base = KVTOPHYS(v);
1843                 I2O_SGE_SIMPLE_ELEMENT_setPhysicalAddress(sg, base);
1844
1845                 /* How far can we go contiguously */
1846                 while ((len > 0) && (base == next)) {
1847                         next = trunc_page(base) + PAGE_SIZE;
1848                         size = next - base;
1849                         if (size > len) {
1850                                 size = len;
1851                         }
1852                         span += size;
1853                         v += size;
1854                         len -= size;
1855                         base = KVTOPHYS(v);
1856                 }
1857
1858                 I2O_FLAGS_COUNT_setCount(&(sg->FlagsCount), span);
1859                 if (len == 0) {
1860                         rw |= I2O_SGL_FLAGS_LAST_ELEMENT;
1861                 }
1862                 I2O_FLAGS_COUNT_setFlags(&(sg->FlagsCount),
1863                   I2O_SGL_FLAGS_SIMPLE_ADDRESS_ELEMENT | rw);
1864                 ++sg;
1865                 MessageSize += sizeof(*sg) / sizeof(U32);
1866         }
1867         /* We always do the request sense ... */
1868         if ((span = ccb->csio.sense_len) == 0) {
1869                 span = sizeof(ccb->csio.sense_data);
1870         }
1871         SG(sg, 0, I2O_SGL_FLAGS_LAST_ELEMENT | I2O_SGL_FLAGS_END_OF_BUFFER,
1872           &(ccb->csio.sense_data), span);
1873         I2O_MESSAGE_FRAME_setMessageSize(Message_Ptr,
1874           MessageSize + (sizeof(*sg) / sizeof(U32)));
1875         return (Message_Ptr);
1876 } /* ASR_init_message */
1877
1878 /*
1879  *      Reset the adapter.
1880  */
1881 static U32
1882 ASR_initOutBound(Asr_softc_t *sc)
1883 {
1884         struct initOutBoundMessage {
1885                 I2O_EXEC_OUTBOUND_INIT_MESSAGE M;
1886                 U32                            R;
1887         }                               Message;
1888         PI2O_EXEC_OUTBOUND_INIT_MESSAGE Message_Ptr;
1889         U32                             *volatile Reply_Ptr;
1890         U32                             Old;
1891
1892         /*
1893          *  Build up our copy of the Message.
1894          */
1895         Message_Ptr = (PI2O_EXEC_OUTBOUND_INIT_MESSAGE)ASR_fillMessage(&Message,
1896           sizeof(I2O_EXEC_OUTBOUND_INIT_MESSAGE));
1897         I2O_MESSAGE_FRAME_setFunction(&(Message_Ptr->StdMessageFrame),
1898           I2O_EXEC_OUTBOUND_INIT);
1899         I2O_EXEC_OUTBOUND_INIT_MESSAGE_setHostPageFrameSize(Message_Ptr, PAGE_SIZE);
1900         I2O_EXEC_OUTBOUND_INIT_MESSAGE_setOutboundMFrameSize(Message_Ptr,
1901           sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME));
1902         /*
1903          *  Reset the Reply Status
1904          */
1905         *(Reply_Ptr = (U32 *)((char *)Message_Ptr
1906           + sizeof(I2O_EXEC_OUTBOUND_INIT_MESSAGE))) = 0;
1907         SG (&(Message_Ptr->SGL), 0, I2O_SGL_FLAGS_LAST_ELEMENT, Reply_Ptr,
1908           sizeof(U32));
1909         /*
1910          *      Send the Message out
1911          */
1912         if ((Old = ASR_initiateCp(sc, (PI2O_MESSAGE_FRAME)Message_Ptr)) != 
1913             0xffffffff) {
1914                 u_long size, addr;
1915
1916                 /*
1917                  *      Wait for a response (Poll).
1918                  */
1919                 while (*Reply_Ptr < I2O_EXEC_OUTBOUND_INIT_REJECTED);
1920                 /*
1921                  *      Re-enable the interrupts.
1922                  */
1923                 asr_set_intr(sc, Old);
1924                 /*
1925                  *      Populate the outbound table.
1926                  */
1927                 if (sc->ha_Msgs == NULL) {
1928
1929                         /* Allocate the reply frames */
1930                         size = sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)
1931                           * sc->ha_Msgs_Count;
1932
1933                         /*
1934                          *      contigmalloc only works reliably at
1935                          * initialization time.
1936                          */
1937                         if ((sc->ha_Msgs = (PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)
1938                           contigmalloc (size, M_DEVBUF, M_WAITOK, 0ul,
1939                             0xFFFFFFFFul, (u_long)sizeof(U32), 0ul)) != NULL) {
1940                                 bzero(sc->ha_Msgs, size);
1941                                 sc->ha_Msgs_Phys = KVTOPHYS(sc->ha_Msgs);
1942                         }
1943                 }
1944
1945                 /* Initialize the outbound FIFO */
1946                 if (sc->ha_Msgs != NULL)
1947                 for(size = sc->ha_Msgs_Count, addr = sc->ha_Msgs_Phys;
1948                     size; --size) {
1949                         asr_set_FromFIFO(sc, addr);
1950                         addr += sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME);
1951                 }
1952                 return (*Reply_Ptr);
1953         }
1954         return (0);
1955 } /* ASR_initOutBound */
1956
1957 /*
1958  *      Set the system table
1959  */
1960 static int
1961 ASR_setSysTab(Asr_softc_t *sc)
1962 {
1963         PI2O_EXEC_SYS_TAB_SET_MESSAGE Message_Ptr;
1964         PI2O_SET_SYSTAB_HEADER        SystemTable;
1965         Asr_softc_t                 * ha;
1966         PI2O_SGE_SIMPLE_ELEMENT       sg;
1967         int                           retVal;
1968
1969         if ((SystemTable = (PI2O_SET_SYSTAB_HEADER)malloc (
1970           sizeof(I2O_SET_SYSTAB_HEADER), M_TEMP, M_WAITOK | M_ZERO)) == NULL) {
1971                 return (ENOMEM);
1972         }
1973         for (ha = Asr_softc_list; ha; ha = ha->ha_next) {
1974                 ++SystemTable->NumberEntries;
1975         }
1976         if ((Message_Ptr = (PI2O_EXEC_SYS_TAB_SET_MESSAGE)malloc (
1977           sizeof(I2O_EXEC_SYS_TAB_SET_MESSAGE) - sizeof(I2O_SG_ELEMENT)
1978            + ((3+SystemTable->NumberEntries) * sizeof(I2O_SGE_SIMPLE_ELEMENT)),
1979           M_TEMP, M_WAITOK)) == NULL) {
1980                 free(SystemTable, M_TEMP);
1981                 return (ENOMEM);
1982         }
1983         (void)ASR_fillMessage((void *)Message_Ptr,
1984           sizeof(I2O_EXEC_SYS_TAB_SET_MESSAGE) - sizeof(I2O_SG_ELEMENT)
1985            + ((3+SystemTable->NumberEntries) * sizeof(I2O_SGE_SIMPLE_ELEMENT)));
1986         I2O_MESSAGE_FRAME_setVersionOffset(&(Message_Ptr->StdMessageFrame),
1987           (I2O_VERSION_11 +
1988           (((sizeof(I2O_EXEC_SYS_TAB_SET_MESSAGE) - sizeof(I2O_SG_ELEMENT))
1989                         / sizeof(U32)) << 4)));
1990         I2O_MESSAGE_FRAME_setFunction(&(Message_Ptr->StdMessageFrame),
1991           I2O_EXEC_SYS_TAB_SET);
1992         /*
1993          *      Call the LCT table to determine the number of device entries
1994          * to reserve space for.
1995          *      since this code is reused in several systems, code efficiency
1996          * is greater by using a shift operation rather than a divide by
1997          * sizeof(u_int32_t).
1998          */
1999         sg = (PI2O_SGE_SIMPLE_ELEMENT)((char *)Message_Ptr
2000           + ((I2O_MESSAGE_FRAME_getVersionOffset(
2001               &(Message_Ptr->StdMessageFrame)) & 0xF0) >> 2));
2002         SG(sg, 0, I2O_SGL_FLAGS_DIR, SystemTable, sizeof(I2O_SET_SYSTAB_HEADER));
2003         ++sg;
2004         for (ha = Asr_softc_list; ha; ha = ha->ha_next) {
2005                 SG(sg, 0,
2006                   ((ha->ha_next)
2007                     ? (I2O_SGL_FLAGS_DIR)
2008                     : (I2O_SGL_FLAGS_DIR | I2O_SGL_FLAGS_END_OF_BUFFER)),
2009                   &(ha->ha_SystemTable), sizeof(ha->ha_SystemTable));
2010                 ++sg;
2011         }
2012         SG(sg, 0, I2O_SGL_FLAGS_DIR | I2O_SGL_FLAGS_END_OF_BUFFER, NULL, 0);
2013         SG(sg, 1, I2O_SGL_FLAGS_DIR | I2O_SGL_FLAGS_LAST_ELEMENT
2014             | I2O_SGL_FLAGS_END_OF_BUFFER, NULL, 0);
2015         retVal = ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr);
2016         free(Message_Ptr, M_TEMP);
2017         free(SystemTable, M_TEMP);
2018         return (retVal);
2019 } /* ASR_setSysTab */
2020
2021 static int
2022 ASR_acquireHrt(Asr_softc_t *sc)
2023 {
2024         I2O_EXEC_HRT_GET_MESSAGE        Message;
2025         I2O_EXEC_HRT_GET_MESSAGE        *Message_Ptr;
2026         struct {
2027                 I2O_HRT       Header;
2028                 I2O_HRT_ENTRY Entry[MAX_CHANNEL];
2029         }                               Hrt;
2030         u_int8_t                        NumberOfEntries;
2031         PI2O_HRT_ENTRY                  Entry;
2032
2033         bzero(&Hrt, sizeof (Hrt));
2034         Message_Ptr = (I2O_EXEC_HRT_GET_MESSAGE *)ASR_fillMessage(&Message,
2035           sizeof(I2O_EXEC_HRT_GET_MESSAGE) - sizeof(I2O_SG_ELEMENT)
2036           + sizeof(I2O_SGE_SIMPLE_ELEMENT));
2037         I2O_MESSAGE_FRAME_setVersionOffset(&(Message_Ptr->StdMessageFrame),
2038           (I2O_VERSION_11
2039           + (((sizeof(I2O_EXEC_HRT_GET_MESSAGE) - sizeof(I2O_SG_ELEMENT))
2040                    / sizeof(U32)) << 4)));
2041         I2O_MESSAGE_FRAME_setFunction (&(Message_Ptr->StdMessageFrame),
2042           I2O_EXEC_HRT_GET);
2043
2044         /*
2045          *  Set up the buffers as scatter gather elements.
2046          */
2047         SG(&(Message_Ptr->SGL), 0,
2048           I2O_SGL_FLAGS_LAST_ELEMENT | I2O_SGL_FLAGS_END_OF_BUFFER,
2049           &Hrt, sizeof(Hrt));
2050         if (ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr) != CAM_REQ_CMP) {
2051                 return (ENODEV);
2052         }
2053         if ((NumberOfEntries = I2O_HRT_getNumberEntries(&Hrt.Header))
2054           > (MAX_CHANNEL + 1)) {
2055                 NumberOfEntries = MAX_CHANNEL + 1;
2056         }
2057         for (Entry = Hrt.Header.HRTEntry;
2058           NumberOfEntries != 0;
2059           ++Entry, --NumberOfEntries) {
2060                 PI2O_LCT_ENTRY Device;
2061
2062                 for (Device = sc->ha_LCT->LCTEntry; Device < (PI2O_LCT_ENTRY)
2063                   (((U32 *)sc->ha_LCT)+I2O_LCT_getTableSize(sc->ha_LCT));
2064                   ++Device) {
2065                         if (I2O_LCT_ENTRY_getLocalTID(Device)
2066                           == (I2O_HRT_ENTRY_getAdapterID(Entry) & 0xFFF)) {
2067                                 Device->le_bus = I2O_HRT_ENTRY_getAdapterID(
2068                                   Entry) >> 16;
2069                                 if ((Device->le_bus > sc->ha_MaxBus)
2070                                  && (Device->le_bus <= MAX_CHANNEL)) {
2071                                         sc->ha_MaxBus = Device->le_bus;
2072                                 }
2073                         }
2074                 }
2075         }
2076         return (0);
2077 } /* ASR_acquireHrt */
2078
2079 /*
2080  *      Enable the adapter.
2081  */
2082 static int
2083 ASR_enableSys(Asr_softc_t *sc)
2084 {
2085         I2O_EXEC_SYS_ENABLE_MESSAGE     Message;
2086         PI2O_EXEC_SYS_ENABLE_MESSAGE    Message_Ptr;
2087
2088         Message_Ptr = (PI2O_EXEC_SYS_ENABLE_MESSAGE)ASR_fillMessage(&Message,
2089           sizeof(I2O_EXEC_SYS_ENABLE_MESSAGE));
2090         I2O_MESSAGE_FRAME_setFunction(&(Message_Ptr->StdMessageFrame),
2091           I2O_EXEC_SYS_ENABLE);
2092         return (ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr) != 0);
2093 } /* ASR_enableSys */
2094
2095 /*
2096  *      Perform the stages necessary to initialize the adapter
2097  */
2098 static int
2099 ASR_init(Asr_softc_t *sc)
2100 {
2101         return ((ASR_initOutBound(sc) == 0)
2102          || (ASR_setSysTab(sc) != CAM_REQ_CMP)
2103          || (ASR_enableSys(sc) != CAM_REQ_CMP));
2104 } /* ASR_init */
2105
2106 /*
2107  *      Send a Synchronize Cache command to the target device.
2108  */
2109 static void
2110 ASR_sync(Asr_softc_t *sc, int bus, int target, int lun)
2111 {
2112         tid_t TID;
2113
2114         /*
2115          * We will not synchronize the device when there are outstanding
2116          * commands issued by the OS (this is due to a locked up device,
2117          * as the OS normally would flush all outstanding commands before
2118          * issuing a shutdown or an adapter reset).
2119          */
2120         if ((sc != NULL)
2121          && (LIST_FIRST(&(sc->ha_ccb)) != NULL)
2122          && ((TID = ASR_getTid (sc, bus, target, lun)) != (tid_t)-1)
2123          && (TID != (tid_t)0)) {
2124                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE        Message;
2125                 PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE       Message_Ptr;
2126
2127                 Message_Ptr = (PRIVATE_SCSI_SCB_EXECUTE_MESSAGE *)&Message;
2128                 bzero(Message_Ptr, sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE)
2129                     - sizeof(I2O_SG_ELEMENT) + sizeof(I2O_SGE_SIMPLE_ELEMENT));
2130
2131                 I2O_MESSAGE_FRAME_setVersionOffset(
2132                   (PI2O_MESSAGE_FRAME)Message_Ptr,
2133                   I2O_VERSION_11
2134                     | (((sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE)
2135                     - sizeof(I2O_SG_ELEMENT))
2136                         / sizeof(U32)) << 4));
2137                 I2O_MESSAGE_FRAME_setMessageSize(
2138                   (PI2O_MESSAGE_FRAME)Message_Ptr,
2139                   (sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE)
2140                   - sizeof(I2O_SG_ELEMENT))
2141                         / sizeof(U32));
2142                 I2O_MESSAGE_FRAME_setInitiatorAddress (
2143                   (PI2O_MESSAGE_FRAME)Message_Ptr, 1);
2144                 I2O_MESSAGE_FRAME_setFunction(
2145                   (PI2O_MESSAGE_FRAME)Message_Ptr, I2O_PRIVATE_MESSAGE);
2146                 I2O_MESSAGE_FRAME_setTargetAddress(
2147                   (PI2O_MESSAGE_FRAME)Message_Ptr, TID);
2148                 I2O_PRIVATE_MESSAGE_FRAME_setXFunctionCode (
2149                   (PI2O_PRIVATE_MESSAGE_FRAME)Message_Ptr,
2150                   I2O_SCSI_SCB_EXEC);
2151                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setTID(Message_Ptr, TID);
2152                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setSCBFlags (Message_Ptr,
2153                     I2O_SCB_FLAG_ENABLE_DISCONNECT
2154                   | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
2155                   | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER);
2156                 I2O_PRIVATE_MESSAGE_FRAME_setOrganizationID(
2157                   (PI2O_PRIVATE_MESSAGE_FRAME)Message_Ptr,
2158                   DPT_ORGANIZATION_ID);
2159                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setCDBLength(Message_Ptr, 6);
2160                 Message_Ptr->CDB[0] = SYNCHRONIZE_CACHE;
2161                 Message_Ptr->CDB[1] = (lun << 5);
2162
2163                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setSCBFlags (Message_Ptr,
2164                   (I2O_SCB_FLAG_XFER_FROM_DEVICE
2165                     | I2O_SCB_FLAG_ENABLE_DISCONNECT
2166                     | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
2167                     | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER));
2168
2169                 (void)ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr);
2170
2171         }
2172 }
2173
2174 static void
2175 ASR_synchronize(Asr_softc_t *sc)
2176 {
2177         int bus, target, lun;
2178
2179         for (bus = 0; bus <= sc->ha_MaxBus; ++bus) {
2180                 for (target = 0; target <= sc->ha_MaxId; ++target) {
2181                         for (lun = 0; lun <= sc->ha_MaxLun; ++lun) {
2182                                 ASR_sync(sc,bus,target,lun);
2183                         }
2184                 }
2185         }
2186 }
2187
2188 /*
2189  *      Reset the HBA, targets and BUS.
2190  *              Currently this resets *all* the SCSI busses.
2191  */
2192 static __inline void
2193 asr_hbareset(Asr_softc_t *sc)
2194 {
2195         ASR_synchronize(sc);
2196         (void)ASR_reset(sc);
2197 } /* asr_hbareset */
2198
2199 /*
2200  *      A reduced copy of the real pci_map_mem, incorporating the MAX_MAP
2201  * limit and a reduction in error checking (in the pre 4.0 case).
2202  */
2203 static int
2204 asr_pci_map_mem(device_t dev, Asr_softc_t *sc)
2205 {
2206         int             rid;
2207         u_int32_t       p, l, s;
2208
2209         /*
2210          * I2O specification says we must find first *memory* mapped BAR
2211          */
2212         for (rid = 0; rid < 4; rid++) {
2213                 p = pci_read_config(dev, PCIR_BAR(rid), sizeof(p));
2214                 if ((p & 1) == 0) {
2215                         break;
2216                 }
2217         }
2218         /*
2219          *      Give up?
2220          */
2221         if (rid >= 4) {
2222                 rid = 0;
2223         }
2224         rid = PCIR_BAR(rid);
2225         p = pci_read_config(dev, rid, sizeof(p));
2226         pci_write_config(dev, rid, -1, sizeof(p));
2227         l = 0 - (pci_read_config(dev, rid, sizeof(l)) & ~15);
2228         pci_write_config(dev, rid, p, sizeof(p));
2229         if (l > MAX_MAP) {
2230                 l = MAX_MAP;
2231         }
2232         /*
2233          * The 2005S Zero Channel RAID solution is not a perfect PCI
2234          * citizen. It asks for 4MB on BAR0, and 0MB on BAR1, once
2235          * enabled it rewrites the size of BAR0 to 2MB, sets BAR1 to
2236          * BAR0+2MB and sets it's size to 2MB. The IOP registers are
2237          * accessible via BAR0, the messaging registers are accessible
2238          * via BAR1. If the subdevice code is 50 to 59 decimal.
2239          */
2240         s = pci_read_config(dev, PCIR_DEVVENDOR, sizeof(s));
2241         if (s != 0xA5111044) {
2242                 s = pci_read_config(dev, PCIR_SUBVEND_0, sizeof(s));
2243                 if ((((ADPTDOMINATOR_SUB_ID_START ^ s) & 0xF000FFFF) == 0)
2244                  && (ADPTDOMINATOR_SUB_ID_START <= s)
2245                  && (s <= ADPTDOMINATOR_SUB_ID_END)) {
2246                         l = MAX_MAP; /* Conjoined BAR Raptor Daptor */
2247                 }
2248         }
2249         p &= ~15;
2250         sc->ha_mem_res = bus_alloc_resource(dev, SYS_RES_MEMORY, &rid,
2251           p, p + l, l, RF_ACTIVE);
2252         if (sc->ha_mem_res == NULL) {
2253                 return (0);
2254         }
2255         sc->ha_Base = rman_get_start(sc->ha_mem_res);
2256         sc->ha_i2o_bhandle = rman_get_bushandle(sc->ha_mem_res);
2257         sc->ha_i2o_btag = rman_get_bustag(sc->ha_mem_res);
2258
2259         if (s == 0xA5111044) { /* Split BAR Raptor Daptor */
2260                 if ((rid += sizeof(u_int32_t)) >= PCIR_BAR(4)) {
2261                         return (0);
2262                 }
2263                 p = pci_read_config(dev, rid, sizeof(p));
2264                 pci_write_config(dev, rid, -1, sizeof(p));
2265                 l = 0 - (pci_read_config(dev, rid, sizeof(l)) & ~15);
2266                 pci_write_config(dev, rid, p, sizeof(p));
2267                 if (l > MAX_MAP) {
2268                         l = MAX_MAP;
2269                 }
2270                 p &= ~15;
2271                 sc->ha_mes_res = bus_alloc_resource(dev, SYS_RES_MEMORY, &rid,
2272                   p, p + l, l, RF_ACTIVE);
2273                 if (sc->ha_mes_res == NULL) {
2274                         return (0);
2275                 }
2276                 sc->ha_frame_bhandle = rman_get_bushandle(sc->ha_mes_res);
2277                 sc->ha_frame_btag = rman_get_bustag(sc->ha_mes_res);
2278         } else {
2279                 sc->ha_frame_bhandle = sc->ha_i2o_bhandle;
2280                 sc->ha_frame_btag = sc->ha_i2o_btag;
2281         }
2282         return (1);
2283 } /* asr_pci_map_mem */
2284
2285 /*
2286  *      A simplified copy of the real pci_map_int with additional
2287  * registration requirements.
2288  */
2289 static int
2290 asr_pci_map_int(device_t dev, Asr_softc_t *sc)
2291 {
2292         int rid = 0;
2293
2294         sc->ha_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
2295           RF_ACTIVE | RF_SHAREABLE);
2296         if (sc->ha_irq_res == NULL) {
2297                 return (0);
2298         }
2299         if (bus_setup_intr(dev, sc->ha_irq_res, INTR_TYPE_CAM | INTR_ENTROPY,
2300           NULL, (driver_intr_t *)asr_intr, (void *)sc, &(sc->ha_intr))) {
2301                 return (0);
2302         }
2303         sc->ha_irq = pci_read_config(dev, PCIR_INTLINE, sizeof(char));
2304         return (1);
2305 } /* asr_pci_map_int */
2306
2307 static void
2308 asr_status_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2309 {
2310         Asr_softc_t *sc;
2311
2312         if (error)
2313                 return;
2314
2315         sc = (Asr_softc_t *)arg;
2316
2317         /* XXX
2318          * The status word can be at a 64-bit address, but the existing
2319          * accessor macros simply cannot manipulate 64-bit addresses.
2320          */
2321         sc->ha_status_phys = (u_int32_t)segs[0].ds_addr +
2322             offsetof(struct Asr_status_mem, status);
2323         sc->ha_rstatus_phys = (u_int32_t)segs[0].ds_addr +
2324             offsetof(struct Asr_status_mem, rstatus);
2325 }
2326
2327 static int
2328 asr_alloc_dma(Asr_softc_t *sc)
2329 {
2330         device_t dev;
2331
2332         dev = sc->ha_dev;
2333
2334         if (bus_dma_tag_create(NULL,                    /* parent */
2335                                1, 0,                    /* algnmnt, boundary */
2336                                BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
2337                                BUS_SPACE_MAXADDR,       /* highaddr */
2338                                NULL, NULL,              /* filter, filterarg */
2339                                BUS_SPACE_MAXSIZE_32BIT, /* maxsize */
2340                                BUS_SPACE_UNRESTRICTED,  /* nsegments */
2341                                BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */
2342                                0,                       /* flags */
2343                                NULL, NULL,              /* lockfunc, lockarg */
2344                                &sc->ha_parent_dmat)) {
2345                 device_printf(dev, "Cannot allocate parent DMA tag\n");
2346                 return (ENOMEM);
2347         }
2348
2349         if (bus_dma_tag_create(sc->ha_parent_dmat,      /* parent */
2350                                1, 0,                    /* algnmnt, boundary */
2351                                BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
2352                                BUS_SPACE_MAXADDR,       /* highaddr */
2353                                NULL, NULL,              /* filter, filterarg */
2354                                sizeof(sc->ha_statusmem),/* maxsize */
2355                                1,                       /* nsegments */
2356                                sizeof(sc->ha_statusmem),/* maxsegsize */
2357                                0,                       /* flags */
2358                                NULL, NULL,              /* lockfunc, lockarg */
2359                                &sc->ha_statusmem_dmat)) {
2360                 device_printf(dev, "Cannot allocate status DMA tag\n");
2361                 bus_dma_tag_destroy(sc->ha_parent_dmat);
2362                 return (ENOMEM);
2363         }
2364
2365         if (bus_dmamem_alloc(sc->ha_statusmem_dmat, (void **)&sc->ha_statusmem,
2366             BUS_DMA_NOWAIT, &sc->ha_statusmem_dmamap)) {
2367                 device_printf(dev, "Cannot allocate status memory\n");
2368                 bus_dma_tag_destroy(sc->ha_statusmem_dmat);
2369                 bus_dma_tag_destroy(sc->ha_parent_dmat);
2370                 return (ENOMEM);
2371         }
2372         (void)bus_dmamap_load(sc->ha_statusmem_dmat, sc->ha_statusmem_dmamap,
2373             sc->ha_statusmem, sizeof(sc->ha_statusmem), asr_status_cb, sc, 0);
2374
2375         return (0);
2376 }
2377
2378 static void
2379 asr_release_dma(Asr_softc_t *sc)
2380 {
2381
2382         if (sc->ha_rstatus_phys != 0)
2383                 bus_dmamap_unload(sc->ha_statusmem_dmat,
2384                     sc->ha_statusmem_dmamap);
2385         if (sc->ha_statusmem != NULL)
2386                 bus_dmamem_free(sc->ha_statusmem_dmat, sc->ha_statusmem,
2387                     sc->ha_statusmem_dmamap);
2388         if (sc->ha_statusmem_dmat != NULL)
2389                 bus_dma_tag_destroy(sc->ha_statusmem_dmat);
2390         if (sc->ha_parent_dmat != NULL)
2391                 bus_dma_tag_destroy(sc->ha_parent_dmat);
2392 }
2393
2394 /*
2395  *      Attach the devices, and virtual devices to the driver list.
2396  */
2397 static int
2398 asr_attach(device_t dev)
2399 {
2400         PI2O_EXEC_STATUS_GET_REPLY status;
2401         PI2O_LCT_ENTRY           Device;
2402         Asr_softc_t              *sc, **ha;
2403         struct scsi_inquiry_data *iq;
2404         int                      bus, size, unit;
2405         int                      error;
2406
2407         sc = device_get_softc(dev);
2408         unit = device_get_unit(dev);
2409         sc->ha_dev = dev;
2410
2411         if (Asr_softc_list == NULL) {
2412                 /*
2413                  *      Fixup the OS revision as saved in the dptsig for the
2414                  *      engine (dptioctl.h) to pick up.
2415                  */
2416                 bcopy(osrelease, &ASR_sig.dsDescription[16], 5);
2417         }
2418         /*
2419          *      Initialize the software structure
2420          */
2421         LIST_INIT(&(sc->ha_ccb));
2422         /* Link us into the HA list */
2423         for (ha = &Asr_softc_list; *ha; ha = &((*ha)->ha_next));
2424                 *(ha) = sc;
2425
2426         /*
2427          *      This is the real McCoy!
2428          */
2429         if (!asr_pci_map_mem(dev, sc)) {
2430                 device_printf(dev, "could not map memory\n");
2431                 return(ENXIO);
2432         }
2433         /* Enable if not formerly enabled */
2434         pci_write_config(dev, PCIR_COMMAND,
2435             pci_read_config(dev, PCIR_COMMAND, sizeof(char)) |
2436             PCIM_CMD_MEMEN | PCIM_CMD_BUSMASTEREN, sizeof(char));
2437
2438         sc->ha_pciBusNum = pci_get_bus(dev);
2439         sc->ha_pciDeviceNum = (pci_get_slot(dev) << 3) | pci_get_function(dev);
2440
2441         if ((error = asr_alloc_dma(sc)) != 0)
2442                 return (error);
2443
2444         /* Check if the device is there? */
2445         if (ASR_resetIOP(sc) == 0) {
2446                 device_printf(dev, "Cannot reset adapter\n");
2447                 asr_release_dma(sc);
2448                 return (EIO);
2449         }
2450         status = &sc->ha_statusmem->status;
2451         if (ASR_getStatus(sc) == NULL) {
2452                 device_printf(dev, "could not initialize hardware\n");
2453                 asr_release_dma(sc);
2454                 return(ENODEV);
2455         }
2456         sc->ha_SystemTable.OrganizationID = status->OrganizationID;
2457         sc->ha_SystemTable.IOP_ID = status->IOP_ID;
2458         sc->ha_SystemTable.I2oVersion = status->I2oVersion;
2459         sc->ha_SystemTable.IopState = status->IopState;
2460         sc->ha_SystemTable.MessengerType = status->MessengerType;
2461         sc->ha_SystemTable.InboundMessageFrameSize = status->InboundMFrameSize;
2462         sc->ha_SystemTable.MessengerInfo.InboundMessagePortAddressLow =
2463             (U32)(sc->ha_Base + I2O_REG_TOFIFO);        /* XXX 64-bit */
2464
2465         if (!asr_pci_map_int(dev, (void *)sc)) {
2466                 device_printf(dev, "could not map interrupt\n");
2467                 asr_release_dma(sc);
2468                 return(ENXIO);
2469         }
2470
2471         /* Adjust the maximim inbound count */
2472         if (((sc->ha_QueueSize =
2473             I2O_EXEC_STATUS_GET_REPLY_getMaxInboundMFrames(status)) >
2474             MAX_INBOUND) || (sc->ha_QueueSize == 0)) {
2475                 sc->ha_QueueSize = MAX_INBOUND;
2476         }
2477
2478         /* Adjust the maximum outbound count */
2479         if (((sc->ha_Msgs_Count =
2480             I2O_EXEC_STATUS_GET_REPLY_getMaxOutboundMFrames(status)) >
2481             MAX_OUTBOUND) || (sc->ha_Msgs_Count == 0)) {
2482                 sc->ha_Msgs_Count = MAX_OUTBOUND;
2483         }
2484         if (sc->ha_Msgs_Count > sc->ha_QueueSize) {
2485                 sc->ha_Msgs_Count = sc->ha_QueueSize;
2486         }
2487
2488         /* Adjust the maximum SG size to adapter */
2489         if ((size = (I2O_EXEC_STATUS_GET_REPLY_getInboundMFrameSize(status) <<
2490             2)) > MAX_INBOUND_SIZE) {
2491                 size = MAX_INBOUND_SIZE;
2492         }
2493         sc->ha_SgSize = (size - sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE)
2494           + sizeof(I2O_SG_ELEMENT)) / sizeof(I2O_SGE_SIMPLE_ELEMENT);
2495
2496         /*
2497          *      Only do a bus/HBA reset on the first time through. On this
2498          * first time through, we do not send a flush to the devices.
2499          */
2500         if (ASR_init(sc) == 0) {
2501                 struct BufferInfo {
2502                         I2O_PARAM_RESULTS_LIST_HEADER       Header;
2503                         I2O_PARAM_READ_OPERATION_RESULT     Read;
2504                         I2O_DPT_EXEC_IOP_BUFFERS_SCALAR     Info;
2505                 } Buffer;
2506                 PI2O_DPT_EXEC_IOP_BUFFERS_SCALAR Info;
2507 #define FW_DEBUG_BLED_OFFSET 8
2508
2509                 if ((Info = (PI2O_DPT_EXEC_IOP_BUFFERS_SCALAR)
2510                     ASR_getParams(sc, 0, I2O_DPT_EXEC_IOP_BUFFERS_GROUP_NO,
2511                     &Buffer, sizeof(struct BufferInfo))) != NULL) {
2512                         sc->ha_blinkLED = FW_DEBUG_BLED_OFFSET +
2513                             I2O_DPT_EXEC_IOP_BUFFERS_SCALAR_getSerialOutputOffset(Info);
2514                 }
2515                 if (ASR_acquireLct(sc) == 0) {
2516                         (void)ASR_acquireHrt(sc);
2517                 }
2518         } else {
2519                 device_printf(dev, "failed to initialize\n");
2520                 asr_release_dma(sc);
2521                 return(ENXIO);
2522         }
2523         /*
2524          *      Add in additional probe responses for more channels. We
2525          * are reusing the variable `target' for a channel loop counter.
2526          * Done here because of we need both the acquireLct and
2527          * acquireHrt data.
2528          */
2529         for (Device = sc->ha_LCT->LCTEntry; Device < (PI2O_LCT_ENTRY)
2530             (((U32 *)sc->ha_LCT)+I2O_LCT_getTableSize(sc->ha_LCT)); ++Device) {
2531                 if (Device->le_type == I2O_UNKNOWN) {
2532                         continue;
2533                 }
2534                 if (I2O_LCT_ENTRY_getUserTID(Device) == 0xFFF) {
2535                         if (Device->le_target > sc->ha_MaxId) {
2536                                 sc->ha_MaxId = Device->le_target;
2537                         }
2538                         if (Device->le_lun > sc->ha_MaxLun) {
2539                                 sc->ha_MaxLun = Device->le_lun;
2540                         }
2541                 }
2542                 if (((Device->le_type & I2O_PORT) != 0)
2543                  && (Device->le_bus <= MAX_CHANNEL)) {
2544                         /* Do not increase MaxId for efficiency */
2545                         sc->ha_adapter_target[Device->le_bus] =
2546                             Device->le_target;
2547                 }
2548         }
2549
2550         /*
2551          *      Print the HBA model number as inquired from the card.
2552          */
2553
2554         device_printf(dev, " ");
2555
2556         if ((iq = (struct scsi_inquiry_data *)malloc(
2557             sizeof(struct scsi_inquiry_data), M_TEMP, M_WAITOK | M_ZERO)) !=
2558             NULL) {
2559                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE        Message;
2560                 PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE       Message_Ptr;
2561                 int                                     posted = 0;
2562
2563                 Message_Ptr = (PRIVATE_SCSI_SCB_EXECUTE_MESSAGE *)&Message;
2564                 bzero(Message_Ptr, sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE) -
2565                     sizeof(I2O_SG_ELEMENT) + sizeof(I2O_SGE_SIMPLE_ELEMENT));
2566
2567                 I2O_MESSAGE_FRAME_setVersionOffset(
2568                     (PI2O_MESSAGE_FRAME)Message_Ptr, I2O_VERSION_11 |
2569                     (((sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE)
2570                     - sizeof(I2O_SG_ELEMENT)) / sizeof(U32)) << 4));
2571                 I2O_MESSAGE_FRAME_setMessageSize(
2572                     (PI2O_MESSAGE_FRAME)Message_Ptr,
2573                     (sizeof(PRIVATE_SCSI_SCB_EXECUTE_MESSAGE) -
2574                     sizeof(I2O_SG_ELEMENT) + sizeof(I2O_SGE_SIMPLE_ELEMENT)) /
2575                     sizeof(U32));
2576                 I2O_MESSAGE_FRAME_setInitiatorAddress(
2577                     (PI2O_MESSAGE_FRAME)Message_Ptr, 1);
2578                 I2O_MESSAGE_FRAME_setFunction(
2579                     (PI2O_MESSAGE_FRAME)Message_Ptr, I2O_PRIVATE_MESSAGE);
2580                 I2O_PRIVATE_MESSAGE_FRAME_setXFunctionCode(
2581                     (PI2O_PRIVATE_MESSAGE_FRAME)Message_Ptr, I2O_SCSI_SCB_EXEC);
2582                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setSCBFlags (Message_Ptr,
2583                     I2O_SCB_FLAG_ENABLE_DISCONNECT
2584                   | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
2585                   | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER);
2586                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setInterpret(Message_Ptr, 1);
2587                 I2O_PRIVATE_MESSAGE_FRAME_setOrganizationID(
2588                     (PI2O_PRIVATE_MESSAGE_FRAME)Message_Ptr,
2589                     DPT_ORGANIZATION_ID);
2590                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setCDBLength(Message_Ptr, 6);
2591                 Message_Ptr->CDB[0] = INQUIRY;
2592                 Message_Ptr->CDB[4] =
2593                     (unsigned char)sizeof(struct scsi_inquiry_data);
2594                 if (Message_Ptr->CDB[4] == 0) {
2595                         Message_Ptr->CDB[4] = 255;
2596                 }
2597
2598                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setSCBFlags (Message_Ptr,
2599                   (I2O_SCB_FLAG_XFER_FROM_DEVICE
2600                     | I2O_SCB_FLAG_ENABLE_DISCONNECT
2601                     | I2O_SCB_FLAG_SIMPLE_QUEUE_TAG
2602                     | I2O_SCB_FLAG_SENSE_DATA_IN_BUFFER));
2603
2604                 PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_setByteCount(
2605                   (PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr,
2606                   sizeof(struct scsi_inquiry_data));
2607                 SG(&(Message_Ptr->SGL), 0,
2608                   I2O_SGL_FLAGS_LAST_ELEMENT | I2O_SGL_FLAGS_END_OF_BUFFER,
2609                   iq, sizeof(struct scsi_inquiry_data));
2610                 (void)ASR_queue_c(sc, (PI2O_MESSAGE_FRAME)Message_Ptr);
2611
2612                 if (iq->vendor[0] && (iq->vendor[0] != ' ')) {
2613                         printf (" ");
2614                         ASR_prstring (iq->vendor, 8);
2615                         ++posted;
2616                 }
2617                 if (iq->product[0] && (iq->product[0] != ' ')) {
2618                         printf (" ");
2619                         ASR_prstring (iq->product, 16);
2620                         ++posted;
2621                 }
2622                 if (iq->revision[0] && (iq->revision[0] != ' ')) {
2623                         printf (" FW Rev. ");
2624                         ASR_prstring (iq->revision, 4);
2625                         ++posted;
2626                 }
2627                 free(iq, M_TEMP);
2628                 if (posted) {
2629                         printf (",");
2630                 }
2631         }
2632         printf (" %d channel, %d CCBs, Protocol I2O\n", sc->ha_MaxBus + 1,
2633           (sc->ha_QueueSize > MAX_INBOUND) ? MAX_INBOUND : sc->ha_QueueSize);
2634
2635         for (bus = 0; bus <= sc->ha_MaxBus; ++bus) {
2636                 struct cam_devq   * devq;
2637                 int                 QueueSize = sc->ha_QueueSize;
2638
2639                 if (QueueSize > MAX_INBOUND) {
2640                         QueueSize = MAX_INBOUND;
2641                 }
2642
2643                 /*
2644                  *      Create the device queue for our SIM(s).
2645                  */
2646                 if ((devq = cam_simq_alloc(QueueSize)) == NULL) {
2647                         continue;
2648                 }
2649
2650                 /*
2651                  *      Construct our first channel SIM entry
2652                  */
2653                 sc->ha_sim[bus] = cam_sim_alloc(asr_action, asr_poll, "asr", sc,
2654                                                 unit, &Giant,
2655                                                 1, QueueSize, devq);
2656                 if (sc->ha_sim[bus] == NULL) {
2657                         continue;
2658                 }
2659
2660                 if (xpt_bus_register(sc->ha_sim[bus], dev, bus) != CAM_SUCCESS){
2661                         cam_sim_free(sc->ha_sim[bus],
2662                           /*free_devq*/TRUE);
2663                         sc->ha_sim[bus] = NULL;
2664                         continue;
2665                 }
2666
2667                 if (xpt_create_path(&(sc->ha_path[bus]), /*periph*/NULL,
2668                     cam_sim_path(sc->ha_sim[bus]), CAM_TARGET_WILDCARD,
2669                     CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2670                         xpt_bus_deregister( cam_sim_path(sc->ha_sim[bus]));
2671                         cam_sim_free(sc->ha_sim[bus], /*free_devq*/TRUE);
2672                         sc->ha_sim[bus] = NULL;
2673                         continue;
2674                 }
2675         }
2676
2677         /*
2678          *      Generate the device node information
2679          */
2680         sc->ha_devt = make_dev(&asr_cdevsw, unit, UID_ROOT, GID_OPERATOR, 0640,
2681                                "asr%d", unit);
2682         if (sc->ha_devt != NULL)
2683                 (void)make_dev_alias(sc->ha_devt, "rdpti%d", unit);
2684         sc->ha_devt->si_drv1 = sc;
2685         return(0);
2686 } /* asr_attach */
2687
2688 static void
2689 asr_poll(struct cam_sim *sim)
2690 {
2691         asr_intr(cam_sim_softc(sim));
2692 } /* asr_poll */
2693
2694 static void
2695 asr_action(struct cam_sim *sim, union ccb  *ccb)
2696 {
2697         struct Asr_softc *sc;
2698
2699         debug_asr_printf("asr_action(%lx,%lx{%x})\n", (u_long)sim, (u_long)ccb,
2700                          ccb->ccb_h.func_code);
2701
2702         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("asr_action\n"));
2703
2704         ccb->ccb_h.spriv_ptr0 = sc = (struct Asr_softc *)cam_sim_softc(sim);
2705
2706         switch (ccb->ccb_h.func_code) {
2707
2708         /* Common cases first */
2709         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
2710         {
2711                 struct Message {
2712                         char M[MAX_INBOUND_SIZE];
2713                 } Message;
2714                 PI2O_MESSAGE_FRAME   Message_Ptr;
2715
2716                 /* Reject incoming commands while we are resetting the card */
2717                 if (sc->ha_in_reset != HA_OPERATIONAL) {
2718                         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2719                         if (sc->ha_in_reset >= HA_OFF_LINE) {
2720                                 /* HBA is now off-line */
2721                                 ccb->ccb_h.status |= CAM_UNREC_HBA_ERROR;
2722                         } else {
2723                                 /* HBA currently resetting, try again later. */
2724                                 ccb->ccb_h.status |= CAM_REQUEUE_REQ;
2725                         }
2726                         debug_asr_cmd_printf (" e\n");
2727                         xpt_done(ccb);
2728                         debug_asr_cmd_printf (" q\n");
2729                         break;
2730                 }
2731                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2732                         printf(
2733                           "asr%d WARNING: scsi_cmd(%x) already done on b%dt%du%d\n",
2734                           cam_sim_unit(xpt_path_sim(ccb->ccb_h.path)),
2735                           ccb->csio.cdb_io.cdb_bytes[0],
2736                           cam_sim_bus(sim),
2737                           ccb->ccb_h.target_id,
2738                           ccb->ccb_h.target_lun);
2739                 }
2740                 debug_asr_cmd_printf("(%d,%d,%d,%d)", cam_sim_unit(sim),
2741                                      cam_sim_bus(sim), ccb->ccb_h.target_id,
2742                                      ccb->ccb_h.target_lun);
2743                 debug_asr_dump_ccb(ccb);
2744
2745                 if ((Message_Ptr = ASR_init_message((union asr_ccb *)ccb,
2746                   (PI2O_MESSAGE_FRAME)&Message)) != NULL) {
2747                         debug_asr_cmd2_printf ("TID=%x:\n",
2748                           PRIVATE_SCSI_SCB_EXECUTE_MESSAGE_getTID(
2749                             (PPRIVATE_SCSI_SCB_EXECUTE_MESSAGE)Message_Ptr));
2750                         debug_asr_cmd2_dump_message(Message_Ptr);
2751                         debug_asr_cmd1_printf (" q");
2752
2753                         if (ASR_queue (sc, Message_Ptr) == EMPTY_QUEUE) {
2754                                 ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2755                                 ccb->ccb_h.status |= CAM_REQUEUE_REQ;
2756                                 debug_asr_cmd_printf (" E\n");
2757                                 xpt_done(ccb);
2758                         }
2759                         debug_asr_cmd_printf(" Q\n");
2760                         break;
2761                 }
2762                 /*
2763                  *      We will get here if there is no valid TID for the device
2764                  * referenced in the scsi command packet.
2765                  */
2766                 ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2767                 ccb->ccb_h.status |= CAM_SEL_TIMEOUT;
2768                 debug_asr_cmd_printf (" B\n");
2769                 xpt_done(ccb);
2770                 break;
2771         }
2772
2773         case XPT_RESET_DEV:     /* Bus Device Reset the specified SCSI device */
2774                 /* Rese HBA device ... */
2775                 asr_hbareset (sc);
2776                 ccb->ccb_h.status = CAM_REQ_CMP;
2777                 xpt_done(ccb);
2778                 break;
2779
2780 #if (defined(REPORT_LUNS))
2781         case REPORT_LUNS:
2782 #endif
2783         case XPT_ABORT:                 /* Abort the specified CCB */
2784                 /* XXX Implement */
2785                 ccb->ccb_h.status = CAM_REQ_INVALID;
2786                 xpt_done(ccb);
2787                 break;
2788
2789         case XPT_SET_TRAN_SETTINGS:
2790                 /* XXX Implement */
2791                 ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2792                 xpt_done(ccb);
2793                 break;
2794
2795         case XPT_GET_TRAN_SETTINGS:
2796         /* Get default/user set transfer settings for the target */
2797         {
2798                 struct  ccb_trans_settings *cts = &(ccb->cts);
2799                 struct ccb_trans_settings_scsi *scsi =
2800                     &cts->proto_specific.scsi;
2801                 struct ccb_trans_settings_spi *spi =
2802                     &cts->xport_specific.spi;
2803
2804                 if (cts->type == CTS_TYPE_USER_SETTINGS) {
2805                         cts->protocol = PROTO_SCSI;
2806                         cts->protocol_version = SCSI_REV_2;
2807                         cts->transport = XPORT_SPI;
2808                         cts->transport_version = 2;
2809
2810                         scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
2811                         spi->flags = CTS_SPI_FLAGS_DISC_ENB;
2812                         spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
2813                         spi->sync_period = 6; /* 40MHz */
2814                         spi->sync_offset = 15;
2815                         spi->valid = CTS_SPI_VALID_SYNC_RATE
2816                                    | CTS_SPI_VALID_SYNC_OFFSET
2817                                    | CTS_SPI_VALID_BUS_WIDTH
2818                                    | CTS_SPI_VALID_DISC;
2819                         scsi->valid = CTS_SCSI_VALID_TQ;
2820
2821                         ccb->ccb_h.status = CAM_REQ_CMP;
2822                 } else {
2823                         ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2824                 }
2825                 xpt_done(ccb);
2826                 break;
2827         }
2828
2829         case XPT_CALC_GEOMETRY:
2830         {
2831                 struct    ccb_calc_geometry *ccg;
2832                 u_int32_t size_mb;
2833                 u_int32_t secs_per_cylinder;
2834
2835                 ccg = &(ccb->ccg);
2836                 size_mb = ccg->volume_size
2837                         / ((1024L * 1024L) / ccg->block_size);
2838
2839                 if (size_mb > 4096) {
2840                         ccg->heads = 255;
2841                         ccg->secs_per_track = 63;
2842                 } else if (size_mb > 2048) {
2843                         ccg->heads = 128;
2844                         ccg->secs_per_track = 63;
2845                 } else if (size_mb > 1024) {
2846                         ccg->heads = 65;
2847                         ccg->secs_per_track = 63;
2848                 } else {
2849                         ccg->heads = 64;
2850                         ccg->secs_per_track = 32;
2851                 }
2852                 secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2853                 ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2854                 ccb->ccb_h.status = CAM_REQ_CMP;
2855                 xpt_done(ccb);
2856                 break;
2857         }
2858
2859         case XPT_RESET_BUS:             /* Reset the specified SCSI bus */
2860                 ASR_resetBus (sc, cam_sim_bus(sim));
2861                 ccb->ccb_h.status = CAM_REQ_CMP;
2862                 xpt_done(ccb);
2863                 break;
2864
2865         case XPT_TERM_IO:               /* Terminate the I/O process */
2866                 /* XXX Implement */
2867                 ccb->ccb_h.status = CAM_REQ_INVALID;
2868                 xpt_done(ccb);
2869                 break;
2870
2871         case XPT_PATH_INQ:              /* Path routing inquiry */
2872         {
2873                 struct ccb_pathinq *cpi = &(ccb->cpi);
2874
2875                 cpi->version_num = 1; /* XXX??? */
2876                 cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
2877                 cpi->target_sprt = 0;
2878                 /* Not necessary to reset bus, done by HDM initialization */
2879                 cpi->hba_misc = PIM_NOBUSRESET;
2880                 cpi->hba_eng_cnt = 0;
2881                 cpi->max_target = sc->ha_MaxId;
2882                 cpi->max_lun = sc->ha_MaxLun;
2883                 cpi->initiator_id = sc->ha_adapter_target[cam_sim_bus(sim)];
2884                 cpi->bus_id = cam_sim_bus(sim);
2885                 cpi->base_transfer_speed = 3300;
2886                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2887                 strncpy(cpi->hba_vid, "Adaptec", HBA_IDLEN);
2888                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2889                 cpi->unit_number = cam_sim_unit(sim);
2890                 cpi->ccb_h.status = CAM_REQ_CMP;
2891                 cpi->transport = XPORT_SPI;
2892                 cpi->transport_version = 2;
2893                 cpi->protocol = PROTO_SCSI;
2894                 cpi->protocol_version = SCSI_REV_2;
2895                 xpt_done(ccb);
2896                 break;
2897         }
2898         default:
2899                 ccb->ccb_h.status = CAM_REQ_INVALID;
2900                 xpt_done(ccb);
2901                 break;
2902         }
2903 } /* asr_action */
2904
2905 /*
2906  * Handle processing of current CCB as pointed to by the Status.
2907  */
2908 static int
2909 asr_intr(Asr_softc_t *sc)
2910 {
2911         int processed;
2912
2913         for(processed = 0; asr_get_status(sc) & Mask_InterruptsDisabled;
2914             processed = 1) {
2915                 union asr_ccb                      *ccb;
2916                 u_int                               dsc;
2917                 U32                                 ReplyOffset;
2918                 PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME Reply;
2919
2920                 if (((ReplyOffset = asr_get_FromFIFO(sc)) == EMPTY_QUEUE)
2921                  && ((ReplyOffset = asr_get_FromFIFO(sc)) == EMPTY_QUEUE)) {
2922                         break;
2923                 }
2924                 Reply = (PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)(ReplyOffset
2925                   - sc->ha_Msgs_Phys + (char *)(sc->ha_Msgs));
2926                 /*
2927                  * We do not need any (optional byteswapping) method access to
2928                  * the Initiator context field.
2929                  */
2930                 ccb = (union asr_ccb *)(long)
2931                   I2O_MESSAGE_FRAME_getInitiatorContext64(
2932                     &(Reply->StdReplyFrame.StdMessageFrame));
2933                 if (I2O_MESSAGE_FRAME_getMsgFlags(
2934                   &(Reply->StdReplyFrame.StdMessageFrame))
2935                   & I2O_MESSAGE_FLAGS_FAIL) {
2936                         I2O_UTIL_NOP_MESSAGE    Message;
2937                         PI2O_UTIL_NOP_MESSAGE   Message_Ptr;
2938                         U32                     MessageOffset;
2939
2940                         MessageOffset = (u_long)
2941                           I2O_FAILURE_REPLY_MESSAGE_FRAME_getPreservedMFA(
2942                             (PI2O_FAILURE_REPLY_MESSAGE_FRAME)Reply);
2943                         /*
2944                          *  Get the Original Message Frame's address, and get
2945                          * it's Transaction Context into our space. (Currently
2946                          * unused at original authorship, but better to be
2947                          * safe than sorry). Straight copy means that we
2948                          * need not concern ourselves with the (optional
2949                          * byteswapping) method access.
2950                          */
2951                         Reply->StdReplyFrame.TransactionContext =
2952                             bus_space_read_4(sc->ha_frame_btag,
2953                             sc->ha_frame_bhandle, MessageOffset +
2954                             offsetof(I2O_SINGLE_REPLY_MESSAGE_FRAME,
2955                             TransactionContext));
2956                         /*
2957                          *      For 64 bit machines, we need to reconstruct the
2958                          * 64 bit context.
2959                          */
2960                         ccb = (union asr_ccb *)(long)
2961                           I2O_MESSAGE_FRAME_getInitiatorContext64(
2962                             &(Reply->StdReplyFrame.StdMessageFrame));
2963                         /*
2964                          * Unique error code for command failure.
2965                          */
2966                         I2O_SINGLE_REPLY_MESSAGE_FRAME_setDetailedStatusCode(
2967                           &(Reply->StdReplyFrame), (u_int16_t)-2);
2968                         /*
2969                          *  Modify the message frame to contain a NOP and
2970                          * re-issue it to the controller.
2971                          */
2972                         Message_Ptr = (PI2O_UTIL_NOP_MESSAGE)ASR_fillMessage(
2973                             &Message, sizeof(I2O_UTIL_NOP_MESSAGE));
2974 #if (I2O_UTIL_NOP != 0)
2975                                 I2O_MESSAGE_FRAME_setFunction (
2976                                   &(Message_Ptr->StdMessageFrame),
2977                                   I2O_UTIL_NOP);
2978 #endif
2979                         /*
2980                          *  Copy the packet out to the Original Message
2981                          */
2982                         asr_set_frame(sc, Message_Ptr, MessageOffset,
2983                                       sizeof(I2O_UTIL_NOP_MESSAGE));
2984                         /*
2985                          *  Issue the NOP
2986                          */
2987                         asr_set_ToFIFO(sc, MessageOffset);
2988                 }
2989
2990                 /*
2991                  *      Asynchronous command with no return requirements,
2992                  * and a generic handler for immunity against odd error
2993                  * returns from the adapter.
2994                  */
2995                 if (ccb == NULL) {
2996                         /*
2997                          * Return Reply so that it can be used for the
2998                          * next command
2999                          */
3000                         asr_set_FromFIFO(sc, ReplyOffset);
3001                         continue;
3002                 }
3003
3004                 /* Welease Wadjah! (and stop timeouts) */
3005                 ASR_ccbRemove (sc, ccb);
3006
3007                 dsc = I2O_SINGLE_REPLY_MESSAGE_FRAME_getDetailedStatusCode(
3008                     &(Reply->StdReplyFrame));
3009                 ccb->csio.scsi_status = dsc & I2O_SCSI_DEVICE_DSC_MASK;
3010                 ccb->ccb_h.status &= ~CAM_STATUS_MASK;
3011                 switch (dsc) {
3012
3013                 case I2O_SCSI_DSC_SUCCESS:
3014                         ccb->ccb_h.status |= CAM_REQ_CMP;
3015                         break;
3016
3017                 case I2O_SCSI_DSC_CHECK_CONDITION:
3018                         ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR |
3019                             CAM_AUTOSNS_VALID;
3020                         break;
3021
3022                 case I2O_SCSI_DSC_BUSY:
3023                         /* FALLTHRU */
3024                 case I2O_SCSI_HBA_DSC_ADAPTER_BUSY:
3025                         /* FALLTHRU */
3026                 case I2O_SCSI_HBA_DSC_SCSI_BUS_RESET:
3027                         /* FALLTHRU */
3028                 case I2O_SCSI_HBA_DSC_BUS_BUSY:
3029                         ccb->ccb_h.status |= CAM_SCSI_BUSY;
3030                         break;
3031
3032                 case I2O_SCSI_HBA_DSC_SELECTION_TIMEOUT:
3033                         ccb->ccb_h.status |= CAM_SEL_TIMEOUT;
3034                         break;
3035
3036                 case I2O_SCSI_HBA_DSC_COMMAND_TIMEOUT:
3037                         /* FALLTHRU */
3038                 case I2O_SCSI_HBA_DSC_DEVICE_NOT_PRESENT:
3039                         /* FALLTHRU */
3040                 case I2O_SCSI_HBA_DSC_LUN_INVALID:
3041                         /* FALLTHRU */
3042                 case I2O_SCSI_HBA_DSC_SCSI_TID_INVALID:
3043                         ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
3044                         break;
3045
3046                 case I2O_SCSI_HBA_DSC_DATA_OVERRUN:
3047                         /* FALLTHRU */
3048                 case I2O_SCSI_HBA_DSC_REQUEST_LENGTH_ERROR:
3049                         ccb->ccb_h.status |= CAM_DATA_RUN_ERR;
3050                         break;
3051
3052                 default:
3053                         ccb->ccb_h.status |= CAM_REQUEUE_REQ;
3054                         break;
3055                 }
3056                 if ((ccb->csio.resid = ccb->csio.dxfer_len) != 0) {
3057                         ccb->csio.resid -=
3058                           I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME_getTransferCount(
3059                             Reply);
3060                 }
3061
3062                 /* Sense data in reply packet */
3063                 if (ccb->ccb_h.status & CAM_AUTOSNS_VALID) {
3064                         u_int16_t size = I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME_getAutoSenseTransferCount(Reply);
3065
3066                         if (size) {
3067                                 if (size > sizeof(ccb->csio.sense_data)) {
3068                                         size = sizeof(ccb->csio.sense_data);
3069                                 }
3070                                 if (size > I2O_SCSI_SENSE_DATA_SZ) {
3071                                         size = I2O_SCSI_SENSE_DATA_SZ;
3072                                 }
3073                                 if ((ccb->csio.sense_len)
3074                                  && (size > ccb->csio.sense_len)) {
3075                                         size = ccb->csio.sense_len;
3076                                 }
3077                                 bcopy(Reply->SenseData,
3078                                       &(ccb->csio.sense_data), size);
3079                         }
3080                 }
3081
3082                 /*
3083                  * Return Reply so that it can be used for the next command
3084                  * since we have no more need for it now
3085                  */
3086                 asr_set_FromFIFO(sc, ReplyOffset);
3087
3088                 if (ccb->ccb_h.path) {
3089                         xpt_done ((union ccb *)ccb);
3090                 } else {
3091                         wakeup (ccb);
3092                 }
3093         }
3094         return (processed);
3095 } /* asr_intr */
3096
3097 #undef QueueSize        /* Grrrr */
3098 #undef SG_Size          /* Grrrr */
3099
3100 /*
3101  *      Meant to be included at the bottom of asr.c !!!
3102  */
3103
3104 /*
3105  *      Included here as hard coded. Done because other necessary include
3106  *      files utilize C++ comment structures which make them a nuisance to
3107  *      included here just to pick up these three typedefs.
3108  */
3109 typedef U32   DPT_TAG_T;
3110 typedef U32   DPT_MSG_T;
3111 typedef U32   DPT_RTN_T;
3112
3113 #undef SCSI_RESET       /* Conflicts with "scsi/scsiconf.h" defintion */
3114 #include        "dev/asr/osd_unix.h"
3115
3116 #define asr_unit(dev)     minor(dev)
3117
3118 static u_int8_t ASR_ctlr_held;
3119
3120 static int
3121 asr_open(struct cdev *dev, int32_t flags, int32_t ifmt, struct thread *td)
3122 {
3123         int              s;
3124         int              error;
3125
3126         if (dev->si_drv1 == NULL) {
3127                 return (ENODEV);
3128         }
3129         s = splcam ();
3130         if (ASR_ctlr_held) {
3131                 error = EBUSY;
3132         } else if ((error = priv_check(td, PRIV_DRIVER)) == 0) {
3133                 ++ASR_ctlr_held;
3134         }
3135         splx(s);
3136         return (error);
3137 } /* asr_open */
3138
3139 static int
3140 asr_close(struct cdev *dev, int flags, int ifmt, struct thread *td)
3141 {
3142
3143         ASR_ctlr_held = 0;
3144         return (0);
3145 } /* asr_close */
3146
3147
3148 /*-------------------------------------------------------------------------*/
3149 /*                    Function ASR_queue_i                                 */
3150 /*-------------------------------------------------------------------------*/
3151 /* The Parameters Passed To This Function Are :                            */
3152 /*     Asr_softc_t *      : HBA miniport driver's adapter data storage.    */
3153 /*     PI2O_MESSAGE_FRAME : Msg Structure Pointer For This Command         */
3154 /*      I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME following the Msg Structure     */
3155 /*                                                                         */
3156 /* This Function Will Take The User Request Packet And Convert It To An    */
3157 /* I2O MSG And Send It Off To The Adapter.                                 */
3158 /*                                                                         */
3159 /* Return : 0 For OK, Error Code Otherwise                                 */
3160 /*-------------------------------------------------------------------------*/
3161 static int
3162 ASR_queue_i(Asr_softc_t *sc, PI2O_MESSAGE_FRAME Packet)
3163 {
3164         union asr_ccb                              * ccb;
3165         PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME          Reply;
3166         PI2O_MESSAGE_FRAME                           Message_Ptr;
3167         PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME          Reply_Ptr;
3168         int                                          MessageSizeInBytes;
3169         int                                          ReplySizeInBytes;
3170         int                                          error;
3171         int                                          s;
3172         /* Scatter Gather buffer list */
3173         struct ioctlSgList_S {
3174                 SLIST_ENTRY(ioctlSgList_S) link;
3175                 caddr_t                    UserSpace;
3176                 I2O_FLAGS_COUNT            FlagsCount;
3177                 char                       KernelSpace[sizeof(long)];
3178         }                                          * elm;
3179         /* Generates a `first' entry */
3180         SLIST_HEAD(ioctlSgListHead_S, ioctlSgList_S) sgList;
3181
3182         if (ASR_getBlinkLedCode(sc)) {
3183                 debug_usr_cmd_printf ("Adapter currently in BlinkLed %x\n",
3184                   ASR_getBlinkLedCode(sc));
3185                 return (EIO);
3186         }
3187         /* Copy in the message into a local allocation */
3188         if ((Message_Ptr = (PI2O_MESSAGE_FRAME)malloc (
3189           sizeof(I2O_MESSAGE_FRAME), M_TEMP, M_WAITOK)) == NULL) {
3190                 debug_usr_cmd_printf (
3191                   "Failed to acquire I2O_MESSAGE_FRAME memory\n");
3192                 return (ENOMEM);
3193         }
3194         if ((error = copyin ((caddr_t)Packet, (caddr_t)Message_Ptr,
3195           sizeof(I2O_MESSAGE_FRAME))) != 0) {
3196                 free(Message_Ptr, M_TEMP);
3197                 debug_usr_cmd_printf ("Can't copy in packet errno=%d\n", error);
3198                 return (error);
3199         }
3200         /* Acquire information to determine type of packet */
3201         MessageSizeInBytes = (I2O_MESSAGE_FRAME_getMessageSize(Message_Ptr)<<2);
3202         /* The offset of the reply information within the user packet */
3203         Reply = (PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)((char *)Packet
3204           + MessageSizeInBytes);
3205
3206         /* Check if the message is a synchronous initialization command */
3207         s = I2O_MESSAGE_FRAME_getFunction(Message_Ptr);
3208         free(Message_Ptr, M_TEMP);
3209         switch (s) {
3210
3211         case I2O_EXEC_IOP_RESET:
3212         {       U32 status;
3213
3214                 status = ASR_resetIOP(sc);
3215                 ReplySizeInBytes = sizeof(status);
3216                 debug_usr_cmd_printf ("resetIOP done\n");
3217                 return (copyout ((caddr_t)&status, (caddr_t)Reply,
3218                   ReplySizeInBytes));
3219         }
3220
3221         case I2O_EXEC_STATUS_GET:
3222         {       PI2O_EXEC_STATUS_GET_REPLY status;
3223
3224                 status = &sc->ha_statusmem->status;
3225                 if (ASR_getStatus(sc) == NULL) {
3226                         debug_usr_cmd_printf ("getStatus failed\n");
3227                         return (ENXIO);
3228                 }
3229                 ReplySizeInBytes = sizeof(status);
3230                 debug_usr_cmd_printf ("getStatus done\n");
3231                 return (copyout ((caddr_t)status, (caddr_t)Reply,
3232                   ReplySizeInBytes));
3233         }
3234
3235         case I2O_EXEC_OUTBOUND_INIT:
3236         {       U32 status;
3237
3238                 status = ASR_initOutBound(sc);
3239                 ReplySizeInBytes = sizeof(status);
3240                 debug_usr_cmd_printf ("intOutBound done\n");
3241                 return (copyout ((caddr_t)&status, (caddr_t)Reply,
3242                   ReplySizeInBytes));
3243         }
3244         }
3245
3246         /* Determine if the message size is valid */
3247         if ((MessageSizeInBytes < sizeof(I2O_MESSAGE_FRAME))
3248          || (MAX_INBOUND_SIZE < MessageSizeInBytes)) {
3249                 debug_usr_cmd_printf ("Packet size %d incorrect\n",
3250                   MessageSizeInBytes);
3251                 return (EINVAL);
3252         }
3253
3254         if ((Message_Ptr = (PI2O_MESSAGE_FRAME)malloc (MessageSizeInBytes,
3255           M_TEMP, M_WAITOK)) == NULL) {
3256                 debug_usr_cmd_printf ("Failed to acquire frame[%d] memory\n",
3257                   MessageSizeInBytes);
3258                 return (ENOMEM);
3259         }
3260         if ((error = copyin ((caddr_t)Packet, (caddr_t)Message_Ptr,
3261           MessageSizeInBytes)) != 0) {
3262                 free(Message_Ptr, M_TEMP);
3263                 debug_usr_cmd_printf ("Can't copy in packet[%d] errno=%d\n",
3264                   MessageSizeInBytes, error);
3265                 return (error);
3266         }
3267
3268         /* Check the size of the reply frame, and start constructing */
3269
3270         if ((Reply_Ptr = (PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)malloc (
3271           sizeof(I2O_MESSAGE_FRAME), M_TEMP, M_WAITOK)) == NULL) {
3272                 free(Message_Ptr, M_TEMP);
3273                 debug_usr_cmd_printf (
3274                   "Failed to acquire I2O_MESSAGE_FRAME memory\n");
3275                 return (ENOMEM);
3276         }
3277         if ((error = copyin ((caddr_t)Reply, (caddr_t)Reply_Ptr,
3278           sizeof(I2O_MESSAGE_FRAME))) != 0) {
3279                 free(Reply_Ptr, M_TEMP);
3280                 free(Message_Ptr, M_TEMP);
3281                 debug_usr_cmd_printf (
3282                   "Failed to copy in reply frame, errno=%d\n",
3283                   error);
3284                 return (error);
3285         }
3286         ReplySizeInBytes = (I2O_MESSAGE_FRAME_getMessageSize(
3287           &(Reply_Ptr->StdReplyFrame.StdMessageFrame)) << 2);
3288         free(Reply_Ptr, M_TEMP);
3289         if (ReplySizeInBytes < sizeof(I2O_SINGLE_REPLY_MESSAGE_FRAME)) {
3290                 free(Message_Ptr, M_TEMP);
3291                 debug_usr_cmd_printf (
3292                   "Failed to copy in reply frame[%d], errno=%d\n",
3293                   ReplySizeInBytes, error);
3294                 return (EINVAL);
3295         }
3296
3297         if ((Reply_Ptr = (PI2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)malloc (
3298           ((ReplySizeInBytes > sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME))
3299             ? ReplySizeInBytes : sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)),
3300           M_TEMP, M_WAITOK)) == NULL) {
3301                 free(Message_Ptr, M_TEMP);
3302                 debug_usr_cmd_printf ("Failed to acquire frame[%d] memory\n",
3303                   ReplySizeInBytes);
3304                 return (ENOMEM);
3305         }
3306         (void)ASR_fillMessage((void *)Reply_Ptr, ReplySizeInBytes);
3307         Reply_Ptr->StdReplyFrame.StdMessageFrame.InitiatorContext
3308           = Message_Ptr->InitiatorContext;
3309         Reply_Ptr->StdReplyFrame.TransactionContext
3310           = ((PI2O_PRIVATE_MESSAGE_FRAME)Message_Ptr)->TransactionContext;
3311         I2O_MESSAGE_FRAME_setMsgFlags(
3312           &(Reply_Ptr->StdReplyFrame.StdMessageFrame),
3313           I2O_MESSAGE_FRAME_getMsgFlags(
3314             &(Reply_Ptr->StdReplyFrame.StdMessageFrame))
3315               | I2O_MESSAGE_FLAGS_REPLY);
3316
3317         /* Check if the message is a special case command */
3318         switch (I2O_MESSAGE_FRAME_getFunction(Message_Ptr)) {
3319         case I2O_EXEC_SYS_TAB_SET: /* Special Case of empty Scatter Gather */
3320                 if (MessageSizeInBytes == ((I2O_MESSAGE_FRAME_getVersionOffset(
3321                   Message_Ptr) & 0xF0) >> 2)) {
3322                         free(Message_Ptr, M_TEMP);
3323                         I2O_SINGLE_REPLY_MESSAGE_FRAME_setDetailedStatusCode(
3324                           &(Reply_Ptr->StdReplyFrame),
3325                           (ASR_setSysTab(sc) != CAM_REQ_CMP));
3326                         I2O_MESSAGE_FRAME_setMessageSize(
3327                           &(Reply_Ptr->StdReplyFrame.StdMessageFrame),
3328                           sizeof(I2O_SINGLE_REPLY_MESSAGE_FRAME));
3329                         error = copyout ((caddr_t)Reply_Ptr, (caddr_t)Reply,
3330                           ReplySizeInBytes);
3331                         free(Reply_Ptr, M_TEMP);
3332                         return (error);
3333                 }
3334         }
3335
3336         /* Deal in the general case */
3337         /* First allocate and optionally copy in each scatter gather element */
3338         SLIST_INIT(&sgList);
3339         if ((I2O_MESSAGE_FRAME_getVersionOffset(Message_Ptr) & 0xF0) != 0) {
3340                 PI2O_SGE_SIMPLE_ELEMENT sg;
3341
3342                 /*
3343                  *      since this code is reused in several systems, code
3344                  * efficiency is greater by using a shift operation rather
3345                  * than a divide by sizeof(u_int32_t).
3346                  */
3347                 sg = (PI2O_SGE_SIMPLE_ELEMENT)((char *)Message_Ptr
3348                   + ((I2O_MESSAGE_FRAME_getVersionOffset(Message_Ptr) & 0xF0)
3349                     >> 2));
3350                 while (sg < (PI2O_SGE_SIMPLE_ELEMENT)(((caddr_t)Message_Ptr)
3351                   + MessageSizeInBytes)) {
3352                         caddr_t v;
3353                         int     len;
3354
3355                         if ((I2O_FLAGS_COUNT_getFlags(&(sg->FlagsCount))
3356                          & I2O_SGL_FLAGS_SIMPLE_ADDRESS_ELEMENT) == 0) {
3357                                 error = EINVAL;
3358                                 break;
3359                         }
3360                         len = I2O_FLAGS_COUNT_getCount(&(sg->FlagsCount));
3361                         debug_usr_cmd_printf ("SG[%d] = %x[%d]\n",
3362                           sg - (PI2O_SGE_SIMPLE_ELEMENT)((char *)Message_Ptr
3363                           + ((I2O_MESSAGE_FRAME_getVersionOffset(
3364                                 Message_Ptr) & 0xF0) >> 2)),
3365                           I2O_SGE_SIMPLE_ELEMENT_getPhysicalAddress(sg), len);
3366
3367                         if ((elm = (struct ioctlSgList_S *)malloc (
3368                           sizeof(*elm) - sizeof(elm->KernelSpace) + len,
3369                           M_TEMP, M_WAITOK)) == NULL) {
3370                                 debug_usr_cmd_printf (
3371                                   "Failed to allocate SG[%d]\n", len);
3372                                 error = ENOMEM;
3373                                 break;
3374                         }
3375                         SLIST_INSERT_HEAD(&sgList, elm, link);
3376                         elm->FlagsCount = sg->FlagsCount;
3377                         elm->UserSpace = (caddr_t)
3378                           (I2O_SGE_SIMPLE_ELEMENT_getPhysicalAddress(sg));
3379                         v = elm->KernelSpace;
3380                         /* Copy in outgoing data (DIR bit could be invalid) */
3381                         if ((error = copyin (elm->UserSpace, (caddr_t)v, len))
3382                           != 0) {
3383                                 break;
3384                         }
3385                         /*
3386                          *      If the buffer is not contiguous, lets
3387                          * break up the scatter/gather entries.
3388                          */
3389                         while ((len > 0)
3390                          && (sg < (PI2O_SGE_SIMPLE_ELEMENT)
3391                           (((caddr_t)Message_Ptr) + MAX_INBOUND_SIZE))) {
3392                                 int next, base, span;
3393
3394                                 span = 0;
3395                                 next = base = KVTOPHYS(v);
3396                                 I2O_SGE_SIMPLE_ELEMENT_setPhysicalAddress(sg,
3397                                   base);
3398
3399                                 /* How far can we go physically contiguously */
3400                                 while ((len > 0) && (base == next)) {
3401                                         int size;
3402
3403                                         next = trunc_page(base) + PAGE_SIZE;
3404                                         size = next - base;
3405                                         if (size > len) {
3406                                                 size = len;
3407                                         }
3408                                         span += size;
3409                                         v += size;
3410                                         len -= size;
3411                                         base = KVTOPHYS(v);
3412                                 }
3413
3414                                 /* Construct the Flags */
3415                                 I2O_FLAGS_COUNT_setCount(&(sg->FlagsCount),
3416                                   span);
3417                                 {
3418                                         int flags = I2O_FLAGS_COUNT_getFlags(
3419                                           &(elm->FlagsCount));
3420                                         /* Any remaining length? */
3421                                         if (len > 0) {
3422                                             flags &=
3423                                                 ~(I2O_SGL_FLAGS_END_OF_BUFFER
3424                                                  | I2O_SGL_FLAGS_LAST_ELEMENT);
3425                                         }
3426                                         I2O_FLAGS_COUNT_setFlags(
3427                                           &(sg->FlagsCount), flags);
3428                                 }
3429
3430                                 debug_usr_cmd_printf ("sg[%d] = %x[%d]\n",
3431                                   sg - (PI2O_SGE_SIMPLE_ELEMENT)
3432                                     ((char *)Message_Ptr
3433                                   + ((I2O_MESSAGE_FRAME_getVersionOffset(
3434                                         Message_Ptr) & 0xF0) >> 2)),
3435                                   I2O_SGE_SIMPLE_ELEMENT_getPhysicalAddress(sg),
3436                                   span);
3437                                 if (len <= 0) {
3438                                         break;
3439                                 }
3440
3441                                 /*
3442                                  * Incrementing requires resizing of the
3443                                  * packet, and moving up the existing SG
3444                                  * elements.
3445                                  */
3446                                 ++sg;
3447                                 MessageSizeInBytes += sizeof(*sg);
3448                                 I2O_MESSAGE_FRAME_setMessageSize(Message_Ptr,
3449                                   I2O_MESSAGE_FRAME_getMessageSize(Message_Ptr)
3450                                   + (sizeof(*sg) / sizeof(U32)));
3451                                 {
3452                                         PI2O_MESSAGE_FRAME NewMessage_Ptr;
3453
3454                                         if ((NewMessage_Ptr
3455                                           = (PI2O_MESSAGE_FRAME)
3456                                             malloc (MessageSizeInBytes,
3457                                              M_TEMP, M_WAITOK)) == NULL) {
3458                                                 debug_usr_cmd_printf (
3459                                                   "Failed to acquire frame[%d] memory\n",
3460                                                   MessageSizeInBytes);
3461                                                 error = ENOMEM;
3462                                                 break;
3463                                         }
3464                                         span = ((caddr_t)sg)
3465                                              - (caddr_t)Message_Ptr;
3466                                         bcopy(Message_Ptr,NewMessage_Ptr, span);
3467                                         bcopy((caddr_t)(sg-1),
3468                                           ((caddr_t)NewMessage_Ptr) + span,
3469                                           MessageSizeInBytes - span);
3470                                         free(Message_Ptr, M_TEMP);
3471                                         sg = (PI2O_SGE_SIMPLE_ELEMENT)
3472                                           (((caddr_t)NewMessage_Ptr) + span);
3473                                         Message_Ptr = NewMessage_Ptr;
3474                                 }
3475                         }
3476                         if ((error)
3477                          || ((I2O_FLAGS_COUNT_getFlags(&(sg->FlagsCount))
3478                           & I2O_SGL_FLAGS_LAST_ELEMENT) != 0)) {
3479                                 break;
3480                         }
3481                         ++sg;
3482                 }
3483                 if (error) {
3484                         while ((elm = SLIST_FIRST(&sgList)) != NULL) {
3485                                 SLIST_REMOVE_HEAD(&sgList, link);
3486                                 free(elm, M_TEMP);
3487                         }
3488                         free(Reply_Ptr, M_TEMP);
3489                         free(Message_Ptr, M_TEMP);
3490                         return (error);
3491                 }
3492         }
3493
3494         debug_usr_cmd_printf ("Inbound: ");
3495         debug_usr_cmd_dump_message(Message_Ptr);
3496
3497         /* Send the command */
3498         if ((ccb = asr_alloc_ccb (sc)) == NULL) {
3499                 /* Free up in-kernel buffers */
3500                 while ((elm = SLIST_FIRST(&sgList)) != NULL) {
3501                         SLIST_REMOVE_HEAD(&sgList, link);
3502                         free(elm, M_TEMP);
3503                 }
3504                 free(Reply_Ptr, M_TEMP);
3505                 free(Message_Ptr, M_TEMP);
3506                 return (ENOMEM);
3507         }
3508
3509         /*
3510          * We do not need any (optional byteswapping) method access to
3511          * the Initiator context field.
3512          */
3513         I2O_MESSAGE_FRAME_setInitiatorContext64(
3514           (PI2O_MESSAGE_FRAME)Message_Ptr, (long)ccb);
3515
3516         (void)ASR_queue (sc, (PI2O_MESSAGE_FRAME)Message_Ptr);
3517
3518         free(Message_Ptr, M_TEMP);
3519
3520         /*
3521          * Wait for the board to report a finished instruction.
3522          */
3523         s = splcam();
3524         while ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
3525                 if (ASR_getBlinkLedCode(sc)) {
3526                         /* Reset Adapter */
3527                         printf ("asr%d: Blink LED 0x%x resetting adapter\n",
3528                           cam_sim_unit(xpt_path_sim(ccb->ccb_h.path)),
3529                           ASR_getBlinkLedCode(sc));
3530                         if (ASR_reset (sc) == ENXIO) {
3531                                 /* Command Cleanup */
3532                                 ASR_ccbRemove(sc, ccb);
3533                         }
3534                         splx(s);
3535                         /* Free up in-kernel buffers */
3536                         while ((elm = SLIST_FIRST(&sgList)) != NULL) {
3537                                 SLIST_REMOVE_HEAD(&sgList, link);
3538                                 free(elm, M_TEMP);
3539                         }
3540                         free(Reply_Ptr, M_TEMP);
3541                         asr_free_ccb(ccb);
3542                         return (EIO);
3543                 }
3544                 /* Check every second for BlinkLed */
3545                 /* There is no PRICAM, but outwardly PRIBIO is functional */
3546                 tsleep(ccb, PRIBIO, "asr", hz);
3547         }
3548         splx(s);
3549
3550         debug_usr_cmd_printf ("Outbound: ");
3551         debug_usr_cmd_dump_message(Reply_Ptr);
3552
3553         I2O_SINGLE_REPLY_MESSAGE_FRAME_setDetailedStatusCode(
3554           &(Reply_Ptr->StdReplyFrame),
3555           (ccb->ccb_h.status != CAM_REQ_CMP));
3556
3557         if (ReplySizeInBytes >= (sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)
3558           - I2O_SCSI_SENSE_DATA_SZ - sizeof(U32))) {
3559                 I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME_setTransferCount(Reply_Ptr,
3560                   ccb->csio.dxfer_len - ccb->csio.resid);
3561         }
3562         if ((ccb->ccb_h.status & CAM_AUTOSNS_VALID) && (ReplySizeInBytes
3563          > (sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)
3564          - I2O_SCSI_SENSE_DATA_SZ))) {
3565                 int size = ReplySizeInBytes
3566                   - sizeof(I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME)
3567                   - I2O_SCSI_SENSE_DATA_SZ;
3568
3569                 if (size > sizeof(ccb->csio.sense_data)) {
3570                         size = sizeof(ccb->csio.sense_data);
3571                 }
3572                 bcopy(&(ccb->csio.sense_data), Reply_Ptr->SenseData, size);
3573                 I2O_SCSI_ERROR_REPLY_MESSAGE_FRAME_setAutoSenseTransferCount(
3574                     Reply_Ptr, size);
3575         }
3576
3577         /* Free up in-kernel buffers */
3578         while ((elm = SLIST_FIRST(&sgList)) != NULL) {
3579                 /* Copy out as necessary */
3580                 if ((error == 0)
3581                 /* DIR bit considered `valid', error due to ignorance works */
3582                  && ((I2O_FLAGS_COUNT_getFlags(&(elm->FlagsCount))
3583                   & I2O_SGL_FLAGS_DIR) == 0)) {
3584                         error = copyout((caddr_t)(elm->KernelSpace),
3585                           elm->UserSpace,
3586                           I2O_FLAGS_COUNT_getCount(&(elm->FlagsCount)));
3587                 }
3588                 SLIST_REMOVE_HEAD(&sgList, link);
3589                 free(elm, M_TEMP);
3590         }
3591         if (error == 0) {
3592         /* Copy reply frame to user space */
3593                 error = copyout((caddr_t)Reply_Ptr, (caddr_t)Reply,
3594                                 ReplySizeInBytes);
3595         }
3596         free(Reply_Ptr, M_TEMP);
3597         asr_free_ccb(ccb);
3598
3599         return (error);
3600 } /* ASR_queue_i */
3601
3602 /*----------------------------------------------------------------------*/
3603 /*                          Function asr_ioctl                         */
3604 /*----------------------------------------------------------------------*/
3605 /* The parameters passed to this function are :                         */
3606 /*     dev  : Device number.                                            */
3607 /*     cmd  : Ioctl Command                                             */
3608 /*     data : User Argument Passed In.                                  */
3609 /*     flag : Mode Parameter                                            */
3610 /*     proc : Process Parameter                                         */
3611 /*                                                                      */
3612 /* This function is the user interface into this adapter driver         */
3613 /*                                                                      */
3614 /* Return : zero if OK, error code if not                               */
3615 /*----------------------------------------------------------------------*/
3616
3617 static int
3618 asr_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3619 {
3620         Asr_softc_t     *sc = dev->si_drv1;
3621         int             i, error = 0;
3622 #ifdef ASR_IOCTL_COMPAT
3623         int             j;
3624 #endif /* ASR_IOCTL_COMPAT */
3625
3626         if (sc != NULL)
3627         switch(cmd) {
3628
3629         case DPT_SIGNATURE:
3630 #ifdef ASR_IOCTL_COMPAT
3631 #if (dsDescription_size != 50)
3632         case DPT_SIGNATURE + ((50 - dsDescription_size) << 16):
3633 #endif
3634                 if (cmd & 0xFFFF0000) {
3635                         bcopy(&ASR_sig, data, sizeof(dpt_sig_S));
3636                         return (0);
3637                 }
3638         /* Traditional version of the ioctl interface */
3639         case DPT_SIGNATURE & 0x0000FFFF:
3640 #endif
3641                 return (copyout((caddr_t)(&ASR_sig), *((caddr_t *)data),
3642                                 sizeof(dpt_sig_S)));
3643
3644         /* Traditional version of the ioctl interface */
3645         case DPT_CTRLINFO & 0x0000FFFF:
3646         case DPT_CTRLINFO: {
3647                 struct {
3648                         u_int16_t length;
3649                         u_int16_t drvrHBAnum;
3650                         u_int32_t baseAddr;
3651                         u_int16_t blinkState;
3652                         u_int8_t  pciBusNum;
3653                         u_int8_t  pciDeviceNum;
3654                         u_int16_t hbaFlags;
3655                         u_int16_t Interrupt;
3656                         u_int32_t reserved1;
3657                         u_int32_t reserved2;
3658                         u_int32_t reserved3;
3659                 } CtlrInfo;
3660
3661                 bzero(&CtlrInfo, sizeof(CtlrInfo));
3662                 CtlrInfo.length = sizeof(CtlrInfo) - sizeof(u_int16_t);
3663                 CtlrInfo.drvrHBAnum = asr_unit(dev);
3664                 CtlrInfo.baseAddr = sc->ha_Base;
3665                 i = ASR_getBlinkLedCode (sc);
3666                 if (i == -1)
3667                         i = 0;
3668
3669                 CtlrInfo.blinkState = i;
3670                 CtlrInfo.pciBusNum = sc->ha_pciBusNum;
3671                 CtlrInfo.pciDeviceNum = sc->ha_pciDeviceNum;
3672 #define FLG_OSD_PCI_VALID 0x0001
3673 #define FLG_OSD_DMA       0x0002
3674 #define FLG_OSD_I2O       0x0004
3675                 CtlrInfo.hbaFlags = FLG_OSD_PCI_VALID|FLG_OSD_DMA|FLG_OSD_I2O;
3676                 CtlrInfo.Interrupt = sc->ha_irq;
3677 #ifdef ASR_IOCTL_COMPAT
3678                 if (cmd & 0xffff0000)
3679                         bcopy(&CtlrInfo, data, sizeof(CtlrInfo));
3680                 else
3681 #endif /* ASR_IOCTL_COMPAT */
3682                 error = copyout(&CtlrInfo, *(caddr_t *)data, sizeof(CtlrInfo));
3683         }       return (error);
3684
3685         /* Traditional version of the ioctl interface */
3686         case DPT_SYSINFO & 0x0000FFFF:
3687         case DPT_SYSINFO: {
3688                 sysInfo_S       Info;
3689 #ifdef ASR_IOCTL_COMPAT
3690                 char          * cp;
3691                 /* Kernel Specific ptok `hack' */
3692 #define         ptok(a) ((char *)(uintptr_t)(a) + KERNBASE)
3693
3694                 bzero(&Info, sizeof(Info));
3695
3696                 /* Appears I am the only person in the Kernel doing this */
3697                 outb (0x70, 0x12);
3698                 i = inb(0x71);
3699                 j = i >> 4;
3700                 if (i == 0x0f) {
3701                         outb (0x70, 0x19);
3702                         j = inb (0x71);
3703                 }
3704                 Info.drive0CMOS = j;
3705
3706                 j = i & 0x0f;
3707                 if (i == 0x0f) {
3708                         outb (0x70, 0x1a);
3709                         j = inb (0x71);
3710                 }
3711                 Info.drive1CMOS = j;
3712
3713                 Info.numDrives = *((char *)ptok(0x475));
3714 #endif /* ASR_IOCTL_COMPAT */
3715
3716                 bzero(&Info, sizeof(Info));
3717
3718                 Info.processorFamily = ASR_sig.dsProcessorFamily;
3719 #if defined(__i386__)
3720                 switch (cpu) {
3721                 case CPU_386SX: case CPU_386:
3722                         Info.processorType = PROC_386; break;
3723                 case CPU_486SX: case CPU_486:
3724                         Info.processorType = PROC_486; break;
3725                 case CPU_586:
3726                         Info.processorType = PROC_PENTIUM; break;
3727                 case CPU_686:
3728                         Info.processorType = PROC_SEXIUM; break;
3729                 }
3730 #endif
3731
3732                 Info.osType = OS_BSDI_UNIX;
3733                 Info.osMajorVersion = osrelease[0] - '0';
3734                 Info.osMinorVersion = osrelease[2] - '0';
3735                 /* Info.osRevision = 0; */
3736                 /* Info.osSubRevision = 0; */
3737                 Info.busType = SI_PCI_BUS;
3738                 Info.flags = SI_OSversionValid|SI_BusTypeValid|SI_NO_SmartROM;
3739
3740 #ifdef ASR_IOCTL_COMPAT
3741                 Info.flags |= SI_CMOS_Valid | SI_NumDrivesValid;
3742                 /* Go Out And Look For I2O SmartROM */
3743                 for(j = 0xC8000; j < 0xE0000; j += 2048) {
3744                         int k;
3745
3746                         cp = ptok(j);
3747                         if (*((unsigned short *)cp) != 0xAA55) {
3748                                 continue;
3749                         }
3750                         j += (cp[2] * 512) - 2048;
3751                         if ((*((u_long *)(cp + 6))
3752                           != ('S' + (' ' * 256) + (' ' * 65536L)))
3753                          || (*((u_long *)(cp + 10))
3754                           != ('I' + ('2' * 256) + ('0' * 65536L)))) {
3755                                 continue;
3756                         }
3757                         cp += 0x24;
3758                         for (k = 0; k < 64; ++k) {
3759                                 if (*((unsigned short *)cp)
3760                                  == (' ' + ('v' * 256))) {
3761                                         break;
3762                                 }
3763                         }
3764                         if (k < 64) {
3765                                 Info.smartROMMajorVersion
3766                                     = *((unsigned char *)(cp += 4)) - '0';
3767                                 Info.smartROMMinorVersion
3768                                     = *((unsigned char *)(cp += 2));
3769                                 Info.smartROMRevision
3770                                     = *((unsigned char *)(++cp));
3771                                 Info.flags |= SI_SmartROMverValid;
3772                                 Info.flags &= ~SI_NO_SmartROM;
3773                                 break;
3774                         }
3775                 }
3776                 /* Get The Conventional Memory Size From CMOS */
3777                 outb (0x70, 0x16);
3778                 j = inb (0x71);
3779                 j <<= 8;
3780                 outb (0x70, 0x15);
3781                 j |= inb(0x71);
3782                 Info.conventionalMemSize = j;
3783
3784                 /* Get The Extended Memory Found At Power On From CMOS */
3785                 outb (0x70, 0x31);
3786                 j = inb (0x71);
3787                 j <<= 8;
3788                 outb (0x70, 0x30);
3789                 j |= inb(0x71);
3790                 Info.extendedMemSize = j;
3791                 Info.flags |= SI_MemorySizeValid;
3792
3793                 /* Copy Out The Info Structure To The User */
3794                 if (cmd & 0xFFFF0000)
3795                         bcopy(&Info, data, sizeof(Info));
3796                 else
3797 #endif /* ASR_IOCTL_COMPAT */
3798                 error = copyout(&Info, *(caddr_t *)data, sizeof(Info));
3799                 return (error); }
3800
3801                 /* Get The BlinkLED State */
3802         case DPT_BLINKLED:
3803                 i = ASR_getBlinkLedCode (sc);
3804                 if (i == -1)
3805                         i = 0;
3806 #ifdef ASR_IOCTL_COMPAT
3807                 if (cmd & 0xffff0000)
3808                         bcopy(&i, data, sizeof(i));
3809                 else
3810 #endif /* ASR_IOCTL_COMPAT */
3811                 error = copyout(&i, *(caddr_t *)data, sizeof(i));
3812                 break;
3813
3814                 /* Send an I2O command */
3815         case I2OUSRCMD:
3816                 return (ASR_queue_i(sc, *((PI2O_MESSAGE_FRAME *)data)));
3817
3818                 /* Reset and re-initialize the adapter */
3819         case I2ORESETCMD:
3820                 return (ASR_reset(sc));
3821
3822                 /* Rescan the LCT table and resynchronize the information */
3823         case I2ORESCANCMD:
3824                 return (ASR_rescan(sc));
3825         }
3826         return (EINVAL);
3827 } /* asr_ioctl */