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