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