xref: /illumos-gate/usr/src/uts/common/io/aac/aac.c (revision 8a2b682e57a046b828f37bcde1776f131ef4629f)
1 /*
2  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
3  */
4 
5 /*
6  * Copyright (c) 2018, Joyent, Inc.
7  * Copyright 2005-08 Adaptec, Inc.
8  * Copyright (c) 2005-08 Adaptec Inc., Achim Leubner
9  * Copyright (c) 2000 Michael Smith
10  * Copyright (c) 2001 Scott Long
11  * Copyright (c) 2000 BSDi
12  * All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 #include <sys/modctl.h>
36 #include <sys/conf.h>
37 #include <sys/cmn_err.h>
38 #include <sys/ddi.h>
39 #include <sys/devops.h>
40 #include <sys/pci.h>
41 #include <sys/types.h>
42 #include <sys/ddidmareq.h>
43 #include <sys/scsi/scsi.h>
44 #include <sys/ksynch.h>
45 #include <sys/sunddi.h>
46 #include <sys/byteorder.h>
47 #include "aac_regs.h"
48 #include "aac.h"
49 
50 /*
51  * FMA header files
52  */
53 #include <sys/ddifm.h>
54 #include <sys/fm/protocol.h>
55 #include <sys/fm/util.h>
56 #include <sys/fm/io/ddi.h>
57 
58 /*
59  * For minor nodes created by the SCSA framework, minor numbers are
60  * formed by left-shifting instance by INST_MINOR_SHIFT and OR in a
61  * number less than 64.
62  *
63  * To support cfgadm, need to confirm the SCSA framework by creating
64  * devctl/scsi and driver specific minor nodes under SCSA format,
65  * and calling scsi_hba_xxx() functions aacordingly.
66  */
67 
68 #define	AAC_MINOR		32
69 #define	INST2AAC(x)		(((x) << INST_MINOR_SHIFT) | AAC_MINOR)
70 #define	AAC_SCSA_MINOR(x)	((x) & TRAN_MINOR_MASK)
71 #define	AAC_IS_SCSA_NODE(x)	((x) == DEVCTL_MINOR || (x) == SCSI_MINOR)
72 
73 #define	SD2TRAN(sd)		((sd)->sd_address.a_hba_tran)
74 #define	AAC_TRAN2SOFTS(tran) ((struct aac_softstate *)(tran)->tran_hba_private)
75 #define	AAC_DIP2TRAN(dip)	((scsi_hba_tran_t *)ddi_get_driver_private(dip))
76 #define	AAC_DIP2SOFTS(dip)	(AAC_TRAN2SOFTS(AAC_DIP2TRAN(dip)))
77 #define	SD2AAC(sd)		(AAC_TRAN2SOFTS(SD2TRAN(sd)))
78 #define	AAC_PD(t)		((t) - AAC_MAX_LD)
79 #define	AAC_DEV(softs, t)	(((t) < AAC_MAX_LD) ? \
80 				&(softs)->containers[(t)].dev : \
81 				((t) < AAC_MAX_DEV(softs)) ? \
82 				&(softs)->nondasds[AAC_PD(t)].dev : NULL)
83 #define	AAC_DEVCFG_BEGIN(softs, tgt) \
84 				aac_devcfg((softs), (tgt), 1)
85 #define	AAC_DEVCFG_END(softs, tgt) \
86 				aac_devcfg((softs), (tgt), 0)
87 #define	PKT2AC(pkt)		((struct aac_cmd *)(pkt)->pkt_ha_private)
88 #define	AAC_BUSYWAIT(cond, timeout /* in millisecond */) { \
89 		if (!(cond)) { \
90 			int count = (timeout) * 10; \
91 			while (count) { \
92 				drv_usecwait(100); \
93 				if (cond) \
94 					break; \
95 				count--; \
96 			} \
97 			(timeout) = (count + 9) / 10; \
98 		} \
99 	}
100 
101 #define	AAC_SENSE_DATA_DESCR_LEN \
102 	(sizeof (struct scsi_descr_sense_hdr) + \
103 	sizeof (struct scsi_information_sense_descr))
104 #define	AAC_ARQ64_LENGTH \
105 	(sizeof (struct scsi_arq_status) + \
106 	AAC_SENSE_DATA_DESCR_LEN - SENSE_LENGTH)
107 
108 /* NOTE: GETG4ADDRTL(cdbp) is int32_t */
109 #define	AAC_GETGXADDR(cmdlen, cdbp) \
110 	((cmdlen == 6) ? GETG0ADDR(cdbp) : \
111 	(cmdlen == 10) ? (uint32_t)GETG1ADDR(cdbp) : \
112 	((uint64_t)GETG4ADDR(cdbp) << 32) | (uint32_t)GETG4ADDRTL(cdbp))
113 
114 #define	AAC_CDB_INQUIRY_CMDDT	0x02
115 #define	AAC_CDB_INQUIRY_EVPD	0x01
116 #define	AAC_VPD_PAGE_CODE	1
117 #define	AAC_VPD_PAGE_LENGTH	3
118 #define	AAC_VPD_PAGE_DATA	4
119 #define	AAC_VPD_ID_CODESET	0
120 #define	AAC_VPD_ID_TYPE		1
121 #define	AAC_VPD_ID_LENGTH	3
122 #define	AAC_VPD_ID_DATA		4
123 
124 #define	AAC_SCSI_RPTLUNS_HEAD_SIZE			0x08
125 #define	AAC_SCSI_RPTLUNS_ADDR_SIZE			0x08
126 #define	AAC_SCSI_RPTLUNS_ADDR_MASK			0xC0
127 /* 00b - peripheral device addressing method */
128 #define	AAC_SCSI_RPTLUNS_ADDR_PERIPHERAL		0x00
129 /* 01b - flat space addressing method */
130 #define	AAC_SCSI_RPTLUNS_ADDR_FLAT_SPACE		0x40
131 /* 10b - logical unit addressing method */
132 #define	AAC_SCSI_RPTLUNS_ADDR_LOGICAL_UNIT		0x80
133 
134 /* Return the size of FIB with data part type data_type */
135 #define	AAC_FIB_SIZEOF(data_type) \
136 	(sizeof (struct aac_fib_header) + sizeof (data_type))
137 /* Return the container size defined in mir */
138 #define	AAC_MIR_SIZE(softs, acc, mir) \
139 	(((softs)->flags & AAC_FLAGS_LBA_64BIT) ? \
140 	(uint64_t)ddi_get32((acc), &(mir)->MntObj.Capacity) + \
141 	((uint64_t)ddi_get32((acc), &(mir)->MntObj.CapacityHigh) << 32) : \
142 	(uint64_t)ddi_get32((acc), &(mir)->MntObj.Capacity))
143 
144 /* The last entry of aac_cards[] is for unknown cards */
145 #define	AAC_UNKNOWN_CARD \
146 	(sizeof (aac_cards) / sizeof (struct aac_card_type) - 1)
147 #define	CARD_IS_UNKNOWN(i)	(i == AAC_UNKNOWN_CARD)
148 #define	BUF_IS_READ(bp)		((bp)->b_flags & B_READ)
149 #define	AAC_IS_Q_EMPTY(q)	((q)->q_head == NULL)
150 #define	AAC_CMDQ(acp)		(!((acp)->flags & AAC_CMD_SYNC))
151 
152 #define	PCI_MEM_GET32(softs, off) \
153 	ddi_get32((softs)->pci_mem_handle, \
154 	    (void *)((softs)->pci_mem_base_vaddr + (off)))
155 #define	PCI_MEM_PUT32(softs, off, val) \
156 	ddi_put32((softs)->pci_mem_handle, \
157 	    (void *)((softs)->pci_mem_base_vaddr + (off)), \
158 	    (uint32_t)(val))
159 #define	PCI_MEM_GET16(softs, off) \
160 	ddi_get16((softs)->pci_mem_handle, \
161 	(void *)((softs)->pci_mem_base_vaddr + (off)))
162 #define	PCI_MEM_PUT16(softs, off, val) \
163 	ddi_put16((softs)->pci_mem_handle, \
164 	(void *)((softs)->pci_mem_base_vaddr + (off)), (uint16_t)(val))
165 /* Write host data at valp to device mem[off] repeatedly count times */
166 #define	PCI_MEM_REP_PUT8(softs, off, valp, count) \
167 	ddi_rep_put8((softs)->pci_mem_handle, (uint8_t *)(valp), \
168 	    (uint8_t *)((softs)->pci_mem_base_vaddr + (off)), \
169 	    count, DDI_DEV_AUTOINCR)
170 /* Read device data at mem[off] to host addr valp repeatedly count times */
171 #define	PCI_MEM_REP_GET8(softs, off, valp, count) \
172 	ddi_rep_get8((softs)->pci_mem_handle, (uint8_t *)(valp), \
173 	    (uint8_t *)((softs)->pci_mem_base_vaddr + (off)), \
174 	    count, DDI_DEV_AUTOINCR)
175 #define	AAC_GET_FIELD8(acc, d, s, field) \
176 	(d)->field = ddi_get8(acc, (uint8_t *)&(s)->field)
177 #define	AAC_GET_FIELD32(acc, d, s, field) \
178 	(d)->field = ddi_get32(acc, (uint32_t *)&(s)->field)
179 #define	AAC_GET_FIELD64(acc, d, s, field) \
180 	(d)->field = ddi_get64(acc, (uint64_t *)&(s)->field)
181 #define	AAC_REP_GET_FIELD8(acc, d, s, field, r) \
182 	ddi_rep_get8((acc), (uint8_t *)&(d)->field, \
183 	    (uint8_t *)&(s)->field, (r), DDI_DEV_AUTOINCR)
184 #define	AAC_REP_GET_FIELD32(acc, d, s, field, r) \
185 	ddi_rep_get32((acc), (uint32_t *)&(d)->field, \
186 	    (uint32_t *)&(s)->field, (r), DDI_DEV_AUTOINCR)
187 
188 #define	AAC_ENABLE_INTR(softs) { \
189 		if (softs->flags & AAC_FLAGS_NEW_COMM) \
190 			PCI_MEM_PUT32(softs, AAC_OIMR, ~AAC_DB_INTR_NEW); \
191 		else \
192 			PCI_MEM_PUT32(softs, AAC_OIMR, ~AAC_DB_INTR_BITS); \
193 		softs->state |= AAC_STATE_INTR; \
194 	}
195 
196 #define	AAC_DISABLE_INTR(softs)	{ \
197 		PCI_MEM_PUT32(softs, AAC_OIMR, ~0); \
198 		softs->state &= ~AAC_STATE_INTR; \
199 	}
200 #define	AAC_STATUS_CLR(softs, mask)	PCI_MEM_PUT32(softs, AAC_ODBR, mask)
201 #define	AAC_STATUS_GET(softs)		PCI_MEM_GET32(softs, AAC_ODBR)
202 #define	AAC_NOTIFY(softs, val)		PCI_MEM_PUT32(softs, AAC_IDBR, val)
203 #define	AAC_OUTB_GET(softs)		PCI_MEM_GET32(softs, AAC_OQUE)
204 #define	AAC_OUTB_SET(softs, val)	PCI_MEM_PUT32(softs, AAC_OQUE, val)
205 #define	AAC_FWSTATUS_GET(softs)	\
206 	((softs)->aac_if.aif_get_fwstatus(softs))
207 #define	AAC_MAILBOX_GET(softs, mb) \
208 	((softs)->aac_if.aif_get_mailbox((softs), (mb)))
209 #define	AAC_MAILBOX_SET(softs, cmd, arg0, arg1, arg2, arg3) \
210 	((softs)->aac_if.aif_set_mailbox((softs), (cmd), \
211 	    (arg0), (arg1), (arg2), (arg3)))
212 
213 #define	AAC_MGT_SLOT_NUM	2
214 #define	AAC_THROTTLE_DRAIN	-1
215 
216 #define	AAC_QUIESCE_TICK	1	/* 1 second */
217 #define	AAC_QUIESCE_TIMEOUT	180	/* 180 seconds */
218 #define	AAC_DEFAULT_TICK	10	/* 10 seconds */
219 #define	AAC_SYNC_TICK		(30*60)	/* 30 minutes */
220 
221 /* Poll time for aac_do_poll_io() */
222 #define	AAC_POLL_TIME		60	/* 60 seconds */
223 
224 /* IOP reset */
225 #define	AAC_IOP_RESET_SUCCEED		0	/* IOP reset succeed */
226 #define	AAC_IOP_RESET_FAILED		-1	/* IOP reset failed */
227 #define	AAC_IOP_RESET_ABNORMAL		-2	/* Reset operation abnormal */
228 
229 /*
230  * Hardware access functions
231  */
232 static int aac_rx_get_fwstatus(struct aac_softstate *);
233 static int aac_rx_get_mailbox(struct aac_softstate *, int);
234 static void aac_rx_set_mailbox(struct aac_softstate *, uint32_t, uint32_t,
235     uint32_t, uint32_t, uint32_t);
236 static int aac_rkt_get_fwstatus(struct aac_softstate *);
237 static int aac_rkt_get_mailbox(struct aac_softstate *, int);
238 static void aac_rkt_set_mailbox(struct aac_softstate *, uint32_t, uint32_t,
239     uint32_t, uint32_t, uint32_t);
240 
241 /*
242  * SCSA function prototypes
243  */
244 static int aac_attach(dev_info_t *, ddi_attach_cmd_t);
245 static int aac_detach(dev_info_t *, ddi_detach_cmd_t);
246 static int aac_reset(dev_info_t *, ddi_reset_cmd_t);
247 static int aac_quiesce(dev_info_t *);
248 static int aac_getinfo(dev_info_t *, ddi_info_cmd_t, void *, void **);
249 
250 /*
251  * Interrupt handler functions
252  */
253 static int aac_query_intrs(struct aac_softstate *, int);
254 static int aac_add_intrs(struct aac_softstate *);
255 static void aac_remove_intrs(struct aac_softstate *);
256 static int aac_enable_intrs(struct aac_softstate *);
257 static int aac_disable_intrs(struct aac_softstate *);
258 static uint_t aac_intr_old(caddr_t, caddr_t);
259 static uint_t aac_intr_new(caddr_t, caddr_t);
260 static uint_t aac_softintr(caddr_t);
261 
262 /*
263  * Internal functions in attach
264  */
265 static int aac_check_card_type(struct aac_softstate *);
266 static int aac_check_firmware(struct aac_softstate *);
267 static int aac_common_attach(struct aac_softstate *);
268 static void aac_common_detach(struct aac_softstate *);
269 static int aac_probe_containers(struct aac_softstate *);
270 static int aac_alloc_comm_space(struct aac_softstate *);
271 static int aac_setup_comm_space(struct aac_softstate *);
272 static void aac_free_comm_space(struct aac_softstate *);
273 static int aac_hba_setup(struct aac_softstate *);
274 
275 /*
276  * Sync FIB operation functions
277  */
278 int aac_sync_mbcommand(struct aac_softstate *, uint32_t, uint32_t,
279     uint32_t, uint32_t, uint32_t, uint32_t *);
280 static int aac_sync_fib(struct aac_softstate *, uint16_t, uint16_t);
281 
282 /*
283  * Command queue operation functions
284  */
285 static void aac_cmd_initq(struct aac_cmd_queue *);
286 static void aac_cmd_enqueue(struct aac_cmd_queue *, struct aac_cmd *);
287 static struct aac_cmd *aac_cmd_dequeue(struct aac_cmd_queue *);
288 static void aac_cmd_delete(struct aac_cmd_queue *, struct aac_cmd *);
289 
290 /*
291  * FIB queue operation functions
292  */
293 static int aac_fib_enqueue(struct aac_softstate *, int, uint32_t, uint32_t);
294 static int aac_fib_dequeue(struct aac_softstate *, int, int *);
295 
296 /*
297  * Slot operation functions
298  */
299 static int aac_create_slots(struct aac_softstate *);
300 static void aac_destroy_slots(struct aac_softstate *);
301 static void aac_alloc_fibs(struct aac_softstate *);
302 static void aac_destroy_fibs(struct aac_softstate *);
303 static struct aac_slot *aac_get_slot(struct aac_softstate *);
304 static void aac_release_slot(struct aac_softstate *, struct aac_slot *);
305 static int aac_alloc_fib(struct aac_softstate *, struct aac_slot *);
306 static void aac_free_fib(struct aac_slot *);
307 
308 /*
309  * Internal functions
310  */
311 static void aac_cmd_fib_header(struct aac_softstate *, struct aac_cmd *,
312     uint16_t);
313 static void aac_cmd_fib_rawio(struct aac_softstate *, struct aac_cmd *);
314 static void aac_cmd_fib_brw64(struct aac_softstate *, struct aac_cmd *);
315 static void aac_cmd_fib_brw(struct aac_softstate *, struct aac_cmd *);
316 static void aac_cmd_fib_sync(struct aac_softstate *, struct aac_cmd *);
317 static void aac_cmd_fib_scsi32(struct aac_softstate *, struct aac_cmd *);
318 static void aac_cmd_fib_scsi64(struct aac_softstate *, struct aac_cmd *);
319 static void aac_cmd_fib_startstop(struct aac_softstate *, struct aac_cmd *);
320 static void aac_start_waiting_io(struct aac_softstate *);
321 static void aac_drain_comp_q(struct aac_softstate *);
322 int aac_do_io(struct aac_softstate *, struct aac_cmd *);
323 static int aac_sync_fib_slot_bind(struct aac_softstate *, struct aac_cmd *);
324 static void aac_sync_fib_slot_release(struct aac_softstate *, struct aac_cmd *);
325 static void aac_start_io(struct aac_softstate *, struct aac_cmd *);
326 static int aac_do_poll_io(struct aac_softstate *, struct aac_cmd *);
327 static int aac_do_sync_io(struct aac_softstate *, struct aac_cmd *);
328 static int aac_send_command(struct aac_softstate *, struct aac_slot *);
329 static void aac_cmd_timeout(struct aac_softstate *, struct aac_cmd *);
330 static int aac_dma_sync_ac(struct aac_cmd *);
331 static int aac_shutdown(struct aac_softstate *);
332 static int aac_reset_adapter(struct aac_softstate *);
333 static int aac_do_quiesce(struct aac_softstate *softs);
334 static int aac_do_unquiesce(struct aac_softstate *softs);
335 static void aac_unhold_bus(struct aac_softstate *, int);
336 static void aac_set_throttle(struct aac_softstate *, struct aac_device *,
337     int, int);
338 
339 /*
340  * Adapter Initiated FIB handling function
341  */
342 static void aac_save_aif(struct aac_softstate *, ddi_acc_handle_t,
343     struct aac_fib *, int);
344 static int aac_handle_aif(struct aac_softstate *, struct aac_aif_command *);
345 
346 /*
347  * Event handling related functions
348  */
349 static void aac_timer(void *);
350 static void aac_event_thread(struct aac_softstate *);
351 static void aac_event_disp(struct aac_softstate *, int);
352 
353 /*
354  * IOCTL interface related functions
355  */
356 static int aac_open(dev_t *, int, int, cred_t *);
357 static int aac_close(dev_t, int, int, cred_t *);
358 static int aac_ioctl(dev_t, int, intptr_t, int, cred_t *, int *);
359 extern int aac_do_ioctl(struct aac_softstate *, dev_t, int, intptr_t, int);
360 
361 /*
362  * FMA Prototypes
363  */
364 static void aac_fm_init(struct aac_softstate *);
365 static void aac_fm_fini(struct aac_softstate *);
366 static int aac_fm_error_cb(dev_info_t *, ddi_fm_error_t *, const void *);
367 int aac_check_acc_handle(ddi_acc_handle_t);
368 int aac_check_dma_handle(ddi_dma_handle_t);
369 void aac_fm_ereport(struct aac_softstate *, char *);
370 
371 /*
372  * Auto enumeration functions
373  */
374 static dev_info_t *aac_find_child(struct aac_softstate *, uint16_t, uint8_t);
375 static int aac_tran_bus_config(dev_info_t *, uint_t, ddi_bus_config_op_t,
376     void *, dev_info_t **);
377 static int aac_handle_dr(struct aac_softstate *, int, int, int);
378 
379 extern pri_t minclsyspri;
380 
381 #ifdef DEBUG
382 /*
383  * UART	debug output support
384  */
385 
386 #define	AAC_PRINT_BUFFER_SIZE		512
387 #define	AAC_PRINT_TIMEOUT		250	/* 1/4 sec. = 250 msec. */
388 
389 #define	AAC_FW_DBG_STRLEN_OFFSET	0x00
390 #define	AAC_FW_DBG_FLAGS_OFFSET		0x04
391 #define	AAC_FW_DBG_BLED_OFFSET		0x08
392 
393 static int aac_get_fw_debug_buffer(struct aac_softstate *);
394 static void aac_print_scmd(struct aac_softstate *, struct aac_cmd *);
395 static void aac_print_aif(struct aac_softstate *, struct aac_aif_command *);
396 
397 static char aac_prt_buf[AAC_PRINT_BUFFER_SIZE];
398 static char aac_fmt[] = " %s";
399 static char aac_fmt_header[] = " %s.%d: %s";
400 static kmutex_t aac_prt_mutex;
401 
402 /*
403  * Debug flags to be put into the softstate flags field
404  * when initialized
405  */
406 uint32_t aac_debug_flags =
407 /*    AACDB_FLAGS_KERNEL_PRINT | */
408 /*    AACDB_FLAGS_FW_PRINT |	*/
409 /*    AACDB_FLAGS_MISC |	*/
410 /*    AACDB_FLAGS_FUNC1 |	*/
411 /*    AACDB_FLAGS_FUNC2 |	*/
412 /*    AACDB_FLAGS_SCMD |	*/
413 /*    AACDB_FLAGS_AIF |		*/
414 /*    AACDB_FLAGS_FIB |		*/
415 /*    AACDB_FLAGS_IOCTL |	*/
416 0;
417 uint32_t aac_debug_fib_flags =
418 /*    AACDB_FLAGS_FIB_RW |	*/
419 /*    AACDB_FLAGS_FIB_IOCTL |	*/
420 /*    AACDB_FLAGS_FIB_SRB |	*/
421 /*    AACDB_FLAGS_FIB_SYNC |	*/
422 /*    AACDB_FLAGS_FIB_HEADER |	*/
423 /*    AACDB_FLAGS_FIB_TIMEOUT |	*/
424 0;
425 
426 #endif /* DEBUG */
427 
428 static struct cb_ops aac_cb_ops = {
429 	aac_open,	/* open */
430 	aac_close,	/* close */
431 	nodev,		/* strategy */
432 	nodev,		/* print */
433 	nodev,		/* dump */
434 	nodev,		/* read */
435 	nodev,		/* write */
436 	aac_ioctl,	/* ioctl */
437 	nodev,		/* devmap */
438 	nodev,		/* mmap */
439 	nodev,		/* segmap */
440 	nochpoll,	/* poll */
441 	ddi_prop_op,	/* cb_prop_op */
442 	NULL,		/* streamtab */
443 	D_64BIT | D_NEW | D_MP | D_HOTPLUG,	/* cb_flag */
444 	CB_REV,		/* cb_rev */
445 	nodev,		/* async I/O read entry point */
446 	nodev		/* async I/O write entry point */
447 };
448 
449 static struct dev_ops aac_dev_ops = {
450 	DEVO_REV,
451 	0,
452 	aac_getinfo,
453 	nulldev,
454 	nulldev,
455 	aac_attach,
456 	aac_detach,
457 	aac_reset,
458 	&aac_cb_ops,
459 	NULL,
460 	NULL,
461 	aac_quiesce,
462 };
463 
464 static struct modldrv aac_modldrv = {
465 	&mod_driverops,
466 	"AAC Driver " AAC_DRIVER_VERSION,
467 	&aac_dev_ops,
468 };
469 
470 static struct modlinkage aac_modlinkage = {
471 	MODREV_1,
472 	&aac_modldrv,
473 	NULL
474 };
475 
476 static struct aac_softstate  *aac_softstatep;
477 
478 /*
479  * Supported card list
480  * ordered in vendor id, subvendor id, subdevice id, and device id
481  */
482 static struct aac_card_type aac_cards[] = {
483 	{0x1028, 0x1, 0x1028, 0x1, AAC_HWIF_I960RX,
484 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
485 	    "Dell", "PERC 3/Di"},
486 	{0x1028, 0x2, 0x1028, 0x2, AAC_HWIF_I960RX,
487 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
488 	    "Dell", "PERC 3/Di"},
489 	{0x1028, 0x3, 0x1028, 0x3, AAC_HWIF_I960RX,
490 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
491 	    "Dell", "PERC 3/Si"},
492 	{0x1028, 0x8, 0x1028, 0xcf, AAC_HWIF_I960RX,
493 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
494 	    "Dell", "PERC 3/Di"},
495 	{0x1028, 0x4, 0x1028, 0xd0, AAC_HWIF_I960RX,
496 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
497 	    "Dell", "PERC 3/Si"},
498 	{0x1028, 0x2, 0x1028, 0xd1, AAC_HWIF_I960RX,
499 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
500 	    "Dell", "PERC 3/Di"},
501 	{0x1028, 0x2, 0x1028, 0xd9, AAC_HWIF_I960RX,
502 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
503 	    "Dell", "PERC 3/Di"},
504 	{0x1028, 0xa, 0x1028, 0x106, AAC_HWIF_I960RX,
505 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
506 	    "Dell", "PERC 3/Di"},
507 	{0x1028, 0xa, 0x1028, 0x11b, AAC_HWIF_I960RX,
508 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
509 	    "Dell", "PERC 3/Di"},
510 	{0x1028, 0xa, 0x1028, 0x121, AAC_HWIF_I960RX,
511 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG, AAC_TYPE_SCSI,
512 	    "Dell", "PERC 3/Di"},
513 	{0x9005, 0x285, 0x1028, 0x287, AAC_HWIF_I960RX,
514 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG | AAC_FLAGS_256FIBS, AAC_TYPE_SCSI,
515 	    "Dell", "PERC 320/DC"},
516 	{0x9005, 0x285, 0x1028, 0x291, AAC_HWIF_I960RX,
517 	    AAC_FLAGS_17SG, AAC_TYPE_SATA, "Dell", "CERC SR2"},
518 
519 	{0x9005, 0x285, 0x1014, 0x2f2, AAC_HWIF_I960RX,
520 	    0, AAC_TYPE_SCSI, "IBM", "ServeRAID 8i"},
521 	{0x9005, 0x285, 0x1014, 0x34d, AAC_HWIF_I960RX,
522 	    0, AAC_TYPE_SAS, "IBM", "ServeRAID 8s"},
523 	{0x9005, 0x286, 0x1014, 0x9580, AAC_HWIF_RKT,
524 	    0, AAC_TYPE_SAS, "IBM", "ServeRAID 8k"},
525 
526 	{0x9005, 0x285, 0x103c, 0x3227, AAC_HWIF_I960RX,
527 	    AAC_FLAGS_17SG, AAC_TYPE_SATA, "Adaptec", "2610SA"},
528 	{0x9005, 0x285, 0xe11, 0x295, AAC_HWIF_I960RX,
529 	    AAC_FLAGS_17SG, AAC_TYPE_SATA, "Adaptec", "2610SA"},
530 
531 	{0x9005, 0x285, 0x9005, 0x285, AAC_HWIF_I960RX,
532 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG | AAC_FLAGS_256FIBS, AAC_TYPE_SCSI,
533 	    "Adaptec", "2200S"},
534 	{0x9005, 0x285, 0x9005, 0x286, AAC_HWIF_I960RX,
535 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG | AAC_FLAGS_256FIBS, AAC_TYPE_SCSI,
536 	    "Adaptec", "2120S"},
537 	{0x9005, 0x285, 0x9005, 0x287, AAC_HWIF_I960RX,
538 	    AAC_FLAGS_NO4GB | AAC_FLAGS_34SG | AAC_FLAGS_256FIBS, AAC_TYPE_SCSI,
539 	    "Adaptec", "2200S"},
540 	{0x9005, 0x285, 0x9005, 0x288, AAC_HWIF_I960RX,
541 	    0, AAC_TYPE_SCSI, "Adaptec", "3230S"},
542 	{0x9005, 0x285, 0x9005, 0x289, AAC_HWIF_I960RX,
543 	    0, AAC_TYPE_SCSI, "Adaptec", "3240S"},
544 	{0x9005, 0x285, 0x9005, 0x28a, AAC_HWIF_I960RX,
545 	    0, AAC_TYPE_SCSI, "Adaptec", "2020ZCR"},
546 	{0x9005, 0x285, 0x9005, 0x28b, AAC_HWIF_I960RX,
547 	    0, AAC_TYPE_SCSI, "Adaptec", "2025ZCR"},
548 	{0x9005, 0x286, 0x9005, 0x28c, AAC_HWIF_RKT,
549 	    0, AAC_TYPE_SCSI, "Adaptec", "2230S"},
550 	{0x9005, 0x286, 0x9005, 0x28d, AAC_HWIF_RKT,
551 	    0, AAC_TYPE_SCSI, "Adaptec", "2130S"},
552 	{0x9005, 0x285, 0x9005, 0x28e, AAC_HWIF_I960RX,
553 	    0, AAC_TYPE_SATA, "Adaptec", "2020SA"},
554 	{0x9005, 0x285, 0x9005, 0x28f, AAC_HWIF_I960RX,
555 	    0, AAC_TYPE_SATA, "Adaptec", "2025SA"},
556 	{0x9005, 0x285, 0x9005, 0x290, AAC_HWIF_I960RX,
557 	    AAC_FLAGS_17SG, AAC_TYPE_SATA, "Adaptec", "2410SA"},
558 	{0x9005, 0x285, 0x9005, 0x292, AAC_HWIF_I960RX,
559 	    AAC_FLAGS_17SG, AAC_TYPE_SATA, "Adaptec", "2810SA"},
560 	{0x9005, 0x285, 0x9005, 0x293, AAC_HWIF_I960RX,
561 	    AAC_FLAGS_17SG, AAC_TYPE_SATA, "Adaptec", "21610SA"},
562 	{0x9005, 0x285, 0x9005, 0x294, AAC_HWIF_I960RX,
563 	    0, AAC_TYPE_SATA, "Adaptec", "2026ZCR"},
564 	{0x9005, 0x285, 0x9005, 0x296, AAC_HWIF_I960RX,
565 	    0, AAC_TYPE_SCSI, "Adaptec", "2240S"},
566 	{0x9005, 0x285, 0x9005, 0x297, AAC_HWIF_I960RX,
567 	    0, AAC_TYPE_SAS, "Adaptec", "4005SAS"},
568 	{0x9005, 0x285, 0x9005, 0x298, AAC_HWIF_I960RX,
569 	    0, AAC_TYPE_SAS, "Adaptec", "RAID 4000"},
570 	{0x9005, 0x285, 0x9005, 0x299, AAC_HWIF_I960RX,
571 	    0, AAC_TYPE_SAS, "Adaptec", "4800SAS"},
572 	{0x9005, 0x285, 0x9005, 0x29a, AAC_HWIF_I960RX,
573 	    0, AAC_TYPE_SAS, "Adaptec", "4805SAS"},
574 	{0x9005, 0x286, 0x9005, 0x29b, AAC_HWIF_RKT,
575 	    0, AAC_TYPE_SATA, "Adaptec", "2820SA"},
576 	{0x9005, 0x286, 0x9005, 0x29c, AAC_HWIF_RKT,
577 	    0, AAC_TYPE_SATA, "Adaptec", "2620SA"},
578 	{0x9005, 0x286, 0x9005, 0x29d, AAC_HWIF_RKT,
579 	    0, AAC_TYPE_SATA, "Adaptec", "2420SA"},
580 	{0x9005, 0x286, 0x9005, 0x29e, AAC_HWIF_RKT,
581 	    0, AAC_TYPE_SATA, "ICP", "9024RO"},
582 	{0x9005, 0x286, 0x9005, 0x29f, AAC_HWIF_RKT,
583 	    0, AAC_TYPE_SATA, "ICP", "9014RO"},
584 	{0x9005, 0x286, 0x9005, 0x2a0, AAC_HWIF_RKT,
585 	    0, AAC_TYPE_SATA, "ICP", "9047MA"},
586 	{0x9005, 0x286, 0x9005, 0x2a1, AAC_HWIF_RKT,
587 	    0, AAC_TYPE_SATA, "ICP", "9087MA"},
588 	{0x9005, 0x285, 0x9005, 0x2a4, AAC_HWIF_I960RX,
589 	    0, AAC_TYPE_SAS, "ICP", "9085LI"},
590 	{0x9005, 0x285, 0x9005, 0x2a5, AAC_HWIF_I960RX,
591 	    0, AAC_TYPE_SAS, "ICP", "5085BR"},
592 	{0x9005, 0x286, 0x9005, 0x2a6, AAC_HWIF_RKT,
593 	    0, AAC_TYPE_SATA, "ICP", "9067MA"},
594 	{0x9005, 0x285, 0x9005, 0x2b5, AAC_HWIF_I960RX,
595 	    0, AAC_TYPE_SAS, "Adaptec", "RAID 5445"},
596 	{0x9005, 0x285, 0x9005, 0x2b6, AAC_HWIF_I960RX,
597 	    0, AAC_TYPE_SAS, "Adaptec", "RAID 5805"},
598 	{0x9005, 0x285, 0x9005, 0x2b7, AAC_HWIF_I960RX,
599 	    0, AAC_TYPE_SAS, "Adaptec", "RAID 5085"},
600 	{0x9005, 0x285, 0x9005, 0x2b8, AAC_HWIF_I960RX,
601 	    0, AAC_TYPE_SAS, "ICP", "RAID ICP5445SL"},
602 	{0x9005, 0x285, 0x9005, 0x2b9, AAC_HWIF_I960RX,
603 	    0, AAC_TYPE_SAS, "ICP", "RAID ICP5085SL"},
604 	{0x9005, 0x285, 0x9005, 0x2ba, AAC_HWIF_I960RX,
605 	    0, AAC_TYPE_SAS, "ICP", "RAID ICP5805SL"},
606 
607 	{0, 0, 0, 0, AAC_HWIF_UNKNOWN,
608 	    0, AAC_TYPE_UNKNOWN, "Unknown", "AAC card"},
609 };
610 
611 /*
612  * Hardware access functions for i960 based cards
613  */
614 static struct aac_interface aac_rx_interface = {
615 	aac_rx_get_fwstatus,
616 	aac_rx_get_mailbox,
617 	aac_rx_set_mailbox
618 };
619 
620 /*
621  * Hardware access functions for Rocket based cards
622  */
623 static struct aac_interface aac_rkt_interface = {
624 	aac_rkt_get_fwstatus,
625 	aac_rkt_get_mailbox,
626 	aac_rkt_set_mailbox
627 };
628 
629 ddi_device_acc_attr_t aac_acc_attr = {
630 	DDI_DEVICE_ATTR_V1,
631 	DDI_STRUCTURE_LE_ACC,
632 	DDI_STRICTORDER_ACC,
633 	DDI_DEFAULT_ACC
634 };
635 
636 static struct {
637 	int	size;
638 	int	notify;
639 } aac_qinfo[] = {
640 	{AAC_HOST_NORM_CMD_ENTRIES, AAC_DB_COMMAND_NOT_FULL},
641 	{AAC_HOST_HIGH_CMD_ENTRIES, 0},
642 	{AAC_ADAP_NORM_CMD_ENTRIES, AAC_DB_COMMAND_READY},
643 	{AAC_ADAP_HIGH_CMD_ENTRIES, 0},
644 	{AAC_HOST_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_NOT_FULL},
645 	{AAC_HOST_HIGH_RESP_ENTRIES, 0},
646 	{AAC_ADAP_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_READY},
647 	{AAC_ADAP_HIGH_RESP_ENTRIES, 0}
648 };
649 
650 /*
651  * Default aac dma attributes
652  */
653 static ddi_dma_attr_t aac_dma_attr = {
654 	DMA_ATTR_V0,
655 	0,		/* lowest usable address */
656 	0xffffffffull,	/* high DMA address range */
657 	0xffffffffull,	/* DMA counter register */
658 	AAC_DMA_ALIGN,	/* DMA address alignment */
659 	1,		/* DMA burstsizes */
660 	1,		/* min effective DMA size */
661 	0xffffffffull,	/* max DMA xfer size */
662 	0xffffffffull,	/* segment boundary */
663 	1,		/* s/g list length */
664 	AAC_BLK_SIZE,	/* granularity of device */
665 	0		/* DMA transfer flags */
666 };
667 
668 static int aac_tick = AAC_DEFAULT_TICK;	/* tick for the internal timer */
669 static uint32_t aac_timebase = 0;	/* internal timer in seconds */
670 
671 /*
672  * Warlock directives
673  *
674  * Different variables with the same types have to be protected by the
675  * same mutex; otherwise, warlock will complain with "variables don't
676  * seem to be protected consistently". For example,
677  * aac_softstate::{q_wait, q_comp} are type of aac_cmd_queue, and protected
678  * by aac_softstate::{io_lock, q_comp_mutex} respectively. We have to
679  * declare them as protected explictly at aac_cmd_dequeue().
680  */
681 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_pkt scsi_cdb scsi_status \
682     scsi_arq_status scsi_descr_sense_hdr scsi_information_sense_descr \
683     mode_format mode_geometry mode_header aac_cmd))
684 _NOTE(SCHEME_PROTECTS_DATA("unique per aac_cmd", aac_fib ddi_dma_cookie_t \
685     aac_sge))
686 _NOTE(SCHEME_PROTECTS_DATA("unique per aac_fib", aac_blockread aac_blockwrite \
687     aac_blockread64 aac_raw_io aac_sg_entry aac_sg_entry64 aac_sg_entryraw \
688     aac_sg_table aac_srb))
689 _NOTE(SCHEME_PROTECTS_DATA("unique to sync fib and cdb", scsi_inquiry))
690 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device scsi_address))
691 _NOTE(SCHEME_PROTECTS_DATA("unique to scsi_transport", buf))
692 
693 int
694 _init(void)
695 {
696 	int rval = 0;
697 
698 #ifdef DEBUG
699 	mutex_init(&aac_prt_mutex, NULL, MUTEX_DRIVER, NULL);
700 #endif
701 	DBCALLED(NULL, 1);
702 
703 	if ((rval = ddi_soft_state_init((void *)&aac_softstatep,
704 	    sizeof (struct aac_softstate), 0)) != 0)
705 		goto error;
706 
707 	if ((rval = scsi_hba_init(&aac_modlinkage)) != 0) {
708 		ddi_soft_state_fini((void *)&aac_softstatep);
709 		goto error;
710 	}
711 
712 	if ((rval = mod_install(&aac_modlinkage)) != 0) {
713 		ddi_soft_state_fini((void *)&aac_softstatep);
714 		scsi_hba_fini(&aac_modlinkage);
715 		goto error;
716 	}
717 	return (rval);
718 
719 error:
720 	AACDB_PRINT(NULL, CE_WARN, "Mod init error!");
721 #ifdef DEBUG
722 	mutex_destroy(&aac_prt_mutex);
723 #endif
724 	return (rval);
725 }
726 
727 int
728 _info(struct modinfo *modinfop)
729 {
730 	DBCALLED(NULL, 1);
731 	return (mod_info(&aac_modlinkage, modinfop));
732 }
733 
734 /*
735  * An HBA driver cannot be unload unless you reboot,
736  * so this function will be of no use.
737  */
738 int
739 _fini(void)
740 {
741 	int rval;
742 
743 	DBCALLED(NULL, 1);
744 
745 	if ((rval = mod_remove(&aac_modlinkage)) != 0)
746 		goto error;
747 
748 	scsi_hba_fini(&aac_modlinkage);
749 	ddi_soft_state_fini((void *)&aac_softstatep);
750 #ifdef DEBUG
751 	mutex_destroy(&aac_prt_mutex);
752 #endif
753 	return (0);
754 
755 error:
756 	AACDB_PRINT(NULL, CE_WARN, "AAC is busy, cannot unload!");
757 	return (rval);
758 }
759 
760 static int
761 aac_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
762 {
763 	int instance, i;
764 	struct aac_softstate *softs = NULL;
765 	int attach_state = 0;
766 	char *data;
767 
768 	DBCALLED(NULL, 1);
769 
770 	switch (cmd) {
771 	case DDI_ATTACH:
772 		break;
773 	case DDI_RESUME:
774 		return (DDI_FAILURE);
775 	default:
776 		return (DDI_FAILURE);
777 	}
778 
779 	instance = ddi_get_instance(dip);
780 
781 	/* Get soft state */
782 	if (ddi_soft_state_zalloc(aac_softstatep, instance) != DDI_SUCCESS) {
783 		AACDB_PRINT(softs, CE_WARN, "Cannot alloc soft state");
784 		goto error;
785 	}
786 	softs = ddi_get_soft_state(aac_softstatep, instance);
787 	attach_state |= AAC_ATTACH_SOFTSTATE_ALLOCED;
788 
789 	softs->instance = instance;
790 	softs->devinfo_p = dip;
791 	softs->buf_dma_attr = softs->addr_dma_attr = aac_dma_attr;
792 	softs->addr_dma_attr.dma_attr_granular = 1;
793 	softs->acc_attr = aac_acc_attr;
794 	softs->reg_attr = aac_acc_attr;
795 	softs->card = AAC_UNKNOWN_CARD;
796 #ifdef DEBUG
797 	softs->debug_flags = aac_debug_flags;
798 	softs->debug_fib_flags = aac_debug_fib_flags;
799 #endif
800 
801 	/* Initialize FMA */
802 	aac_fm_init(softs);
803 
804 	/* Check the card type */
805 	if (aac_check_card_type(softs) == AACERR) {
806 		AACDB_PRINT(softs, CE_WARN, "Card not supported");
807 		goto error;
808 	}
809 	/* We have found the right card and everything is OK */
810 	attach_state |= AAC_ATTACH_CARD_DETECTED;
811 
812 	/* Map PCI mem space */
813 	if (ddi_regs_map_setup(dip, 1,
814 	    (caddr_t *)&softs->pci_mem_base_vaddr, 0,
815 	    softs->map_size_min, &softs->reg_attr,
816 	    &softs->pci_mem_handle) != DDI_SUCCESS)
817 		goto error;
818 
819 	softs->map_size = softs->map_size_min;
820 	attach_state |= AAC_ATTACH_PCI_MEM_MAPPED;
821 
822 	AAC_DISABLE_INTR(softs);
823 
824 	/* Init mutexes and condvars */
825 	mutex_init(&softs->io_lock, NULL, MUTEX_DRIVER,
826 	    DDI_INTR_PRI(softs->intr_pri));
827 	mutex_init(&softs->q_comp_mutex, NULL, MUTEX_DRIVER,
828 	    DDI_INTR_PRI(softs->intr_pri));
829 	mutex_init(&softs->time_mutex, NULL, MUTEX_DRIVER,
830 	    DDI_INTR_PRI(softs->intr_pri));
831 	mutex_init(&softs->ev_lock, NULL, MUTEX_DRIVER,
832 	    DDI_INTR_PRI(softs->intr_pri));
833 	mutex_init(&softs->aifq_mutex, NULL,
834 	    MUTEX_DRIVER, DDI_INTR_PRI(softs->intr_pri));
835 	cv_init(&softs->event, NULL, CV_DRIVER, NULL);
836 	cv_init(&softs->sync_fib_cv, NULL, CV_DRIVER, NULL);
837 	cv_init(&softs->drain_cv, NULL, CV_DRIVER, NULL);
838 	cv_init(&softs->event_wait_cv, NULL, CV_DRIVER, NULL);
839 	cv_init(&softs->event_disp_cv, NULL, CV_DRIVER, NULL);
840 	cv_init(&softs->aifq_cv, NULL, CV_DRIVER, NULL);
841 	attach_state |= AAC_ATTACH_KMUTEX_INITED;
842 
843 	/* Init the cmd queues */
844 	for (i = 0; i < AAC_CMDQ_NUM; i++)
845 		aac_cmd_initq(&softs->q_wait[i]);
846 	aac_cmd_initq(&softs->q_busy);
847 	aac_cmd_initq(&softs->q_comp);
848 
849 	/* Check for legacy device naming support */
850 	softs->legacy = 1; /* default to use legacy name */
851 	if ((ddi_prop_lookup_string(DDI_DEV_T_ANY, dip, 0,
852 	    "legacy-name-enable", &data) == DDI_SUCCESS)) {
853 		if (strcmp(data, "no") == 0) {
854 			AACDB_PRINT(softs, CE_NOTE, "legacy-name disabled");
855 			softs->legacy = 0;
856 		}
857 		ddi_prop_free(data);
858 	}
859 
860 	/*
861 	 * Everything has been set up till now,
862 	 * we will do some common attach.
863 	 */
864 	mutex_enter(&softs->io_lock);
865 	if (aac_common_attach(softs) == AACERR) {
866 		mutex_exit(&softs->io_lock);
867 		goto error;
868 	}
869 	mutex_exit(&softs->io_lock);
870 	attach_state |= AAC_ATTACH_COMM_SPACE_SETUP;
871 
872 	/* Check for buf breakup support */
873 	if ((ddi_prop_lookup_string(DDI_DEV_T_ANY, dip, 0,
874 	    "breakup-enable", &data) == DDI_SUCCESS)) {
875 		if (strcmp(data, "yes") == 0) {
876 			AACDB_PRINT(softs, CE_NOTE, "buf breakup enabled");
877 			softs->flags |= AAC_FLAGS_BRKUP;
878 		}
879 		ddi_prop_free(data);
880 	}
881 	softs->dma_max = softs->buf_dma_attr.dma_attr_maxxfer;
882 	if (softs->flags & AAC_FLAGS_BRKUP) {
883 		softs->dma_max = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
884 		    DDI_PROP_DONTPASS, "dma-max", softs->dma_max);
885 	}
886 
887 	if (aac_hba_setup(softs) != AACOK)
888 		goto error;
889 	attach_state |= AAC_ATTACH_SCSI_TRAN_SETUP;
890 
891 	/* Create devctl/scsi nodes for cfgadm */
892 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
893 	    INST2DEVCTL(instance), DDI_NT_SCSI_NEXUS, 0) != DDI_SUCCESS) {
894 		AACDB_PRINT(softs, CE_WARN, "failed to create devctl node");
895 		goto error;
896 	}
897 	attach_state |= AAC_ATTACH_CREATE_DEVCTL;
898 
899 	if (ddi_create_minor_node(dip, "scsi", S_IFCHR, INST2SCSI(instance),
900 	    DDI_NT_SCSI_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
901 		AACDB_PRINT(softs, CE_WARN, "failed to create scsi node");
902 		goto error;
903 	}
904 	attach_state |= AAC_ATTACH_CREATE_SCSI;
905 
906 	/* Create aac node for app. to issue ioctls */
907 	if (ddi_create_minor_node(dip, "aac", S_IFCHR, INST2AAC(instance),
908 	    DDI_PSEUDO, 0) != DDI_SUCCESS) {
909 		AACDB_PRINT(softs, CE_WARN, "failed to create aac node");
910 		goto error;
911 	}
912 
913 	/* Common attach is OK, so we are attached! */
914 	softs->state |= AAC_STATE_RUN;
915 
916 	/* Create event thread */
917 	softs->fibctx_p = &softs->aifctx;
918 	if ((softs->event_thread = thread_create(NULL, 0, aac_event_thread,
919 	    softs, 0, &p0, TS_RUN, minclsyspri)) == NULL) {
920 		AACDB_PRINT(softs, CE_WARN, "aif thread create failed");
921 		softs->state &= ~AAC_STATE_RUN;
922 		goto error;
923 	}
924 
925 	aac_unhold_bus(softs, AAC_IOCMD_SYNC | AAC_IOCMD_ASYNC);
926 
927 	/* Create a thread for command timeout */
928 	softs->timeout_id = timeout(aac_timer, (void *)softs,
929 	    (aac_tick * drv_usectohz(1000000)));
930 
931 	/* Common attach is OK, so we are attached! */
932 	ddi_report_dev(dip);
933 	AACDB_PRINT(softs, CE_NOTE, "aac attached ok");
934 	return (DDI_SUCCESS);
935 
936 error:
937 	if (attach_state & AAC_ATTACH_CREATE_SCSI)
938 		ddi_remove_minor_node(dip, "scsi");
939 	if (attach_state & AAC_ATTACH_CREATE_DEVCTL)
940 		ddi_remove_minor_node(dip, "devctl");
941 	if (attach_state & AAC_ATTACH_COMM_SPACE_SETUP)
942 		aac_common_detach(softs);
943 	if (attach_state & AAC_ATTACH_SCSI_TRAN_SETUP) {
944 		(void) scsi_hba_detach(dip);
945 		scsi_hba_tran_free(AAC_DIP2TRAN(dip));
946 	}
947 	if (attach_state & AAC_ATTACH_KMUTEX_INITED) {
948 		mutex_destroy(&softs->io_lock);
949 		mutex_destroy(&softs->q_comp_mutex);
950 		mutex_destroy(&softs->time_mutex);
951 		mutex_destroy(&softs->ev_lock);
952 		mutex_destroy(&softs->aifq_mutex);
953 		cv_destroy(&softs->event);
954 		cv_destroy(&softs->sync_fib_cv);
955 		cv_destroy(&softs->drain_cv);
956 		cv_destroy(&softs->event_wait_cv);
957 		cv_destroy(&softs->event_disp_cv);
958 		cv_destroy(&softs->aifq_cv);
959 	}
960 	if (attach_state & AAC_ATTACH_PCI_MEM_MAPPED)
961 		ddi_regs_map_free(&softs->pci_mem_handle);
962 	aac_fm_fini(softs);
963 	if (attach_state & AAC_ATTACH_CARD_DETECTED)
964 		softs->card = AACERR;
965 	if (attach_state & AAC_ATTACH_SOFTSTATE_ALLOCED)
966 		ddi_soft_state_free(aac_softstatep, instance);
967 	return (DDI_FAILURE);
968 }
969 
970 static int
971 aac_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
972 {
973 	scsi_hba_tran_t *tran = AAC_DIP2TRAN(dip);
974 	struct aac_softstate *softs = AAC_TRAN2SOFTS(tran);
975 
976 	DBCALLED(softs, 1);
977 
978 	switch (cmd) {
979 	case DDI_DETACH:
980 		break;
981 	case DDI_SUSPEND:
982 		return (DDI_FAILURE);
983 	default:
984 		return (DDI_FAILURE);
985 	}
986 
987 	mutex_enter(&softs->io_lock);
988 	AAC_DISABLE_INTR(softs);
989 	softs->state = AAC_STATE_STOPPED;
990 
991 	ddi_remove_minor_node(dip, "aac");
992 	ddi_remove_minor_node(dip, "scsi");
993 	ddi_remove_minor_node(dip, "devctl");
994 	mutex_exit(&softs->io_lock);
995 
996 	aac_common_detach(softs);
997 
998 	mutex_enter(&softs->io_lock);
999 	(void) scsi_hba_detach(dip);
1000 	scsi_hba_tran_free(tran);
1001 	mutex_exit(&softs->io_lock);
1002 
1003 	/* Stop timer */
1004 	mutex_enter(&softs->time_mutex);
1005 	if (softs->timeout_id) {
1006 		timeout_id_t tid = softs->timeout_id;
1007 		softs->timeout_id = 0;
1008 
1009 		mutex_exit(&softs->time_mutex);
1010 		(void) untimeout(tid);
1011 		mutex_enter(&softs->time_mutex);
1012 	}
1013 	mutex_exit(&softs->time_mutex);
1014 
1015 	/* Destroy event thread */
1016 	mutex_enter(&softs->ev_lock);
1017 	cv_signal(&softs->event_disp_cv);
1018 	cv_wait(&softs->event_wait_cv, &softs->ev_lock);
1019 	mutex_exit(&softs->ev_lock);
1020 
1021 	cv_destroy(&softs->aifq_cv);
1022 	cv_destroy(&softs->event_disp_cv);
1023 	cv_destroy(&softs->event_wait_cv);
1024 	cv_destroy(&softs->drain_cv);
1025 	cv_destroy(&softs->sync_fib_cv);
1026 	cv_destroy(&softs->event);
1027 	mutex_destroy(&softs->aifq_mutex);
1028 	mutex_destroy(&softs->ev_lock);
1029 	mutex_destroy(&softs->time_mutex);
1030 	mutex_destroy(&softs->q_comp_mutex);
1031 	mutex_destroy(&softs->io_lock);
1032 
1033 	ddi_regs_map_free(&softs->pci_mem_handle);
1034 	aac_fm_fini(softs);
1035 	softs->hwif = AAC_HWIF_UNKNOWN;
1036 	softs->card = AAC_UNKNOWN_CARD;
1037 	ddi_soft_state_free(aac_softstatep, ddi_get_instance(dip));
1038 
1039 	return (DDI_SUCCESS);
1040 }
1041 
1042 /*ARGSUSED*/
1043 static int
1044 aac_reset(dev_info_t *dip, ddi_reset_cmd_t cmd)
1045 {
1046 	struct aac_softstate *softs = AAC_DIP2SOFTS(dip);
1047 
1048 	DBCALLED(softs, 1);
1049 
1050 	mutex_enter(&softs->io_lock);
1051 	AAC_DISABLE_INTR(softs);
1052 	(void) aac_shutdown(softs);
1053 	mutex_exit(&softs->io_lock);
1054 
1055 	return (DDI_SUCCESS);
1056 }
1057 
1058 /*
1059  * quiesce(9E) entry point.
1060  *
1061  * This function is called when the system is single-threaded at high
1062  * PIL with preemption disabled. Therefore, this function must not be
1063  * blocked.
1064  *
1065  * This function returns DDI_SUCCESS on success, or DDI_FAILURE on failure.
1066  * DDI_FAILURE indicates an error condition and should almost never happen.
1067  */
1068 static int
1069 aac_quiesce(dev_info_t *dip)
1070 {
1071 	struct aac_softstate *softs = AAC_DIP2SOFTS(dip);
1072 
1073 	if (softs == NULL)
1074 		return (DDI_FAILURE);
1075 
1076 	_NOTE(ASSUMING_PROTECTED(softs->state))
1077 	AAC_DISABLE_INTR(softs);
1078 
1079 	return (DDI_SUCCESS);
1080 }
1081 
1082 /* ARGSUSED */
1083 static int
1084 aac_getinfo(dev_info_t *self, ddi_info_cmd_t infocmd, void *arg,
1085     void **result)
1086 {
1087 	int error = DDI_SUCCESS;
1088 
1089 	switch (infocmd) {
1090 	case DDI_INFO_DEVT2INSTANCE:
1091 		*result = (void *)(intptr_t)(MINOR2INST(getminor((dev_t)arg)));
1092 		break;
1093 	default:
1094 		error = DDI_FAILURE;
1095 	}
1096 	return (error);
1097 }
1098 
1099 /*
1100  * Bring the controller down to a dormant state and detach all child devices.
1101  * This function is called before detach or system shutdown.
1102  * Note: we can assume that the q_wait on the controller is empty, as we
1103  * won't allow shutdown if any device is open.
1104  */
1105 static int
1106 aac_shutdown(struct aac_softstate *softs)
1107 {
1108 	ddi_acc_handle_t acc;
1109 	struct aac_close_command *cc;
1110 	int rval;
1111 
1112 	(void) aac_sync_fib_slot_bind(softs, &softs->sync_ac);
1113 	acc = softs->sync_ac.slotp->fib_acc_handle;
1114 
1115 	cc = (struct aac_close_command *)&softs->sync_ac.slotp->fibp->data[0];
1116 
1117 	ddi_put32(acc, &cc->Command, VM_CloseAll);
1118 	ddi_put32(acc, &cc->ContainerId, 0xfffffffful);
1119 
1120 	/* Flush all caches, set FW to write through mode */
1121 	rval = aac_sync_fib(softs, ContainerCommand,
1122 	    AAC_FIB_SIZEOF(struct aac_close_command));
1123 	aac_sync_fib_slot_release(softs, &softs->sync_ac);
1124 
1125 	AACDB_PRINT(softs, CE_NOTE,
1126 	    "shutting down aac %s", (rval == AACOK) ? "ok" : "fail");
1127 	return (rval);
1128 }
1129 
1130 static uint_t
1131 aac_softintr(caddr_t arg)
1132 {
1133 	struct aac_softstate *softs = (void *)arg;
1134 
1135 	if (!AAC_IS_Q_EMPTY(&softs->q_comp)) {
1136 		aac_drain_comp_q(softs);
1137 	}
1138 	return (DDI_INTR_CLAIMED);
1139 }
1140 
1141 /*
1142  * Setup auto sense data for pkt
1143  */
1144 static void
1145 aac_set_arq_data(struct scsi_pkt *pkt, uchar_t key,
1146     uchar_t add_code, uchar_t qual_code, uint64_t info)
1147 {
1148 	struct scsi_arq_status *arqstat = (void *)(pkt->pkt_scbp);
1149 
1150 	*pkt->pkt_scbp = STATUS_CHECK; /* CHECK CONDITION */
1151 	pkt->pkt_state |= STATE_ARQ_DONE;
1152 
1153 	*(uint8_t *)&arqstat->sts_rqpkt_status = STATUS_GOOD;
1154 	arqstat->sts_rqpkt_reason = CMD_CMPLT;
1155 	arqstat->sts_rqpkt_resid = 0;
1156 	arqstat->sts_rqpkt_state =
1157 	    STATE_GOT_BUS |
1158 	    STATE_GOT_TARGET |
1159 	    STATE_SENT_CMD |
1160 	    STATE_XFERRED_DATA;
1161 	arqstat->sts_rqpkt_statistics = 0;
1162 
1163 	if (info <= 0xfffffffful) {
1164 		arqstat->sts_sensedata.es_valid = 1;
1165 		arqstat->sts_sensedata.es_class = CLASS_EXTENDED_SENSE;
1166 		arqstat->sts_sensedata.es_code = CODE_FMT_FIXED_CURRENT;
1167 		arqstat->sts_sensedata.es_key = key;
1168 		arqstat->sts_sensedata.es_add_code = add_code;
1169 		arqstat->sts_sensedata.es_qual_code = qual_code;
1170 
1171 		arqstat->sts_sensedata.es_info_1 = (info >> 24) & 0xFF;
1172 		arqstat->sts_sensedata.es_info_2 = (info >> 16) & 0xFF;
1173 		arqstat->sts_sensedata.es_info_3 = (info >>  8) & 0xFF;
1174 		arqstat->sts_sensedata.es_info_4 = info & 0xFF;
1175 	} else { /* 64-bit LBA */
1176 		struct scsi_descr_sense_hdr *dsp;
1177 		struct scsi_information_sense_descr *isd;
1178 
1179 		dsp = (struct scsi_descr_sense_hdr *)&arqstat->sts_sensedata;
1180 		dsp->ds_class = CLASS_EXTENDED_SENSE;
1181 		dsp->ds_code = CODE_FMT_DESCR_CURRENT;
1182 		dsp->ds_key = key;
1183 		dsp->ds_add_code = add_code;
1184 		dsp->ds_qual_code = qual_code;
1185 		dsp->ds_addl_sense_length =
1186 		    sizeof (struct scsi_information_sense_descr);
1187 
1188 		isd = (struct scsi_information_sense_descr *)(dsp+1);
1189 		isd->isd_descr_type = DESCR_INFORMATION;
1190 		isd->isd_valid = 1;
1191 		isd->isd_information[0] = (info >> 56) & 0xFF;
1192 		isd->isd_information[1] = (info >> 48) & 0xFF;
1193 		isd->isd_information[2] = (info >> 40) & 0xFF;
1194 		isd->isd_information[3] = (info >> 32) & 0xFF;
1195 		isd->isd_information[4] = (info >> 24) & 0xFF;
1196 		isd->isd_information[5] = (info >> 16) & 0xFF;
1197 		isd->isd_information[6] = (info >>  8) & 0xFF;
1198 		isd->isd_information[7] = (info) & 0xFF;
1199 	}
1200 }
1201 
1202 /*
1203  * Setup auto sense data for HARDWARE ERROR
1204  */
1205 static void
1206 aac_set_arq_data_hwerr(struct aac_cmd *acp)
1207 {
1208 	union scsi_cdb *cdbp;
1209 	uint64_t err_blkno;
1210 
1211 	cdbp = (void *)acp->pkt->pkt_cdbp;
1212 	err_blkno = AAC_GETGXADDR(acp->cmdlen, cdbp);
1213 	aac_set_arq_data(acp->pkt, KEY_HARDWARE_ERROR, 0x00, 0x00, err_blkno);
1214 }
1215 
1216 /*
1217  * Send a command to the adapter in New Comm. interface
1218  */
1219 static int
1220 aac_send_command(struct aac_softstate *softs, struct aac_slot *slotp)
1221 {
1222 	uint32_t index, device;
1223 
1224 	index = PCI_MEM_GET32(softs, AAC_IQUE);
1225 	if (index == 0xffffffffUL) {
1226 		index = PCI_MEM_GET32(softs, AAC_IQUE);
1227 		if (index == 0xffffffffUL)
1228 			return (AACERR);
1229 	}
1230 
1231 	device = index;
1232 	PCI_MEM_PUT32(softs, device,
1233 	    (uint32_t)(slotp->fib_phyaddr & 0xfffffffful));
1234 	device += 4;
1235 	PCI_MEM_PUT32(softs, device, (uint32_t)(slotp->fib_phyaddr >> 32));
1236 	device += 4;
1237 	PCI_MEM_PUT32(softs, device, slotp->acp->fib_size);
1238 	PCI_MEM_PUT32(softs, AAC_IQUE, index);
1239 	return (AACOK);
1240 }
1241 
1242 static void
1243 aac_end_io(struct aac_softstate *softs, struct aac_cmd *acp)
1244 {
1245 	struct aac_device *dvp = acp->dvp;
1246 	int q = AAC_CMDQ(acp);
1247 
1248 	if (acp->slotp) { /* outstanding cmd */
1249 		if (!(acp->flags & AAC_CMD_IN_SYNC_SLOT)) {
1250 			aac_release_slot(softs, acp->slotp);
1251 			acp->slotp = NULL;
1252 		}
1253 		if (dvp) {
1254 			dvp->ncmds[q]--;
1255 			if (dvp->throttle[q] == AAC_THROTTLE_DRAIN &&
1256 			    dvp->ncmds[q] == 0 && q == AAC_CMDQ_ASYNC)
1257 				aac_set_throttle(softs, dvp, q,
1258 				    softs->total_slots);
1259 			/*
1260 			 * Setup auto sense data for UNIT ATTENTION
1261 			 * Each lun should generate a unit attention
1262 			 * condition when reset.
1263 			 * Phys. drives are treated as logical ones
1264 			 * during error recovery.
1265 			 */
1266 			if (dvp->type == AAC_DEV_LD) {
1267 				struct aac_container *ctp =
1268 				    (struct aac_container *)dvp;
1269 				if (ctp->reset == 0)
1270 					goto noreset;
1271 
1272 				AACDB_PRINT(softs, CE_NOTE,
1273 				    "Unit attention: reset");
1274 				ctp->reset = 0;
1275 				aac_set_arq_data(acp->pkt, KEY_UNIT_ATTENTION,
1276 				    0x29, 0x02, 0);
1277 			}
1278 		}
1279 noreset:
1280 		softs->bus_ncmds[q]--;
1281 		aac_cmd_delete(&softs->q_busy, acp);
1282 	} else { /* cmd in waiting queue */
1283 		aac_cmd_delete(&softs->q_wait[q], acp);
1284 	}
1285 
1286 	if (!(acp->flags & (AAC_CMD_NO_CB | AAC_CMD_NO_INTR))) { /* async IO */
1287 		mutex_enter(&softs->q_comp_mutex);
1288 		aac_cmd_enqueue(&softs->q_comp, acp);
1289 		mutex_exit(&softs->q_comp_mutex);
1290 	} else if (acp->flags & AAC_CMD_NO_CB) { /* sync IO */
1291 		cv_broadcast(&softs->event);
1292 	}
1293 }
1294 
1295 static void
1296 aac_handle_io(struct aac_softstate *softs, int index)
1297 {
1298 	struct aac_slot *slotp;
1299 	struct aac_cmd *acp;
1300 	uint32_t fast;
1301 
1302 	fast = index & AAC_SENDERADDR_MASK_FAST_RESPONSE;
1303 	index >>= 2;
1304 
1305 	/* Make sure firmware reported index is valid */
1306 	ASSERT(index >= 0 && index < softs->total_slots);
1307 	slotp = &softs->io_slot[index];
1308 	ASSERT(slotp->index == index);
1309 	acp = slotp->acp;
1310 
1311 	if (acp == NULL || acp->slotp != slotp) {
1312 		cmn_err(CE_WARN,
1313 		    "Firmware error: invalid slot index received from FW");
1314 		return;
1315 	}
1316 
1317 	acp->flags |= AAC_CMD_CMPLT;
1318 	(void) ddi_dma_sync(slotp->fib_dma_handle, 0, 0, DDI_DMA_SYNC_FORCPU);
1319 
1320 	if (aac_check_dma_handle(slotp->fib_dma_handle) == DDI_SUCCESS) {
1321 		/*
1322 		 * For fast response IO, the firmware do not return any FIB
1323 		 * data, so we need to fill in the FIB status and state so that
1324 		 * FIB users can handle it correctly.
1325 		 */
1326 		if (fast) {
1327 			uint32_t state;
1328 
1329 			state = ddi_get32(slotp->fib_acc_handle,
1330 			    &slotp->fibp->Header.XferState);
1331 			/*
1332 			 * Update state for CPU not for device, no DMA sync
1333 			 * needed
1334 			 */
1335 			ddi_put32(slotp->fib_acc_handle,
1336 			    &slotp->fibp->Header.XferState,
1337 			    state | AAC_FIBSTATE_DONEADAP);
1338 			ddi_put32(slotp->fib_acc_handle,
1339 			    (void *)&slotp->fibp->data[0], ST_OK);
1340 		}
1341 
1342 		/* Handle completed ac */
1343 		acp->ac_comp(softs, acp);
1344 	} else {
1345 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_UNAFFECTED);
1346 		acp->flags |= AAC_CMD_ERR;
1347 		if (acp->pkt) {
1348 			acp->pkt->pkt_reason = CMD_TRAN_ERR;
1349 			acp->pkt->pkt_statistics = 0;
1350 		}
1351 	}
1352 	aac_end_io(softs, acp);
1353 }
1354 
1355 /*
1356  * Interrupt handler for New Comm. interface
1357  * New Comm. interface use a different mechanism for interrupt. No explict
1358  * message queues, and driver need only accesses the mapped PCI mem space to
1359  * find the completed FIB or AIF.
1360  */
1361 static int
1362 aac_process_intr_new(struct aac_softstate *softs)
1363 {
1364 	uint32_t index;
1365 
1366 	index = AAC_OUTB_GET(softs);
1367 	if (index == 0xfffffffful)
1368 		index = AAC_OUTB_GET(softs);
1369 	if (aac_check_acc_handle(softs->pci_mem_handle) != DDI_SUCCESS) {
1370 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_UNAFFECTED);
1371 		return (0);
1372 	}
1373 	if (index != 0xfffffffful) {
1374 		do {
1375 			if ((index & AAC_SENDERADDR_MASK_AIF) == 0) {
1376 				aac_handle_io(softs, index);
1377 			} else if (index != 0xfffffffeul) {
1378 				struct aac_fib *fibp;	/* FIB in AIF queue */
1379 				uint16_t fib_size;
1380 
1381 				/*
1382 				 * 0xfffffffe means that the controller wants
1383 				 * more work, ignore it for now. Otherwise,
1384 				 * AIF received.
1385 				 */
1386 				index &= ~2;
1387 
1388 				fibp = (struct aac_fib *)(softs-> \
1389 				    pci_mem_base_vaddr + index);
1390 				fib_size = PCI_MEM_GET16(softs, index + \
1391 				    offsetof(struct aac_fib, Header.Size));
1392 
1393 				aac_save_aif(softs, softs->pci_mem_handle,
1394 				    fibp, fib_size);
1395 
1396 				/*
1397 				 * AIF memory is owned by the adapter, so let it
1398 				 * know that we are done with it.
1399 				 */
1400 				AAC_OUTB_SET(softs, index);
1401 				AAC_STATUS_CLR(softs, AAC_DB_RESPONSE_READY);
1402 			}
1403 
1404 			index = AAC_OUTB_GET(softs);
1405 		} while (index != 0xfffffffful);
1406 
1407 		/*
1408 		 * Process waiting cmds before start new ones to
1409 		 * ensure first IOs are serviced first.
1410 		 */
1411 		aac_start_waiting_io(softs);
1412 		return (AAC_DB_COMMAND_READY);
1413 	} else {
1414 		return (0);
1415 	}
1416 }
1417 
1418 static uint_t
1419 aac_intr_new(caddr_t arg, caddr_t arg1 __unused)
1420 {
1421 	struct aac_softstate *softs = (void *)arg;
1422 	uint_t rval;
1423 
1424 	mutex_enter(&softs->io_lock);
1425 	if (aac_process_intr_new(softs))
1426 		rval = DDI_INTR_CLAIMED;
1427 	else
1428 		rval = DDI_INTR_UNCLAIMED;
1429 	mutex_exit(&softs->io_lock);
1430 
1431 	aac_drain_comp_q(softs);
1432 	return (rval);
1433 }
1434 
1435 /*
1436  * Interrupt handler for old interface
1437  * Explicit message queues are used to send FIB to and get completed FIB from
1438  * the adapter. Driver and adapter maitain the queues in the producer/consumer
1439  * manner. The driver has to query the queues to find the completed FIB.
1440  */
1441 static int
1442 aac_process_intr_old(struct aac_softstate *softs)
1443 {
1444 	uint16_t status;
1445 
1446 	status = AAC_STATUS_GET(softs);
1447 	if (aac_check_acc_handle(softs->pci_mem_handle) != DDI_SUCCESS) {
1448 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_UNAFFECTED);
1449 		return (DDI_INTR_UNCLAIMED);
1450 	}
1451 	if (status & AAC_DB_RESPONSE_READY) {
1452 		int slot_idx;
1453 
1454 		/* ACK the intr */
1455 		AAC_STATUS_CLR(softs, AAC_DB_RESPONSE_READY);
1456 		(void) AAC_STATUS_GET(softs);
1457 		while (aac_fib_dequeue(softs, AAC_HOST_NORM_RESP_Q,
1458 		    &slot_idx) == AACOK)
1459 			aac_handle_io(softs, slot_idx);
1460 
1461 		/*
1462 		 * Process waiting cmds before start new ones to
1463 		 * ensure first IOs are serviced first.
1464 		 */
1465 		aac_start_waiting_io(softs);
1466 		return (AAC_DB_RESPONSE_READY);
1467 	} else if (status & AAC_DB_COMMAND_READY) {
1468 		int aif_idx;
1469 
1470 		AAC_STATUS_CLR(softs, AAC_DB_COMMAND_READY);
1471 		(void) AAC_STATUS_GET(softs);
1472 		if (aac_fib_dequeue(softs, AAC_HOST_NORM_CMD_Q, &aif_idx) ==
1473 		    AACOK) {
1474 			ddi_acc_handle_t acc = softs->comm_space_acc_handle;
1475 			struct aac_fib *fibp;	/* FIB in communication space */
1476 			uint16_t fib_size;
1477 			uint32_t fib_xfer_state;
1478 			uint32_t addr, size;
1479 
1480 			ASSERT((aif_idx >= 0) && (aif_idx < AAC_ADAPTER_FIBS));
1481 
1482 #define	AAC_SYNC_AIF(softs, aif_idx, type) \
1483 	{ (void) ddi_dma_sync((softs)->comm_space_dma_handle, \
1484 	    offsetof(struct aac_comm_space, \
1485 	    adapter_fibs[(aif_idx)]), AAC_FIB_SIZE, \
1486 	    (type)); }
1487 
1488 			/* Copy AIF from adapter to the empty AIF slot */
1489 			AAC_SYNC_AIF(softs, aif_idx, DDI_DMA_SYNC_FORCPU);
1490 			fibp = &softs->comm_space->adapter_fibs[aif_idx];
1491 			fib_size = ddi_get16(acc, &fibp->Header.Size);
1492 
1493 			aac_save_aif(softs, acc, fibp, fib_size);
1494 
1495 			/* Complete AIF back to adapter with good status */
1496 			fib_xfer_state = LE_32(fibp->Header.XferState);
1497 			if (fib_xfer_state & AAC_FIBSTATE_FROMADAP) {
1498 				ddi_put32(acc, &fibp->Header.XferState,
1499 				    fib_xfer_state | AAC_FIBSTATE_DONEHOST);
1500 				ddi_put32(acc, (void *)&fibp->data[0], ST_OK);
1501 				if (fib_size > AAC_FIB_SIZE)
1502 					ddi_put16(acc, &fibp->Header.Size,
1503 					    AAC_FIB_SIZE);
1504 				AAC_SYNC_AIF(softs, aif_idx,
1505 				    DDI_DMA_SYNC_FORDEV);
1506 			}
1507 
1508 			/* Put the AIF response on the response queue */
1509 			addr = ddi_get32(acc,
1510 			    &softs->comm_space->adapter_fibs[aif_idx]. \
1511 			    Header.SenderFibAddress);
1512 			size = (uint32_t)ddi_get16(acc,
1513 			    &softs->comm_space->adapter_fibs[aif_idx]. \
1514 			    Header.Size);
1515 			ddi_put32(acc,
1516 			    &softs->comm_space->adapter_fibs[aif_idx]. \
1517 			    Header.ReceiverFibAddress, addr);
1518 			if (aac_fib_enqueue(softs, AAC_ADAP_NORM_RESP_Q,
1519 			    addr, size) == AACERR)
1520 				cmn_err(CE_NOTE, "!AIF ack failed");
1521 		}
1522 		return (AAC_DB_COMMAND_READY);
1523 	} else if (status & AAC_DB_PRINTF_READY) {
1524 		/* ACK the intr */
1525 		AAC_STATUS_CLR(softs, AAC_DB_PRINTF_READY);
1526 		(void) AAC_STATUS_GET(softs);
1527 		(void) ddi_dma_sync(softs->comm_space_dma_handle,
1528 		    offsetof(struct aac_comm_space, adapter_print_buf),
1529 		    AAC_ADAPTER_PRINT_BUFSIZE, DDI_DMA_SYNC_FORCPU);
1530 		if (aac_check_dma_handle(softs->comm_space_dma_handle) ==
1531 		    DDI_SUCCESS)
1532 			cmn_err(CE_NOTE, "MSG From Adapter: %s",
1533 			    softs->comm_space->adapter_print_buf);
1534 		else
1535 			ddi_fm_service_impact(softs->devinfo_p,
1536 			    DDI_SERVICE_UNAFFECTED);
1537 		AAC_NOTIFY(softs, AAC_DB_PRINTF_READY);
1538 		return (AAC_DB_PRINTF_READY);
1539 	} else if (status & AAC_DB_COMMAND_NOT_FULL) {
1540 		/*
1541 		 * Without these two condition statements, the OS could hang
1542 		 * after a while, especially if there are a lot of AIF's to
1543 		 * handle, for instance if a drive is pulled from an array
1544 		 * under heavy load.
1545 		 */
1546 		AAC_STATUS_CLR(softs, AAC_DB_COMMAND_NOT_FULL);
1547 		return (AAC_DB_COMMAND_NOT_FULL);
1548 	} else if (status & AAC_DB_RESPONSE_NOT_FULL) {
1549 		AAC_STATUS_CLR(softs, AAC_DB_COMMAND_NOT_FULL);
1550 		AAC_STATUS_CLR(softs, AAC_DB_RESPONSE_NOT_FULL);
1551 		return (AAC_DB_RESPONSE_NOT_FULL);
1552 	} else {
1553 		return (0);
1554 	}
1555 }
1556 
1557 static uint_t
1558 aac_intr_old(caddr_t arg, caddr_t arg1 __unused)
1559 {
1560 	struct aac_softstate *softs = (void *)arg;
1561 	int rval;
1562 
1563 	mutex_enter(&softs->io_lock);
1564 	if (aac_process_intr_old(softs))
1565 		rval = DDI_INTR_CLAIMED;
1566 	else
1567 		rval = DDI_INTR_UNCLAIMED;
1568 	mutex_exit(&softs->io_lock);
1569 
1570 	aac_drain_comp_q(softs);
1571 	return (rval);
1572 }
1573 
1574 /*
1575  * Query FIXED or MSI interrupts
1576  */
1577 static int
1578 aac_query_intrs(struct aac_softstate *softs, int intr_type)
1579 {
1580 	dev_info_t *dip = softs->devinfo_p;
1581 	int avail, actual, count;
1582 	int i, flag, ret;
1583 
1584 	AACDB_PRINT(softs, CE_NOTE,
1585 	    "aac_query_intrs:interrupt type 0x%x", intr_type);
1586 
1587 	/* Get number of interrupts */
1588 	ret = ddi_intr_get_nintrs(dip, intr_type, &count);
1589 	if ((ret != DDI_SUCCESS) || (count == 0)) {
1590 		AACDB_PRINT(softs, CE_WARN,
1591 		    "ddi_intr_get_nintrs() failed, ret %d count %d",
1592 		    ret, count);
1593 		return (DDI_FAILURE);
1594 	}
1595 
1596 	/* Get number of available interrupts */
1597 	ret = ddi_intr_get_navail(dip, intr_type, &avail);
1598 	if ((ret != DDI_SUCCESS) || (avail == 0)) {
1599 		AACDB_PRINT(softs, CE_WARN,
1600 		    "ddi_intr_get_navail() failed, ret %d avail %d",
1601 		    ret, avail);
1602 		return (DDI_FAILURE);
1603 	}
1604 
1605 	AACDB_PRINT(softs, CE_NOTE,
1606 	    "ddi_intr_get_nvail returned %d, navail() returned %d",
1607 	    count, avail);
1608 
1609 	/* Allocate an array of interrupt handles */
1610 	softs->intr_size = count * sizeof (ddi_intr_handle_t);
1611 	softs->htable = kmem_alloc(softs->intr_size, KM_SLEEP);
1612 
1613 	if (intr_type == DDI_INTR_TYPE_MSI) {
1614 		count = 1; /* only one vector needed by now */
1615 		flag = DDI_INTR_ALLOC_STRICT;
1616 	} else { /* must be DDI_INTR_TYPE_FIXED */
1617 		flag = DDI_INTR_ALLOC_NORMAL;
1618 	}
1619 
1620 	/* Call ddi_intr_alloc() */
1621 	ret = ddi_intr_alloc(dip, softs->htable, intr_type, 0,
1622 	    count, &actual, flag);
1623 
1624 	if ((ret != DDI_SUCCESS) || (actual == 0)) {
1625 		AACDB_PRINT(softs, CE_WARN,
1626 		    "ddi_intr_alloc() failed, ret = %d", ret);
1627 		actual = 0;
1628 		goto error;
1629 	}
1630 
1631 	if (actual < count) {
1632 		AACDB_PRINT(softs, CE_NOTE,
1633 		    "Requested: %d, Received: %d", count, actual);
1634 		goto error;
1635 	}
1636 
1637 	softs->intr_cnt = actual;
1638 
1639 	/* Get priority for first msi, assume remaining are all the same */
1640 	if ((ret = ddi_intr_get_pri(softs->htable[0],
1641 	    &softs->intr_pri)) != DDI_SUCCESS) {
1642 		AACDB_PRINT(softs, CE_WARN,
1643 		    "ddi_intr_get_pri() failed, ret = %d", ret);
1644 		goto error;
1645 	}
1646 
1647 	/* Test for high level mutex */
1648 	if (softs->intr_pri >= ddi_intr_get_hilevel_pri()) {
1649 		AACDB_PRINT(softs, CE_WARN,
1650 		    "aac_query_intrs: Hi level interrupt not supported");
1651 		goto error;
1652 	}
1653 
1654 	return (DDI_SUCCESS);
1655 
1656 error:
1657 	/* Free already allocated intr */
1658 	for (i = 0; i < actual; i++)
1659 		(void) ddi_intr_free(softs->htable[i]);
1660 
1661 	kmem_free(softs->htable, softs->intr_size);
1662 	return (DDI_FAILURE);
1663 }
1664 
1665 
1666 /*
1667  * Register FIXED or MSI interrupts, and enable them
1668  */
1669 static int
1670 aac_add_intrs(struct aac_softstate *softs)
1671 {
1672 	int i, ret;
1673 	int actual;
1674 	ddi_intr_handler_t *aac_intr;
1675 
1676 	actual = softs->intr_cnt;
1677 	aac_intr = ((softs->flags & AAC_FLAGS_NEW_COMM) ?
1678 	    aac_intr_new : aac_intr_old);
1679 
1680 	/* Call ddi_intr_add_handler() */
1681 	for (i = 0; i < actual; i++) {
1682 		if ((ret = ddi_intr_add_handler(softs->htable[i],
1683 		    aac_intr, (caddr_t)softs, NULL)) != DDI_SUCCESS) {
1684 			cmn_err(CE_WARN,
1685 			    "ddi_intr_add_handler() failed ret = %d", ret);
1686 
1687 			/* Free already allocated intr */
1688 			for (i = 0; i < actual; i++)
1689 				(void) ddi_intr_free(softs->htable[i]);
1690 
1691 			kmem_free(softs->htable, softs->intr_size);
1692 			return (DDI_FAILURE);
1693 		}
1694 	}
1695 
1696 	if ((ret = ddi_intr_get_cap(softs->htable[0], &softs->intr_cap))
1697 	    != DDI_SUCCESS) {
1698 		cmn_err(CE_WARN, "ddi_intr_get_cap() failed, ret = %d", ret);
1699 
1700 		/* Free already allocated intr */
1701 		for (i = 0; i < actual; i++)
1702 			(void) ddi_intr_free(softs->htable[i]);
1703 
1704 		kmem_free(softs->htable, softs->intr_size);
1705 		return (DDI_FAILURE);
1706 	}
1707 
1708 	return (DDI_SUCCESS);
1709 }
1710 
1711 /*
1712  * Unregister FIXED or MSI interrupts
1713  */
1714 static void
1715 aac_remove_intrs(struct aac_softstate *softs)
1716 {
1717 	int i;
1718 
1719 	/* Disable all interrupts */
1720 	(void) aac_disable_intrs(softs);
1721 	/* Call ddi_intr_remove_handler() */
1722 	for (i = 0; i < softs->intr_cnt; i++) {
1723 		(void) ddi_intr_remove_handler(softs->htable[i]);
1724 		(void) ddi_intr_free(softs->htable[i]);
1725 	}
1726 
1727 	kmem_free(softs->htable, softs->intr_size);
1728 }
1729 
1730 static int
1731 aac_enable_intrs(struct aac_softstate *softs)
1732 {
1733 	int rval = AACOK;
1734 
1735 	if (softs->intr_cap & DDI_INTR_FLAG_BLOCK) {
1736 		/* for MSI block enable */
1737 		if (ddi_intr_block_enable(softs->htable, softs->intr_cnt) !=
1738 		    DDI_SUCCESS)
1739 			rval = AACERR;
1740 	} else {
1741 		int i;
1742 
1743 		/* Call ddi_intr_enable() for legacy/MSI non block enable */
1744 		for (i = 0; i < softs->intr_cnt; i++) {
1745 			if (ddi_intr_enable(softs->htable[i]) != DDI_SUCCESS)
1746 				rval = AACERR;
1747 		}
1748 	}
1749 	return (rval);
1750 }
1751 
1752 static int
1753 aac_disable_intrs(struct aac_softstate *softs)
1754 {
1755 	int rval = AACOK;
1756 
1757 	if (softs->intr_cap & DDI_INTR_FLAG_BLOCK) {
1758 		/* Call ddi_intr_block_disable() */
1759 		if (ddi_intr_block_disable(softs->htable, softs->intr_cnt) !=
1760 		    DDI_SUCCESS)
1761 			rval = AACERR;
1762 	} else {
1763 		int i;
1764 
1765 		for (i = 0; i < softs->intr_cnt; i++) {
1766 			if (ddi_intr_disable(softs->htable[i]) != DDI_SUCCESS)
1767 				rval = AACERR;
1768 		}
1769 	}
1770 	return (rval);
1771 }
1772 
1773 /*
1774  * Set pkt_reason and OR in pkt_statistics flag
1775  */
1776 static void
1777 aac_set_pkt_reason(struct aac_softstate *softs, struct aac_cmd *acp,
1778     uchar_t reason, uint_t stat)
1779 {
1780 #ifndef __lock_lint
1781 	_NOTE(ARGUNUSED(softs))
1782 #endif
1783 	if (acp->pkt->pkt_reason == CMD_CMPLT)
1784 		acp->pkt->pkt_reason = reason;
1785 	acp->pkt->pkt_statistics |= stat;
1786 }
1787 
1788 /*
1789  * Handle a finished pkt of soft SCMD
1790  */
1791 static void
1792 aac_soft_callback(struct aac_softstate *softs, struct aac_cmd *acp)
1793 {
1794 	ASSERT(acp->pkt);
1795 
1796 	acp->flags |= AAC_CMD_CMPLT;
1797 
1798 	acp->pkt->pkt_state |= STATE_GOT_BUS | STATE_GOT_TARGET | \
1799 	    STATE_SENT_CMD | STATE_GOT_STATUS;
1800 	if (acp->pkt->pkt_state & STATE_XFERRED_DATA)
1801 		acp->pkt->pkt_resid = 0;
1802 
1803 	/* AAC_CMD_NO_INTR means no complete callback */
1804 	if (!(acp->flags & AAC_CMD_NO_INTR)) {
1805 		mutex_enter(&softs->q_comp_mutex);
1806 		aac_cmd_enqueue(&softs->q_comp, acp);
1807 		mutex_exit(&softs->q_comp_mutex);
1808 		ddi_trigger_softintr(softs->softint_id);
1809 	}
1810 }
1811 
1812 /*
1813  * Handlers for completed IOs, common to aac_intr_new() and aac_intr_old()
1814  */
1815 
1816 /*
1817  * Handle completed logical device IO command
1818  */
1819 /*ARGSUSED*/
1820 static void
1821 aac_ld_complete(struct aac_softstate *softs, struct aac_cmd *acp)
1822 {
1823 	struct aac_slot *slotp = acp->slotp;
1824 	struct aac_blockread_response *resp;
1825 	uint32_t status;
1826 
1827 	ASSERT(!(acp->flags & AAC_CMD_SYNC));
1828 	ASSERT(!(acp->flags & AAC_CMD_NO_CB));
1829 
1830 	acp->pkt->pkt_state |= STATE_GOT_STATUS;
1831 
1832 	/*
1833 	 * block_read/write has a similar response header, use blockread
1834 	 * response for both.
1835 	 */
1836 	resp = (struct aac_blockread_response *)&slotp->fibp->data[0];
1837 	status = ddi_get32(slotp->fib_acc_handle, &resp->Status);
1838 	if (status == ST_OK) {
1839 		acp->pkt->pkt_resid = 0;
1840 		acp->pkt->pkt_state |= STATE_XFERRED_DATA;
1841 	} else {
1842 		aac_set_arq_data_hwerr(acp);
1843 	}
1844 }
1845 
1846 /*
1847  * Handle completed phys. device IO command
1848  */
1849 static void
1850 aac_pd_complete(struct aac_softstate *softs, struct aac_cmd *acp)
1851 {
1852 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
1853 	struct aac_fib *fibp = acp->slotp->fibp;
1854 	struct scsi_pkt *pkt = acp->pkt;
1855 	struct aac_srb_reply *resp;
1856 	uint32_t resp_status;
1857 
1858 	ASSERT(!(acp->flags & AAC_CMD_SYNC));
1859 	ASSERT(!(acp->flags & AAC_CMD_NO_CB));
1860 
1861 	resp = (struct aac_srb_reply *)&fibp->data[0];
1862 	resp_status = ddi_get32(acc, &resp->status);
1863 
1864 	/* First check FIB status */
1865 	if (resp_status == ST_OK) {
1866 		uint32_t scsi_status;
1867 		uint32_t srb_status;
1868 		uint32_t data_xfer_length;
1869 
1870 		scsi_status = ddi_get32(acc, &resp->scsi_status);
1871 		srb_status = ddi_get32(acc, &resp->srb_status);
1872 		data_xfer_length = ddi_get32(acc, &resp->data_xfer_length);
1873 
1874 		*pkt->pkt_scbp = (uint8_t)scsi_status;
1875 		pkt->pkt_state |= STATE_GOT_STATUS;
1876 		if (scsi_status == STATUS_GOOD) {
1877 			uchar_t cmd = ((union scsi_cdb *)(void *)
1878 			    (pkt->pkt_cdbp))->scc_cmd;
1879 
1880 			/* Next check SRB status */
1881 			switch (srb_status & 0x3f) {
1882 			case SRB_STATUS_DATA_OVERRUN:
1883 				AACDB_PRINT(softs, CE_NOTE, "DATA_OVERRUN: " \
1884 				    "scmd=%d, xfer=%d, buflen=%d",
1885 				    (uint32_t)cmd, data_xfer_length,
1886 				    acp->bcount);
1887 
1888 				switch (cmd) {
1889 				case SCMD_READ:
1890 				case SCMD_WRITE:
1891 				case SCMD_READ_G1:
1892 				case SCMD_WRITE_G1:
1893 				case SCMD_READ_G4:
1894 				case SCMD_WRITE_G4:
1895 				case SCMD_READ_G5:
1896 				case SCMD_WRITE_G5:
1897 					aac_set_pkt_reason(softs, acp,
1898 					    CMD_DATA_OVR, 0);
1899 					break;
1900 				}
1901 				/*FALLTHRU*/
1902 			case SRB_STATUS_ERROR_RECOVERY:
1903 			case SRB_STATUS_PENDING:
1904 			case SRB_STATUS_SUCCESS:
1905 				/*
1906 				 * pkt_resid should only be calculated if the
1907 				 * status is ERROR_RECOVERY/PENDING/SUCCESS/
1908 				 * OVERRUN/UNDERRUN
1909 				 */
1910 				if (data_xfer_length) {
1911 					pkt->pkt_state |= STATE_XFERRED_DATA;
1912 					pkt->pkt_resid = acp->bcount - \
1913 					    data_xfer_length;
1914 					ASSERT(pkt->pkt_resid >= 0);
1915 				}
1916 				break;
1917 			case SRB_STATUS_ABORTED:
1918 				AACDB_PRINT(softs, CE_NOTE,
1919 				    "SRB_STATUS_ABORTED, xfer=%d, resid=%d",
1920 				    data_xfer_length, pkt->pkt_resid);
1921 				aac_set_pkt_reason(softs, acp, CMD_ABORTED,
1922 				    STAT_ABORTED);
1923 				break;
1924 			case SRB_STATUS_ABORT_FAILED:
1925 				AACDB_PRINT(softs, CE_NOTE,
1926 				    "SRB_STATUS_ABORT_FAILED, xfer=%d, " \
1927 				    "resid=%d", data_xfer_length,
1928 				    pkt->pkt_resid);
1929 				aac_set_pkt_reason(softs, acp, CMD_ABORT_FAIL,
1930 				    0);
1931 				break;
1932 			case SRB_STATUS_PARITY_ERROR:
1933 				AACDB_PRINT(softs, CE_NOTE,
1934 				    "SRB_STATUS_PARITY_ERROR, xfer=%d, " \
1935 				    "resid=%d", data_xfer_length,
1936 				    pkt->pkt_resid);
1937 				aac_set_pkt_reason(softs, acp, CMD_PER_FAIL, 0);
1938 				break;
1939 			case SRB_STATUS_NO_DEVICE:
1940 			case SRB_STATUS_INVALID_PATH_ID:
1941 			case SRB_STATUS_INVALID_TARGET_ID:
1942 			case SRB_STATUS_INVALID_LUN:
1943 			case SRB_STATUS_SELECTION_TIMEOUT:
1944 #ifdef DEBUG
1945 				if (AAC_DEV_IS_VALID(acp->dvp)) {
1946 					AACDB_PRINT(softs, CE_NOTE,
1947 					    "SRB_STATUS_NO_DEVICE(%d), " \
1948 					    "xfer=%d, resid=%d ",
1949 					    srb_status & 0x3f,
1950 					    data_xfer_length, pkt->pkt_resid);
1951 				}
1952 #endif
1953 				aac_set_pkt_reason(softs, acp, CMD_DEV_GONE, 0);
1954 				break;
1955 			case SRB_STATUS_COMMAND_TIMEOUT:
1956 			case SRB_STATUS_TIMEOUT:
1957 				AACDB_PRINT(softs, CE_NOTE,
1958 				    "SRB_STATUS_COMMAND_TIMEOUT, xfer=%d, " \
1959 				    "resid=%d", data_xfer_length,
1960 				    pkt->pkt_resid);
1961 				aac_set_pkt_reason(softs, acp, CMD_TIMEOUT,
1962 				    STAT_TIMEOUT);
1963 				break;
1964 			case SRB_STATUS_BUS_RESET:
1965 				AACDB_PRINT(softs, CE_NOTE,
1966 				    "SRB_STATUS_BUS_RESET, xfer=%d, " \
1967 				    "resid=%d", data_xfer_length,
1968 				    pkt->pkt_resid);
1969 				aac_set_pkt_reason(softs, acp, CMD_RESET,
1970 				    STAT_BUS_RESET);
1971 				break;
1972 			default:
1973 				AACDB_PRINT(softs, CE_NOTE, "srb_status=%d, " \
1974 				    "xfer=%d, resid=%d", srb_status & 0x3f,
1975 				    data_xfer_length, pkt->pkt_resid);
1976 				aac_set_pkt_reason(softs, acp, CMD_TRAN_ERR, 0);
1977 				break;
1978 			}
1979 		} else if (scsi_status == STATUS_CHECK) {
1980 			/* CHECK CONDITION */
1981 			struct scsi_arq_status *arqstat =
1982 			    (void *)(pkt->pkt_scbp);
1983 			uint32_t sense_data_size;
1984 
1985 			pkt->pkt_state |= STATE_ARQ_DONE;
1986 
1987 			*(uint8_t *)&arqstat->sts_rqpkt_status = STATUS_GOOD;
1988 			arqstat->sts_rqpkt_reason = CMD_CMPLT;
1989 			arqstat->sts_rqpkt_resid = 0;
1990 			arqstat->sts_rqpkt_state =
1991 			    STATE_GOT_BUS |
1992 			    STATE_GOT_TARGET |
1993 			    STATE_SENT_CMD |
1994 			    STATE_XFERRED_DATA;
1995 			arqstat->sts_rqpkt_statistics = 0;
1996 
1997 			sense_data_size = ddi_get32(acc,
1998 			    &resp->sense_data_size);
1999 			ASSERT(sense_data_size <= AAC_SENSE_BUFFERSIZE);
2000 			AACDB_PRINT(softs, CE_NOTE,
2001 			    "CHECK CONDITION: sense len=%d, xfer len=%d",
2002 			    sense_data_size, data_xfer_length);
2003 
2004 			if (sense_data_size > SENSE_LENGTH)
2005 				sense_data_size = SENSE_LENGTH;
2006 			ddi_rep_get8(acc, (uint8_t *)&arqstat->sts_sensedata,
2007 			    (uint8_t *)resp->sense_data, sense_data_size,
2008 			    DDI_DEV_AUTOINCR);
2009 		} else {
2010 			AACDB_PRINT(softs, CE_WARN, "invaild scsi status: " \
2011 			    "scsi_status=%d, srb_status=%d",
2012 			    scsi_status, srb_status);
2013 			aac_set_pkt_reason(softs, acp, CMD_TRAN_ERR, 0);
2014 		}
2015 	} else {
2016 		AACDB_PRINT(softs, CE_NOTE, "SRB failed: fib status %d",
2017 		    resp_status);
2018 		aac_set_pkt_reason(softs, acp, CMD_TRAN_ERR, 0);
2019 	}
2020 }
2021 
2022 /*
2023  * Handle completed IOCTL command
2024  */
2025 /*ARGSUSED*/
2026 void
2027 aac_ioctl_complete(struct aac_softstate *softs, struct aac_cmd *acp)
2028 {
2029 	struct aac_slot *slotp = acp->slotp;
2030 
2031 	/*
2032 	 * NOTE: Both aac_ioctl_send_fib() and aac_send_raw_srb()
2033 	 * may wait on softs->event, so use cv_broadcast() instead
2034 	 * of cv_signal().
2035 	 */
2036 	ASSERT(acp->flags & AAC_CMD_SYNC);
2037 	ASSERT(acp->flags & AAC_CMD_NO_CB);
2038 
2039 	/* Get the size of the response FIB from its FIB.Header.Size field */
2040 	acp->fib_size = ddi_get16(slotp->fib_acc_handle,
2041 	    &slotp->fibp->Header.Size);
2042 
2043 	ASSERT(acp->fib_size <= softs->aac_max_fib_size);
2044 	ddi_rep_get8(slotp->fib_acc_handle, (uint8_t *)acp->fibp,
2045 	    (uint8_t *)slotp->fibp, acp->fib_size, DDI_DEV_AUTOINCR);
2046 }
2047 
2048 /*
2049  * Handle completed sync fib command
2050  */
2051 /*ARGSUSED*/
2052 void
2053 aac_sync_complete(struct aac_softstate *softs, struct aac_cmd *acp)
2054 {
2055 }
2056 
2057 /*
2058  * Handle completed Flush command
2059  */
2060 /*ARGSUSED*/
2061 static void
2062 aac_synccache_complete(struct aac_softstate *softs, struct aac_cmd *acp)
2063 {
2064 	struct aac_slot *slotp = acp->slotp;
2065 	ddi_acc_handle_t acc = slotp->fib_acc_handle;
2066 	struct aac_synchronize_reply *resp;
2067 	uint32_t status;
2068 
2069 	ASSERT(!(acp->flags & AAC_CMD_SYNC));
2070 
2071 	acp->pkt->pkt_state |= STATE_GOT_STATUS;
2072 
2073 	resp = (struct aac_synchronize_reply *)&slotp->fibp->data[0];
2074 	status = ddi_get32(acc, &resp->Status);
2075 	if (status != CT_OK)
2076 		aac_set_arq_data_hwerr(acp);
2077 }
2078 
2079 /*ARGSUSED*/
2080 static void
2081 aac_startstop_complete(struct aac_softstate *softs, struct aac_cmd *acp)
2082 {
2083 	struct aac_slot *slotp = acp->slotp;
2084 	ddi_acc_handle_t acc = slotp->fib_acc_handle;
2085 	struct aac_Container_resp *resp;
2086 	uint32_t status;
2087 
2088 	ASSERT(!(acp->flags & AAC_CMD_SYNC));
2089 
2090 	acp->pkt->pkt_state |= STATE_GOT_STATUS;
2091 
2092 	resp = (struct aac_Container_resp *)&slotp->fibp->data[0];
2093 	status = ddi_get32(acc, &resp->Status);
2094 	if (status != 0) {
2095 		AACDB_PRINT(softs, CE_WARN, "Cannot start/stop a unit");
2096 		aac_set_arq_data_hwerr(acp);
2097 	}
2098 }
2099 
2100 /*
2101  * Access PCI space to see if the driver can support the card
2102  */
2103 static int
2104 aac_check_card_type(struct aac_softstate *softs)
2105 {
2106 	ddi_acc_handle_t pci_config_handle;
2107 	int card_index;
2108 	uint32_t pci_cmd;
2109 
2110 	/* Map pci configuration space */
2111 	if ((pci_config_setup(softs->devinfo_p, &pci_config_handle)) !=
2112 	    DDI_SUCCESS) {
2113 		AACDB_PRINT(softs, CE_WARN, "Cannot setup pci config space");
2114 		return (AACERR);
2115 	}
2116 
2117 	softs->vendid = pci_config_get16(pci_config_handle, PCI_CONF_VENID);
2118 	softs->devid = pci_config_get16(pci_config_handle, PCI_CONF_DEVID);
2119 	softs->subvendid = pci_config_get16(pci_config_handle,
2120 	    PCI_CONF_SUBVENID);
2121 	softs->subsysid = pci_config_get16(pci_config_handle,
2122 	    PCI_CONF_SUBSYSID);
2123 
2124 	card_index = 0;
2125 	while (!CARD_IS_UNKNOWN(card_index)) {
2126 		if ((aac_cards[card_index].vendor == softs->vendid) &&
2127 		    (aac_cards[card_index].device == softs->devid) &&
2128 		    (aac_cards[card_index].subvendor == softs->subvendid) &&
2129 		    (aac_cards[card_index].subsys == softs->subsysid)) {
2130 			break;
2131 		}
2132 		card_index++;
2133 	}
2134 
2135 	softs->card = card_index;
2136 	softs->hwif = aac_cards[card_index].hwif;
2137 
2138 	/*
2139 	 * Unknown aac card
2140 	 * do a generic match based on the VendorID and DeviceID to
2141 	 * support the new cards in the aac family
2142 	 */
2143 	if (CARD_IS_UNKNOWN(card_index)) {
2144 		if (softs->vendid != 0x9005) {
2145 			AACDB_PRINT(softs, CE_WARN,
2146 			    "Unknown vendor 0x%x", softs->vendid);
2147 			goto error;
2148 		}
2149 		switch (softs->devid) {
2150 		case 0x285:
2151 			softs->hwif = AAC_HWIF_I960RX;
2152 			break;
2153 		case 0x286:
2154 			softs->hwif = AAC_HWIF_RKT;
2155 			break;
2156 		default:
2157 			AACDB_PRINT(softs, CE_WARN,
2158 			    "Unknown device \"pci9005,%x\"", softs->devid);
2159 			goto error;
2160 		}
2161 	}
2162 
2163 	/* Set hardware dependent interface */
2164 	switch (softs->hwif) {
2165 	case AAC_HWIF_I960RX:
2166 		softs->aac_if = aac_rx_interface;
2167 		softs->map_size_min = AAC_MAP_SIZE_MIN_RX;
2168 		break;
2169 	case AAC_HWIF_RKT:
2170 		softs->aac_if = aac_rkt_interface;
2171 		softs->map_size_min = AAC_MAP_SIZE_MIN_RKT;
2172 		break;
2173 	default:
2174 		AACDB_PRINT(softs, CE_WARN,
2175 		    "Unknown hardware interface %d", softs->hwif);
2176 		goto error;
2177 	}
2178 
2179 	/* Set card names */
2180 	(void *)strncpy(softs->vendor_name, aac_cards[card_index].vid,
2181 	    AAC_VENDOR_LEN);
2182 	(void *)strncpy(softs->product_name, aac_cards[card_index].desc,
2183 	    AAC_PRODUCT_LEN);
2184 
2185 	/* Set up quirks */
2186 	softs->flags = aac_cards[card_index].quirks;
2187 
2188 	/* Force the busmaster enable bit on */
2189 	pci_cmd = pci_config_get16(pci_config_handle, PCI_CONF_COMM);
2190 	if ((pci_cmd & PCI_COMM_ME) == 0) {
2191 		pci_cmd |= PCI_COMM_ME;
2192 		pci_config_put16(pci_config_handle, PCI_CONF_COMM, pci_cmd);
2193 		pci_cmd = pci_config_get16(pci_config_handle, PCI_CONF_COMM);
2194 		if ((pci_cmd & PCI_COMM_ME) == 0) {
2195 			cmn_err(CE_CONT, "?Cannot enable busmaster bit");
2196 			goto error;
2197 		}
2198 	}
2199 
2200 	/* Set memory base to map */
2201 	softs->pci_mem_base_paddr = 0xfffffff0UL & \
2202 	    pci_config_get32(pci_config_handle, PCI_CONF_BASE0);
2203 
2204 	pci_config_teardown(&pci_config_handle);
2205 
2206 	return (AACOK); /* card type detected */
2207 error:
2208 	pci_config_teardown(&pci_config_handle);
2209 	return (AACERR); /* no matched card found */
2210 }
2211 
2212 /*
2213  * Do the usual interrupt handler setup stuff.
2214  */
2215 static int
2216 aac_register_intrs(struct aac_softstate *softs)
2217 {
2218 	dev_info_t *dip;
2219 	int intr_types;
2220 
2221 	ASSERT(softs->devinfo_p);
2222 	dip = softs->devinfo_p;
2223 
2224 	/* Get the type of device intrrupts */
2225 	if (ddi_intr_get_supported_types(dip, &intr_types) != DDI_SUCCESS) {
2226 		AACDB_PRINT(softs, CE_WARN,
2227 		    "ddi_intr_get_supported_types() failed");
2228 		return (AACERR);
2229 	}
2230 	AACDB_PRINT(softs, CE_NOTE,
2231 	    "ddi_intr_get_supported_types() ret: 0x%x", intr_types);
2232 
2233 	/* Query interrupt, and alloc/init all needed struct */
2234 	if (intr_types & DDI_INTR_TYPE_MSI) {
2235 		if (aac_query_intrs(softs, DDI_INTR_TYPE_MSI)
2236 		    != DDI_SUCCESS) {
2237 			AACDB_PRINT(softs, CE_WARN,
2238 			    "MSI interrupt query failed");
2239 			return (AACERR);
2240 		}
2241 		softs->intr_type = DDI_INTR_TYPE_MSI;
2242 	} else if (intr_types & DDI_INTR_TYPE_FIXED) {
2243 		if (aac_query_intrs(softs, DDI_INTR_TYPE_FIXED)
2244 		    != DDI_SUCCESS) {
2245 			AACDB_PRINT(softs, CE_WARN,
2246 			    "FIXED interrupt query failed");
2247 			return (AACERR);
2248 		}
2249 		softs->intr_type = DDI_INTR_TYPE_FIXED;
2250 	} else {
2251 		AACDB_PRINT(softs, CE_WARN,
2252 		    "Device cannot suppport both FIXED and MSI interrupts");
2253 		return (AACERR);
2254 	}
2255 
2256 	/* Connect interrupt handlers */
2257 	if (aac_add_intrs(softs) != DDI_SUCCESS) {
2258 		AACDB_PRINT(softs, CE_WARN,
2259 		    "Interrupt registration failed, intr type: %s",
2260 		    softs->intr_type == DDI_INTR_TYPE_MSI ? "MSI" : "FIXED");
2261 		return (AACERR);
2262 	}
2263 	(void) aac_enable_intrs(softs);
2264 
2265 	if (ddi_add_softintr(dip, DDI_SOFTINT_LOW, &softs->softint_id,
2266 	    NULL, NULL, aac_softintr, (caddr_t)softs) != DDI_SUCCESS) {
2267 		AACDB_PRINT(softs, CE_WARN,
2268 		    "Can not setup soft interrupt handler!");
2269 		aac_remove_intrs(softs);
2270 		return (AACERR);
2271 	}
2272 
2273 	return (AACOK);
2274 }
2275 
2276 static void
2277 aac_unregister_intrs(struct aac_softstate *softs)
2278 {
2279 	aac_remove_intrs(softs);
2280 	ddi_remove_softintr(softs->softint_id);
2281 }
2282 
2283 /*
2284  * Check the firmware to determine the features to support and the FIB
2285  * parameters to use.
2286  */
2287 static int
2288 aac_check_firmware(struct aac_softstate *softs)
2289 {
2290 	uint32_t options;
2291 	uint32_t atu_size;
2292 	ddi_acc_handle_t pci_handle;
2293 	uint8_t *data;
2294 	uint32_t max_fibs;
2295 	uint32_t max_fib_size;
2296 	uint32_t sg_tablesize;
2297 	uint32_t max_sectors;
2298 	uint32_t status;
2299 
2300 	/* Get supported options */
2301 	if ((aac_sync_mbcommand(softs, AAC_MONKER_GETINFO, 0, 0, 0, 0,
2302 	    &status)) != AACOK) {
2303 		if (status != SRB_STATUS_INVALID_REQUEST) {
2304 			cmn_err(CE_CONT,
2305 			    "?Fatal error: request adapter info error");
2306 			return (AACERR);
2307 		}
2308 		options = 0;
2309 		atu_size = 0;
2310 	} else {
2311 		options = AAC_MAILBOX_GET(softs, 1);
2312 		atu_size = AAC_MAILBOX_GET(softs, 2);
2313 	}
2314 
2315 	if (softs->state & AAC_STATE_RESET) {
2316 		if ((softs->support_opt == options) &&
2317 		    (softs->atu_size == atu_size))
2318 			return (AACOK);
2319 
2320 		cmn_err(CE_WARN,
2321 		    "?Fatal error: firmware changed, system needs reboot");
2322 		return (AACERR);
2323 	}
2324 
2325 	/*
2326 	 * The following critical settings are initialized only once during
2327 	 * driver attachment.
2328 	 */
2329 	softs->support_opt = options;
2330 	softs->atu_size = atu_size;
2331 
2332 	/* Process supported options */
2333 	if ((options & AAC_SUPPORTED_4GB_WINDOW) != 0 &&
2334 	    (softs->flags & AAC_FLAGS_NO4GB) == 0) {
2335 		AACDB_PRINT(softs, CE_NOTE, "!Enable FIB map 4GB window");
2336 		softs->flags |= AAC_FLAGS_4GB_WINDOW;
2337 	} else {
2338 		/*
2339 		 * Quirk AAC_FLAGS_NO4GB is for FIB address and thus comm space
2340 		 * only. IO is handled by the DMA engine which does not suffer
2341 		 * from the ATU window programming workarounds necessary for
2342 		 * CPU copy operations.
2343 		 */
2344 		softs->addr_dma_attr.dma_attr_addr_lo = 0x2000ull;
2345 		softs->addr_dma_attr.dma_attr_addr_hi = 0x7fffffffull;
2346 	}
2347 
2348 	if ((options & AAC_SUPPORTED_SGMAP_HOST64) != 0) {
2349 		AACDB_PRINT(softs, CE_NOTE, "!Enable SG map 64-bit address");
2350 		softs->buf_dma_attr.dma_attr_addr_hi = 0xffffffffffffffffull;
2351 		softs->buf_dma_attr.dma_attr_seg = 0xffffffffffffffffull;
2352 		softs->flags |= AAC_FLAGS_SG_64BIT;
2353 	}
2354 
2355 	if (options & AAC_SUPPORTED_64BIT_ARRAYSIZE) {
2356 		softs->flags |= AAC_FLAGS_ARRAY_64BIT;
2357 		AACDB_PRINT(softs, CE_NOTE, "!Enable 64-bit array size");
2358 	}
2359 
2360 	if (options & AAC_SUPPORTED_NONDASD) {
2361 		if ((ddi_prop_lookup_string(DDI_DEV_T_ANY, softs->devinfo_p, 0,
2362 		    "nondasd-enable", (char **)&data) == DDI_SUCCESS)) {
2363 			if (strcmp((char *)data, "yes") == 0) {
2364 				AACDB_PRINT(softs, CE_NOTE,
2365 				    "!Enable Non-DASD access");
2366 				softs->flags |= AAC_FLAGS_NONDASD;
2367 			}
2368 			ddi_prop_free(data);
2369 		}
2370 	}
2371 
2372 	/* Read preferred settings */
2373 	max_fib_size = 0;
2374 	if ((aac_sync_mbcommand(softs, AAC_MONKER_GETCOMMPREF,
2375 	    0, 0, 0, 0, NULL)) == AACOK) {
2376 		options = AAC_MAILBOX_GET(softs, 1);
2377 		max_fib_size = (options & 0xffff);
2378 		max_sectors = (options >> 16) << 1;
2379 		options = AAC_MAILBOX_GET(softs, 2);
2380 		sg_tablesize = (options >> 16);
2381 		options = AAC_MAILBOX_GET(softs, 3);
2382 		max_fibs = (options & 0xffff);
2383 	}
2384 
2385 	/* Enable new comm. and rawio at the same time */
2386 	if ((softs->support_opt & AAC_SUPPORTED_NEW_COMM) &&
2387 	    (max_fib_size != 0)) {
2388 		/* read out and save PCI MBR */
2389 		if ((atu_size > softs->map_size) &&
2390 		    (ddi_regs_map_setup(softs->devinfo_p, 1,
2391 		    (caddr_t *)&data, 0, atu_size, &softs->reg_attr,
2392 		    &pci_handle) == DDI_SUCCESS)) {
2393 			ddi_regs_map_free(&softs->pci_mem_handle);
2394 			softs->pci_mem_handle = pci_handle;
2395 			softs->pci_mem_base_vaddr = data;
2396 			softs->map_size = atu_size;
2397 		}
2398 		if (atu_size == softs->map_size) {
2399 			softs->flags |= AAC_FLAGS_NEW_COMM;
2400 			AACDB_PRINT(softs, CE_NOTE,
2401 			    "!Enable New Comm. interface");
2402 		}
2403 	}
2404 
2405 	/* Set FIB parameters */
2406 	if (softs->flags & AAC_FLAGS_NEW_COMM) {
2407 		softs->aac_max_fibs = max_fibs;
2408 		softs->aac_max_fib_size = max_fib_size;
2409 		softs->aac_max_sectors = max_sectors;
2410 		softs->aac_sg_tablesize = sg_tablesize;
2411 
2412 		softs->flags |= AAC_FLAGS_RAW_IO;
2413 		AACDB_PRINT(softs, CE_NOTE, "!Enable RawIO");
2414 	} else {
2415 		softs->aac_max_fibs =
2416 		    (softs->flags & AAC_FLAGS_256FIBS) ? 256 : 512;
2417 		softs->aac_max_fib_size = AAC_FIB_SIZE;
2418 		softs->aac_max_sectors = 128;	/* 64K */
2419 		if (softs->flags & AAC_FLAGS_17SG)
2420 			softs->aac_sg_tablesize = 17;
2421 		else if (softs->flags & AAC_FLAGS_34SG)
2422 			softs->aac_sg_tablesize = 34;
2423 		else if (softs->flags & AAC_FLAGS_SG_64BIT)
2424 			softs->aac_sg_tablesize = (AAC_FIB_DATASIZE -
2425 			    sizeof (struct aac_blockwrite64) +
2426 			    sizeof (struct aac_sg_entry64)) /
2427 			    sizeof (struct aac_sg_entry64);
2428 		else
2429 			softs->aac_sg_tablesize = (AAC_FIB_DATASIZE -
2430 			    sizeof (struct aac_blockwrite) +
2431 			    sizeof (struct aac_sg_entry)) /
2432 			    sizeof (struct aac_sg_entry);
2433 	}
2434 
2435 	if ((softs->flags & AAC_FLAGS_RAW_IO) &&
2436 	    (softs->flags & AAC_FLAGS_ARRAY_64BIT)) {
2437 		softs->flags |= AAC_FLAGS_LBA_64BIT;
2438 		AACDB_PRINT(softs, CE_NOTE, "!Enable 64-bit array");
2439 	}
2440 	softs->buf_dma_attr.dma_attr_sgllen = softs->aac_sg_tablesize;
2441 	softs->buf_dma_attr.dma_attr_maxxfer = softs->aac_max_sectors << 9;
2442 	/*
2443 	 * 64K maximum segment size in scatter gather list is controlled by
2444 	 * the NEW_COMM bit in the adapter information. If not set, the card
2445 	 * can only accept a maximum of 64K. It is not recommended to permit
2446 	 * more than 128KB of total transfer size to the adapters because
2447 	 * performance is negatively impacted.
2448 	 *
2449 	 * For new comm, segment size equals max xfer size. For old comm,
2450 	 * we use 64K for both.
2451 	 */
2452 	softs->buf_dma_attr.dma_attr_count_max =
2453 	    softs->buf_dma_attr.dma_attr_maxxfer - 1;
2454 
2455 	/* Setup FIB operations */
2456 	if (softs->flags & AAC_FLAGS_RAW_IO)
2457 		softs->aac_cmd_fib = aac_cmd_fib_rawio;
2458 	else if (softs->flags & AAC_FLAGS_SG_64BIT)
2459 		softs->aac_cmd_fib = aac_cmd_fib_brw64;
2460 	else
2461 		softs->aac_cmd_fib = aac_cmd_fib_brw;
2462 	softs->aac_cmd_fib_scsi = (softs->flags & AAC_FLAGS_SG_64BIT) ? \
2463 	    aac_cmd_fib_scsi64 : aac_cmd_fib_scsi32;
2464 
2465 	/* 64-bit LBA needs descriptor format sense data */
2466 	softs->slen = sizeof (struct scsi_arq_status);
2467 	if ((softs->flags & AAC_FLAGS_LBA_64BIT) &&
2468 	    softs->slen < AAC_ARQ64_LENGTH)
2469 		softs->slen = AAC_ARQ64_LENGTH;
2470 
2471 	AACDB_PRINT(softs, CE_NOTE,
2472 	    "!max_fibs %d max_fibsize 0x%x max_sectors %d max_sg %d",
2473 	    softs->aac_max_fibs, softs->aac_max_fib_size,
2474 	    softs->aac_max_sectors, softs->aac_sg_tablesize);
2475 
2476 	return (AACOK);
2477 }
2478 
2479 static void
2480 aac_fsa_rev(struct aac_softstate *softs, struct FsaRev *fsarev0,
2481     struct FsaRev *fsarev1)
2482 {
2483 	ddi_acc_handle_t acc = softs->sync_ac.slotp->fib_acc_handle;
2484 
2485 	AAC_GET_FIELD8(acc, fsarev1, fsarev0, external.comp.dash);
2486 	AAC_GET_FIELD8(acc, fsarev1, fsarev0, external.comp.type);
2487 	AAC_GET_FIELD8(acc, fsarev1, fsarev0, external.comp.minor);
2488 	AAC_GET_FIELD8(acc, fsarev1, fsarev0, external.comp.major);
2489 	AAC_GET_FIELD32(acc, fsarev1, fsarev0, buildNumber);
2490 }
2491 
2492 /*
2493  * The following function comes from Adaptec:
2494  *
2495  * Query adapter information and supplement adapter information
2496  */
2497 static int
2498 aac_get_adapter_info(struct aac_softstate *softs,
2499     struct aac_adapter_info *ainfr, struct aac_supplement_adapter_info *sinfr)
2500 {
2501 	struct aac_cmd *acp = &softs->sync_ac;
2502 	ddi_acc_handle_t acc;
2503 	struct aac_fib *fibp;
2504 	struct aac_adapter_info *ainfp;
2505 	struct aac_supplement_adapter_info *sinfp;
2506 	int rval;
2507 
2508 	(void) aac_sync_fib_slot_bind(softs, acp);
2509 	acc = acp->slotp->fib_acc_handle;
2510 	fibp = acp->slotp->fibp;
2511 
2512 	ddi_put8(acc, &fibp->data[0], 0);
2513 	if (aac_sync_fib(softs, RequestAdapterInfo,
2514 	    AAC_FIB_SIZEOF(struct aac_adapter_info)) != AACOK) {
2515 		AACDB_PRINT(softs, CE_WARN, "RequestAdapterInfo failed");
2516 		rval = AACERR;
2517 		goto finish;
2518 	}
2519 	ainfp = (struct aac_adapter_info *)fibp->data;
2520 	if (ainfr) {
2521 		AAC_GET_FIELD32(acc, ainfr, ainfp, SupportedOptions);
2522 		AAC_GET_FIELD32(acc, ainfr, ainfp, PlatformBase);
2523 		AAC_GET_FIELD32(acc, ainfr, ainfp, CpuArchitecture);
2524 		AAC_GET_FIELD32(acc, ainfr, ainfp, CpuVariant);
2525 		AAC_GET_FIELD32(acc, ainfr, ainfp, ClockSpeed);
2526 		AAC_GET_FIELD32(acc, ainfr, ainfp, ExecutionMem);
2527 		AAC_GET_FIELD32(acc, ainfr, ainfp, BufferMem);
2528 		AAC_GET_FIELD32(acc, ainfr, ainfp, TotalMem);
2529 		aac_fsa_rev(softs, &ainfp->KernelRevision,
2530 		    &ainfr->KernelRevision);
2531 		aac_fsa_rev(softs, &ainfp->MonitorRevision,
2532 		    &ainfr->MonitorRevision);
2533 		aac_fsa_rev(softs, &ainfp->HardwareRevision,
2534 		    &ainfr->HardwareRevision);
2535 		aac_fsa_rev(softs, &ainfp->BIOSRevision,
2536 		    &ainfr->BIOSRevision);
2537 		AAC_GET_FIELD32(acc, ainfr, ainfp, ClusteringEnabled);
2538 		AAC_GET_FIELD32(acc, ainfr, ainfp, ClusterChannelMask);
2539 		AAC_GET_FIELD64(acc, ainfr, ainfp, SerialNumber);
2540 		AAC_GET_FIELD32(acc, ainfr, ainfp, batteryPlatform);
2541 		AAC_GET_FIELD32(acc, ainfr, ainfp, SupportedOptions);
2542 		AAC_GET_FIELD32(acc, ainfr, ainfp, OemVariant);
2543 	}
2544 	if (sinfr) {
2545 		if (!(softs->support_opt &
2546 		    AAC_SUPPORTED_SUPPLEMENT_ADAPTER_INFO)) {
2547 			AACDB_PRINT(softs, CE_WARN,
2548 			    "SupplementAdapterInfo not supported");
2549 			rval = AACERR;
2550 			goto finish;
2551 		}
2552 		ddi_put8(acc, &fibp->data[0], 0);
2553 		if (aac_sync_fib(softs, RequestSupplementAdapterInfo,
2554 		    AAC_FIB_SIZEOF(struct aac_supplement_adapter_info))
2555 		    != AACOK) {
2556 			AACDB_PRINT(softs, CE_WARN,
2557 			    "RequestSupplementAdapterInfo failed");
2558 			rval = AACERR;
2559 			goto finish;
2560 		}
2561 		sinfp = (struct aac_supplement_adapter_info *)fibp->data;
2562 		AAC_REP_GET_FIELD8(acc, sinfr, sinfp, AdapterTypeText[0], 17+1);
2563 		AAC_REP_GET_FIELD8(acc, sinfr, sinfp, Pad[0], 2);
2564 		AAC_GET_FIELD32(acc, sinfr, sinfp, FlashMemoryByteSize);
2565 		AAC_GET_FIELD32(acc, sinfr, sinfp, FlashImageId);
2566 		AAC_GET_FIELD32(acc, sinfr, sinfp, MaxNumberPorts);
2567 		AAC_GET_FIELD32(acc, sinfr, sinfp, Version);
2568 		AAC_GET_FIELD32(acc, sinfr, sinfp, FeatureBits);
2569 		AAC_GET_FIELD8(acc, sinfr, sinfp, SlotNumber);
2570 		AAC_REP_GET_FIELD8(acc, sinfr, sinfp, ReservedPad0[0], 3);
2571 		AAC_REP_GET_FIELD8(acc, sinfr, sinfp, BuildDate[0], 12);
2572 		AAC_GET_FIELD32(acc, sinfr, sinfp, CurrentNumberPorts);
2573 		AAC_REP_GET_FIELD8(acc, sinfr, sinfp, VpdInfo,
2574 		    sizeof (struct vpd_info));
2575 		aac_fsa_rev(softs, &sinfp->FlashFirmwareRevision,
2576 		    &sinfr->FlashFirmwareRevision);
2577 		AAC_GET_FIELD32(acc, sinfr, sinfp, RaidTypeMorphOptions);
2578 		aac_fsa_rev(softs, &sinfp->FlashFirmwareBootRevision,
2579 		    &sinfr->FlashFirmwareBootRevision);
2580 		AAC_REP_GET_FIELD8(acc, sinfr, sinfp, MfgPcbaSerialNo,
2581 		    MFG_PCBA_SERIAL_NUMBER_WIDTH);
2582 		AAC_REP_GET_FIELD8(acc, sinfr, sinfp, MfgWWNName[0],
2583 		    MFG_WWN_WIDTH);
2584 		AAC_GET_FIELD32(acc, sinfr, sinfp, SupportedOptions2);
2585 		AAC_GET_FIELD32(acc, sinfr, sinfp, ExpansionFlag);
2586 		if (sinfr->ExpansionFlag == 1) {
2587 			AAC_GET_FIELD32(acc, sinfr, sinfp, FeatureBits3);
2588 			AAC_GET_FIELD32(acc, sinfr, sinfp,
2589 			    SupportedPerformanceMode);
2590 			AAC_REP_GET_FIELD32(acc, sinfr, sinfp,
2591 			    ReservedGrowth[0], 80);
2592 		}
2593 	}
2594 	rval = AACOK;
2595 finish:
2596 	aac_sync_fib_slot_release(softs, acp);
2597 	return (rval);
2598 }
2599 
2600 static int
2601 aac_get_bus_info(struct aac_softstate *softs, uint32_t *bus_max,
2602     uint32_t *tgt_max)
2603 {
2604 	struct aac_cmd *acp = &softs->sync_ac;
2605 	ddi_acc_handle_t acc;
2606 	struct aac_fib *fibp;
2607 	struct aac_ctcfg *c_cmd;
2608 	struct aac_ctcfg_resp *c_resp;
2609 	uint32_t scsi_method_id;
2610 	struct aac_bus_info *cmd;
2611 	struct aac_bus_info_response *resp;
2612 	int rval;
2613 
2614 	(void) aac_sync_fib_slot_bind(softs, acp);
2615 	acc = acp->slotp->fib_acc_handle;
2616 	fibp = acp->slotp->fibp;
2617 
2618 	/* Detect MethodId */
2619 	c_cmd = (struct aac_ctcfg *)&fibp->data[0];
2620 	ddi_put32(acc, &c_cmd->Command, VM_ContainerConfig);
2621 	ddi_put32(acc, &c_cmd->cmd, CT_GET_SCSI_METHOD);
2622 	ddi_put32(acc, &c_cmd->param, 0);
2623 	rval = aac_sync_fib(softs, ContainerCommand,
2624 	    AAC_FIB_SIZEOF(struct aac_ctcfg));
2625 	c_resp = (struct aac_ctcfg_resp *)&fibp->data[0];
2626 	if (rval != AACOK || ddi_get32(acc, &c_resp->Status) != 0) {
2627 		AACDB_PRINT(softs, CE_WARN,
2628 		    "VM_ContainerConfig command fail");
2629 		rval = AACERR;
2630 		goto finish;
2631 	}
2632 	scsi_method_id = ddi_get32(acc, &c_resp->param);
2633 
2634 	/* Detect phys. bus count and max. target id first */
2635 	cmd = (struct aac_bus_info *)&fibp->data[0];
2636 	ddi_put32(acc, &cmd->Command, VM_Ioctl);
2637 	ddi_put32(acc, &cmd->ObjType, FT_DRIVE); /* physical drive */
2638 	ddi_put32(acc, &cmd->MethodId, scsi_method_id);
2639 	ddi_put32(acc, &cmd->ObjectId, 0);
2640 	ddi_put32(acc, &cmd->CtlCmd, GetBusInfo);
2641 	/*
2642 	 * For VM_Ioctl, the firmware uses the Header.Size filled from the
2643 	 * driver as the size to be returned. Therefore the driver has to use
2644 	 * sizeof (struct aac_bus_info_response) because it is greater than
2645 	 * sizeof (struct aac_bus_info).
2646 	 */
2647 	rval = aac_sync_fib(softs, ContainerCommand,
2648 	    AAC_FIB_SIZEOF(struct aac_bus_info_response));
2649 	resp = (struct aac_bus_info_response *)cmd;
2650 
2651 	/* Scan all coordinates with INQUIRY */
2652 	if ((rval != AACOK) || (ddi_get32(acc, &resp->Status) != 0)) {
2653 		AACDB_PRINT(softs, CE_WARN, "GetBusInfo command fail");
2654 		rval = AACERR;
2655 		goto finish;
2656 	}
2657 	*bus_max = ddi_get32(acc, &resp->BusCount);
2658 	*tgt_max = ddi_get32(acc, &resp->TargetsPerBus);
2659 
2660 finish:
2661 	aac_sync_fib_slot_release(softs, acp);
2662 	return (AACOK);
2663 }
2664 
2665 /*
2666  * The following function comes from Adaptec:
2667  *
2668  * Routine to be called during initialization of communications with
2669  * the adapter to handle possible adapter configuration issues. When
2670  * the adapter first boots up, it examines attached drives, etc, and
2671  * potentially comes up with a new or revised configuration (relative to
2672  * what's stored in it's NVRAM). Additionally it may discover problems
2673  * that make the current physical configuration unworkable (currently
2674  * applicable only to cluster configuration issues).
2675  *
2676  * If there are no configuration issues or the issues are considered
2677  * trival by the adapter, it will set it's configuration status to
2678  * "FSACT_CONTINUE" and execute the "commit confiuguration" action
2679  * automatically on it's own.
2680  *
2681  * However, if there are non-trivial issues, the adapter will set it's
2682  * internal configuration status to "FSACT_PAUSE" or "FASCT_ABORT"
2683  * and wait for some agent on the host to issue the "\ContainerCommand
2684  * \VM_ContainerConfig\CT_COMMIT_CONFIG" FIB command to cause the
2685  * adapter to commit the new/updated configuration and enable
2686  * un-inhibited operation.  The host agent should first issue the
2687  * "\ContainerCommand\VM_ContainerConfig\CT_GET_CONFIG_STATUS" FIB
2688  * command to obtain information about config issues detected by
2689  * the adapter.
2690  *
2691  * Normally the adapter's PC BIOS will execute on the host following
2692  * adapter poweron and reset and will be responsible for querring the
2693  * adapter with CT_GET_CONFIG_STATUS and issuing the CT_COMMIT_CONFIG
2694  * command if appropriate.
2695  *
2696  * However, with the introduction of IOP reset support, the adapter may
2697  * boot up without the benefit of the adapter's PC BIOS host agent.
2698  * This routine is intended to take care of these issues in situations
2699  * where BIOS doesn't execute following adapter poweron or reset.  The
2700  * CT_COMMIT_CONFIG command is a no-op if it's already been issued, so
2701  * there is no harm in doing this when it's already been done.
2702  */
2703 static int
2704 aac_handle_adapter_config_issues(struct aac_softstate *softs)
2705 {
2706 	struct aac_cmd *acp = &softs->sync_ac;
2707 	ddi_acc_handle_t acc;
2708 	struct aac_fib *fibp;
2709 	struct aac_Container *cmd;
2710 	struct aac_Container_resp *resp;
2711 	struct aac_cf_status_header *cfg_sts_hdr;
2712 	uint32_t resp_status;
2713 	uint32_t ct_status;
2714 	uint32_t cfg_stat_action;
2715 	int rval;
2716 
2717 	(void) aac_sync_fib_slot_bind(softs, acp);
2718 	acc = acp->slotp->fib_acc_handle;
2719 	fibp = acp->slotp->fibp;
2720 
2721 	/* Get adapter config status */
2722 	cmd = (struct aac_Container *)&fibp->data[0];
2723 
2724 	bzero(cmd, sizeof (*cmd) - CT_PACKET_SIZE);
2725 	ddi_put32(acc, &cmd->Command, VM_ContainerConfig);
2726 	ddi_put32(acc, &cmd->CTCommand.command, CT_GET_CONFIG_STATUS);
2727 	ddi_put32(acc, &cmd->CTCommand.param[CNT_SIZE],
2728 	    sizeof (struct aac_cf_status_header));
2729 	rval = aac_sync_fib(softs, ContainerCommand,
2730 	    AAC_FIB_SIZEOF(struct aac_Container));
2731 	resp = (struct aac_Container_resp *)cmd;
2732 	cfg_sts_hdr = (struct aac_cf_status_header *)resp->CTResponse.data;
2733 
2734 	resp_status = ddi_get32(acc, &resp->Status);
2735 	ct_status = ddi_get32(acc, &resp->CTResponse.param[0]);
2736 	if ((rval == AACOK) && (resp_status == 0) && (ct_status == CT_OK)) {
2737 		cfg_stat_action = ddi_get32(acc, &cfg_sts_hdr->action);
2738 
2739 		/* Commit configuration if it's reasonable to do so. */
2740 		if (cfg_stat_action <= CFACT_PAUSE) {
2741 			bzero(cmd, sizeof (*cmd) - CT_PACKET_SIZE);
2742 			ddi_put32(acc, &cmd->Command, VM_ContainerConfig);
2743 			ddi_put32(acc, &cmd->CTCommand.command,
2744 			    CT_COMMIT_CONFIG);
2745 			rval = aac_sync_fib(softs, ContainerCommand,
2746 			    AAC_FIB_SIZEOF(struct aac_Container));
2747 
2748 			resp_status = ddi_get32(acc, &resp->Status);
2749 			ct_status = ddi_get32(acc, &resp->CTResponse.param[0]);
2750 			if ((rval == AACOK) && (resp_status == 0) &&
2751 			    (ct_status == CT_OK))
2752 				/* Successful completion */
2753 				rval = AACMPE_OK;
2754 			else
2755 				/* Auto-commit aborted due to error(s). */
2756 				rval = AACMPE_COMMIT_CONFIG;
2757 		} else {
2758 			/*
2759 			 * Auto-commit aborted due to adapter indicating
2760 			 * configuration issue(s) too dangerous to auto-commit.
2761 			 */
2762 			rval = AACMPE_CONFIG_STATUS;
2763 		}
2764 	} else {
2765 		cmn_err(CE_WARN, "!Configuration issue, auto-commit aborted");
2766 		rval = AACMPE_CONFIG_STATUS;
2767 	}
2768 
2769 	aac_sync_fib_slot_release(softs, acp);
2770 	return (rval);
2771 }
2772 
2773 /*
2774  * Hardware initialization and resource allocation
2775  */
2776 static int
2777 aac_common_attach(struct aac_softstate *softs)
2778 {
2779 	uint32_t status;
2780 	int i;
2781 	struct aac_supplement_adapter_info sinf;
2782 
2783 	DBCALLED(softs, 1);
2784 
2785 	/*
2786 	 * Do a little check here to make sure there aren't any outstanding
2787 	 * FIBs in the message queue. At this point there should not be and
2788 	 * if there are they are probably left over from another instance of
2789 	 * the driver like when the system crashes and the crash dump driver
2790 	 * gets loaded.
2791 	 */
2792 	while (AAC_OUTB_GET(softs) != 0xfffffffful)
2793 		;
2794 
2795 	/*
2796 	 * Wait the card to complete booting up before do anything that
2797 	 * attempts to communicate with it.
2798 	 */
2799 	status = AAC_FWSTATUS_GET(softs);
2800 	if (status == AAC_SELF_TEST_FAILED || status == AAC_KERNEL_PANIC)
2801 		goto error;
2802 	i = AAC_FWUP_TIMEOUT * 1000; /* set timeout */
2803 	AAC_BUSYWAIT(AAC_FWSTATUS_GET(softs) & AAC_KERNEL_UP_AND_RUNNING, i);
2804 	if (i == 0) {
2805 		cmn_err(CE_CONT, "?Fatal error: controller not ready");
2806 		aac_fm_ereport(softs, DDI_FM_DEVICE_NO_RESPONSE);
2807 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
2808 		goto error;
2809 	}
2810 
2811 	/* Read and set card supported options and settings */
2812 	if (aac_check_firmware(softs) == AACERR) {
2813 		aac_fm_ereport(softs, DDI_FM_DEVICE_NO_RESPONSE);
2814 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
2815 		goto error;
2816 	}
2817 
2818 	/* Add interrupt handlers */
2819 	if (aac_register_intrs(softs) == AACERR) {
2820 		cmn_err(CE_CONT,
2821 		    "?Fatal error: interrupts register failed");
2822 		goto error;
2823 	}
2824 
2825 	/* Setup communication space with the card */
2826 	if (softs->comm_space_dma_handle == NULL) {
2827 		if (aac_alloc_comm_space(softs) != AACOK)
2828 			goto error;
2829 	}
2830 	if (aac_setup_comm_space(softs) != AACOK) {
2831 		cmn_err(CE_CONT, "?Setup communication space failed");
2832 		aac_fm_ereport(softs, DDI_FM_DEVICE_NO_RESPONSE);
2833 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
2834 		goto error;
2835 	}
2836 
2837 #ifdef DEBUG
2838 	if (aac_get_fw_debug_buffer(softs) != AACOK)
2839 		cmn_err(CE_CONT, "?firmware UART trace not supported");
2840 #endif
2841 
2842 	/* Allocate slots */
2843 	if ((softs->total_slots == 0) && (aac_create_slots(softs) != AACOK)) {
2844 		cmn_err(CE_CONT, "?Fatal error: slots allocate failed");
2845 		goto error;
2846 	}
2847 	AACDB_PRINT(softs, CE_NOTE, "%d slots allocated", softs->total_slots);
2848 
2849 	/* Allocate FIBs */
2850 	if (softs->total_fibs < softs->total_slots) {
2851 		aac_alloc_fibs(softs);
2852 		if (softs->total_fibs == 0)
2853 			goto error;
2854 		AACDB_PRINT(softs, CE_NOTE, "%d fibs allocated",
2855 		    softs->total_fibs);
2856 	}
2857 
2858 	AAC_STATUS_CLR(softs, ~0); /* Clear out all interrupts */
2859 	AAC_ENABLE_INTR(softs); /* Enable the interrupts we can handle */
2860 
2861 	if (aac_get_adapter_info(softs, NULL, &sinf) == AACOK) {
2862 		softs->feature_bits = sinf.FeatureBits;
2863 		softs->support_opt2 = sinf.SupportedOptions2;
2864 
2865 		/* Get adapter names */
2866 		if (CARD_IS_UNKNOWN(softs->card)) {
2867 			char *p, *p0, *p1;
2868 
2869 			/*
2870 			 * Now find the controller name in supp_adapter_info->
2871 			 * AdapterTypeText. Use the first word as the vendor
2872 			 * and the other words as the product name.
2873 			 */
2874 			AACDB_PRINT(softs, CE_NOTE, "sinf.AdapterTypeText = "
2875 			    "\"%s\"", sinf.AdapterTypeText);
2876 			p = sinf.AdapterTypeText;
2877 			p0 = p1 = NULL;
2878 			/* Skip heading spaces */
2879 			while (*p && (*p == ' ' || *p == '\t'))
2880 				p++;
2881 			p0 = p;
2882 			while (*p && (*p != ' ' && *p != '\t'))
2883 				p++;
2884 			/* Remove middle spaces */
2885 			while (*p && (*p == ' ' || *p == '\t'))
2886 				*p++ = 0;
2887 			p1 = p;
2888 			/* Remove trailing spaces */
2889 			p = p1 + strlen(p1) - 1;
2890 			while (p > p1 && (*p == ' ' || *p == '\t'))
2891 				*p-- = 0;
2892 			if (*p0 && *p1) {
2893 				(void *)strncpy(softs->vendor_name, p0,
2894 				    AAC_VENDOR_LEN);
2895 				(void *)strncpy(softs->product_name, p1,
2896 				    AAC_PRODUCT_LEN);
2897 			} else {
2898 				cmn_err(CE_WARN,
2899 				    "?adapter name mis-formatted\n");
2900 				if (*p0)
2901 					(void *)strncpy(softs->product_name,
2902 					    p0, AAC_PRODUCT_LEN);
2903 			}
2904 		}
2905 	} else {
2906 		cmn_err(CE_CONT, "?Query adapter information failed");
2907 	}
2908 
2909 
2910 	cmn_err(CE_NOTE,
2911 	    "!aac driver %d.%02d.%02d-%d, found card: " \
2912 	    "%s %s(pci0x%x.%x.%x.%x) at 0x%x",
2913 	    AAC_DRIVER_MAJOR_VERSION,
2914 	    AAC_DRIVER_MINOR_VERSION,
2915 	    AAC_DRIVER_BUGFIX_LEVEL,
2916 	    AAC_DRIVER_BUILD,
2917 	    softs->vendor_name, softs->product_name,
2918 	    softs->vendid, softs->devid, softs->subvendid, softs->subsysid,
2919 	    softs->pci_mem_base_paddr);
2920 
2921 	/* Perform acceptance of adapter-detected config changes if possible */
2922 	if (aac_handle_adapter_config_issues(softs) != AACMPE_OK) {
2923 		cmn_err(CE_CONT, "?Handle adapter config issues failed");
2924 		aac_fm_ereport(softs, DDI_FM_DEVICE_NO_RESPONSE);
2925 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
2926 		goto error;
2927 	}
2928 
2929 	/* Setup containers (logical devices) */
2930 	if (aac_probe_containers(softs) != AACOK) {
2931 		cmn_err(CE_CONT, "?Fatal error: get container info error");
2932 		goto error;
2933 	}
2934 
2935 	/* Check for JBOD support. Default disable */
2936 	char *data;
2937 	if (softs->feature_bits & AAC_FEATURE_SUPPORTED_JBOD) {
2938 		if ((ddi_prop_lookup_string(DDI_DEV_T_ANY, softs->devinfo_p,
2939 		    0, "jbod-enable", &data) == DDI_SUCCESS)) {
2940 			if (strcmp(data, "yes") == 0) {
2941 				AACDB_PRINT(softs, CE_NOTE,
2942 				    "Enable JBOD access");
2943 				softs->flags |= AAC_FLAGS_JBOD;
2944 			}
2945 			ddi_prop_free(data);
2946 		}
2947 	}
2948 
2949 	/* Setup phys. devices */
2950 	if (softs->flags & (AAC_FLAGS_NONDASD | AAC_FLAGS_JBOD)) {
2951 		uint32_t bus_max, tgt_max;
2952 		uint32_t bus, tgt;
2953 		int index;
2954 
2955 		if (aac_get_bus_info(softs, &bus_max, &tgt_max) != AACOK) {
2956 			cmn_err(CE_CONT, "?Fatal error: get bus info error");
2957 			goto error;
2958 		}
2959 		AACDB_PRINT(softs, CE_NOTE, "bus_max=%d, tgt_max=%d",
2960 		    bus_max, tgt_max);
2961 		if (bus_max != softs->bus_max || tgt_max != softs->tgt_max) {
2962 			if (softs->state & AAC_STATE_RESET) {
2963 				cmn_err(CE_WARN,
2964 				    "?Fatal error: bus map changed");
2965 				goto error;
2966 			}
2967 			softs->bus_max = bus_max;
2968 			softs->tgt_max = tgt_max;
2969 			if (softs->nondasds) {
2970 				kmem_free(softs->nondasds, AAC_MAX_PD(softs) * \
2971 				    sizeof (struct aac_nondasd));
2972 			}
2973 			softs->nondasds = kmem_zalloc(AAC_MAX_PD(softs) * \
2974 			    sizeof (struct aac_nondasd), KM_SLEEP);
2975 
2976 			index = 0;
2977 			for (bus = 0; bus < softs->bus_max; bus++) {
2978 				for (tgt = 0; tgt < softs->tgt_max; tgt++) {
2979 					struct aac_nondasd *dvp =
2980 					    &softs->nondasds[index++];
2981 					dvp->dev.type = AAC_DEV_PD;
2982 					dvp->bus = bus;
2983 					dvp->tid = tgt;
2984 				}
2985 			}
2986 		}
2987 	}
2988 
2989 	/* Check dma & acc handles allocated in attach */
2990 	if (aac_check_dma_handle(softs->comm_space_dma_handle) != DDI_SUCCESS) {
2991 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
2992 		goto error;
2993 	}
2994 
2995 	if (aac_check_acc_handle(softs->pci_mem_handle) != DDI_SUCCESS) {
2996 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
2997 		goto error;
2998 	}
2999 
3000 	for (i = 0; i < softs->total_slots; i++) {
3001 		if (aac_check_dma_handle(softs->io_slot[i].fib_dma_handle) !=
3002 		    DDI_SUCCESS) {
3003 			ddi_fm_service_impact(softs->devinfo_p,
3004 			    DDI_SERVICE_LOST);
3005 			goto error;
3006 		}
3007 	}
3008 
3009 	return (AACOK);
3010 error:
3011 	if (softs->state & AAC_STATE_RESET)
3012 		return (AACERR);
3013 	if (softs->nondasds) {
3014 		kmem_free(softs->nondasds, AAC_MAX_PD(softs) * \
3015 		    sizeof (struct aac_nondasd));
3016 		softs->nondasds = NULL;
3017 	}
3018 	if (softs->total_fibs > 0)
3019 		aac_destroy_fibs(softs);
3020 	if (softs->total_slots > 0)
3021 		aac_destroy_slots(softs);
3022 	if (softs->comm_space_dma_handle)
3023 		aac_free_comm_space(softs);
3024 	return (AACERR);
3025 }
3026 
3027 /*
3028  * Hardware shutdown and resource release
3029  */
3030 static void
3031 aac_common_detach(struct aac_softstate *softs)
3032 {
3033 	DBCALLED(softs, 1);
3034 
3035 	aac_unregister_intrs(softs);
3036 
3037 	mutex_enter(&softs->io_lock);
3038 	(void) aac_shutdown(softs);
3039 
3040 	if (softs->nondasds) {
3041 		kmem_free(softs->nondasds, AAC_MAX_PD(softs) * \
3042 		    sizeof (struct aac_nondasd));
3043 		softs->nondasds = NULL;
3044 	}
3045 	aac_destroy_fibs(softs);
3046 	aac_destroy_slots(softs);
3047 	aac_free_comm_space(softs);
3048 	mutex_exit(&softs->io_lock);
3049 }
3050 
3051 /*
3052  * Send a synchronous command to the controller and wait for a result.
3053  * Indicate if the controller completed the command with an error status.
3054  */
3055 int
3056 aac_sync_mbcommand(struct aac_softstate *softs, uint32_t cmd,
3057     uint32_t arg0, uint32_t arg1, uint32_t arg2, uint32_t arg3,
3058     uint32_t *statusp)
3059 {
3060 	int timeout;
3061 	uint32_t status;
3062 
3063 	if (statusp != NULL)
3064 		*statusp = SRB_STATUS_SUCCESS;
3065 
3066 	/* Fill in mailbox */
3067 	AAC_MAILBOX_SET(softs, cmd, arg0, arg1, arg2, arg3);
3068 
3069 	/* Ensure the sync command doorbell flag is cleared */
3070 	AAC_STATUS_CLR(softs, AAC_DB_SYNC_COMMAND);
3071 
3072 	/* Then set it to signal the adapter */
3073 	AAC_NOTIFY(softs, AAC_DB_SYNC_COMMAND);
3074 
3075 	/* Spin waiting for the command to complete */
3076 	timeout = AAC_IMMEDIATE_TIMEOUT * 1000;
3077 	AAC_BUSYWAIT(AAC_STATUS_GET(softs) & AAC_DB_SYNC_COMMAND, timeout);
3078 	if (!timeout) {
3079 		AACDB_PRINT(softs, CE_WARN,
3080 		    "Sync command timed out after %d seconds (0x%x)!",
3081 		    AAC_IMMEDIATE_TIMEOUT, AAC_FWSTATUS_GET(softs));
3082 		return (AACERR);
3083 	}
3084 
3085 	/* Clear the completion flag */
3086 	AAC_STATUS_CLR(softs, AAC_DB_SYNC_COMMAND);
3087 
3088 	/* Get the command status */
3089 	status = AAC_MAILBOX_GET(softs, 0);
3090 	if (statusp != NULL)
3091 		*statusp = status;
3092 	if (status != SRB_STATUS_SUCCESS) {
3093 		AACDB_PRINT(softs, CE_WARN,
3094 		    "Sync command fail: status = 0x%x", status);
3095 		return (AACERR);
3096 	}
3097 
3098 	return (AACOK);
3099 }
3100 
3101 /*
3102  * Send a synchronous FIB to the adapter and wait for its completion
3103  */
3104 static int
3105 aac_sync_fib(struct aac_softstate *softs, uint16_t cmd, uint16_t fibsize)
3106 {
3107 	struct aac_cmd *acp = &softs->sync_ac;
3108 
3109 	acp->flags = AAC_CMD_SYNC | AAC_CMD_IN_SYNC_SLOT;
3110 	if (softs->state & AAC_STATE_INTR)
3111 		acp->flags |= AAC_CMD_NO_CB;
3112 	else
3113 		acp->flags |= AAC_CMD_NO_INTR;
3114 
3115 	acp->ac_comp = aac_sync_complete;
3116 	acp->timeout = AAC_SYNC_TIMEOUT;
3117 	acp->fib_size = fibsize;
3118 
3119 	/*
3120 	 * Only need to setup sync fib header, caller should have init
3121 	 * fib data
3122 	 */
3123 	aac_cmd_fib_header(softs, acp, cmd);
3124 
3125 	(void) ddi_dma_sync(acp->slotp->fib_dma_handle, 0, fibsize,
3126 	    DDI_DMA_SYNC_FORDEV);
3127 
3128 	aac_start_io(softs, acp);
3129 
3130 	if (softs->state & AAC_STATE_INTR)
3131 		return (aac_do_sync_io(softs, acp));
3132 	else
3133 		return (aac_do_poll_io(softs, acp));
3134 }
3135 
3136 static void
3137 aac_cmd_initq(struct aac_cmd_queue *q)
3138 {
3139 	q->q_head = NULL;
3140 	q->q_tail = (struct aac_cmd *)&q->q_head;
3141 }
3142 
3143 /*
3144  * Remove a cmd from the head of q
3145  */
3146 static struct aac_cmd *
3147 aac_cmd_dequeue(struct aac_cmd_queue *q)
3148 {
3149 	struct aac_cmd *acp;
3150 
3151 	_NOTE(ASSUMING_PROTECTED(*q))
3152 
3153 	if ((acp = q->q_head) != NULL) {
3154 		if ((q->q_head = acp->next) != NULL)
3155 			acp->next = NULL;
3156 		else
3157 			q->q_tail = (struct aac_cmd *)&q->q_head;
3158 		acp->prev = NULL;
3159 	}
3160 	return (acp);
3161 }
3162 
3163 /*
3164  * Add a cmd to the tail of q
3165  */
3166 static void
3167 aac_cmd_enqueue(struct aac_cmd_queue *q, struct aac_cmd *acp)
3168 {
3169 	ASSERT(acp->next == NULL);
3170 	acp->prev = q->q_tail;
3171 	q->q_tail->next = acp;
3172 	q->q_tail = acp;
3173 }
3174 
3175 /*
3176  * Remove the cmd ac from q
3177  */
3178 static void
3179 aac_cmd_delete(struct aac_cmd_queue *q, struct aac_cmd *acp)
3180 {
3181 	if (acp->prev) {
3182 		if ((acp->prev->next = acp->next) != NULL) {
3183 			acp->next->prev = acp->prev;
3184 			acp->next = NULL;
3185 		} else {
3186 			q->q_tail = acp->prev;
3187 		}
3188 		acp->prev = NULL;
3189 	}
3190 	/* ac is not in the queue */
3191 }
3192 
3193 /*
3194  * Atomically insert an entry into the nominated queue, returns 0 on success or
3195  * AACERR if the queue is full.
3196  *
3197  * Note: it would be more efficient to defer notifying the controller in
3198  *	 the case where we may be inserting several entries in rapid succession,
3199  *	 but implementing this usefully may be difficult (it would involve a
3200  *	 separate queue/notify interface).
3201  */
3202 static int
3203 aac_fib_enqueue(struct aac_softstate *softs, int queue, uint32_t fib_addr,
3204     uint32_t fib_size)
3205 {
3206 	ddi_dma_handle_t dma = softs->comm_space_dma_handle;
3207 	ddi_acc_handle_t acc = softs->comm_space_acc_handle;
3208 	uint32_t pi, ci;
3209 
3210 	DBCALLED(softs, 2);
3211 
3212 	ASSERT(queue == AAC_ADAP_NORM_CMD_Q || queue == AAC_ADAP_NORM_RESP_Q);
3213 
3214 	/* Get the producer/consumer indices */
3215 	(void) ddi_dma_sync(dma, (uintptr_t)softs->qtablep->qt_qindex[queue] - \
3216 	    (uintptr_t)softs->comm_space, sizeof (uint32_t) * 2,
3217 	    DDI_DMA_SYNC_FORCPU);
3218 	if (aac_check_dma_handle(dma) != DDI_SUCCESS) {
3219 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_UNAFFECTED);
3220 		return (AACERR);
3221 	}
3222 
3223 	pi = ddi_get32(acc,
3224 	    &softs->qtablep->qt_qindex[queue][AAC_PRODUCER_INDEX]);
3225 	ci = ddi_get32(acc,
3226 	    &softs->qtablep->qt_qindex[queue][AAC_CONSUMER_INDEX]);
3227 
3228 	/*
3229 	 * Wrap the queue first before we check the queue to see
3230 	 * if it is full
3231 	 */
3232 	if (pi >= aac_qinfo[queue].size)
3233 		pi = 0;
3234 
3235 	/* XXX queue full */
3236 	if ((pi + 1) == ci)
3237 		return (AACERR);
3238 
3239 	/* Fill in queue entry */
3240 	ddi_put32(acc, &((softs->qentries[queue] + pi)->aq_fib_size), fib_size);
3241 	ddi_put32(acc, &((softs->qentries[queue] + pi)->aq_fib_addr), fib_addr);
3242 	(void) ddi_dma_sync(dma, (uintptr_t)(softs->qentries[queue] + pi) - \
3243 	    (uintptr_t)softs->comm_space, sizeof (struct aac_queue_entry),
3244 	    DDI_DMA_SYNC_FORDEV);
3245 
3246 	/* Update producer index */
3247 	ddi_put32(acc, &softs->qtablep->qt_qindex[queue][AAC_PRODUCER_INDEX],
3248 	    pi + 1);
3249 	(void) ddi_dma_sync(dma,
3250 	    (uintptr_t)&softs->qtablep->qt_qindex[queue][AAC_PRODUCER_INDEX] - \
3251 	    (uintptr_t)softs->comm_space, sizeof (uint32_t),
3252 	    DDI_DMA_SYNC_FORDEV);
3253 
3254 	if (aac_qinfo[queue].notify != 0)
3255 		AAC_NOTIFY(softs, aac_qinfo[queue].notify);
3256 	return (AACOK);
3257 }
3258 
3259 /*
3260  * Atomically remove one entry from the nominated queue, returns 0 on
3261  * success or AACERR if the queue is empty.
3262  */
3263 static int
3264 aac_fib_dequeue(struct aac_softstate *softs, int queue, int *idxp)
3265 {
3266 	ddi_acc_handle_t acc = softs->comm_space_acc_handle;
3267 	ddi_dma_handle_t dma = softs->comm_space_dma_handle;
3268 	uint32_t pi, ci;
3269 	int unfull = 0;
3270 
3271 	DBCALLED(softs, 2);
3272 
3273 	ASSERT(idxp);
3274 
3275 	/* Get the producer/consumer indices */
3276 	(void) ddi_dma_sync(dma, (uintptr_t)softs->qtablep->qt_qindex[queue] - \
3277 	    (uintptr_t)softs->comm_space, sizeof (uint32_t) * 2,
3278 	    DDI_DMA_SYNC_FORCPU);
3279 	pi = ddi_get32(acc,
3280 	    &softs->qtablep->qt_qindex[queue][AAC_PRODUCER_INDEX]);
3281 	ci = ddi_get32(acc,
3282 	    &softs->qtablep->qt_qindex[queue][AAC_CONSUMER_INDEX]);
3283 
3284 	/* Check for queue empty */
3285 	if (ci == pi)
3286 		return (AACERR);
3287 
3288 	if (pi >= aac_qinfo[queue].size)
3289 		pi = 0;
3290 
3291 	/* Check for queue full */
3292 	if (ci == pi + 1)
3293 		unfull = 1;
3294 
3295 	/*
3296 	 * The controller does not wrap the queue,
3297 	 * so we have to do it by ourselves
3298 	 */
3299 	if (ci >= aac_qinfo[queue].size)
3300 		ci = 0;
3301 
3302 	/* Fetch the entry */
3303 	(void) ddi_dma_sync(dma, (uintptr_t)(softs->qentries[queue] + pi) - \
3304 	    (uintptr_t)softs->comm_space, sizeof (struct aac_queue_entry),
3305 	    DDI_DMA_SYNC_FORCPU);
3306 	if (aac_check_dma_handle(dma) != DDI_SUCCESS) {
3307 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_UNAFFECTED);
3308 		return (AACERR);
3309 	}
3310 
3311 	switch (queue) {
3312 	case AAC_HOST_NORM_RESP_Q:
3313 	case AAC_HOST_HIGH_RESP_Q:
3314 		*idxp = ddi_get32(acc,
3315 		    &(softs->qentries[queue] + ci)->aq_fib_addr);
3316 		break;
3317 
3318 	case AAC_HOST_NORM_CMD_Q:
3319 	case AAC_HOST_HIGH_CMD_Q:
3320 		*idxp = ddi_get32(acc,
3321 		    &(softs->qentries[queue] + ci)->aq_fib_addr) / AAC_FIB_SIZE;
3322 		break;
3323 
3324 	default:
3325 		cmn_err(CE_NOTE, "!Invalid queue in aac_fib_dequeue()");
3326 		return (AACERR);
3327 	}
3328 
3329 	/* Update consumer index */
3330 	ddi_put32(acc, &softs->qtablep->qt_qindex[queue][AAC_CONSUMER_INDEX],
3331 	    ci + 1);
3332 	(void) ddi_dma_sync(dma,
3333 	    (uintptr_t)&softs->qtablep->qt_qindex[queue][AAC_CONSUMER_INDEX] - \
3334 	    (uintptr_t)softs->comm_space, sizeof (uint32_t),
3335 	    DDI_DMA_SYNC_FORDEV);
3336 
3337 	if (unfull && aac_qinfo[queue].notify != 0)
3338 		AAC_NOTIFY(softs, aac_qinfo[queue].notify);
3339 	return (AACOK);
3340 }
3341 
3342 static struct aac_mntinforesp *
3343 aac_get_mntinfo(struct aac_softstate *softs, int cid)
3344 {
3345 	ddi_acc_handle_t acc = softs->sync_ac.slotp->fib_acc_handle;
3346 	struct aac_fib *fibp = softs->sync_ac.slotp->fibp;
3347 	struct aac_mntinfo *mi = (struct aac_mntinfo *)&fibp->data[0];
3348 	struct aac_mntinforesp *mir;
3349 
3350 	ddi_put32(acc, &mi->Command, /* Use 64-bit LBA if enabled */
3351 	    (softs->flags & AAC_FLAGS_LBA_64BIT) ?
3352 	    VM_NameServe64 : VM_NameServe);
3353 	ddi_put32(acc, &mi->MntType, FT_FILESYS);
3354 	ddi_put32(acc, &mi->MntCount, cid);
3355 
3356 	if (aac_sync_fib(softs, ContainerCommand,
3357 	    AAC_FIB_SIZEOF(struct aac_mntinfo)) == AACERR) {
3358 		AACDB_PRINT(softs, CE_WARN, "Error probe container %d", cid);
3359 		return (NULL);
3360 	}
3361 
3362 	mir = (struct aac_mntinforesp *)&fibp->data[0];
3363 	if (ddi_get32(acc, &mir->Status) == ST_OK)
3364 		return (mir);
3365 	return (NULL);
3366 }
3367 
3368 static int
3369 aac_get_container_count(struct aac_softstate *softs, int *count)
3370 {
3371 	ddi_acc_handle_t acc;
3372 	struct aac_mntinforesp *mir;
3373 	int rval;
3374 
3375 	(void) aac_sync_fib_slot_bind(softs, &softs->sync_ac);
3376 	acc = softs->sync_ac.slotp->fib_acc_handle;
3377 
3378 	if ((mir = aac_get_mntinfo(softs, 0)) == NULL) {
3379 		rval = AACERR;
3380 		goto finish;
3381 	}
3382 	*count = ddi_get32(acc, &mir->MntRespCount);
3383 	if (*count > AAC_MAX_LD) {
3384 		AACDB_PRINT(softs, CE_CONT,
3385 		    "container count(%d) > AAC_MAX_LD", *count);
3386 		rval = AACERR;
3387 		goto finish;
3388 	}
3389 	rval = AACOK;
3390 
3391 finish:
3392 	aac_sync_fib_slot_release(softs, &softs->sync_ac);
3393 	return (rval);
3394 }
3395 
3396 static int
3397 aac_get_container_uid(struct aac_softstate *softs, uint32_t cid, uint32_t *uid)
3398 {
3399 	ddi_acc_handle_t acc = softs->sync_ac.slotp->fib_acc_handle;
3400 	struct aac_Container *ct = (struct aac_Container *) \
3401 	    &softs->sync_ac.slotp->fibp->data[0];
3402 
3403 	bzero(ct, sizeof (*ct) - CT_PACKET_SIZE);
3404 	ddi_put32(acc, &ct->Command, VM_ContainerConfig);
3405 	ddi_put32(acc, &ct->CTCommand.command, CT_CID_TO_32BITS_UID);
3406 	ddi_put32(acc, &ct->CTCommand.param[0], cid);
3407 
3408 	if (aac_sync_fib(softs, ContainerCommand,
3409 	    AAC_FIB_SIZEOF(struct aac_Container)) == AACERR)
3410 		return (AACERR);
3411 	if (ddi_get32(acc, &ct->CTCommand.param[0]) != CT_OK)
3412 		return (AACERR);
3413 
3414 	*uid = ddi_get32(acc, &ct->CTCommand.param[1]);
3415 	return (AACOK);
3416 }
3417 
3418 /*
3419  * Request information of the container cid
3420  */
3421 static struct aac_mntinforesp *
3422 aac_get_container_info(struct aac_softstate *softs, int cid)
3423 {
3424 	ddi_acc_handle_t acc = softs->sync_ac.slotp->fib_acc_handle;
3425 	struct aac_mntinforesp *mir;
3426 	int rval_uid;
3427 	uint32_t uid;
3428 
3429 	/* Get container UID first so that it will not overwrite mntinfo */
3430 	rval_uid = aac_get_container_uid(softs, cid, &uid);
3431 
3432 	/* Get container basic info */
3433 	if ((mir = aac_get_mntinfo(softs, cid)) == NULL) {
3434 		AACDB_PRINT(softs, CE_CONT,
3435 		    "query container %d info failed", cid);
3436 		return (NULL);
3437 	}
3438 	if (ddi_get32(acc, &mir->MntObj.VolType) == CT_NONE)
3439 		return (mir);
3440 	if (rval_uid != AACOK) {
3441 		AACDB_PRINT(softs, CE_CONT,
3442 		    "query container %d uid failed", cid);
3443 		return (NULL);
3444 	}
3445 
3446 	ddi_put32(acc, &mir->Status, uid);
3447 	return (mir);
3448 }
3449 
3450 static enum aac_cfg_event
3451 aac_probe_container(struct aac_softstate *softs, uint32_t cid)
3452 {
3453 	enum aac_cfg_event event = AAC_CFG_NULL_NOEXIST;
3454 	struct aac_container *dvp = &softs->containers[cid];
3455 	struct aac_mntinforesp *mir;
3456 	ddi_acc_handle_t acc;
3457 
3458 	(void) aac_sync_fib_slot_bind(softs, &softs->sync_ac);
3459 	acc = softs->sync_ac.slotp->fib_acc_handle;
3460 
3461 	/* Get container basic info */
3462 	if ((mir = aac_get_container_info(softs, cid)) == NULL) {
3463 		/* AAC_CFG_NULL_NOEXIST */
3464 		goto finish;
3465 	}
3466 
3467 	if (ddi_get32(acc, &mir->MntObj.VolType) == CT_NONE) {
3468 		if (AAC_DEV_IS_VALID(&dvp->dev)) {
3469 			AACDB_PRINT(softs, CE_NOTE,
3470 			    ">>> Container %d deleted", cid);
3471 			dvp->dev.flags &= ~AAC_DFLAG_VALID;
3472 			event = AAC_CFG_DELETE;
3473 		}
3474 		/* AAC_CFG_NULL_NOEXIST */
3475 	} else {
3476 		uint64_t size;
3477 		uint32_t uid;
3478 
3479 		event = AAC_CFG_NULL_EXIST;
3480 
3481 		size = AAC_MIR_SIZE(softs, acc, mir);
3482 		uid = ddi_get32(acc, &mir->Status);
3483 		if (AAC_DEV_IS_VALID(&dvp->dev)) {
3484 			if (dvp->uid != uid) {
3485 				AACDB_PRINT(softs, CE_WARN,
3486 				    ">>> Container %u uid changed to %d",
3487 				    cid, uid);
3488 				dvp->uid = uid;
3489 				event = AAC_CFG_CHANGE;
3490 			}
3491 			if (dvp->size != size) {
3492 				AACDB_PRINT(softs, CE_NOTE,
3493 				    ">>> Container %u size changed to %"PRIu64,
3494 				    cid, size);
3495 				dvp->size = size;
3496 				event = AAC_CFG_CHANGE;
3497 			}
3498 		} else { /* Init new container */
3499 			AACDB_PRINT(softs, CE_NOTE,
3500 			    ">>> Container %d added: " \
3501 			    "size=0x%x.%08x, type=%d, name=%s",
3502 			    cid,
3503 			    ddi_get32(acc, &mir->MntObj.CapacityHigh),
3504 			    ddi_get32(acc, &mir->MntObj.Capacity),
3505 			    ddi_get32(acc, &mir->MntObj.VolType),
3506 			    mir->MntObj.FileSystemName);
3507 			dvp->dev.flags |= AAC_DFLAG_VALID;
3508 			dvp->dev.type = AAC_DEV_LD;
3509 
3510 			dvp->cid = cid;
3511 			dvp->uid = uid;
3512 			dvp->size = size;
3513 			dvp->locked = 0;
3514 			dvp->deleted = 0;
3515 
3516 			event = AAC_CFG_ADD;
3517 		}
3518 	}
3519 
3520 finish:
3521 	aac_sync_fib_slot_release(softs, &softs->sync_ac);
3522 	return (event);
3523 }
3524 
3525 /*
3526  * Do a rescan of all the possible containers and update the container list
3527  * with newly online/offline containers, and prepare for autoconfiguration.
3528  */
3529 static int
3530 aac_probe_containers(struct aac_softstate *softs)
3531 {
3532 	int i, count, total;
3533 
3534 	/* Loop over possible containers */
3535 	count = softs->container_count;
3536 	if (aac_get_container_count(softs, &count) == AACERR)
3537 		return (AACERR);
3538 
3539 	for (i = total = 0; i < count; i++) {
3540 		enum aac_cfg_event event = aac_probe_container(softs, i);
3541 		if ((event != AAC_CFG_NULL_NOEXIST) &&
3542 		    (event != AAC_CFG_NULL_EXIST)) {
3543 			(void) aac_handle_dr(softs, i, -1, event);
3544 			total++;
3545 		}
3546 	}
3547 
3548 	if (count < softs->container_count) {
3549 		struct aac_container *dvp;
3550 
3551 		for (dvp = &softs->containers[count];
3552 		    dvp < &softs->containers[softs->container_count]; dvp++) {
3553 			if (!AAC_DEV_IS_VALID(&dvp->dev))
3554 				continue;
3555 			AACDB_PRINT(softs, CE_NOTE, ">>> Container %d deleted",
3556 			    dvp->cid);
3557 			dvp->dev.flags &= ~AAC_DFLAG_VALID;
3558 			(void) aac_handle_dr(softs, dvp->cid, -1,
3559 			    AAC_CFG_DELETE);
3560 		}
3561 	}
3562 
3563 	softs->container_count = count;
3564 	AACDB_PRINT(softs, CE_CONT, "?Total %d container(s) found", total);
3565 	return (AACOK);
3566 }
3567 
3568 static int
3569 aac_probe_jbod(struct aac_softstate *softs, int tgt, int event)
3570 {
3571 	ASSERT(AAC_MAX_LD <= tgt);
3572 	ASSERT(tgt < AAC_MAX_DEV(softs));
3573 	struct aac_device *dvp;
3574 	dvp = AAC_DEV(softs, tgt);
3575 
3576 	switch (event) {
3577 	case AAC_CFG_ADD:
3578 		AACDB_PRINT(softs, CE_NOTE,
3579 		    ">>> Jbod %d added", tgt - AAC_MAX_LD);
3580 		dvp->flags |= AAC_DFLAG_VALID;
3581 		dvp->type = AAC_DEV_PD;
3582 		break;
3583 	case AAC_CFG_DELETE:
3584 		AACDB_PRINT(softs, CE_NOTE,
3585 		    ">>> Jbod %d deleted", tgt - AAC_MAX_LD);
3586 		dvp->flags &= ~AAC_DFLAG_VALID;
3587 		break;
3588 	default:
3589 		return (AACERR);
3590 	}
3591 	(void) aac_handle_dr(softs, tgt, 0, event);
3592 	return (AACOK);
3593 }
3594 
3595 static int
3596 aac_alloc_comm_space(struct aac_softstate *softs)
3597 {
3598 	size_t rlen;
3599 	ddi_dma_cookie_t cookie;
3600 	uint_t cookien;
3601 
3602 	/* Allocate DMA for comm. space */
3603 	if (ddi_dma_alloc_handle(
3604 	    softs->devinfo_p,
3605 	    &softs->addr_dma_attr,
3606 	    DDI_DMA_SLEEP,
3607 	    NULL,
3608 	    &softs->comm_space_dma_handle) != DDI_SUCCESS) {
3609 		AACDB_PRINT(softs, CE_WARN,
3610 		    "Cannot alloc dma handle for communication area");
3611 		goto error;
3612 	}
3613 	if (ddi_dma_mem_alloc(
3614 	    softs->comm_space_dma_handle,
3615 	    sizeof (struct aac_comm_space),
3616 	    &softs->acc_attr,
3617 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
3618 	    DDI_DMA_SLEEP,
3619 	    NULL,
3620 	    (caddr_t *)&softs->comm_space,
3621 	    &rlen,
3622 	    &softs->comm_space_acc_handle) != DDI_SUCCESS) {
3623 		AACDB_PRINT(softs, CE_WARN,
3624 		    "Cannot alloc mem for communication area");
3625 		goto error;
3626 	}
3627 	if (ddi_dma_addr_bind_handle(
3628 	    softs->comm_space_dma_handle,
3629 	    NULL,
3630 	    (caddr_t)softs->comm_space,
3631 	    sizeof (struct aac_comm_space),
3632 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
3633 	    DDI_DMA_SLEEP,
3634 	    NULL,
3635 	    &cookie,
3636 	    &cookien) != DDI_DMA_MAPPED) {
3637 		AACDB_PRINT(softs, CE_WARN,
3638 		    "DMA bind failed for communication area");
3639 		goto error;
3640 	}
3641 	softs->comm_space_phyaddr = cookie.dmac_address;
3642 
3643 	return (AACOK);
3644 error:
3645 	if (softs->comm_space_acc_handle) {
3646 		ddi_dma_mem_free(&softs->comm_space_acc_handle);
3647 		softs->comm_space_acc_handle = NULL;
3648 	}
3649 	if (softs->comm_space_dma_handle) {
3650 		ddi_dma_free_handle(&softs->comm_space_dma_handle);
3651 		softs->comm_space_dma_handle = NULL;
3652 	}
3653 	return (AACERR);
3654 }
3655 
3656 static void
3657 aac_free_comm_space(struct aac_softstate *softs)
3658 {
3659 
3660 	(void) ddi_dma_unbind_handle(softs->comm_space_dma_handle);
3661 	ddi_dma_mem_free(&softs->comm_space_acc_handle);
3662 	softs->comm_space_acc_handle = NULL;
3663 	ddi_dma_free_handle(&softs->comm_space_dma_handle);
3664 	softs->comm_space_dma_handle = NULL;
3665 	softs->comm_space_phyaddr = 0;
3666 }
3667 
3668 /*
3669  * Initialize the data structures that are required for the communication
3670  * interface to operate
3671  */
3672 static int
3673 aac_setup_comm_space(struct aac_softstate *softs)
3674 {
3675 	ddi_dma_handle_t dma = softs->comm_space_dma_handle;
3676 	ddi_acc_handle_t acc = softs->comm_space_acc_handle;
3677 	uint32_t comm_space_phyaddr;
3678 	struct aac_adapter_init *initp;
3679 	int qoffset;
3680 
3681 	comm_space_phyaddr = softs->comm_space_phyaddr;
3682 
3683 	/* Setup adapter init struct */
3684 	initp = &softs->comm_space->init_data;
3685 	bzero(initp, sizeof (struct aac_adapter_init));
3686 
3687 	ddi_put32(acc, &initp->InitStructRevision, AAC_INIT_STRUCT_REVISION);
3688 	ddi_put32(acc, &initp->HostElapsedSeconds, ddi_get_time());
3689 
3690 	/* Setup new/old comm. specific data */
3691 	if (softs->flags & AAC_FLAGS_RAW_IO) {
3692 		uint32_t init_flags = 0;
3693 
3694 		if (softs->flags & AAC_FLAGS_NEW_COMM)
3695 			init_flags |= AAC_INIT_FLAGS_NEW_COMM_SUPPORTED;
3696 		/* AAC_SUPPORTED_POWER_MANAGEMENT */
3697 		init_flags |= AAC_INIT_FLAGS_DRIVER_SUPPORTS_PM;
3698 		init_flags |= AAC_INIT_FLAGS_DRIVER_USES_UTC_TIME;
3699 
3700 		ddi_put32(acc, &initp->InitStructRevision,
3701 		    AAC_INIT_STRUCT_REVISION_4);
3702 		ddi_put32(acc, &initp->InitFlags, init_flags);
3703 		/* Setup the preferred settings */
3704 		ddi_put32(acc, &initp->MaxIoCommands, softs->aac_max_fibs);
3705 		ddi_put32(acc, &initp->MaxIoSize,
3706 		    (softs->aac_max_sectors << 9));
3707 		ddi_put32(acc, &initp->MaxFibSize, softs->aac_max_fib_size);
3708 	} else {
3709 		/*
3710 		 * Tells the adapter about the physical location of various
3711 		 * important shared data structures
3712 		 */
3713 		ddi_put32(acc, &initp->AdapterFibsPhysicalAddress,
3714 		    comm_space_phyaddr + \
3715 		    offsetof(struct aac_comm_space, adapter_fibs));
3716 		ddi_put32(acc, &initp->AdapterFibsVirtualAddress, 0);
3717 		ddi_put32(acc, &initp->AdapterFibAlign, AAC_FIB_SIZE);
3718 		ddi_put32(acc, &initp->AdapterFibsSize,
3719 		    AAC_ADAPTER_FIBS * AAC_FIB_SIZE);
3720 		ddi_put32(acc, &initp->PrintfBufferAddress,
3721 		    comm_space_phyaddr + \
3722 		    offsetof(struct aac_comm_space, adapter_print_buf));
3723 		ddi_put32(acc, &initp->PrintfBufferSize,
3724 		    AAC_ADAPTER_PRINT_BUFSIZE);
3725 		ddi_put32(acc, &initp->MiniPortRevision,
3726 		    AAC_INIT_STRUCT_MINIPORT_REVISION);
3727 		ddi_put32(acc, &initp->HostPhysMemPages, AAC_MAX_PFN);
3728 
3729 		qoffset = (comm_space_phyaddr + \
3730 		    offsetof(struct aac_comm_space, qtable)) % \
3731 		    AAC_QUEUE_ALIGN;
3732 		if (qoffset)
3733 			qoffset = AAC_QUEUE_ALIGN - qoffset;
3734 		softs->qtablep = (struct aac_queue_table *) \
3735 		    ((char *)&softs->comm_space->qtable + qoffset);
3736 		ddi_put32(acc, &initp->CommHeaderAddress, comm_space_phyaddr + \
3737 		    offsetof(struct aac_comm_space, qtable) + qoffset);
3738 
3739 		/* Init queue table */
3740 		ddi_put32(acc, &softs->qtablep-> \
3741 		    qt_qindex[AAC_HOST_NORM_CMD_Q][AAC_PRODUCER_INDEX],
3742 		    AAC_HOST_NORM_CMD_ENTRIES);
3743 		ddi_put32(acc, &softs->qtablep-> \
3744 		    qt_qindex[AAC_HOST_NORM_CMD_Q][AAC_CONSUMER_INDEX],
3745 		    AAC_HOST_NORM_CMD_ENTRIES);
3746 		ddi_put32(acc, &softs->qtablep-> \
3747 		    qt_qindex[AAC_HOST_HIGH_CMD_Q][AAC_PRODUCER_INDEX],
3748 		    AAC_HOST_HIGH_CMD_ENTRIES);
3749 		ddi_put32(acc, &softs->qtablep-> \
3750 		    qt_qindex[AAC_HOST_HIGH_CMD_Q][AAC_CONSUMER_INDEX],
3751 		    AAC_HOST_HIGH_CMD_ENTRIES);
3752 		ddi_put32(acc, &softs->qtablep-> \
3753 		    qt_qindex[AAC_ADAP_NORM_CMD_Q][AAC_PRODUCER_INDEX],
3754 		    AAC_ADAP_NORM_CMD_ENTRIES);
3755 		ddi_put32(acc, &softs->qtablep-> \
3756 		    qt_qindex[AAC_ADAP_NORM_CMD_Q][AAC_CONSUMER_INDEX],
3757 		    AAC_ADAP_NORM_CMD_ENTRIES);
3758 		ddi_put32(acc, &softs->qtablep-> \
3759 		    qt_qindex[AAC_ADAP_HIGH_CMD_Q][AAC_PRODUCER_INDEX],
3760 		    AAC_ADAP_HIGH_CMD_ENTRIES);
3761 		ddi_put32(acc, &softs->qtablep-> \
3762 		    qt_qindex[AAC_ADAP_HIGH_CMD_Q][AAC_CONSUMER_INDEX],
3763 		    AAC_ADAP_HIGH_CMD_ENTRIES);
3764 		ddi_put32(acc, &softs->qtablep-> \
3765 		    qt_qindex[AAC_HOST_NORM_RESP_Q][AAC_PRODUCER_INDEX],
3766 		    AAC_HOST_NORM_RESP_ENTRIES);
3767 		ddi_put32(acc, &softs->qtablep-> \
3768 		    qt_qindex[AAC_HOST_NORM_RESP_Q][AAC_CONSUMER_INDEX],
3769 		    AAC_HOST_NORM_RESP_ENTRIES);
3770 		ddi_put32(acc, &softs->qtablep-> \
3771 		    qt_qindex[AAC_HOST_HIGH_RESP_Q][AAC_PRODUCER_INDEX],
3772 		    AAC_HOST_HIGH_RESP_ENTRIES);
3773 		ddi_put32(acc, &softs->qtablep-> \
3774 		    qt_qindex[AAC_HOST_HIGH_RESP_Q][AAC_CONSUMER_INDEX],
3775 		    AAC_HOST_HIGH_RESP_ENTRIES);
3776 		ddi_put32(acc, &softs->qtablep-> \
3777 		    qt_qindex[AAC_ADAP_NORM_RESP_Q][AAC_PRODUCER_INDEX],
3778 		    AAC_ADAP_NORM_RESP_ENTRIES);
3779 		ddi_put32(acc, &softs->qtablep-> \
3780 		    qt_qindex[AAC_ADAP_NORM_RESP_Q][AAC_CONSUMER_INDEX],
3781 		    AAC_ADAP_NORM_RESP_ENTRIES);
3782 		ddi_put32(acc, &softs->qtablep-> \
3783 		    qt_qindex[AAC_ADAP_HIGH_RESP_Q][AAC_PRODUCER_INDEX],
3784 		    AAC_ADAP_HIGH_RESP_ENTRIES);
3785 		ddi_put32(acc, &softs->qtablep-> \
3786 		    qt_qindex[AAC_ADAP_HIGH_RESP_Q][AAC_CONSUMER_INDEX],
3787 		    AAC_ADAP_HIGH_RESP_ENTRIES);
3788 
3789 		/* Init queue entries */
3790 		softs->qentries[AAC_HOST_NORM_CMD_Q] =
3791 		    &softs->qtablep->qt_HostNormCmdQueue[0];
3792 		softs->qentries[AAC_HOST_HIGH_CMD_Q] =
3793 		    &softs->qtablep->qt_HostHighCmdQueue[0];
3794 		softs->qentries[AAC_ADAP_NORM_CMD_Q] =
3795 		    &softs->qtablep->qt_AdapNormCmdQueue[0];
3796 		softs->qentries[AAC_ADAP_HIGH_CMD_Q] =
3797 		    &softs->qtablep->qt_AdapHighCmdQueue[0];
3798 		softs->qentries[AAC_HOST_NORM_RESP_Q] =
3799 		    &softs->qtablep->qt_HostNormRespQueue[0];
3800 		softs->qentries[AAC_HOST_HIGH_RESP_Q] =
3801 		    &softs->qtablep->qt_HostHighRespQueue[0];
3802 		softs->qentries[AAC_ADAP_NORM_RESP_Q] =
3803 		    &softs->qtablep->qt_AdapNormRespQueue[0];
3804 		softs->qentries[AAC_ADAP_HIGH_RESP_Q] =
3805 		    &softs->qtablep->qt_AdapHighRespQueue[0];
3806 	}
3807 	(void) ddi_dma_sync(dma, 0, 0, DDI_DMA_SYNC_FORDEV);
3808 
3809 	/* Send init structure to the card */
3810 	if (aac_sync_mbcommand(softs, AAC_MONKER_INITSTRUCT,
3811 	    comm_space_phyaddr + \
3812 	    offsetof(struct aac_comm_space, init_data),
3813 	    0, 0, 0, NULL) == AACERR) {
3814 		AACDB_PRINT(softs, CE_WARN,
3815 		    "Cannot send init structure to adapter");
3816 		return (AACERR);
3817 	}
3818 
3819 	return (AACOK);
3820 }
3821 
3822 static uchar_t *
3823 aac_vendor_id(struct aac_softstate *softs, uchar_t *buf)
3824 {
3825 	(void) memset(buf, ' ', AAC_VENDOR_LEN);
3826 	bcopy(softs->vendor_name, buf, strlen(softs->vendor_name));
3827 	return (buf + AAC_VENDOR_LEN);
3828 }
3829 
3830 static uchar_t *
3831 aac_product_id(struct aac_softstate *softs, uchar_t *buf)
3832 {
3833 	(void) memset(buf, ' ', AAC_PRODUCT_LEN);
3834 	bcopy(softs->product_name, buf, strlen(softs->product_name));
3835 	return (buf + AAC_PRODUCT_LEN);
3836 }
3837 
3838 /*
3839  * Construct unit serial number from container uid
3840  */
3841 static uchar_t *
3842 aac_lun_serialno(struct aac_softstate *softs, int tgt, uchar_t *buf)
3843 {
3844 	int i, d;
3845 	uint32_t uid;
3846 
3847 	ASSERT(tgt >= 0 && tgt < AAC_MAX_LD);
3848 
3849 	uid = softs->containers[tgt].uid;
3850 	for (i = 7; i >= 0; i--) {
3851 		d = uid & 0xf;
3852 		buf[i] = d > 9 ? 'A' + (d - 0xa) : '0' + d;
3853 		uid >>= 4;
3854 	}
3855 	return (buf + 8);
3856 }
3857 
3858 /*
3859  * SPC-3 7.5 INQUIRY command implementation
3860  */
3861 static void
3862 aac_inquiry(struct aac_softstate *softs, struct scsi_pkt *pkt,
3863     union scsi_cdb *cdbp, struct buf *bp)
3864 {
3865 	int tgt = pkt->pkt_address.a_target;
3866 	char *b_addr = NULL;
3867 	uchar_t page = cdbp->cdb_opaque[2];
3868 
3869 	if (cdbp->cdb_opaque[1] & AAC_CDB_INQUIRY_CMDDT) {
3870 		/* Command Support Data is not supported */
3871 		aac_set_arq_data(pkt, KEY_ILLEGAL_REQUEST, 0x24, 0x00, 0);
3872 		return;
3873 	}
3874 
3875 	if (bp && bp->b_un.b_addr && bp->b_bcount) {
3876 		if (bp->b_flags & (B_PHYS | B_PAGEIO))
3877 			bp_mapin(bp);
3878 		b_addr = bp->b_un.b_addr;
3879 	}
3880 
3881 	if (cdbp->cdb_opaque[1] & AAC_CDB_INQUIRY_EVPD) {
3882 		uchar_t *vpdp = (uchar_t *)b_addr;
3883 		uchar_t *idp, *sp;
3884 
3885 		/* SPC-3 8.4 Vital product data parameters */
3886 		switch (page) {
3887 		case 0x00:
3888 			/* Supported VPD pages */
3889 			if (vpdp == NULL ||
3890 			    bp->b_bcount < (AAC_VPD_PAGE_DATA + 3))
3891 				return;
3892 			bzero(vpdp, AAC_VPD_PAGE_LENGTH);
3893 			vpdp[AAC_VPD_PAGE_CODE] = 0x00;
3894 			vpdp[AAC_VPD_PAGE_LENGTH] = 3;
3895 
3896 			vpdp[AAC_VPD_PAGE_DATA] = 0x00;
3897 			vpdp[AAC_VPD_PAGE_DATA + 1] = 0x80;
3898 			vpdp[AAC_VPD_PAGE_DATA + 2] = 0x83;
3899 
3900 			pkt->pkt_state |= STATE_XFERRED_DATA;
3901 			break;
3902 
3903 		case 0x80:
3904 			/* Unit serial number page */
3905 			if (vpdp == NULL ||
3906 			    bp->b_bcount < (AAC_VPD_PAGE_DATA + 8))
3907 				return;
3908 			bzero(vpdp, AAC_VPD_PAGE_LENGTH);
3909 			vpdp[AAC_VPD_PAGE_CODE] = 0x80;
3910 			vpdp[AAC_VPD_PAGE_LENGTH] = 8;
3911 
3912 			sp = &vpdp[AAC_VPD_PAGE_DATA];
3913 			(void) aac_lun_serialno(softs, tgt, sp);
3914 
3915 			pkt->pkt_state |= STATE_XFERRED_DATA;
3916 			break;
3917 
3918 		case 0x83:
3919 			/* Device identification page */
3920 			if (vpdp == NULL ||
3921 			    bp->b_bcount < (AAC_VPD_PAGE_DATA + 32))
3922 				return;
3923 			bzero(vpdp, AAC_VPD_PAGE_LENGTH);
3924 			vpdp[AAC_VPD_PAGE_CODE] = 0x83;
3925 
3926 			idp = &vpdp[AAC_VPD_PAGE_DATA];
3927 			bzero(idp, AAC_VPD_ID_LENGTH);
3928 			idp[AAC_VPD_ID_CODESET] = 0x02;
3929 			idp[AAC_VPD_ID_TYPE] = 0x01;
3930 
3931 			/*
3932 			 * SPC-3 Table 111 - Identifier type
3933 			 * One recommanded method of constructing the remainder
3934 			 * of identifier field is to concatenate the product
3935 			 * identification field from the standard INQUIRY data
3936 			 * field and the product serial number field from the
3937 			 * unit serial number page.
3938 			 */
3939 			sp = &idp[AAC_VPD_ID_DATA];
3940 			sp = aac_vendor_id(softs, sp);
3941 			sp = aac_product_id(softs, sp);
3942 			sp = aac_lun_serialno(softs, tgt, sp);
3943 			idp[AAC_VPD_ID_LENGTH] = (uintptr_t)sp - \
3944 			    (uintptr_t)&idp[AAC_VPD_ID_DATA];
3945 
3946 			vpdp[AAC_VPD_PAGE_LENGTH] = (uintptr_t)sp - \
3947 			    (uintptr_t)&vpdp[AAC_VPD_PAGE_DATA];
3948 			pkt->pkt_state |= STATE_XFERRED_DATA;
3949 			break;
3950 
3951 		default:
3952 			aac_set_arq_data(pkt, KEY_ILLEGAL_REQUEST,
3953 			    0x24, 0x00, 0);
3954 			break;
3955 		}
3956 	} else {
3957 		struct scsi_inquiry *inqp = (struct scsi_inquiry *)b_addr;
3958 		size_t len = sizeof (struct scsi_inquiry);
3959 
3960 		if (page != 0) {
3961 			aac_set_arq_data(pkt, KEY_ILLEGAL_REQUEST,
3962 			    0x24, 0x00, 0);
3963 			return;
3964 		}
3965 		if (inqp == NULL || bp->b_bcount < len)
3966 			return;
3967 
3968 		bzero(inqp, len);
3969 		inqp->inq_len = AAC_ADDITIONAL_LEN;
3970 		inqp->inq_ansi = AAC_ANSI_VER;
3971 		inqp->inq_rdf = AAC_RESP_DATA_FORMAT;
3972 		(void) aac_vendor_id(softs, (uchar_t *)inqp->inq_vid);
3973 		(void) aac_product_id(softs, (uchar_t *)inqp->inq_pid);
3974 		bcopy("V1.0", inqp->inq_revision, 4);
3975 		inqp->inq_cmdque = 1; /* enable tagged-queuing */
3976 		/*
3977 		 * For "sd-max-xfer-size" property which may impact performance
3978 		 * when IO threads increase.
3979 		 */
3980 		inqp->inq_wbus32 = 1;
3981 
3982 		pkt->pkt_state |= STATE_XFERRED_DATA;
3983 	}
3984 }
3985 
3986 /*
3987  * SPC-3 7.10 MODE SENSE command implementation
3988  */
3989 static void
3990 aac_mode_sense(struct aac_softstate *softs, struct scsi_pkt *pkt,
3991     union scsi_cdb *cdbp, struct buf *bp, int capacity)
3992 {
3993 	uchar_t pagecode;
3994 	struct mode_header *headerp;
3995 	struct mode_header_g1 *g1_headerp;
3996 	unsigned int ncyl;
3997 	caddr_t sense_data;
3998 	caddr_t next_page;
3999 	size_t sdata_size;
4000 	size_t pages_size;
4001 	int unsupport_page = 0;
4002 
4003 	ASSERT(cdbp->scc_cmd == SCMD_MODE_SENSE ||
4004 	    cdbp->scc_cmd == SCMD_MODE_SENSE_G1);
4005 
4006 	if (!(bp && bp->b_un.b_addr && bp->b_bcount))
4007 		return;
4008 
4009 	if (bp->b_flags & (B_PHYS | B_PAGEIO))
4010 		bp_mapin(bp);
4011 	pkt->pkt_state |= STATE_XFERRED_DATA;
4012 	pagecode = cdbp->cdb_un.sg.scsi[0] & 0x3F;
4013 
4014 	/* calculate the size of needed buffer */
4015 	if (cdbp->scc_cmd == SCMD_MODE_SENSE)
4016 		sdata_size = MODE_HEADER_LENGTH;
4017 	else /* must be SCMD_MODE_SENSE_G1 */
4018 		sdata_size = MODE_HEADER_LENGTH_G1;
4019 
4020 	pages_size = 0;
4021 	switch (pagecode) {
4022 	case SD_MODE_SENSE_PAGE3_CODE:
4023 		pages_size += sizeof (struct mode_format);
4024 		break;
4025 
4026 	case SD_MODE_SENSE_PAGE4_CODE:
4027 		pages_size += sizeof (struct mode_geometry);
4028 		break;
4029 
4030 	case MODEPAGE_CTRL_MODE:
4031 		if (softs->flags & AAC_FLAGS_LBA_64BIT) {
4032 			pages_size += sizeof (struct mode_control_scsi3);
4033 		} else {
4034 			unsupport_page = 1;
4035 		}
4036 		break;
4037 
4038 	case MODEPAGE_ALLPAGES:
4039 		if (softs->flags & AAC_FLAGS_LBA_64BIT) {
4040 			pages_size += sizeof (struct mode_format) +
4041 			    sizeof (struct mode_geometry) +
4042 			    sizeof (struct mode_control_scsi3);
4043 		} else {
4044 			pages_size += sizeof (struct mode_format) +
4045 			    sizeof (struct mode_geometry);
4046 		}
4047 		break;
4048 
4049 	default:
4050 		/* unsupported pages */
4051 		unsupport_page = 1;
4052 	}
4053 
4054 	/* allocate buffer to fill the send data */
4055 	sdata_size += pages_size;
4056 	sense_data = kmem_zalloc(sdata_size, KM_SLEEP);
4057 
4058 	if (cdbp->scc_cmd == SCMD_MODE_SENSE) {
4059 		headerp = (struct mode_header *)sense_data;
4060 		headerp->length = MODE_HEADER_LENGTH + pages_size -
4061 		    sizeof (headerp->length);
4062 		headerp->bdesc_length = 0;
4063 		next_page = sense_data + sizeof (struct mode_header);
4064 	} else {
4065 		g1_headerp = (void *)sense_data;
4066 		g1_headerp->length = BE_16(MODE_HEADER_LENGTH_G1 + pages_size -
4067 		    sizeof (g1_headerp->length));
4068 		g1_headerp->bdesc_length = 0;
4069 		next_page = sense_data + sizeof (struct mode_header_g1);
4070 	}
4071 
4072 	if (unsupport_page)
4073 		goto finish;
4074 
4075 	if (pagecode == SD_MODE_SENSE_PAGE3_CODE ||
4076 	    pagecode == MODEPAGE_ALLPAGES) {
4077 		/* SBC-3 7.1.3.3 Format device page */
4078 		struct mode_format *page3p;
4079 
4080 		page3p = (void *)next_page;
4081 		page3p->mode_page.code = SD_MODE_SENSE_PAGE3_CODE;
4082 		page3p->mode_page.length = sizeof (struct mode_format);
4083 		page3p->data_bytes_sect = BE_16(AAC_SECTOR_SIZE);
4084 		page3p->sect_track = BE_16(AAC_SECTORS_PER_TRACK);
4085 
4086 		next_page += sizeof (struct mode_format);
4087 	}
4088 
4089 	if (pagecode == SD_MODE_SENSE_PAGE4_CODE ||
4090 	    pagecode == MODEPAGE_ALLPAGES) {
4091 		/* SBC-3 7.1.3.8 Rigid disk device geometry page */
4092 		struct mode_geometry *page4p;
4093 
4094 		page4p = (void *)next_page;
4095 		page4p->mode_page.code = SD_MODE_SENSE_PAGE4_CODE;
4096 		page4p->mode_page.length = sizeof (struct mode_geometry);
4097 		page4p->heads = AAC_NUMBER_OF_HEADS;
4098 		page4p->rpm = BE_16(AAC_ROTATION_SPEED);
4099 		ncyl = capacity / (AAC_NUMBER_OF_HEADS * AAC_SECTORS_PER_TRACK);
4100 		page4p->cyl_lb = ncyl & 0xff;
4101 		page4p->cyl_mb = (ncyl >> 8) & 0xff;
4102 		page4p->cyl_ub = (ncyl >> 16) & 0xff;
4103 
4104 		next_page += sizeof (struct mode_geometry);
4105 	}
4106 
4107 	if ((pagecode == MODEPAGE_CTRL_MODE || pagecode == MODEPAGE_ALLPAGES) &&
4108 	    softs->flags & AAC_FLAGS_LBA_64BIT) {
4109 		/* 64-bit LBA need large sense data */
4110 		struct mode_control_scsi3 *mctl;
4111 
4112 		mctl = (void *)next_page;
4113 		mctl->mode_page.code = MODEPAGE_CTRL_MODE;
4114 		mctl->mode_page.length =
4115 		    sizeof (struct mode_control_scsi3) -
4116 		    sizeof (struct mode_page);
4117 		mctl->d_sense = 1;
4118 	}
4119 
4120 finish:
4121 	/* copyout the valid data. */
4122 	bcopy(sense_data, bp->b_un.b_addr, min(sdata_size, bp->b_bcount));
4123 	kmem_free(sense_data, sdata_size);
4124 }
4125 
4126 static int
4127 aac_name_node(dev_info_t *dip, char *name, int len)
4128 {
4129 	int tgt, lun;
4130 
4131 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
4132 	    DDI_PROP_DONTPASS, "target", -1);
4133 	if (tgt == -1)
4134 		return (DDI_FAILURE);
4135 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
4136 	    DDI_PROP_DONTPASS, "lun", -1);
4137 	if (lun == -1)
4138 		return (DDI_FAILURE);
4139 
4140 	(void) snprintf(name, len, "%x,%x", tgt, lun);
4141 	return (DDI_SUCCESS);
4142 }
4143 
4144 /*ARGSUSED*/
4145 static int
4146 aac_tran_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
4147     scsi_hba_tran_t *tran, struct scsi_device *sd)
4148 {
4149 	struct aac_softstate *softs = AAC_TRAN2SOFTS(tran);
4150 #if defined(DEBUG) || defined(__lock_lint)
4151 	int ctl = ddi_get_instance(softs->devinfo_p);
4152 #endif
4153 	uint16_t tgt = sd->sd_address.a_target;
4154 	uint8_t lun = sd->sd_address.a_lun;
4155 	struct aac_device *dvp;
4156 
4157 	DBCALLED(softs, 2);
4158 
4159 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
4160 		/*
4161 		 * If no persistent node exist, we don't allow .conf node
4162 		 * to be created.
4163 		 */
4164 		if (aac_find_child(softs, tgt, lun) != NULL) {
4165 			if (ndi_merge_node(tgt_dip, aac_name_node) !=
4166 			    DDI_SUCCESS)
4167 				/* Create this .conf node */
4168 				return (DDI_SUCCESS);
4169 		}
4170 		return (DDI_FAILURE);
4171 	}
4172 
4173 	/*
4174 	 * Only support container/phys. device that has been
4175 	 * detected and valid
4176 	 */
4177 	mutex_enter(&softs->io_lock);
4178 	if (tgt >= AAC_MAX_DEV(softs)) {
4179 		AACDB_PRINT_TRAN(softs,
4180 		    "aac_tran_tgt_init: c%dt%dL%d out", ctl, tgt, lun);
4181 		mutex_exit(&softs->io_lock);
4182 		return (DDI_FAILURE);
4183 	}
4184 
4185 	if (tgt < AAC_MAX_LD) {
4186 		dvp = (struct aac_device *)&softs->containers[tgt];
4187 		if (lun != 0 || !AAC_DEV_IS_VALID(dvp)) {
4188 			AACDB_PRINT_TRAN(softs, "aac_tran_tgt_init: c%dt%dL%d",
4189 			    ctl, tgt, lun);
4190 			mutex_exit(&softs->io_lock);
4191 			return (DDI_FAILURE);
4192 		}
4193 		/*
4194 		 * Save the tgt_dip for the given target if one doesn't exist
4195 		 * already. Dip's for non-existance tgt's will be cleared in
4196 		 * tgt_free.
4197 		 */
4198 		if (softs->containers[tgt].dev.dip == NULL &&
4199 		    strcmp(ddi_driver_name(sd->sd_dev), "sd") == 0)
4200 			softs->containers[tgt].dev.dip = tgt_dip;
4201 	} else {
4202 		dvp = (struct aac_device *)&softs->nondasds[AAC_PD(tgt)];
4203 		/*
4204 		 * Save the tgt_dip for the given target if one doesn't exist
4205 		 * already. Dip's for non-existance tgt's will be cleared in
4206 		 * tgt_free.
4207 		 */
4208 
4209 		if (softs->nondasds[AAC_PD(tgt)].dev.dip  == NULL &&
4210 		    strcmp(ddi_driver_name(sd->sd_dev), "sd") == 0)
4211 			softs->nondasds[AAC_PD(tgt)].dev.dip  = tgt_dip;
4212 	}
4213 
4214 	if (softs->flags & AAC_FLAGS_BRKUP) {
4215 		if (ndi_prop_update_int(DDI_DEV_T_NONE, tgt_dip,
4216 		    "buf_break", 1) != DDI_PROP_SUCCESS) {
4217 			cmn_err(CE_CONT, "unable to create "
4218 			    "property for t%dL%d (buf_break)", tgt, lun);
4219 		}
4220 	}
4221 
4222 	AACDB_PRINT(softs, CE_NOTE,
4223 	    "aac_tran_tgt_init: c%dt%dL%d ok (%s)", ctl, tgt, lun,
4224 	    (dvp->type == AAC_DEV_PD) ? "pd" : "ld");
4225 	mutex_exit(&softs->io_lock);
4226 	return (DDI_SUCCESS);
4227 }
4228 
4229 static void
4230 aac_tran_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
4231     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
4232 {
4233 #ifndef __lock_lint
4234 	_NOTE(ARGUNUSED(hba_dip, tgt_dip, hba_tran))
4235 #endif
4236 
4237 	struct aac_softstate *softs = SD2AAC(sd);
4238 	int tgt = sd->sd_address.a_target;
4239 
4240 	mutex_enter(&softs->io_lock);
4241 	if (tgt < AAC_MAX_LD) {
4242 		if (softs->containers[tgt].dev.dip == tgt_dip)
4243 			softs->containers[tgt].dev.dip = NULL;
4244 	} else {
4245 		if (softs->nondasds[AAC_PD(tgt)].dev.dip == tgt_dip)
4246 			softs->nondasds[AAC_PD(tgt)].dev.dip = NULL;
4247 		softs->nondasds[AAC_PD(tgt)].dev.flags &= ~AAC_DFLAG_VALID;
4248 	}
4249 	mutex_exit(&softs->io_lock);
4250 }
4251 
4252 /*
4253  * Check if the firmware is Up And Running. If it is in the Kernel Panic
4254  * state, (BlinkLED code + 1) is returned.
4255  *    0 -- firmware up and running
4256  *   -1 -- firmware dead
4257  *   >0 -- firmware kernel panic
4258  */
4259 static int
4260 aac_check_adapter_health(struct aac_softstate *softs)
4261 {
4262 	int rval;
4263 
4264 	rval = PCI_MEM_GET32(softs, AAC_OMR0);
4265 
4266 	if (rval & AAC_KERNEL_UP_AND_RUNNING) {
4267 		rval = 0;
4268 	} else if (rval & AAC_KERNEL_PANIC) {
4269 		cmn_err(CE_WARN, "firmware panic");
4270 		rval = ((rval >> 16) & 0xff) + 1; /* avoid 0 as return value */
4271 	} else {
4272 		cmn_err(CE_WARN, "firmware dead");
4273 		rval = -1;
4274 	}
4275 	return (rval);
4276 }
4277 
4278 static void
4279 aac_abort_iocmd(struct aac_softstate *softs, struct aac_cmd *acp,
4280     uchar_t reason)
4281 {
4282 	acp->flags |= AAC_CMD_ABORT;
4283 
4284 	if (acp->pkt) {
4285 		if (acp->slotp) { /* outstanding cmd */
4286 			acp->pkt->pkt_state |= STATE_GOT_STATUS;
4287 		}
4288 
4289 		switch (reason) {
4290 		case CMD_TIMEOUT:
4291 			AACDB_PRINT(softs, CE_NOTE, "CMD_TIMEOUT: acp=0x%p",
4292 			    acp);
4293 			aac_set_pkt_reason(softs, acp, CMD_TIMEOUT,
4294 			    STAT_TIMEOUT | STAT_BUS_RESET);
4295 			break;
4296 		case CMD_RESET:
4297 			/* aac support only RESET_ALL */
4298 			AACDB_PRINT(softs, CE_NOTE, "CMD_RESET: acp=0x%p", acp);
4299 			aac_set_pkt_reason(softs, acp, CMD_RESET,
4300 			    STAT_BUS_RESET);
4301 			break;
4302 		case CMD_ABORTED:
4303 			AACDB_PRINT(softs, CE_NOTE, "CMD_ABORTED: acp=0x%p",
4304 			    acp);
4305 			aac_set_pkt_reason(softs, acp, CMD_ABORTED,
4306 			    STAT_ABORTED);
4307 			break;
4308 		}
4309 	}
4310 	aac_end_io(softs, acp);
4311 }
4312 
4313 /*
4314  * Abort all the pending commands of type iocmd or just the command pkt
4315  * corresponding to pkt
4316  */
4317 static void
4318 aac_abort_iocmds(struct aac_softstate *softs, int iocmd, struct scsi_pkt *pkt,
4319     int reason)
4320 {
4321 	struct aac_cmd *ac_arg, *acp;
4322 	int i;
4323 
4324 	if (pkt == NULL) {
4325 		ac_arg = NULL;
4326 	} else {
4327 		ac_arg = PKT2AC(pkt);
4328 		iocmd = (ac_arg->flags & AAC_CMD_SYNC) ?
4329 		    AAC_IOCMD_SYNC : AAC_IOCMD_ASYNC;
4330 	}
4331 
4332 	/*
4333 	 * a) outstanding commands on the controller
4334 	 * Note: should abort outstanding commands only after one
4335 	 * IOP reset has been done.
4336 	 */
4337 	if (iocmd & AAC_IOCMD_OUTSTANDING) {
4338 		struct aac_cmd *acp;
4339 
4340 		for (i = 0; i < AAC_MAX_LD; i++) {
4341 			if (AAC_DEV_IS_VALID(&softs->containers[i].dev))
4342 				softs->containers[i].reset = 1;
4343 		}
4344 		while ((acp = softs->q_busy.q_head) != NULL)
4345 			aac_abort_iocmd(softs, acp, reason);
4346 	}
4347 
4348 	/* b) commands in the waiting queues */
4349 	for (i = 0; i < AAC_CMDQ_NUM; i++) {
4350 		if (iocmd & (1 << i)) {
4351 			if (ac_arg) {
4352 				aac_abort_iocmd(softs, ac_arg, reason);
4353 			} else {
4354 				while ((acp = softs->q_wait[i].q_head) != NULL)
4355 					aac_abort_iocmd(softs, acp, reason);
4356 			}
4357 		}
4358 	}
4359 }
4360 
4361 /*
4362  * The draining thread is shared among quiesce threads. It terminates
4363  * when the adapter is quiesced or stopped by aac_stop_drain().
4364  */
4365 static void
4366 aac_check_drain(void *arg)
4367 {
4368 	struct aac_softstate *softs = arg;
4369 
4370 	mutex_enter(&softs->io_lock);
4371 	if (softs->ndrains) {
4372 		softs->drain_timeid = 0;
4373 		/*
4374 		 * If both ASYNC and SYNC bus throttle are held,
4375 		 * wake up threads only when both are drained out.
4376 		 */
4377 		if ((softs->bus_throttle[AAC_CMDQ_ASYNC] > 0 ||
4378 		    softs->bus_ncmds[AAC_CMDQ_ASYNC] == 0) &&
4379 		    (softs->bus_throttle[AAC_CMDQ_SYNC] > 0 ||
4380 		    softs->bus_ncmds[AAC_CMDQ_SYNC] == 0))
4381 			cv_broadcast(&softs->drain_cv);
4382 		else
4383 			softs->drain_timeid = timeout(aac_check_drain, softs,
4384 			    AAC_QUIESCE_TICK * drv_usectohz(1000000));
4385 	}
4386 	mutex_exit(&softs->io_lock);
4387 }
4388 
4389 /*
4390  * If not draining the outstanding cmds, drain them. Otherwise,
4391  * only update ndrains.
4392  */
4393 static void
4394 aac_start_drain(struct aac_softstate *softs)
4395 {
4396 	if (softs->ndrains == 0) {
4397 		ASSERT(softs->drain_timeid == 0);
4398 		softs->drain_timeid = timeout(aac_check_drain, softs,
4399 		    AAC_QUIESCE_TICK * drv_usectohz(1000000));
4400 	}
4401 	softs->ndrains++;
4402 }
4403 
4404 /*
4405  * Stop the draining thread when no other threads use it any longer.
4406  * Side effect: io_lock may be released in the middle.
4407  */
4408 static void
4409 aac_stop_drain(struct aac_softstate *softs)
4410 {
4411 	softs->ndrains--;
4412 	if (softs->ndrains == 0) {
4413 		if (softs->drain_timeid != 0) {
4414 			timeout_id_t tid = softs->drain_timeid;
4415 
4416 			softs->drain_timeid = 0;
4417 			mutex_exit(&softs->io_lock);
4418 			(void) untimeout(tid);
4419 			mutex_enter(&softs->io_lock);
4420 		}
4421 	}
4422 }
4423 
4424 /*
4425  * The following function comes from Adaptec:
4426  *
4427  * Once do an IOP reset, basically the driver have to re-initialize the card
4428  * as if up from a cold boot, and the driver is responsible for any IO that
4429  * is outstanding to the adapter at the time of the IOP RESET. And prepare
4430  * for IOP RESET by making the init code modular with the ability to call it
4431  * from multiple places.
4432  */
4433 static int
4434 aac_reset_adapter(struct aac_softstate *softs)
4435 {
4436 	int health;
4437 	uint32_t status;
4438 	int rval = AAC_IOP_RESET_FAILED;
4439 
4440 	DBCALLED(softs, 1);
4441 
4442 	ASSERT(softs->state & AAC_STATE_RESET);
4443 
4444 	ddi_fm_acc_err_clear(softs->pci_mem_handle, DDI_FME_VER0);
4445 	/* Disable interrupt */
4446 	AAC_DISABLE_INTR(softs);
4447 
4448 	health = aac_check_adapter_health(softs);
4449 	if (health == -1) {
4450 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
4451 		goto finish;
4452 	}
4453 	if (health == 0) /* flush drives if possible */
4454 		(void) aac_shutdown(softs);
4455 
4456 	/* Execute IOP reset */
4457 	if ((aac_sync_mbcommand(softs, AAC_IOP_RESET, 0, 0, 0, 0,
4458 	    &status)) != AACOK) {
4459 		ddi_acc_handle_t acc;
4460 		struct aac_fib *fibp;
4461 		struct aac_pause_command *pc;
4462 
4463 		if ((status & 0xf) == 0xf) {
4464 			uint32_t wait_count;
4465 
4466 			/*
4467 			 * Sunrise Lake has dual cores and we must drag the
4468 			 * other core with us to reset simultaneously. There
4469 			 * are 2 bits in the Inbound Reset Control and Status
4470 			 * Register (offset 0x38) of the Sunrise Lake to reset
4471 			 * the chip without clearing out the PCI configuration
4472 			 * info (COMMAND & BARS).
4473 			 */
4474 			PCI_MEM_PUT32(softs, AAC_IRCSR, AAC_IRCSR_CORES_RST);
4475 
4476 			/*
4477 			 * We need to wait for 5 seconds before accessing the MU
4478 			 * again 10000 * 100us = 1000,000us = 1000ms = 1s
4479 			 */
4480 			wait_count = 5 * 10000;
4481 			while (wait_count) {
4482 				drv_usecwait(100); /* delay 100 microseconds */
4483 				wait_count--;
4484 			}
4485 		} else {
4486 			if (status == SRB_STATUS_INVALID_REQUEST)
4487 				cmn_err(CE_WARN, "!IOP_RESET not supported");
4488 			else /* probably timeout */
4489 				cmn_err(CE_WARN, "!IOP_RESET failed");
4490 
4491 			/* Unwind aac_shutdown() */
4492 			(void) aac_sync_fib_slot_bind(softs, &softs->sync_ac);
4493 			acc = softs->sync_ac.slotp->fib_acc_handle;
4494 
4495 			fibp = softs->sync_ac.slotp->fibp;
4496 			pc = (struct aac_pause_command *)&fibp->data[0];
4497 
4498 			bzero(pc, sizeof (*pc));
4499 			ddi_put32(acc, &pc->Command, VM_ContainerConfig);
4500 			ddi_put32(acc, &pc->Type, CT_PAUSE_IO);
4501 			ddi_put32(acc, &pc->Timeout, 1);
4502 			ddi_put32(acc, &pc->Min, 1);
4503 			ddi_put32(acc, &pc->NoRescan, 1);
4504 
4505 			(void) aac_sync_fib(softs, ContainerCommand,
4506 			    AAC_FIB_SIZEOF(struct aac_pause_command));
4507 			aac_sync_fib_slot_release(softs, &softs->sync_ac);
4508 
4509 			if (aac_check_adapter_health(softs) != 0)
4510 				ddi_fm_service_impact(softs->devinfo_p,
4511 				    DDI_SERVICE_LOST);
4512 			else
4513 				/*
4514 				 * IOP reset not supported or IOP not reseted
4515 				 */
4516 				rval = AAC_IOP_RESET_ABNORMAL;
4517 			goto finish;
4518 		}
4519 	}
4520 
4521 	/*
4522 	 * Re-read and renegotiate the FIB parameters, as one of the actions
4523 	 * that can result from an IOP reset is the running of a new firmware
4524 	 * image.
4525 	 */
4526 	if (aac_common_attach(softs) != AACOK)
4527 		goto finish;
4528 
4529 	rval = AAC_IOP_RESET_SUCCEED;
4530 
4531 finish:
4532 	AAC_ENABLE_INTR(softs);
4533 	return (rval);
4534 }
4535 
4536 static void
4537 aac_set_throttle(struct aac_softstate *softs, struct aac_device *dvp, int q,
4538     int throttle)
4539 {
4540 	/*
4541 	 * If the bus is draining/quiesced, no changes to the throttles
4542 	 * are allowed. All throttles should have been set to 0.
4543 	 */
4544 	if ((softs->state & AAC_STATE_QUIESCED) || softs->ndrains)
4545 		return;
4546 	dvp->throttle[q] = throttle;
4547 }
4548 
4549 static void
4550 aac_hold_bus(struct aac_softstate *softs, int iocmds)
4551 {
4552 	int i, q;
4553 
4554 	/* Hold bus by holding every device on the bus */
4555 	for (q = 0; q < AAC_CMDQ_NUM; q++) {
4556 		if (iocmds & (1 << q)) {
4557 			softs->bus_throttle[q] = 0;
4558 			for (i = 0; i < AAC_MAX_LD; i++)
4559 				aac_set_throttle(softs,
4560 				    &softs->containers[i].dev, q, 0);
4561 			for (i = 0; i < AAC_MAX_PD(softs); i++)
4562 				aac_set_throttle(softs,
4563 				    &softs->nondasds[i].dev, q, 0);
4564 		}
4565 	}
4566 }
4567 
4568 static void
4569 aac_unhold_bus(struct aac_softstate *softs, int iocmds)
4570 {
4571 	int i, q, max_throttle;
4572 
4573 	for (q = 0; q < AAC_CMDQ_NUM; q++) {
4574 		if (iocmds & (1 << q)) {
4575 			/*
4576 			 * Should not unhold AAC_IOCMD_ASYNC bus, if it has been
4577 			 * quiesced or being drained by possibly some quiesce
4578 			 * threads.
4579 			 */
4580 			if (q == AAC_CMDQ_ASYNC && ((softs->state &
4581 			    AAC_STATE_QUIESCED) || softs->ndrains))
4582 				continue;
4583 			if (q == AAC_CMDQ_ASYNC)
4584 				max_throttle = softs->total_slots -
4585 				    AAC_MGT_SLOT_NUM;
4586 			else
4587 				max_throttle = softs->total_slots - 1;
4588 			softs->bus_throttle[q] = max_throttle;
4589 			for (i = 0; i < AAC_MAX_LD; i++)
4590 				aac_set_throttle(softs,
4591 				    &softs->containers[i].dev,
4592 				    q, max_throttle);
4593 			for (i = 0; i < AAC_MAX_PD(softs); i++)
4594 				aac_set_throttle(softs, &softs->nondasds[i].dev,
4595 				    q, max_throttle);
4596 		}
4597 	}
4598 }
4599 
4600 static int
4601 aac_do_reset(struct aac_softstate *softs)
4602 {
4603 	int health;
4604 	int rval;
4605 
4606 	softs->state |= AAC_STATE_RESET;
4607 	health = aac_check_adapter_health(softs);
4608 
4609 	/*
4610 	 * Hold off new io commands and wait all outstanding io
4611 	 * commands to complete.
4612 	 */
4613 	if (health == 0) {
4614 		int sync_cmds = softs->bus_ncmds[AAC_CMDQ_SYNC];
4615 		int async_cmds = softs->bus_ncmds[AAC_CMDQ_ASYNC];
4616 
4617 		if (sync_cmds == 0 && async_cmds == 0) {
4618 			rval = AAC_IOP_RESET_SUCCEED;
4619 			goto finish;
4620 		}
4621 		/*
4622 		 * Give the adapter up to AAC_QUIESCE_TIMEOUT more seconds
4623 		 * to complete the outstanding io commands
4624 		 */
4625 		int timeout = AAC_QUIESCE_TIMEOUT * 1000 * 10;
4626 		int (*intr_handler)(struct aac_softstate *);
4627 
4628 		aac_hold_bus(softs, AAC_IOCMD_SYNC | AAC_IOCMD_ASYNC);
4629 		/*
4630 		 * Poll the adapter by ourselves in case interrupt is disabled
4631 		 * and to avoid releasing the io_lock.
4632 		 */
4633 		intr_handler = (softs->flags & AAC_FLAGS_NEW_COMM) ?
4634 		    aac_process_intr_new : aac_process_intr_old;
4635 		while ((softs->bus_ncmds[AAC_CMDQ_SYNC] ||
4636 		    softs->bus_ncmds[AAC_CMDQ_ASYNC]) && timeout) {
4637 			drv_usecwait(100);
4638 			(void) intr_handler(softs);
4639 			timeout--;
4640 		}
4641 		aac_unhold_bus(softs, AAC_IOCMD_SYNC | AAC_IOCMD_ASYNC);
4642 
4643 		if (softs->bus_ncmds[AAC_CMDQ_SYNC] == 0 &&
4644 		    softs->bus_ncmds[AAC_CMDQ_ASYNC] == 0) {
4645 			/* Cmds drained out */
4646 			rval = AAC_IOP_RESET_SUCCEED;
4647 			goto finish;
4648 		} else if (softs->bus_ncmds[AAC_CMDQ_SYNC] < sync_cmds ||
4649 		    softs->bus_ncmds[AAC_CMDQ_ASYNC] < async_cmds) {
4650 			/* Cmds not drained out, adapter overloaded */
4651 			rval = AAC_IOP_RESET_ABNORMAL;
4652 			goto finish;
4653 		}
4654 	}
4655 
4656 	/*
4657 	 * If a longer waiting time still can't drain any outstanding io
4658 	 * commands, do IOP reset.
4659 	 */
4660 	if ((rval = aac_reset_adapter(softs)) == AAC_IOP_RESET_FAILED)
4661 		softs->state |= AAC_STATE_DEAD;
4662 
4663 finish:
4664 	softs->state &= ~AAC_STATE_RESET;
4665 	return (rval);
4666 }
4667 
4668 static int
4669 aac_tran_reset(struct scsi_address *ap, int level)
4670 {
4671 	struct aac_softstate *softs = AAC_TRAN2SOFTS(ap->a_hba_tran);
4672 	int rval;
4673 
4674 	DBCALLED(softs, 1);
4675 
4676 	if (level != RESET_ALL) {
4677 		cmn_err(CE_NOTE, "!reset target/lun not supported");
4678 		return (0);
4679 	}
4680 
4681 	mutex_enter(&softs->io_lock);
4682 	switch (rval = aac_do_reset(softs)) {
4683 	case AAC_IOP_RESET_SUCCEED:
4684 		aac_abort_iocmds(softs, AAC_IOCMD_OUTSTANDING | AAC_IOCMD_ASYNC,
4685 		    NULL, CMD_RESET);
4686 		aac_start_waiting_io(softs);
4687 		break;
4688 	case AAC_IOP_RESET_FAILED:
4689 		/* Abort IOCTL cmds when adapter is dead */
4690 		aac_abort_iocmds(softs, AAC_IOCMD_ALL, NULL, CMD_RESET);
4691 		break;
4692 	case AAC_IOP_RESET_ABNORMAL:
4693 		aac_start_waiting_io(softs);
4694 	}
4695 	mutex_exit(&softs->io_lock);
4696 
4697 	aac_drain_comp_q(softs);
4698 	return (rval == 0);
4699 }
4700 
4701 static int
4702 aac_tran_abort(struct scsi_address *ap, struct scsi_pkt *pkt)
4703 {
4704 	struct aac_softstate *softs = AAC_TRAN2SOFTS(ap->a_hba_tran);
4705 
4706 	DBCALLED(softs, 1);
4707 
4708 	mutex_enter(&softs->io_lock);
4709 	aac_abort_iocmds(softs, 0, pkt, CMD_ABORTED);
4710 	mutex_exit(&softs->io_lock);
4711 
4712 	aac_drain_comp_q(softs);
4713 	return (1);
4714 }
4715 
4716 void
4717 aac_free_dmamap(struct aac_cmd *acp)
4718 {
4719 	/* Free dma mapping */
4720 	if (acp->flags & AAC_CMD_DMA_VALID) {
4721 		ASSERT(acp->buf_dma_handle);
4722 		(void) ddi_dma_unbind_handle(acp->buf_dma_handle);
4723 		acp->flags &= ~AAC_CMD_DMA_VALID;
4724 	}
4725 
4726 	if (acp->abp != NULL) { /* free non-aligned buf DMA */
4727 		ASSERT(acp->buf_dma_handle);
4728 		if ((acp->flags & AAC_CMD_BUF_WRITE) == 0 && acp->bp)
4729 			ddi_rep_get8(acp->abh, (uint8_t *)acp->bp->b_un.b_addr,
4730 			    (uint8_t *)acp->abp, acp->bp->b_bcount,
4731 			    DDI_DEV_AUTOINCR);
4732 		ddi_dma_mem_free(&acp->abh);
4733 		acp->abp = NULL;
4734 	}
4735 
4736 	if (acp->buf_dma_handle) {
4737 		ddi_dma_free_handle(&acp->buf_dma_handle);
4738 		acp->buf_dma_handle = NULL;
4739 	}
4740 }
4741 
4742 static void
4743 aac_unknown_scmd(struct aac_softstate *softs, struct aac_cmd *acp)
4744 {
4745 	AACDB_PRINT(softs, CE_CONT, "SCMD 0x%x not supported",
4746 	    ((union scsi_cdb *)(void *)acp->pkt->pkt_cdbp)->scc_cmd);
4747 	aac_free_dmamap(acp);
4748 	aac_set_arq_data(acp->pkt, KEY_ILLEGAL_REQUEST, 0x20, 0x00, 0);
4749 	aac_soft_callback(softs, acp);
4750 }
4751 
4752 /*
4753  * Handle command to logical device
4754  */
4755 static int
4756 aac_tran_start_ld(struct aac_softstate *softs, struct aac_cmd *acp)
4757 {
4758 	struct aac_container *dvp;
4759 	struct scsi_pkt *pkt;
4760 	union scsi_cdb *cdbp;
4761 	struct buf *bp;
4762 	int rval;
4763 
4764 	dvp = (struct aac_container *)acp->dvp;
4765 	pkt = acp->pkt;
4766 	cdbp = (void *)pkt->pkt_cdbp;
4767 	bp = acp->bp;
4768 
4769 	switch (cdbp->scc_cmd) {
4770 	case SCMD_INQUIRY: /* inquiry */
4771 		aac_free_dmamap(acp);
4772 		aac_inquiry(softs, pkt, cdbp, bp);
4773 		aac_soft_callback(softs, acp);
4774 		rval = TRAN_ACCEPT;
4775 		break;
4776 
4777 	case SCMD_READ_CAPACITY: /* read capacity */
4778 		if (bp && bp->b_un.b_addr && bp->b_bcount) {
4779 			struct scsi_capacity cap;
4780 			uint64_t last_lba;
4781 
4782 			/* check 64-bit LBA */
4783 			last_lba = dvp->size - 1;
4784 			if (last_lba > 0xffffffffull) {
4785 				cap.capacity = 0xfffffffful;
4786 			} else {
4787 				cap.capacity = BE_32(last_lba);
4788 			}
4789 			cap.lbasize = BE_32(AAC_SECTOR_SIZE);
4790 
4791 			aac_free_dmamap(acp);
4792 			if (bp->b_flags & (B_PHYS|B_PAGEIO))
4793 				bp_mapin(bp);
4794 			bcopy(&cap, bp->b_un.b_addr, min(bp->b_bcount, 8));
4795 			pkt->pkt_state |= STATE_XFERRED_DATA;
4796 		}
4797 		aac_soft_callback(softs, acp);
4798 		rval = TRAN_ACCEPT;
4799 		break;
4800 
4801 	case SCMD_SVC_ACTION_IN_G4: /* read capacity 16 */
4802 		/* Check if containers need 64-bit LBA support */
4803 		if (cdbp->cdb_opaque[1] == SSVC_ACTION_READ_CAPACITY_G4) {
4804 			if (bp && bp->b_un.b_addr && bp->b_bcount) {
4805 				struct scsi_capacity_16 cap16;
4806 				int cap_len = sizeof (struct scsi_capacity_16);
4807 
4808 				bzero(&cap16, cap_len);
4809 				cap16.sc_capacity = BE_64(dvp->size - 1);
4810 				cap16.sc_lbasize = BE_32(AAC_SECTOR_SIZE);
4811 
4812 				aac_free_dmamap(acp);
4813 				if (bp->b_flags & (B_PHYS | B_PAGEIO))
4814 					bp_mapin(bp);
4815 				bcopy(&cap16, bp->b_un.b_addr,
4816 				    min(bp->b_bcount, cap_len));
4817 				pkt->pkt_state |= STATE_XFERRED_DATA;
4818 			}
4819 			aac_soft_callback(softs, acp);
4820 		} else {
4821 			aac_unknown_scmd(softs, acp);
4822 		}
4823 		rval = TRAN_ACCEPT;
4824 		break;
4825 
4826 	case SCMD_READ_G4: /* read_16 */
4827 	case SCMD_WRITE_G4: /* write_16 */
4828 		if (softs->flags & AAC_FLAGS_RAW_IO) {
4829 			/* NOTE: GETG4ADDRTL(cdbp) is int32_t */
4830 			acp->blkno = ((uint64_t) \
4831 			    GETG4ADDR(cdbp) << 32) | \
4832 			    (uint32_t)GETG4ADDRTL(cdbp);
4833 			goto do_io;
4834 		}
4835 		AACDB_PRINT(softs, CE_WARN, "64-bit LBA not supported");
4836 		aac_unknown_scmd(softs, acp);
4837 		rval = TRAN_ACCEPT;
4838 		break;
4839 
4840 	case SCMD_READ: /* read_6 */
4841 	case SCMD_WRITE: /* write_6 */
4842 		acp->blkno = GETG0ADDR(cdbp);
4843 		goto do_io;
4844 
4845 	case SCMD_READ_G5: /* read_12 */
4846 	case SCMD_WRITE_G5: /* write_12 */
4847 		acp->blkno = GETG5ADDR(cdbp);
4848 		goto do_io;
4849 
4850 	case SCMD_READ_G1: /* read_10 */
4851 	case SCMD_WRITE_G1: /* write_10 */
4852 		acp->blkno = (uint32_t)GETG1ADDR(cdbp);
4853 do_io:
4854 		if (acp->flags & AAC_CMD_DMA_VALID) {
4855 			uint64_t cnt_size = dvp->size;
4856 
4857 			/*
4858 			 * If LBA > array size AND rawio, the
4859 			 * adapter may hang. So check it before
4860 			 * sending.
4861 			 * NOTE: (blkno + blkcnt) may overflow
4862 			 */
4863 			if ((acp->blkno < cnt_size) &&
4864 			    ((acp->blkno + acp->bcount /
4865 			    AAC_BLK_SIZE) <= cnt_size)) {
4866 				rval = aac_do_io(softs, acp);
4867 			} else {
4868 			/*
4869 			 * Request exceeds the capacity of disk,
4870 			 * set error block number to last LBA
4871 			 * + 1.
4872 			 */
4873 				aac_set_arq_data(pkt,
4874 				    KEY_ILLEGAL_REQUEST, 0x21,
4875 				    0x00, cnt_size);
4876 				aac_soft_callback(softs, acp);
4877 				rval = TRAN_ACCEPT;
4878 			}
4879 		} else if (acp->bcount == 0) {
4880 			/* For 0 length IO, just return ok */
4881 			aac_soft_callback(softs, acp);
4882 			rval = TRAN_ACCEPT;
4883 		} else {
4884 			rval = TRAN_BADPKT;
4885 		}
4886 		break;
4887 
4888 	case SCMD_MODE_SENSE: /* mode_sense_6 */
4889 	case SCMD_MODE_SENSE_G1: { /* mode_sense_10 */
4890 		int capacity;
4891 
4892 		aac_free_dmamap(acp);
4893 		if (dvp->size > 0xffffffffull)
4894 			capacity = 0xfffffffful; /* 64-bit LBA */
4895 		else
4896 			capacity = dvp->size;
4897 		aac_mode_sense(softs, pkt, cdbp, bp, capacity);
4898 		aac_soft_callback(softs, acp);
4899 		rval = TRAN_ACCEPT;
4900 		break;
4901 	}
4902 
4903 	case SCMD_START_STOP:
4904 		if (softs->support_opt2 & AAC_SUPPORTED_POWER_MANAGEMENT) {
4905 			acp->aac_cmd_fib = aac_cmd_fib_startstop;
4906 			acp->ac_comp = aac_startstop_complete;
4907 			rval = aac_do_io(softs, acp);
4908 			break;
4909 		}
4910 	/* FALLTHRU */
4911 	case SCMD_TEST_UNIT_READY:
4912 	case SCMD_REQUEST_SENSE:
4913 	case SCMD_FORMAT:
4914 		aac_free_dmamap(acp);
4915 		if (bp && bp->b_un.b_addr && bp->b_bcount) {
4916 			if (acp->flags & AAC_CMD_BUF_READ) {
4917 				if (bp->b_flags & (B_PHYS|B_PAGEIO))
4918 					bp_mapin(bp);
4919 				bzero(bp->b_un.b_addr, bp->b_bcount);
4920 			}
4921 			pkt->pkt_state |= STATE_XFERRED_DATA;
4922 		}
4923 		aac_soft_callback(softs, acp);
4924 		rval = TRAN_ACCEPT;
4925 		break;
4926 
4927 	case SCMD_SYNCHRONIZE_CACHE:
4928 		acp->flags |= AAC_CMD_NTAG;
4929 		acp->aac_cmd_fib = aac_cmd_fib_sync;
4930 		acp->ac_comp = aac_synccache_complete;
4931 		rval = aac_do_io(softs, acp);
4932 		break;
4933 
4934 	case SCMD_DOORLOCK:
4935 		aac_free_dmamap(acp);
4936 		dvp->locked = (pkt->pkt_cdbp[4] & 0x01) ? 1 : 0;
4937 		aac_soft_callback(softs, acp);
4938 		rval = TRAN_ACCEPT;
4939 		break;
4940 
4941 	default: /* unknown command */
4942 		aac_unknown_scmd(softs, acp);
4943 		rval = TRAN_ACCEPT;
4944 		break;
4945 	}
4946 
4947 	return (rval);
4948 }
4949 
4950 static int
4951 aac_tran_start(struct scsi_address *ap, struct scsi_pkt *pkt)
4952 {
4953 	struct aac_softstate *softs = AAC_TRAN2SOFTS(ap->a_hba_tran);
4954 	struct aac_cmd *acp = PKT2AC(pkt);
4955 	struct aac_device *dvp = acp->dvp;
4956 	int rval;
4957 
4958 	DBCALLED(softs, 2);
4959 
4960 	/*
4961 	 * Reinitialize some fields of ac and pkt; the packet may
4962 	 * have been resubmitted
4963 	 */
4964 	acp->flags &= AAC_CMD_CONSISTENT | AAC_CMD_DMA_PARTIAL | \
4965 	    AAC_CMD_BUF_READ | AAC_CMD_BUF_WRITE | AAC_CMD_DMA_VALID;
4966 	acp->timeout = acp->pkt->pkt_time;
4967 	if (pkt->pkt_flags & FLAG_NOINTR)
4968 		acp->flags |= AAC_CMD_NO_INTR;
4969 #ifdef DEBUG
4970 	acp->fib_flags = AACDB_FLAGS_FIB_SCMD;
4971 #endif
4972 	pkt->pkt_reason = CMD_CMPLT;
4973 	pkt->pkt_state = 0;
4974 	pkt->pkt_statistics = 0;
4975 	*pkt->pkt_scbp = STATUS_GOOD; /* clear arq scsi_status */
4976 
4977 	if (acp->flags & AAC_CMD_DMA_VALID) {
4978 		pkt->pkt_resid = acp->bcount;
4979 		/* Consistent packets need to be sync'ed first */
4980 		if ((acp->flags & AAC_CMD_CONSISTENT) &&
4981 		    (acp->flags & AAC_CMD_BUF_WRITE))
4982 			if (aac_dma_sync_ac(acp) != AACOK) {
4983 				ddi_fm_service_impact(softs->devinfo_p,
4984 				    DDI_SERVICE_UNAFFECTED);
4985 				return (TRAN_BADPKT);
4986 			}
4987 	} else {
4988 		pkt->pkt_resid = 0;
4989 	}
4990 
4991 	mutex_enter(&softs->io_lock);
4992 	AACDB_PRINT_SCMD(softs, acp);
4993 	if ((dvp->flags & (AAC_DFLAG_VALID | AAC_DFLAG_CONFIGURING)) &&
4994 	    !(softs->state & AAC_STATE_DEAD)) {
4995 		if (dvp->type == AAC_DEV_LD) {
4996 			if (ap->a_lun == 0)
4997 				rval = aac_tran_start_ld(softs, acp);
4998 			else
4999 				goto error;
5000 		} else {
5001 			rval = aac_do_io(softs, acp);
5002 		}
5003 	} else {
5004 error:
5005 #ifdef DEBUG
5006 		if (!(softs->state & AAC_STATE_DEAD)) {
5007 			AACDB_PRINT_TRAN(softs,
5008 			    "Cannot send cmd to target t%dL%d: %s",
5009 			    ap->a_target, ap->a_lun,
5010 			    "target invalid");
5011 		} else {
5012 			AACDB_PRINT(softs, CE_WARN,
5013 			    "Cannot send cmd to target t%dL%d: %s",
5014 			    ap->a_target, ap->a_lun,
5015 			    "adapter dead");
5016 		}
5017 #endif
5018 		rval = TRAN_FATAL_ERROR;
5019 	}
5020 	mutex_exit(&softs->io_lock);
5021 	return (rval);
5022 }
5023 
5024 static int
5025 aac_tran_getcap(struct scsi_address *ap, char *cap, int whom)
5026 {
5027 	struct aac_softstate *softs = AAC_TRAN2SOFTS(ap->a_hba_tran);
5028 	struct aac_device *dvp;
5029 	int rval;
5030 
5031 	DBCALLED(softs, 2);
5032 
5033 	/* We don't allow inquiring about capabilities for other targets */
5034 	if (cap == NULL || whom == 0) {
5035 		AACDB_PRINT(softs, CE_WARN,
5036 		    "GetCap> %s not supported: whom=%d", cap, whom);
5037 		return (-1);
5038 	}
5039 
5040 	mutex_enter(&softs->io_lock);
5041 	dvp = AAC_DEV(softs, ap->a_target);
5042 	if (dvp == NULL || !AAC_DEV_IS_VALID(dvp)) {
5043 		mutex_exit(&softs->io_lock);
5044 		AACDB_PRINT_TRAN(softs, "Bad target t%dL%d to getcap",
5045 		    ap->a_target, ap->a_lun);
5046 		return (-1);
5047 	}
5048 
5049 	switch (scsi_hba_lookup_capstr(cap)) {
5050 	case SCSI_CAP_ARQ: /* auto request sense */
5051 		rval = 1;
5052 		break;
5053 	case SCSI_CAP_UNTAGGED_QING:
5054 	case SCSI_CAP_TAGGED_QING:
5055 		rval = 1;
5056 		break;
5057 	case SCSI_CAP_DMA_MAX:
5058 		rval = softs->dma_max;
5059 		break;
5060 	default:
5061 		rval = -1;
5062 		break;
5063 	}
5064 	mutex_exit(&softs->io_lock);
5065 
5066 	AACDB_PRINT_TRAN(softs, "GetCap> %s t%dL%d: rval=%d",
5067 	    cap, ap->a_target, ap->a_lun, rval);
5068 	return (rval);
5069 }
5070 
5071 /*ARGSUSED*/
5072 static int
5073 aac_tran_setcap(struct scsi_address *ap, char *cap, int value, int whom)
5074 {
5075 	struct aac_softstate *softs = AAC_TRAN2SOFTS(ap->a_hba_tran);
5076 	struct aac_device *dvp;
5077 	int rval;
5078 
5079 	DBCALLED(softs, 2);
5080 
5081 	/* We don't allow inquiring about capabilities for other targets */
5082 	if (cap == NULL || whom == 0) {
5083 		AACDB_PRINT(softs, CE_WARN,
5084 		    "SetCap> %s not supported: whom=%d", cap, whom);
5085 		return (-1);
5086 	}
5087 
5088 	mutex_enter(&softs->io_lock);
5089 	dvp = AAC_DEV(softs, ap->a_target);
5090 	if (dvp == NULL || !AAC_DEV_IS_VALID(dvp)) {
5091 		mutex_exit(&softs->io_lock);
5092 		AACDB_PRINT_TRAN(softs, "Bad target t%dL%d to setcap",
5093 		    ap->a_target, ap->a_lun);
5094 		return (-1);
5095 	}
5096 
5097 	switch (scsi_hba_lookup_capstr(cap)) {
5098 	case SCSI_CAP_ARQ:
5099 		/* Force auto request sense */
5100 		rval = (value == 1) ? 1 : 0;
5101 		break;
5102 	case SCSI_CAP_UNTAGGED_QING:
5103 	case SCSI_CAP_TAGGED_QING:
5104 		rval = (value == 1) ? 1 : 0;
5105 		break;
5106 	default:
5107 		rval = -1;
5108 		break;
5109 	}
5110 	mutex_exit(&softs->io_lock);
5111 
5112 	AACDB_PRINT_TRAN(softs, "SetCap> %s t%dL%d val=%d: rval=%d",
5113 	    cap, ap->a_target, ap->a_lun, value, rval);
5114 	return (rval);
5115 }
5116 
5117 static void
5118 aac_tran_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
5119 {
5120 	struct aac_cmd *acp = PKT2AC(pkt);
5121 
5122 	DBCALLED(NULL, 2);
5123 
5124 	if (acp->sgt) {
5125 		kmem_free(acp->sgt, sizeof (struct aac_sge) * \
5126 		    acp->left_cookien);
5127 	}
5128 	aac_free_dmamap(acp);
5129 	ASSERT(acp->slotp == NULL);
5130 	scsi_hba_pkt_free(ap, pkt);
5131 }
5132 
5133 int
5134 aac_cmd_dma_alloc(struct aac_softstate *softs, struct aac_cmd *acp,
5135     struct buf *bp, int flags, int (*cb)(), caddr_t arg)
5136 {
5137 	int kf = (cb == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
5138 	uint_t oldcookiec;
5139 	int bioerr;
5140 	int rval;
5141 
5142 	oldcookiec = acp->left_cookien;
5143 
5144 	/* Move window to build s/g map */
5145 	if (acp->total_nwin > 0) {
5146 		if (++acp->cur_win < acp->total_nwin) {
5147 			off_t off;
5148 			size_t len;
5149 
5150 			rval = ddi_dma_getwin(acp->buf_dma_handle, acp->cur_win,
5151 			    &off, &len, &acp->cookie, &acp->left_cookien);
5152 			if (rval == DDI_SUCCESS)
5153 				goto get_dma_cookies;
5154 			AACDB_PRINT(softs, CE_WARN,
5155 			    "ddi_dma_getwin() fail %d", rval);
5156 			return (AACERR);
5157 		}
5158 		AACDB_PRINT(softs, CE_WARN, "Nothing to transfer");
5159 		return (AACERR);
5160 	}
5161 
5162 	/* We need to transfer data, so we alloc DMA resources for this pkt */
5163 	if (bp && bp->b_bcount != 0 && !(acp->flags & AAC_CMD_DMA_VALID)) {
5164 		uint_t dma_flags = 0;
5165 		struct aac_sge *sge;
5166 
5167 		/*
5168 		 * We will still use this point to fake some
5169 		 * infomation in tran_start
5170 		 */
5171 		acp->bp = bp;
5172 
5173 		/* Set dma flags */
5174 		if (BUF_IS_READ(bp)) {
5175 			dma_flags |= DDI_DMA_READ;
5176 			acp->flags |= AAC_CMD_BUF_READ;
5177 		} else {
5178 			dma_flags |= DDI_DMA_WRITE;
5179 			acp->flags |= AAC_CMD_BUF_WRITE;
5180 		}
5181 		if (flags & PKT_CONSISTENT)
5182 			dma_flags |= DDI_DMA_CONSISTENT;
5183 		if (flags & PKT_DMA_PARTIAL)
5184 			dma_flags |= DDI_DMA_PARTIAL;
5185 
5186 		/* Alloc buf dma handle */
5187 		if (!acp->buf_dma_handle) {
5188 			rval = ddi_dma_alloc_handle(softs->devinfo_p,
5189 			    &softs->buf_dma_attr, cb, arg,
5190 			    &acp->buf_dma_handle);
5191 			if (rval != DDI_SUCCESS) {
5192 				AACDB_PRINT(softs, CE_WARN,
5193 				    "Can't allocate DMA handle, errno=%d",
5194 				    rval);
5195 				goto error_out;
5196 			}
5197 		}
5198 
5199 		/* Bind buf */
5200 		if (((uintptr_t)bp->b_un.b_addr & AAC_DMA_ALIGN_MASK) == 0) {
5201 			rval = ddi_dma_buf_bind_handle(acp->buf_dma_handle,
5202 			    bp, dma_flags, cb, arg, &acp->cookie,
5203 			    &acp->left_cookien);
5204 		} else {
5205 			size_t bufsz;
5206 
5207 			AACDB_PRINT_TRAN(softs,
5208 			    "non-aligned buffer: addr=0x%p, cnt=%lu",
5209 			    (void *)bp->b_un.b_addr, bp->b_bcount);
5210 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
5211 				bp_mapin(bp);
5212 
5213 			rval = ddi_dma_mem_alloc(acp->buf_dma_handle,
5214 			    AAC_ROUNDUP(bp->b_bcount, AAC_DMA_ALIGN),
5215 			    &softs->acc_attr, DDI_DMA_STREAMING,
5216 			    cb, arg, &acp->abp, &bufsz, &acp->abh);
5217 
5218 			if (rval != DDI_SUCCESS) {
5219 				AACDB_PRINT(softs, CE_NOTE,
5220 				    "Cannot alloc DMA to non-aligned buf");
5221 				bioerr = 0;
5222 				goto error_out;
5223 			}
5224 
5225 			if (acp->flags & AAC_CMD_BUF_WRITE)
5226 				ddi_rep_put8(acp->abh,
5227 				    (uint8_t *)bp->b_un.b_addr,
5228 				    (uint8_t *)acp->abp, bp->b_bcount,
5229 				    DDI_DEV_AUTOINCR);
5230 
5231 			rval = ddi_dma_addr_bind_handle(acp->buf_dma_handle,
5232 			    NULL, acp->abp, bufsz, dma_flags, cb, arg,
5233 			    &acp->cookie, &acp->left_cookien);
5234 		}
5235 
5236 		switch (rval) {
5237 		case DDI_DMA_PARTIAL_MAP:
5238 			if (ddi_dma_numwin(acp->buf_dma_handle,
5239 			    &acp->total_nwin) == DDI_FAILURE) {
5240 				AACDB_PRINT(softs, CE_WARN,
5241 				    "Cannot get number of DMA windows");
5242 				bioerr = 0;
5243 				goto error_out;
5244 			}
5245 			AACDB_PRINT_TRAN(softs, "buf bind, %d seg(s)",
5246 			    acp->left_cookien);
5247 			acp->cur_win = 0;
5248 			break;
5249 
5250 		case DDI_DMA_MAPPED:
5251 			AACDB_PRINT_TRAN(softs, "buf bind, %d seg(s)",
5252 			    acp->left_cookien);
5253 			acp->cur_win = 0;
5254 			acp->total_nwin = 1;
5255 			break;
5256 
5257 		case DDI_DMA_NORESOURCES:
5258 			bioerr = 0;
5259 			AACDB_PRINT(softs, CE_WARN,
5260 			    "Cannot bind buf for DMA: DDI_DMA_NORESOURCES");
5261 			goto error_out;
5262 		case DDI_DMA_BADATTR:
5263 		case DDI_DMA_NOMAPPING:
5264 			bioerr = EFAULT;
5265 			AACDB_PRINT(softs, CE_WARN,
5266 			    "Cannot bind buf for DMA: DDI_DMA_NOMAPPING");
5267 			goto error_out;
5268 		case DDI_DMA_TOOBIG:
5269 			bioerr = EINVAL;
5270 			AACDB_PRINT(softs, CE_WARN,
5271 			    "Cannot bind buf for DMA: DDI_DMA_TOOBIG(%d)",
5272 			    bp->b_bcount);
5273 			goto error_out;
5274 		default:
5275 			bioerr = EINVAL;
5276 			AACDB_PRINT(softs, CE_WARN,
5277 			    "Cannot bind buf for DMA: %d", rval);
5278 			goto error_out;
5279 		}
5280 		acp->flags |= AAC_CMD_DMA_VALID;
5281 
5282 get_dma_cookies:
5283 		ASSERT(acp->left_cookien > 0);
5284 		if (acp->left_cookien > softs->aac_sg_tablesize) {
5285 			AACDB_PRINT(softs, CE_NOTE, "large cookiec received %d",
5286 			    acp->left_cookien);
5287 			bioerr = EINVAL;
5288 			goto error_out;
5289 		}
5290 		if (oldcookiec != acp->left_cookien && acp->sgt != NULL) {
5291 			kmem_free(acp->sgt, sizeof (struct aac_sge) * \
5292 			    oldcookiec);
5293 			acp->sgt = NULL;
5294 		}
5295 		if (acp->sgt == NULL) {
5296 			acp->sgt = kmem_alloc(sizeof (struct aac_sge) * \
5297 			    acp->left_cookien, kf);
5298 			if (acp->sgt == NULL) {
5299 				AACDB_PRINT(softs, CE_WARN,
5300 				    "sgt kmem_alloc fail");
5301 				bioerr = ENOMEM;
5302 				goto error_out;
5303 			}
5304 		}
5305 
5306 		sge = &acp->sgt[0];
5307 		sge->bcount = acp->cookie.dmac_size;
5308 		sge->addr.ad64.lo = AAC_LS32(acp->cookie.dmac_laddress);
5309 		sge->addr.ad64.hi = AAC_MS32(acp->cookie.dmac_laddress);
5310 		acp->bcount = acp->cookie.dmac_size;
5311 		for (sge++; sge < &acp->sgt[acp->left_cookien]; sge++) {
5312 			ddi_dma_nextcookie(acp->buf_dma_handle, &acp->cookie);
5313 			sge->bcount = acp->cookie.dmac_size;
5314 			sge->addr.ad64.lo = AAC_LS32(acp->cookie.dmac_laddress);
5315 			sge->addr.ad64.hi = AAC_MS32(acp->cookie.dmac_laddress);
5316 			acp->bcount += acp->cookie.dmac_size;
5317 		}
5318 
5319 		/*
5320 		 * Note: The old DMA engine do not correctly handle
5321 		 * dma_attr_maxxfer attribute. So we have to ensure
5322 		 * it by ourself.
5323 		 */
5324 		if (acp->bcount > softs->buf_dma_attr.dma_attr_maxxfer) {
5325 			AACDB_PRINT(softs, CE_NOTE,
5326 			    "large xfer size received %d\n", acp->bcount);
5327 			bioerr = EINVAL;
5328 			goto error_out;
5329 		}
5330 
5331 		acp->total_xfer += acp->bcount;
5332 
5333 		if (acp->pkt) {
5334 			/* Return remaining byte count */
5335 			if (acp->total_xfer <= bp->b_bcount) {
5336 				acp->pkt->pkt_resid = bp->b_bcount - \
5337 				    acp->total_xfer;
5338 			} else {
5339 				/*
5340 				 * Allocated DMA size is greater than the buf
5341 				 * size of bp. This is caused by devices like
5342 				 * tape. we have extra bytes allocated, but
5343 				 * the packet residual has to stay correct.
5344 				 */
5345 				acp->pkt->pkt_resid = 0;
5346 			}
5347 			AACDB_PRINT_TRAN(softs,
5348 			    "bp=0x%p, xfered=%d/%d, resid=%d",
5349 			    (void *)bp->b_un.b_addr, (int)acp->total_xfer,
5350 			    (int)bp->b_bcount, (int)acp->pkt->pkt_resid);
5351 		}
5352 	}
5353 	return (AACOK);
5354 
5355 error_out:
5356 	bioerror(bp, bioerr);
5357 	return (AACERR);
5358 }
5359 
5360 static struct scsi_pkt *
5361 aac_tran_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
5362     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
5363     int (*callback)(), caddr_t arg)
5364 {
5365 	struct aac_softstate *softs = AAC_TRAN2SOFTS(ap->a_hba_tran);
5366 	struct aac_cmd *acp, *new_acp;
5367 
5368 	DBCALLED(softs, 2);
5369 
5370 	/* Allocate pkt */
5371 	if (pkt == NULL) {
5372 		int slen;
5373 
5374 		/* Force auto request sense */
5375 		slen = (statuslen > softs->slen) ? statuslen : softs->slen;
5376 		pkt = scsi_hba_pkt_alloc(softs->devinfo_p, ap, cmdlen,
5377 		    slen, tgtlen, sizeof (struct aac_cmd), callback, arg);
5378 		if (pkt == NULL) {
5379 			AACDB_PRINT(softs, CE_WARN, "Alloc scsi pkt failed");
5380 			return (NULL);
5381 		}
5382 		acp = new_acp = PKT2AC(pkt);
5383 		acp->pkt = pkt;
5384 		acp->cmdlen = cmdlen;
5385 
5386 		if (ap->a_target < AAC_MAX_LD) {
5387 			acp->dvp = &softs->containers[ap->a_target].dev;
5388 			acp->aac_cmd_fib = softs->aac_cmd_fib;
5389 			acp->ac_comp = aac_ld_complete;
5390 		} else {
5391 			_NOTE(ASSUMING_PROTECTED(softs->nondasds))
5392 
5393 			acp->dvp = &softs->nondasds[AAC_PD(ap->a_target)].dev;
5394 			acp->aac_cmd_fib = softs->aac_cmd_fib_scsi;
5395 			acp->ac_comp = aac_pd_complete;
5396 		}
5397 	} else {
5398 		acp = PKT2AC(pkt);
5399 		new_acp = NULL;
5400 	}
5401 
5402 	if (aac_cmd_dma_alloc(softs, acp, bp, flags, callback, arg) == AACOK)
5403 		return (pkt);
5404 
5405 	if (new_acp)
5406 		aac_tran_destroy_pkt(ap, pkt);
5407 	return (NULL);
5408 }
5409 
5410 /*
5411  * tran_sync_pkt(9E) - explicit DMA synchronization
5412  */
5413 /*ARGSUSED*/
5414 static void
5415 aac_tran_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
5416 {
5417 	struct aac_cmd *acp = PKT2AC(pkt);
5418 
5419 	DBCALLED(NULL, 2);
5420 
5421 	if (aac_dma_sync_ac(acp) != AACOK)
5422 		ddi_fm_service_impact(
5423 		    (AAC_TRAN2SOFTS(ap->a_hba_tran))->devinfo_p,
5424 		    DDI_SERVICE_UNAFFECTED);
5425 }
5426 
5427 /*
5428  * tran_dmafree(9E) - deallocate DMA resources allocated for command
5429  */
5430 /*ARGSUSED*/
5431 static void
5432 aac_tran_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
5433 {
5434 	struct aac_cmd *acp = PKT2AC(pkt);
5435 
5436 	DBCALLED(NULL, 2);
5437 
5438 	aac_free_dmamap(acp);
5439 }
5440 
5441 static int
5442 aac_do_quiesce(struct aac_softstate *softs)
5443 {
5444 	aac_hold_bus(softs, AAC_IOCMD_ASYNC);
5445 	if (softs->bus_ncmds[AAC_CMDQ_ASYNC]) {
5446 		aac_start_drain(softs);
5447 		do {
5448 			if (cv_wait_sig(&softs->drain_cv,
5449 			    &softs->io_lock) == 0) {
5450 				/* Quiesce has been interrupted */
5451 				aac_stop_drain(softs);
5452 				aac_unhold_bus(softs, AAC_IOCMD_ASYNC);
5453 				aac_start_waiting_io(softs);
5454 				return (AACERR);
5455 			}
5456 		} while (softs->bus_ncmds[AAC_CMDQ_ASYNC]);
5457 		aac_stop_drain(softs);
5458 	}
5459 
5460 	softs->state |= AAC_STATE_QUIESCED;
5461 	return (AACOK);
5462 }
5463 
5464 static int
5465 aac_tran_quiesce(dev_info_t *dip)
5466 {
5467 	struct aac_softstate *softs = AAC_DIP2SOFTS(dip);
5468 	int rval;
5469 
5470 	DBCALLED(softs, 1);
5471 
5472 	mutex_enter(&softs->io_lock);
5473 	if (aac_do_quiesce(softs) == AACOK)
5474 		rval = 0;
5475 	else
5476 		rval = 1;
5477 	mutex_exit(&softs->io_lock);
5478 	return (rval);
5479 }
5480 
5481 static int
5482 aac_do_unquiesce(struct aac_softstate *softs)
5483 {
5484 	softs->state &= ~AAC_STATE_QUIESCED;
5485 	aac_unhold_bus(softs, AAC_IOCMD_ASYNC);
5486 
5487 	aac_start_waiting_io(softs);
5488 	return (AACOK);
5489 }
5490 
5491 static int
5492 aac_tran_unquiesce(dev_info_t *dip)
5493 {
5494 	struct aac_softstate *softs = AAC_DIP2SOFTS(dip);
5495 	int rval;
5496 
5497 	DBCALLED(softs, 1);
5498 
5499 	mutex_enter(&softs->io_lock);
5500 	if (aac_do_unquiesce(softs) == AACOK)
5501 		rval = 0;
5502 	else
5503 		rval = 1;
5504 	mutex_exit(&softs->io_lock);
5505 	return (rval);
5506 }
5507 
5508 static int
5509 aac_hba_setup(struct aac_softstate *softs)
5510 {
5511 	scsi_hba_tran_t *hba_tran;
5512 	int rval;
5513 
5514 	hba_tran = scsi_hba_tran_alloc(softs->devinfo_p, SCSI_HBA_CANSLEEP);
5515 	if (hba_tran == NULL)
5516 		return (AACERR);
5517 	hba_tran->tran_hba_private = softs;
5518 	hba_tran->tran_tgt_init = aac_tran_tgt_init;
5519 	hba_tran->tran_tgt_free = aac_tran_tgt_free;
5520 	hba_tran->tran_tgt_probe = scsi_hba_probe;
5521 	hba_tran->tran_start = aac_tran_start;
5522 	hba_tran->tran_getcap = aac_tran_getcap;
5523 	hba_tran->tran_setcap = aac_tran_setcap;
5524 	hba_tran->tran_init_pkt = aac_tran_init_pkt;
5525 	hba_tran->tran_destroy_pkt = aac_tran_destroy_pkt;
5526 	hba_tran->tran_reset = aac_tran_reset;
5527 	hba_tran->tran_abort = aac_tran_abort;
5528 	hba_tran->tran_sync_pkt = aac_tran_sync_pkt;
5529 	hba_tran->tran_dmafree = aac_tran_dmafree;
5530 	hba_tran->tran_quiesce = aac_tran_quiesce;
5531 	hba_tran->tran_unquiesce = aac_tran_unquiesce;
5532 	hba_tran->tran_bus_config = aac_tran_bus_config;
5533 	rval = scsi_hba_attach_setup(softs->devinfo_p, &softs->buf_dma_attr,
5534 	    hba_tran, 0);
5535 	if (rval != DDI_SUCCESS) {
5536 		scsi_hba_tran_free(hba_tran);
5537 		AACDB_PRINT(softs, CE_WARN, "aac_hba_setup failed");
5538 		return (AACERR);
5539 	}
5540 
5541 	softs->hba_tran = hba_tran;
5542 	return (AACOK);
5543 }
5544 
5545 /*
5546  * FIB setup operations
5547  */
5548 
5549 /*
5550  * Init FIB header
5551  */
5552 static void
5553 aac_cmd_fib_header(struct aac_softstate *softs, struct aac_cmd *acp,
5554     uint16_t cmd)
5555 {
5556 	struct aac_slot *slotp = acp->slotp;
5557 	ddi_acc_handle_t acc = slotp->fib_acc_handle;
5558 	struct aac_fib *fibp = slotp->fibp;
5559 	uint32_t xfer_state;
5560 
5561 	xfer_state =
5562 	    AAC_FIBSTATE_HOSTOWNED |
5563 	    AAC_FIBSTATE_INITIALISED |
5564 	    AAC_FIBSTATE_EMPTY |
5565 	    AAC_FIBSTATE_FAST_RESPONSE | /* enable fast io */
5566 	    AAC_FIBSTATE_FROMHOST |
5567 	    AAC_FIBSTATE_REXPECTED |
5568 	    AAC_FIBSTATE_NORM;
5569 
5570 	if (!(acp->flags & AAC_CMD_SYNC))
5571 		xfer_state |= AAC_FIBSTATE_ASYNC;
5572 
5573 	ddi_put32(acc, &fibp->Header.XferState, xfer_state);
5574 	ddi_put16(acc, &fibp->Header.Command, cmd);
5575 	ddi_put8(acc, &fibp->Header.StructType, AAC_FIBTYPE_TFIB);
5576 	ddi_put8(acc, &fibp->Header.Flags, 0); /* don't care */
5577 	ddi_put16(acc, &fibp->Header.Size, acp->fib_size);
5578 	ddi_put16(acc, &fibp->Header.SenderSize, softs->aac_max_fib_size);
5579 	ddi_put32(acc, &fibp->Header.SenderFibAddress, (slotp->index << 2));
5580 	ddi_put32(acc, &fibp->Header.ReceiverFibAddress, slotp->fib_phyaddr);
5581 	ddi_put32(acc, &fibp->Header.SenderData, 0); /* don't care */
5582 }
5583 
5584 /*
5585  * Init FIB for raw IO command
5586  */
5587 static void
5588 aac_cmd_fib_rawio(struct aac_softstate *softs, struct aac_cmd *acp)
5589 {
5590 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5591 	struct aac_raw_io *io = (struct aac_raw_io *)&acp->slotp->fibp->data[0];
5592 	struct aac_sg_entryraw *sgp;
5593 	struct aac_sge *sge;
5594 
5595 	/* Calculate FIB size */
5596 	acp->fib_size = sizeof (struct aac_fib_header) + \
5597 	    sizeof (struct aac_raw_io) + (acp->left_cookien - 1) * \
5598 	    sizeof (struct aac_sg_entryraw);
5599 
5600 	aac_cmd_fib_header(softs, acp, RawIo);
5601 
5602 	ddi_put16(acc, &io->Flags, (acp->flags & AAC_CMD_BUF_READ) ? 1 : 0);
5603 	ddi_put16(acc, &io->BpTotal, 0);
5604 	ddi_put16(acc, &io->BpComplete, 0);
5605 
5606 	ddi_put32(acc, AAC_LO32(&io->BlockNumber), AAC_LS32(acp->blkno));
5607 	ddi_put32(acc, AAC_HI32(&io->BlockNumber), AAC_MS32(acp->blkno));
5608 	ddi_put16(acc, &io->ContainerId,
5609 	    ((struct aac_container *)acp->dvp)->cid);
5610 
5611 	/* Fill SG table */
5612 	ddi_put32(acc, &io->SgMapRaw.SgCount, acp->left_cookien);
5613 	ddi_put32(acc, &io->ByteCount, acp->bcount);
5614 
5615 	for (sge = &acp->sgt[0], sgp = &io->SgMapRaw.SgEntryRaw[0];
5616 	    sge < &acp->sgt[acp->left_cookien]; sge++, sgp++) {
5617 		ddi_put32(acc, AAC_LO32(&sgp->SgAddress), sge->addr.ad64.lo);
5618 		ddi_put32(acc, AAC_HI32(&sgp->SgAddress), sge->addr.ad64.hi);
5619 		ddi_put32(acc, &sgp->SgByteCount, sge->bcount);
5620 		sgp->Next = 0;
5621 		sgp->Prev = 0;
5622 		sgp->Flags = 0;
5623 	}
5624 }
5625 
5626 /* Init FIB for 64-bit block IO command */
5627 static void
5628 aac_cmd_fib_brw64(struct aac_softstate *softs, struct aac_cmd *acp)
5629 {
5630 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5631 	struct aac_blockread64 *br = (struct aac_blockread64 *) \
5632 	    &acp->slotp->fibp->data[0];
5633 	struct aac_sg_entry64 *sgp;
5634 	struct aac_sge *sge;
5635 
5636 	acp->fib_size = sizeof (struct aac_fib_header) + \
5637 	    sizeof (struct aac_blockread64) + (acp->left_cookien - 1) * \
5638 	    sizeof (struct aac_sg_entry64);
5639 
5640 	aac_cmd_fib_header(softs, acp, ContainerCommand64);
5641 
5642 	/*
5643 	 * The definitions for aac_blockread64 and aac_blockwrite64
5644 	 * are the same.
5645 	 */
5646 	ddi_put32(acc, &br->BlockNumber, (uint32_t)acp->blkno);
5647 	ddi_put16(acc, &br->ContainerId,
5648 	    ((struct aac_container *)acp->dvp)->cid);
5649 	ddi_put32(acc, &br->Command, (acp->flags & AAC_CMD_BUF_READ) ?
5650 	    VM_CtHostRead64 : VM_CtHostWrite64);
5651 	ddi_put16(acc, &br->Pad, 0);
5652 	ddi_put16(acc, &br->Flags, 0);
5653 
5654 	/* Fill SG table */
5655 	ddi_put32(acc, &br->SgMap64.SgCount, acp->left_cookien);
5656 	ddi_put16(acc, &br->SectorCount, acp->bcount / AAC_BLK_SIZE);
5657 
5658 	for (sge = &acp->sgt[0], sgp = &br->SgMap64.SgEntry64[0];
5659 	    sge < &acp->sgt[acp->left_cookien]; sge++, sgp++) {
5660 		ddi_put32(acc, AAC_LO32(&sgp->SgAddress), sge->addr.ad64.lo);
5661 		ddi_put32(acc, AAC_HI32(&sgp->SgAddress), sge->addr.ad64.hi);
5662 		ddi_put32(acc, &sgp->SgByteCount, sge->bcount);
5663 	}
5664 }
5665 
5666 /* Init FIB for block IO command */
5667 static void
5668 aac_cmd_fib_brw(struct aac_softstate *softs, struct aac_cmd *acp)
5669 {
5670 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5671 	struct aac_blockread *br = (struct aac_blockread *) \
5672 	    &acp->slotp->fibp->data[0];
5673 	struct aac_sg_entry *sgp;
5674 	struct aac_sge *sge = &acp->sgt[0];
5675 
5676 	if (acp->flags & AAC_CMD_BUF_READ) {
5677 		acp->fib_size = sizeof (struct aac_fib_header) + \
5678 		    sizeof (struct aac_blockread) + (acp->left_cookien - 1) * \
5679 		    sizeof (struct aac_sg_entry);
5680 
5681 		ddi_put32(acc, &br->Command, VM_CtBlockRead);
5682 		ddi_put32(acc, &br->SgMap.SgCount, acp->left_cookien);
5683 		sgp = &br->SgMap.SgEntry[0];
5684 	} else {
5685 		struct aac_blockwrite *bw = (struct aac_blockwrite *)br;
5686 
5687 		acp->fib_size = sizeof (struct aac_fib_header) + \
5688 		    sizeof (struct aac_blockwrite) + (acp->left_cookien - 1) * \
5689 		    sizeof (struct aac_sg_entry);
5690 
5691 		ddi_put32(acc, &bw->Command, VM_CtBlockWrite);
5692 		ddi_put32(acc, &bw->Stable, CUNSTABLE);
5693 		ddi_put32(acc, &bw->SgMap.SgCount, acp->left_cookien);
5694 		sgp = &bw->SgMap.SgEntry[0];
5695 	}
5696 	aac_cmd_fib_header(softs, acp, ContainerCommand);
5697 
5698 	/*
5699 	 * aac_blockread and aac_blockwrite have the similar
5700 	 * structure head, so use br for bw here
5701 	 */
5702 	ddi_put32(acc, &br->BlockNumber, (uint32_t)acp->blkno);
5703 	ddi_put32(acc, &br->ContainerId,
5704 	    ((struct aac_container *)acp->dvp)->cid);
5705 	ddi_put32(acc, &br->ByteCount, acp->bcount);
5706 
5707 	/* Fill SG table */
5708 	for (sge = &acp->sgt[0];
5709 	    sge < &acp->sgt[acp->left_cookien]; sge++, sgp++) {
5710 		ddi_put32(acc, &sgp->SgAddress, sge->addr.ad32);
5711 		ddi_put32(acc, &sgp->SgByteCount, sge->bcount);
5712 	}
5713 }
5714 
5715 /*ARGSUSED*/
5716 void
5717 aac_cmd_fib_copy(struct aac_softstate *softs, struct aac_cmd *acp)
5718 {
5719 	struct aac_slot *slotp = acp->slotp;
5720 	struct aac_fib *fibp = slotp->fibp;
5721 	ddi_acc_handle_t acc = slotp->fib_acc_handle;
5722 
5723 	ddi_rep_put8(acc, (uint8_t *)acp->fibp, (uint8_t *)fibp,
5724 	    acp->fib_size,   /* only copy data of needed length */
5725 	    DDI_DEV_AUTOINCR);
5726 	ddi_put32(acc, &fibp->Header.ReceiverFibAddress, slotp->fib_phyaddr);
5727 	ddi_put32(acc, &fibp->Header.SenderFibAddress, slotp->index << 2);
5728 }
5729 
5730 static void
5731 aac_cmd_fib_sync(struct aac_softstate *softs, struct aac_cmd *acp)
5732 {
5733 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5734 	struct aac_synchronize_command *sync =
5735 	    (struct aac_synchronize_command *)&acp->slotp->fibp->data[0];
5736 
5737 	acp->fib_size = AAC_FIB_SIZEOF(struct aac_synchronize_command);
5738 
5739 	aac_cmd_fib_header(softs, acp, ContainerCommand);
5740 	ddi_put32(acc, &sync->Command, VM_ContainerConfig);
5741 	ddi_put32(acc, &sync->Type, (uint32_t)CT_FLUSH_CACHE);
5742 	ddi_put32(acc, &sync->Cid, ((struct aac_container *)acp->dvp)->cid);
5743 	ddi_put32(acc, &sync->Count,
5744 	    sizeof (((struct aac_synchronize_reply *)0)->Data));
5745 }
5746 
5747 /*
5748  * Start/Stop unit (Power Management)
5749  */
5750 static void
5751 aac_cmd_fib_startstop(struct aac_softstate *softs, struct aac_cmd *acp)
5752 {
5753 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5754 	struct aac_Container *cmd =
5755 	    (struct aac_Container *)&acp->slotp->fibp->data[0];
5756 	union scsi_cdb *cdbp = (void *)acp->pkt->pkt_cdbp;
5757 
5758 	acp->fib_size = AAC_FIB_SIZEOF(struct aac_Container);
5759 
5760 	aac_cmd_fib_header(softs, acp, ContainerCommand);
5761 	bzero(cmd, sizeof (*cmd) - CT_PACKET_SIZE);
5762 	ddi_put32(acc, &cmd->Command, VM_ContainerConfig);
5763 	ddi_put32(acc, &cmd->CTCommand.command, CT_PM_DRIVER_SUPPORT);
5764 	ddi_put32(acc, &cmd->CTCommand.param[0], cdbp->cdb_opaque[4] & 1 ? \
5765 	    AAC_PM_DRIVERSUP_START_UNIT : AAC_PM_DRIVERSUP_STOP_UNIT);
5766 	ddi_put32(acc, &cmd->CTCommand.param[1],
5767 	    ((struct aac_container *)acp->dvp)->cid);
5768 	ddi_put32(acc, &cmd->CTCommand.param[2], cdbp->cdb_opaque[1] & 1);
5769 }
5770 
5771 /*
5772  * Init FIB for pass-through SCMD
5773  */
5774 static void
5775 aac_cmd_fib_srb(struct aac_cmd *acp)
5776 {
5777 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5778 	struct aac_srb *srb = (struct aac_srb *)&acp->slotp->fibp->data[0];
5779 	uint8_t *cdb;
5780 
5781 	ddi_put32(acc, &srb->function, SRBF_ExecuteScsi);
5782 	ddi_put32(acc, &srb->retry_limit, 0);
5783 	ddi_put32(acc, &srb->cdb_size, acp->cmdlen);
5784 	ddi_put32(acc, &srb->timeout, 0); /* use driver timeout */
5785 	if (acp->fibp == NULL) {
5786 		if (acp->flags & AAC_CMD_BUF_READ)
5787 			ddi_put32(acc, &srb->flags, SRB_DataIn);
5788 		else if (acp->flags & AAC_CMD_BUF_WRITE)
5789 			ddi_put32(acc, &srb->flags, SRB_DataOut);
5790 		ddi_put32(acc, &srb->channel,
5791 		    ((struct aac_nondasd *)acp->dvp)->bus);
5792 		ddi_put32(acc, &srb->id, ((struct aac_nondasd *)acp->dvp)->tid);
5793 		ddi_put32(acc, &srb->lun, 0);
5794 		cdb = acp->pkt->pkt_cdbp;
5795 	} else {
5796 		struct aac_srb *srb0 = (struct aac_srb *)&acp->fibp->data[0];
5797 
5798 		ddi_put32(acc, &srb->flags, srb0->flags);
5799 		ddi_put32(acc, &srb->channel, srb0->channel);
5800 		ddi_put32(acc, &srb->id, srb0->id);
5801 		ddi_put32(acc, &srb->lun, srb0->lun);
5802 		cdb = srb0->cdb;
5803 	}
5804 	ddi_rep_put8(acc, cdb, srb->cdb, acp->cmdlen, DDI_DEV_AUTOINCR);
5805 }
5806 
5807 static void
5808 aac_cmd_fib_scsi32(struct aac_softstate *softs, struct aac_cmd *acp)
5809 {
5810 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5811 	struct aac_srb *srb = (struct aac_srb *)&acp->slotp->fibp->data[0];
5812 	struct aac_sg_entry *sgp;
5813 	struct aac_sge *sge;
5814 
5815 	acp->fib_size = sizeof (struct aac_fib_header) + \
5816 	    sizeof (struct aac_srb) - sizeof (struct aac_sg_entry) + \
5817 	    acp->left_cookien * sizeof (struct aac_sg_entry);
5818 
5819 	/* Fill FIB and SRB headers, and copy cdb */
5820 	aac_cmd_fib_header(softs, acp, ScsiPortCommand);
5821 	aac_cmd_fib_srb(acp);
5822 
5823 	/* Fill SG table */
5824 	ddi_put32(acc, &srb->sg.SgCount, acp->left_cookien);
5825 	ddi_put32(acc, &srb->count, acp->bcount);
5826 
5827 	for (sge = &acp->sgt[0], sgp = &srb->sg.SgEntry[0];
5828 	    sge < &acp->sgt[acp->left_cookien]; sge++, sgp++) {
5829 		ddi_put32(acc, &sgp->SgAddress, sge->addr.ad32);
5830 		ddi_put32(acc, &sgp->SgByteCount, sge->bcount);
5831 	}
5832 }
5833 
5834 static void
5835 aac_cmd_fib_scsi64(struct aac_softstate *softs, struct aac_cmd *acp)
5836 {
5837 	ddi_acc_handle_t acc = acp->slotp->fib_acc_handle;
5838 	struct aac_srb *srb = (struct aac_srb *)&acp->slotp->fibp->data[0];
5839 	struct aac_sg_entry64 *sgp;
5840 	struct aac_sge *sge;
5841 
5842 	acp->fib_size = sizeof (struct aac_fib_header) + \
5843 	    sizeof (struct aac_srb) - sizeof (struct aac_sg_entry) + \
5844 	    acp->left_cookien * sizeof (struct aac_sg_entry64);
5845 
5846 	/* Fill FIB and SRB headers, and copy cdb */
5847 	aac_cmd_fib_header(softs, acp, ScsiPortCommandU64);
5848 	aac_cmd_fib_srb(acp);
5849 
5850 	/* Fill SG table */
5851 	ddi_put32(acc, &srb->sg.SgCount, acp->left_cookien);
5852 	ddi_put32(acc, &srb->count, acp->bcount);
5853 
5854 	for (sge = &acp->sgt[0],
5855 	    sgp = &((struct aac_sg_table64 *)&srb->sg)->SgEntry64[0];
5856 	    sge < &acp->sgt[acp->left_cookien]; sge++, sgp++) {
5857 		ddi_put32(acc, AAC_LO32(&sgp->SgAddress), sge->addr.ad64.lo);
5858 		ddi_put32(acc, AAC_HI32(&sgp->SgAddress), sge->addr.ad64.hi);
5859 		ddi_put32(acc, &sgp->SgByteCount, sge->bcount);
5860 	}
5861 }
5862 
5863 static int
5864 aac_cmd_slot_bind(struct aac_softstate *softs, struct aac_cmd *acp)
5865 {
5866 	struct aac_slot *slotp;
5867 
5868 	if (slotp = aac_get_slot(softs)) {
5869 		acp->slotp = slotp;
5870 		slotp->acp = acp;
5871 		acp->aac_cmd_fib(softs, acp);
5872 		(void) ddi_dma_sync(slotp->fib_dma_handle, 0, 0,
5873 		    DDI_DMA_SYNC_FORDEV);
5874 		return (AACOK);
5875 	}
5876 	return (AACERR);
5877 }
5878 
5879 static int
5880 aac_bind_io(struct aac_softstate *softs, struct aac_cmd *acp)
5881 {
5882 	struct aac_device *dvp = acp->dvp;
5883 	int q = AAC_CMDQ(acp);
5884 
5885 	if (softs->bus_ncmds[q] < softs->bus_throttle[q]) {
5886 		if (dvp) {
5887 			if (dvp->ncmds[q] < dvp->throttle[q]) {
5888 				if (!(acp->flags & AAC_CMD_NTAG) ||
5889 				    dvp->ncmds[q] == 0) {
5890 					return (aac_cmd_slot_bind(softs, acp));
5891 				}
5892 				ASSERT(q == AAC_CMDQ_ASYNC);
5893 				aac_set_throttle(softs, dvp, AAC_CMDQ_ASYNC,
5894 				    AAC_THROTTLE_DRAIN);
5895 			}
5896 		} else {
5897 			return (aac_cmd_slot_bind(softs, acp));
5898 		}
5899 	}
5900 	return (AACERR);
5901 }
5902 
5903 static int
5904 aac_sync_fib_slot_bind(struct aac_softstate *softs, struct aac_cmd *acp)
5905 {
5906 	struct aac_slot *slotp;
5907 
5908 	while (softs->sync_ac.slotp)
5909 		cv_wait(&softs->sync_fib_cv, &softs->io_lock);
5910 
5911 	if (slotp = aac_get_slot(softs)) {
5912 		ASSERT(acp->slotp == NULL);
5913 
5914 		acp->slotp = slotp;
5915 		slotp->acp = acp;
5916 		return (AACOK);
5917 	}
5918 	return (AACERR);
5919 }
5920 
5921 static void
5922 aac_sync_fib_slot_release(struct aac_softstate *softs, struct aac_cmd *acp)
5923 {
5924 	ASSERT(acp->slotp);
5925 
5926 	aac_release_slot(softs, acp->slotp);
5927 	acp->slotp->acp = NULL;
5928 	acp->slotp = NULL;
5929 
5930 	cv_signal(&softs->sync_fib_cv);
5931 }
5932 
5933 static void
5934 aac_start_io(struct aac_softstate *softs, struct aac_cmd *acp)
5935 {
5936 	struct aac_slot *slotp = acp->slotp;
5937 	int q = AAC_CMDQ(acp);
5938 	int rval;
5939 
5940 	/* Set ac and pkt */
5941 	if (acp->pkt) { /* ac from ioctl has no pkt */
5942 		acp->pkt->pkt_state |=
5943 		    STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD;
5944 	}
5945 	if (acp->timeout) /* 0 indicates no timeout */
5946 		acp->timeout += aac_timebase + aac_tick;
5947 
5948 	if (acp->dvp)
5949 		acp->dvp->ncmds[q]++;
5950 	softs->bus_ncmds[q]++;
5951 	aac_cmd_enqueue(&softs->q_busy, acp);
5952 
5953 	AACDB_PRINT_FIB(softs, slotp);
5954 
5955 	if (softs->flags & AAC_FLAGS_NEW_COMM) {
5956 		rval = aac_send_command(softs, slotp);
5957 	} else {
5958 		/*
5959 		 * If fib can not be enqueued, the adapter is in an abnormal
5960 		 * state, there will be no interrupt to us.
5961 		 */
5962 		rval = aac_fib_enqueue(softs, AAC_ADAP_NORM_CMD_Q,
5963 		    slotp->fib_phyaddr, acp->fib_size);
5964 	}
5965 
5966 	if (aac_check_dma_handle(slotp->fib_dma_handle) != DDI_SUCCESS)
5967 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_UNAFFECTED);
5968 
5969 	/*
5970 	 * NOTE: We send command only when slots availabe, so should never
5971 	 * reach here.
5972 	 */
5973 	if (rval != AACOK) {
5974 		AACDB_PRINT(softs, CE_NOTE, "SCMD send failed");
5975 		if (acp->pkt) {
5976 			acp->pkt->pkt_state &= ~STATE_SENT_CMD;
5977 			aac_set_pkt_reason(softs, acp, CMD_INCOMPLETE, 0);
5978 		}
5979 		aac_end_io(softs, acp);
5980 		if (!(acp->flags & (AAC_CMD_NO_INTR | AAC_CMD_NO_CB)))
5981 			ddi_trigger_softintr(softs->softint_id);
5982 	}
5983 }
5984 
5985 static void
5986 aac_start_waitq(struct aac_softstate *softs, struct aac_cmd_queue *q)
5987 {
5988 	struct aac_cmd *acp, *next_acp;
5989 
5990 	/* Serve as many waiting io's as possible */
5991 	for (acp = q->q_head; acp; acp = next_acp) {
5992 		next_acp = acp->next;
5993 		if (aac_bind_io(softs, acp) == AACOK) {
5994 			aac_cmd_delete(q, acp);
5995 			aac_start_io(softs, acp);
5996 		}
5997 		if (softs->free_io_slot_head == NULL)
5998 			break;
5999 	}
6000 }
6001 
6002 static void
6003 aac_start_waiting_io(struct aac_softstate *softs)
6004 {
6005 	/*
6006 	 * Sync FIB io is served before async FIB io so that io requests
6007 	 * sent by interactive userland commands get responded asap.
6008 	 */
6009 	if (softs->q_wait[AAC_CMDQ_SYNC].q_head)
6010 		aac_start_waitq(softs, &softs->q_wait[AAC_CMDQ_SYNC]);
6011 	if (softs->q_wait[AAC_CMDQ_ASYNC].q_head)
6012 		aac_start_waitq(softs, &softs->q_wait[AAC_CMDQ_ASYNC]);
6013 }
6014 
6015 static void
6016 aac_drain_comp_q(struct aac_softstate *softs)
6017 {
6018 	struct aac_cmd *acp;
6019 	struct scsi_pkt *pkt;
6020 
6021 	/*CONSTCOND*/
6022 	while (1) {
6023 		mutex_enter(&softs->q_comp_mutex);
6024 		acp = aac_cmd_dequeue(&softs->q_comp);
6025 		mutex_exit(&softs->q_comp_mutex);
6026 		if (acp != NULL) {
6027 			ASSERT(acp->pkt != NULL);
6028 			pkt = acp->pkt;
6029 
6030 			if (pkt->pkt_reason == CMD_CMPLT) {
6031 				/*
6032 				 * Consistent packets need to be sync'ed first
6033 				 */
6034 				if ((acp->flags & AAC_CMD_CONSISTENT) &&
6035 				    (acp->flags & AAC_CMD_BUF_READ)) {
6036 					if (aac_dma_sync_ac(acp) != AACOK) {
6037 						ddi_fm_service_impact(
6038 						    softs->devinfo_p,
6039 						    DDI_SERVICE_UNAFFECTED);
6040 						pkt->pkt_reason = CMD_TRAN_ERR;
6041 						pkt->pkt_statistics = 0;
6042 					}
6043 				}
6044 				if ((aac_check_acc_handle(softs-> \
6045 				    comm_space_acc_handle) != DDI_SUCCESS) ||
6046 				    (aac_check_acc_handle(softs-> \
6047 				    pci_mem_handle) != DDI_SUCCESS)) {
6048 					ddi_fm_service_impact(softs->devinfo_p,
6049 					    DDI_SERVICE_UNAFFECTED);
6050 					ddi_fm_acc_err_clear(softs-> \
6051 					    pci_mem_handle, DDI_FME_VER0);
6052 					pkt->pkt_reason = CMD_TRAN_ERR;
6053 					pkt->pkt_statistics = 0;
6054 				}
6055 				if (aac_check_dma_handle(softs-> \
6056 				    comm_space_dma_handle) != DDI_SUCCESS) {
6057 					ddi_fm_service_impact(softs->devinfo_p,
6058 					    DDI_SERVICE_UNAFFECTED);
6059 					pkt->pkt_reason = CMD_TRAN_ERR;
6060 					pkt->pkt_statistics = 0;
6061 				}
6062 			}
6063 			scsi_hba_pkt_comp(pkt);
6064 		} else {
6065 			break;
6066 		}
6067 	}
6068 }
6069 
6070 static int
6071 aac_alloc_fib(struct aac_softstate *softs, struct aac_slot *slotp)
6072 {
6073 	size_t rlen;
6074 	ddi_dma_cookie_t cookie;
6075 	uint_t cookien;
6076 
6077 	/* Allocate FIB dma resource */
6078 	if (ddi_dma_alloc_handle(
6079 	    softs->devinfo_p,
6080 	    &softs->addr_dma_attr,
6081 	    DDI_DMA_SLEEP,
6082 	    NULL,
6083 	    &slotp->fib_dma_handle) != DDI_SUCCESS) {
6084 		AACDB_PRINT(softs, CE_WARN,
6085 		    "Cannot alloc dma handle for slot fib area");
6086 		goto error;
6087 	}
6088 	if (ddi_dma_mem_alloc(
6089 	    slotp->fib_dma_handle,
6090 	    softs->aac_max_fib_size,
6091 	    &softs->acc_attr,
6092 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
6093 	    DDI_DMA_SLEEP,
6094 	    NULL,
6095 	    (caddr_t *)&slotp->fibp,
6096 	    &rlen,
6097 	    &slotp->fib_acc_handle) != DDI_SUCCESS) {
6098 		AACDB_PRINT(softs, CE_WARN,
6099 		    "Cannot alloc mem for slot fib area");
6100 		goto error;
6101 	}
6102 	if (ddi_dma_addr_bind_handle(
6103 	    slotp->fib_dma_handle,
6104 	    NULL,
6105 	    (caddr_t)slotp->fibp,
6106 	    softs->aac_max_fib_size,
6107 	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
6108 	    DDI_DMA_SLEEP,
6109 	    NULL,
6110 	    &cookie,
6111 	    &cookien) != DDI_DMA_MAPPED) {
6112 		AACDB_PRINT(softs, CE_WARN,
6113 		    "dma bind failed for slot fib area");
6114 		goto error;
6115 	}
6116 
6117 	/* Check dma handles allocated in fib attach */
6118 	if (aac_check_dma_handle(slotp->fib_dma_handle) != DDI_SUCCESS) {
6119 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
6120 		goto error;
6121 	}
6122 
6123 	/* Check acc handles allocated in fib attach */
6124 	if (aac_check_acc_handle(slotp->fib_acc_handle) != DDI_SUCCESS) {
6125 		ddi_fm_service_impact(softs->devinfo_p, DDI_SERVICE_LOST);
6126 		goto error;
6127 	}
6128 
6129 	slotp->fib_phyaddr = cookie.dmac_laddress;
6130 	return (AACOK);
6131 
6132 error:
6133 	if (slotp->fib_acc_handle) {
6134 		ddi_dma_mem_free(&slotp->fib_acc_handle);
6135 		slotp->fib_acc_handle = NULL;
6136 	}
6137 	if (slotp->fib_dma_handle) {
6138 		ddi_dma_free_handle(&slotp->fib_dma_handle);
6139 		slotp->fib_dma_handle = NULL;
6140 	}
6141 	return (AACERR);
6142 }
6143 
6144 static void
6145 aac_free_fib(struct aac_slot *slotp)
6146 {
6147 	(void) ddi_dma_unbind_handle(slotp->fib_dma_handle);
6148 	ddi_dma_mem_free(&slotp->fib_acc_handle);
6149 	slotp->fib_acc_handle = NULL;
6150 	ddi_dma_free_handle(&slotp->fib_dma_handle);
6151 	slotp->fib_dma_handle = NULL;
6152 	slotp->fib_phyaddr = 0;
6153 }
6154 
6155 static void
6156 aac_alloc_fibs(struct aac_softstate *softs)
6157 {
6158 	int i;
6159 	struct aac_slot *slotp;
6160 
6161 	for (i = 0; i < softs->total_slots &&
6162 	    softs->total_fibs < softs->total_slots; i++) {
6163 		slotp = &(softs->io_slot[i]);
6164 		if (slotp->fib_phyaddr)
6165 			continue;
6166 		if (aac_alloc_fib(softs, slotp) != AACOK)
6167 			break;
6168 
6169 		/* Insert the slot to the free slot list */
6170 		aac_release_slot(softs, slotp);
6171 		softs->total_fibs++;
6172 	}
6173 }
6174 
6175 static void
6176 aac_destroy_fibs(struct aac_softstate *softs)
6177 {
6178 	struct aac_slot *slotp;
6179 
6180 	while ((slotp = softs->free_io_slot_head) != NULL) {
6181 		ASSERT(slotp->fib_phyaddr);
6182 		softs->free_io_slot_head = slotp->next;
6183 		aac_free_fib(slotp);
6184 		ASSERT(slotp->index == (slotp - softs->io_slot));
6185 		softs->total_fibs--;
6186 	}
6187 	ASSERT(softs->total_fibs == 0);
6188 }
6189 
6190 static int
6191 aac_create_slots(struct aac_softstate *softs)
6192 {
6193 	int i;
6194 
6195 	softs->total_slots = softs->aac_max_fibs;
6196 	softs->io_slot = kmem_zalloc(sizeof (struct aac_slot) * \
6197 	    softs->total_slots, KM_SLEEP);
6198 	if (softs->io_slot == NULL) {
6199 		AACDB_PRINT(softs, CE_WARN, "Cannot allocate slot");
6200 		return (AACERR);
6201 	}
6202 	for (i = 0; i < softs->total_slots; i++)
6203 		softs->io_slot[i].index = i;
6204 	softs->free_io_slot_head = NULL;
6205 	softs->total_fibs = 0;
6206 	return (AACOK);
6207 }
6208 
6209 static void
6210 aac_destroy_slots(struct aac_softstate *softs)
6211 {
6212 	ASSERT(softs->free_io_slot_head == NULL);
6213 
6214 	kmem_free(softs->io_slot, sizeof (struct aac_slot) * \
6215 	    softs->total_slots);
6216 	softs->io_slot = NULL;
6217 	softs->total_slots = 0;
6218 }
6219 
6220 struct aac_slot *
6221 aac_get_slot(struct aac_softstate *softs)
6222 {
6223 	struct aac_slot *slotp;
6224 
6225 	if ((slotp = softs->free_io_slot_head) != NULL) {
6226 		softs->free_io_slot_head = slotp->next;
6227 		slotp->next = NULL;
6228 	}
6229 	return (slotp);
6230 }
6231 
6232 static void
6233 aac_release_slot(struct aac_softstate *softs, struct aac_slot *slotp)
6234 {
6235 	ASSERT((slotp->index >= 0) && (slotp->index < softs->total_slots));
6236 	ASSERT(slotp == &softs->io_slot[slotp->index]);
6237 
6238 	slotp->acp = NULL;
6239 	slotp->next = softs->free_io_slot_head;
6240 	softs->free_io_slot_head = slotp;
6241 }
6242 
6243 int
6244 aac_do_io(struct aac_softstate *softs, struct aac_cmd *acp)
6245 {
6246 	if (aac_bind_io(softs, acp) == AACOK)
6247 		aac_start_io(softs, acp);
6248 	else
6249 		aac_cmd_enqueue(&softs->q_wait[AAC_CMDQ(acp)], acp);
6250 
6251 	if (!(acp->flags & (AAC_CMD_NO_CB | AAC_CMD_NO_INTR)))
6252 		return (TRAN_ACCEPT);
6253 	/*
6254 	 * Because sync FIB is always 512 bytes and used for critical
6255 	 * functions, async FIB is used for poll IO.
6256 	 */
6257 	if (acp->flags & AAC_CMD_NO_INTR) {
6258 		if (aac_do_poll_io(softs, acp) == AACOK)
6259 			return (TRAN_ACCEPT);
6260 	} else {
6261 		if (aac_do_sync_io(softs, acp) == AACOK)
6262 			return (TRAN_ACCEPT);
6263 	}
6264 	return (TRAN_BADPKT);
6265 }
6266 
6267 static int
6268 aac_do_poll_io(struct aac_softstate *softs, struct aac_cmd *acp)
6269 {
6270 	int (*intr_handler)(struct aac_softstate *);
6271 
6272 	/*
6273 	 * Interrupt is disabled, we have to poll the adapter by ourselves.
6274 	 */
6275 	intr_handler = (softs->flags & AAC_FLAGS_NEW_COMM) ?
6276 	    aac_process_intr_new : aac_process_intr_old;
6277 	while (!(acp->flags & (AAC_CMD_CMPLT | AAC_CMD_ABORT))) {
6278 		int i = AAC_POLL_TIME * 1000;
6279 
6280 		AAC_BUSYWAIT((intr_handler(softs) != AAC_DB_RESPONSE_READY), i);
6281 		if (i == 0)
6282 			aac_cmd_timeout(softs, acp);
6283 	}
6284 
6285 	ddi_trigger_softintr(softs->softint_id);
6286 
6287 	if ((acp->flags & AAC_CMD_CMPLT) && !(acp->flags & AAC_CMD_ERR))
6288 		return (AACOK);
6289 	return (AACERR);
6290 }
6291 
6292 static int
6293 aac_do_sync_io(struct aac_softstate *softs, struct aac_cmd *acp)
6294 {
6295 	ASSERT(softs && acp);
6296 
6297 	while (!(acp->flags & (AAC_CMD_CMPLT | AAC_CMD_ABORT)))
6298 		cv_wait(&softs->event, &softs->io_lock);
6299 
6300 	if (acp->flags & AAC_CMD_CMPLT)
6301 		return (AACOK);
6302 	return (AACERR);
6303 }
6304 
6305 static int
6306 aac_dma_sync_ac(struct aac_cmd *acp)
6307 {
6308 	if (acp->buf_dma_handle) {
6309 		if (acp->flags & AAC_CMD_BUF_WRITE) {
6310 			if (acp->abp != NULL)
6311 				ddi_rep_put8(acp->abh,
6312 				    (uint8_t *)acp->bp->b_un.b_addr,
6313 				    (uint8_t *)acp->abp, acp->bp->b_bcount,
6314 				    DDI_DEV_AUTOINCR);
6315 			(void) ddi_dma_sync(acp->buf_dma_handle, 0, 0,
6316 			    DDI_DMA_SYNC_FORDEV);
6317 		} else {
6318 			(void) ddi_dma_sync(acp->buf_dma_handle, 0, 0,
6319 			    DDI_DMA_SYNC_FORCPU);
6320 			if (aac_check_dma_handle(acp->buf_dma_handle) !=
6321 			    DDI_SUCCESS)
6322 				return (AACERR);
6323 			if (acp->abp != NULL)
6324 				ddi_rep_get8(acp->abh,
6325 				    (uint8_t *)acp->bp->b_un.b_addr,
6326 				    (uint8_t *)acp->abp, acp->bp->b_bcount,
6327 				    DDI_DEV_AUTOINCR);
6328 		}
6329 	}
6330 	return (AACOK);
6331 }
6332 
6333 /*
6334  * Copy AIF from adapter to the empty AIF slot and inform AIF threads
6335  */
6336 static void
6337 aac_save_aif(struct aac_softstate *softs, ddi_acc_handle_t acc,
6338     struct aac_fib *fibp0, int fib_size0)
6339 {
6340 	struct aac_fib *fibp;	/* FIB in AIF queue */
6341 	int fib_size;
6342 	uint16_t fib_command;
6343 	int current, next;
6344 
6345 	/* Ignore non AIF messages */
6346 	fib_command = ddi_get16(acc, &fibp0->Header.Command);
6347 	if (fib_command != AifRequest) {
6348 		cmn_err(CE_WARN, "!Unknown command from controller");
6349 		return;
6350 	}
6351 
6352 	mutex_enter(&softs->aifq_mutex);
6353 
6354 	/* Save AIF */
6355 	fibp = &softs->aifq[softs->aifq_idx].d;
6356 	fib_size = (fib_size0 > AAC_FIB_SIZE) ? AAC_FIB_SIZE : fib_size0;
6357 	ddi_rep_get8(acc, (uint8_t *)fibp, (uint8_t *)fibp0, fib_size,
6358 	    DDI_DEV_AUTOINCR);
6359 
6360 	if (aac_check_acc_handle(softs->pci_mem_handle) != DDI_SUCCESS) {
6361 		ddi_fm_service_impact(softs->devinfo_p,
6362 		    DDI_SERVICE_UNAFFECTED);
6363 		mutex_exit(&softs->aifq_mutex);
6364 		return;
6365 	}
6366 
6367 	AACDB_PRINT_AIF(softs, (struct aac_aif_command *)&fibp->data[0]);
6368 
6369 	/* Modify AIF contexts */
6370 	current = softs->aifq_idx;
6371 	next = (current + 1) % AAC_AIFQ_LENGTH;
6372 	if (next == 0) {
6373 		struct aac_fib_context *ctx_p;
6374 
6375 		softs->aifq_wrap = 1;
6376 		for (ctx_p = softs->fibctx_p; ctx_p; ctx_p = ctx_p->next) {
6377 			if (next == ctx_p->ctx_idx) {
6378 				ctx_p->ctx_flags |= AAC_CTXFLAG_FILLED;
6379 			} else if (current == ctx_p->ctx_idx &&
6380 			    (ctx_p->ctx_flags & AAC_CTXFLAG_FILLED)) {
6381 				ctx_p->ctx_idx = next;
6382 				ctx_p->ctx_overrun++;
6383 			}
6384 		}
6385 	}
6386 	softs->aifq_idx = next;
6387 
6388 	/* Wakeup AIF threads */
6389 	cv_broadcast(&softs->aifq_cv);
6390 	mutex_exit(&softs->aifq_mutex);
6391 
6392 	/* Wakeup event thread to handle aif */
6393 	aac_event_disp(softs, AAC_EVENT_AIF);
6394 }
6395 
6396 static int
6397 aac_return_aif_common(struct aac_softstate *softs, struct aac_fib_context *ctx,
6398     struct aac_fib **fibpp)
6399 {
6400 	int current;
6401 
6402 	current = ctx->ctx_idx;
6403 	if (current == softs->aifq_idx &&
6404 	    !(ctx->ctx_flags & AAC_CTXFLAG_FILLED))
6405 		return (EAGAIN); /* Empty */
6406 
6407 	*fibpp = &softs->aifq[current].d;
6408 
6409 	ctx->ctx_flags &= ~AAC_CTXFLAG_FILLED;
6410 	ctx->ctx_idx = (current + 1) % AAC_AIFQ_LENGTH;
6411 	return (0);
6412 }
6413 
6414 int
6415 aac_return_aif(struct aac_softstate *softs, struct aac_fib_context *ctx,
6416     struct aac_fib **fibpp)
6417 {
6418 	int rval;
6419 
6420 	mutex_enter(&softs->aifq_mutex);
6421 	rval = aac_return_aif_common(softs, ctx, fibpp);
6422 	mutex_exit(&softs->aifq_mutex);
6423 	return (rval);
6424 }
6425 
6426 int
6427 aac_return_aif_wait(struct aac_softstate *softs, struct aac_fib_context *ctx,
6428     struct aac_fib **fibpp)
6429 {
6430 	int rval;
6431 
6432 	mutex_enter(&softs->aifq_mutex);
6433 	rval = aac_return_aif_common(softs, ctx, fibpp);
6434 	if (rval == EAGAIN) {
6435 		AACDB_PRINT(softs, CE_NOTE, "Waiting for AIF");
6436 		rval = cv_wait_sig(&softs->aifq_cv, &softs->aifq_mutex);
6437 	}
6438 	mutex_exit(&softs->aifq_mutex);
6439 	return ((rval > 0) ? 0 : EINTR);
6440 }
6441 
6442 /*
6443  * The following function comes from Adaptec:
6444  *
6445  * When driver sees a particular event that means containers are changed, it
6446  * will rescan containers. However a change may not be complete until some
6447  * other event is received. For example, creating or deleting an array will
6448  * incur as many as six AifEnConfigChange events which would generate six
6449  * container rescans. To diminish rescans, driver set a flag to wait for
6450  * another particular event. When sees that events come in, it will do rescan.
6451  */
6452 static int
6453 aac_handle_aif(struct aac_softstate *softs, struct aac_aif_command *aif)
6454 {
6455 	ddi_acc_handle_t acc = softs->comm_space_acc_handle;
6456 	int en_type;
6457 	int devcfg_needed;
6458 	int cid;
6459 	uint32_t bus_id, tgt_id;
6460 	enum aac_cfg_event event = AAC_CFG_NULL_EXIST;
6461 
6462 	devcfg_needed = 0;
6463 	en_type = LE_32((uint32_t)aif->data.EN.type);
6464 
6465 	switch (LE_32((uint32_t)aif->command)) {
6466 	case AifCmdDriverNotify: {
6467 		cid = LE_32(aif->data.EN.data.ECC.container[0]);
6468 
6469 		switch (en_type) {
6470 		case AifDenMorphComplete:
6471 		case AifDenVolumeExtendComplete:
6472 			if (AAC_DEV_IS_VALID(&softs->containers[cid].dev))
6473 				softs->devcfg_wait_on = AifEnConfigChange;
6474 			break;
6475 		}
6476 		if (softs->devcfg_wait_on == en_type)
6477 			devcfg_needed = 1;
6478 		break;
6479 	}
6480 
6481 	case AifCmdEventNotify:
6482 		cid = LE_32(aif->data.EN.data.ECC.container[0]);
6483 		switch (en_type) {
6484 		case AifEnAddContainer:
6485 		case AifEnDeleteContainer:
6486 			softs->devcfg_wait_on = AifEnConfigChange;
6487 			break;
6488 		case AifEnContainerChange:
6489 			if (!softs->devcfg_wait_on)
6490 				softs->devcfg_wait_on = AifEnConfigChange;
6491 			break;
6492 		case AifEnContainerEvent:
6493 			if (ddi_get32(acc, &aif-> \
6494 			    data.EN.data.ECE.eventType) == CT_PUP_MISSING_DRIVE)
6495 				devcfg_needed = 1;
6496 			break;
6497 		case AifEnAddJBOD:
6498 			if (!(softs->flags & AAC_FLAGS_JBOD))
6499 				return (AACERR);
6500 			event = AAC_CFG_ADD;
6501 			bus_id = (cid >> 24) & 0xf;
6502 			tgt_id = cid & 0xffff;
6503 			break;
6504 		case AifEnDeleteJBOD:
6505 			if (!(softs->flags & AAC_FLAGS_JBOD))
6506 				return (AACERR);
6507 			event = AAC_CFG_DELETE;
6508 			bus_id = (cid >> 24) & 0xf;
6509 			tgt_id = cid & 0xffff;
6510 			break;
6511 		}
6512 		if (softs->devcfg_wait_on == en_type)
6513 			devcfg_needed = 1;
6514 		break;
6515 
6516 	case AifCmdJobProgress:
6517 		if (LE_32((uint32_t)aif->data.PR[0].jd.type) == AifJobCtrZero) {
6518 			int pr_status;
6519 			uint32_t pr_ftick, pr_ctick;
6520 
6521 			pr_status = LE_32((uint32_t)aif->data.PR[0].status);
6522 			pr_ctick = LE_32(aif->data.PR[0].currentTick);
6523 			pr_ftick = LE_32(aif->data.PR[0].finalTick);
6524 
6525 			if ((pr_ctick == pr_ftick) ||
6526 			    (pr_status == AifJobStsSuccess))
6527 				softs->devcfg_wait_on = AifEnContainerChange;
6528 			else if ((pr_ctick == 0) &&
6529 			    (pr_status == AifJobStsRunning))
6530 				softs->devcfg_wait_on = AifEnContainerChange;
6531 		}
6532 		break;
6533 	}
6534 
6535 	if (devcfg_needed) {
6536 		softs->devcfg_wait_on = 0;
6537 		(void) aac_probe_containers(softs);
6538 	}
6539 
6540 	if (event != AAC_CFG_NULL_EXIST) {
6541 		ASSERT(en_type == AifEnAddJBOD || en_type == AifEnDeleteJBOD);
6542 		(void) aac_probe_jbod(softs,
6543 		    AAC_P2VTGT(softs, bus_id, tgt_id), event);
6544 	}
6545 	return (AACOK);
6546 }
6547 
6548 
6549 /*
6550  * Check and handle AIF events
6551  */
6552 static void
6553 aac_aif_event(struct aac_softstate *softs)
6554 {
6555 	struct aac_fib *fibp;
6556 
6557 	/*CONSTCOND*/
6558 	while (1) {
6559 		if (aac_return_aif(softs, &softs->aifctx, &fibp) != 0)
6560 			break; /* No more AIFs to handle, end loop */
6561 
6562 		/* AIF overrun, array create/delete may missed. */
6563 		if (softs->aifctx.ctx_overrun) {
6564 			softs->aifctx.ctx_overrun = 0;
6565 		}
6566 
6567 		/* AIF received, handle it */
6568 		struct aac_aif_command *aifp =
6569 		    (struct aac_aif_command *)&fibp->data[0];
6570 		uint32_t aif_command = LE_32((uint32_t)aifp->command);
6571 
6572 		if (aif_command == AifCmdDriverNotify ||
6573 		    aif_command == AifCmdEventNotify ||
6574 		    aif_command == AifCmdJobProgress)
6575 			(void) aac_handle_aif(softs, aifp);
6576 	}
6577 }
6578 
6579 /*
6580  * Timeout recovery
6581  */
6582 /*ARGSUSED*/
6583 static void
6584 aac_cmd_timeout(struct aac_softstate *softs, struct aac_cmd *acp)
6585 {
6586 #ifdef DEBUG
6587 	acp->fib_flags |= AACDB_FLAGS_FIB_TIMEOUT;
6588 	AACDB_PRINT(softs, CE_WARN, "acp %p timed out", acp);
6589 	AACDB_PRINT_FIB(softs, acp->slotp);
6590 #endif
6591 
6592 	/*
6593 	 * Besides the firmware in unhealthy state, an overloaded
6594 	 * adapter may also incur pkt timeout.
6595 	 * There is a chance for an adapter with a slower IOP to take
6596 	 * longer than 60 seconds to process the commands, such as when
6597 	 * to perform IOs. So the adapter is doing a build on a RAID-5
6598 	 * while being required longer completion times should be
6599 	 * tolerated.
6600 	 */
6601 	switch (aac_do_reset(softs)) {
6602 	case AAC_IOP_RESET_SUCCEED:
6603 		aac_abort_iocmds(softs, AAC_IOCMD_OUTSTANDING, NULL, CMD_RESET);
6604 		aac_start_waiting_io(softs);
6605 		break;
6606 	case AAC_IOP_RESET_FAILED:
6607 		/* Abort all waiting cmds when adapter is dead */
6608 		aac_abort_iocmds(softs, AAC_IOCMD_ALL, NULL, CMD_TIMEOUT);
6609 		break;
6610 	case AAC_IOP_RESET_ABNORMAL:
6611 		aac_start_waiting_io(softs);
6612 	}
6613 }
6614 
6615 /*
6616  * The following function comes from Adaptec:
6617  *
6618  * Time sync. command added to synchronize time with firmware every 30
6619  * minutes (required for correct AIF timestamps etc.)
6620  */
6621 static void
6622 aac_sync_tick(struct aac_softstate *softs)
6623 {
6624 	ddi_acc_handle_t acc;
6625 	int rval;
6626 
6627 	mutex_enter(&softs->time_mutex);
6628 	ASSERT(softs->time_sync <= softs->timebase);
6629 	softs->time_sync = 0;
6630 	mutex_exit(&softs->time_mutex);
6631 
6632 	/* Time sync. with firmware every AAC_SYNC_TICK */
6633 	(void) aac_sync_fib_slot_bind(softs, &softs->sync_ac);
6634 	acc = softs->sync_ac.slotp->fib_acc_handle;
6635 
6636 	ddi_put32(acc, (void *)&softs->sync_ac.slotp->fibp->data[0],
6637 	    ddi_get_time());
6638 	rval = aac_sync_fib(softs, SendHostTime, AAC_FIB_SIZEOF(uint32_t));
6639 	aac_sync_fib_slot_release(softs, &softs->sync_ac);
6640 
6641 	mutex_enter(&softs->time_mutex);
6642 	softs->time_sync = softs->timebase;
6643 	if (rval != AACOK)
6644 		/* retry shortly */
6645 		softs->time_sync += aac_tick << 1;
6646 	else
6647 		softs->time_sync += AAC_SYNC_TICK;
6648 	mutex_exit(&softs->time_mutex);
6649 }
6650 
6651 /*
6652  * Timeout checking and handling
6653  */
6654 static void
6655 aac_daemon(struct aac_softstate *softs)
6656 {
6657 	int time_out; /* set if timeout happened */
6658 	int time_adjust;
6659 	uint32_t softs_timebase;
6660 
6661 	mutex_enter(&softs->time_mutex);
6662 	ASSERT(softs->time_out <= softs->timebase);
6663 	softs->time_out = 0;
6664 	softs_timebase = softs->timebase;
6665 	mutex_exit(&softs->time_mutex);
6666 
6667 	/* Check slots for timeout pkts */
6668 	time_adjust = 0;
6669 	do {
6670 		struct aac_cmd *acp;
6671 
6672 		time_out = 0;
6673 		for (acp = softs->q_busy.q_head; acp; acp = acp->next) {
6674 			if (acp->timeout == 0)
6675 				continue;
6676 
6677 			/*
6678 			 * If timeout happened, update outstanding cmds
6679 			 * to be checked later again.
6680 			 */
6681 			if (time_adjust) {
6682 				acp->timeout += time_adjust;
6683 				continue;
6684 			}
6685 
6686 			if (acp->timeout <= softs_timebase) {
6687 				aac_cmd_timeout(softs, acp);
6688 				time_out = 1;
6689 				time_adjust = aac_tick * drv_usectohz(1000000);
6690 				break; /* timeout happened */
6691 			} else {
6692 				break; /* no timeout */
6693 			}
6694 		}
6695 	} while (time_out);
6696 
6697 	mutex_enter(&softs->time_mutex);
6698 	softs->time_out = softs->timebase + aac_tick;
6699 	mutex_exit(&softs->time_mutex);
6700 }
6701 
6702 /*
6703  * The event thread handles various tasks serially for the other parts of
6704  * the driver, so that they can run fast.
6705  */
6706 static void
6707 aac_event_thread(struct aac_softstate *softs)
6708 {
6709 	int run = 1;
6710 
6711 	DBCALLED(softs, 1);
6712 
6713 	mutex_enter(&softs->ev_lock);
6714 	while (run) {
6715 		int events;
6716 
6717 		if ((events = softs->events) == 0) {
6718 			cv_wait(&softs->event_disp_cv, &softs->ev_lock);
6719 			events = softs->events;
6720 		}
6721 		softs->events = 0;
6722 		mutex_exit(&softs->ev_lock);
6723 
6724 		mutex_enter(&softs->io_lock);
6725 		if ((softs->state & AAC_STATE_RUN) &&
6726 		    (softs->state & AAC_STATE_DEAD) == 0) {
6727 			if (events & AAC_EVENT_TIMEOUT)
6728 				aac_daemon(softs);
6729 			if (events & AAC_EVENT_SYNCTICK)
6730 				aac_sync_tick(softs);
6731 			if (events & AAC_EVENT_AIF)
6732 				aac_aif_event(softs);
6733 		} else {
6734 			run = 0;
6735 		}
6736 		mutex_exit(&softs->io_lock);
6737 
6738 		mutex_enter(&softs->ev_lock);
6739 	}
6740 
6741 	cv_signal(&softs->event_wait_cv);
6742 	mutex_exit(&softs->ev_lock);
6743 }
6744 
6745 /*
6746  * Internal timer. It is only responsbile for time counting and report time
6747  * related events. Events handling is done by aac_event_thread(), so that
6748  * the timer itself could be as precise as possible.
6749  */
6750 static void
6751 aac_timer(void *arg)
6752 {
6753 	struct aac_softstate *softs = arg;
6754 	int events = 0;
6755 
6756 	mutex_enter(&softs->time_mutex);
6757 
6758 	/* If timer is being stopped, exit */
6759 	if (softs->timeout_id) {
6760 		softs->timeout_id = timeout(aac_timer, (void *)softs,
6761 		    (aac_tick * drv_usectohz(1000000)));
6762 	} else {
6763 		mutex_exit(&softs->time_mutex);
6764 		return;
6765 	}
6766 
6767 	/* Time counting */
6768 	softs->timebase += aac_tick;
6769 
6770 	/* Check time related events */
6771 	if (softs->time_out && softs->time_out <= softs->timebase)
6772 		events |= AAC_EVENT_TIMEOUT;
6773 	if (softs->time_sync && softs->time_sync <= softs->timebase)
6774 		events |= AAC_EVENT_SYNCTICK;
6775 
6776 	mutex_exit(&softs->time_mutex);
6777 
6778 	if (events)
6779 		aac_event_disp(softs, events);
6780 }
6781 
6782 /*
6783  * Dispatch events to daemon thread for handling
6784  */
6785 static void
6786 aac_event_disp(struct aac_softstate *softs, int events)
6787 {
6788 	mutex_enter(&softs->ev_lock);
6789 	softs->events |= events;
6790 	cv_broadcast(&softs->event_disp_cv);
6791 	mutex_exit(&softs->ev_lock);
6792 }
6793 
6794 /*
6795  * Architecture dependent functions
6796  */
6797 static int
6798 aac_rx_get_fwstatus(struct aac_softstate *softs)
6799 {
6800 	return (PCI_MEM_GET32(softs, AAC_OMR0));
6801 }
6802 
6803 static int
6804 aac_rx_get_mailbox(struct aac_softstate *softs, int mb)
6805 {
6806 	return (PCI_MEM_GET32(softs, AAC_RX_MAILBOX + mb * 4));
6807 }
6808 
6809 static void
6810 aac_rx_set_mailbox(struct aac_softstate *softs, uint32_t cmd,
6811     uint32_t arg0, uint32_t arg1, uint32_t arg2, uint32_t arg3)
6812 {
6813 	PCI_MEM_PUT32(softs, AAC_RX_MAILBOX, cmd);
6814 	PCI_MEM_PUT32(softs, AAC_RX_MAILBOX + 4, arg0);
6815 	PCI_MEM_PUT32(softs, AAC_RX_MAILBOX + 8, arg1);
6816 	PCI_MEM_PUT32(softs, AAC_RX_MAILBOX + 12, arg2);
6817 	PCI_MEM_PUT32(softs, AAC_RX_MAILBOX + 16, arg3);
6818 }
6819 
6820 static int
6821 aac_rkt_get_fwstatus(struct aac_softstate *softs)
6822 {
6823 	return (PCI_MEM_GET32(softs, AAC_OMR0));
6824 }
6825 
6826 static int
6827 aac_rkt_get_mailbox(struct aac_softstate *softs, int mb)
6828 {
6829 	return (PCI_MEM_GET32(softs, AAC_RKT_MAILBOX + mb *4));
6830 }
6831 
6832 static void
6833 aac_rkt_set_mailbox(struct aac_softstate *softs, uint32_t cmd,
6834     uint32_t arg0, uint32_t arg1, uint32_t arg2, uint32_t arg3)
6835 {
6836 	PCI_MEM_PUT32(softs, AAC_RKT_MAILBOX, cmd);
6837 	PCI_MEM_PUT32(softs, AAC_RKT_MAILBOX + 4, arg0);
6838 	PCI_MEM_PUT32(softs, AAC_RKT_MAILBOX + 8, arg1);
6839 	PCI_MEM_PUT32(softs, AAC_RKT_MAILBOX + 12, arg2);
6840 	PCI_MEM_PUT32(softs, AAC_RKT_MAILBOX + 16, arg3);
6841 }
6842 
6843 /*
6844  * cb_ops functions
6845  */
6846 static int
6847 aac_open(dev_t *devp, int flag, int otyp, cred_t *cred)
6848 {
6849 	struct aac_softstate *softs;
6850 	int minor0, minor;
6851 	int instance;
6852 
6853 	DBCALLED(NULL, 2);
6854 
6855 	if (otyp != OTYP_BLK && otyp != OTYP_CHR)
6856 		return (EINVAL);
6857 
6858 	minor0 = getminor(*devp);
6859 	minor = AAC_SCSA_MINOR(minor0);
6860 
6861 	if (AAC_IS_SCSA_NODE(minor))
6862 		return (scsi_hba_open(devp, flag, otyp, cred));
6863 
6864 	instance = MINOR2INST(minor0);
6865 	if (instance >= AAC_MAX_ADAPTERS)
6866 		return (ENXIO);
6867 
6868 	softs = ddi_get_soft_state(aac_softstatep, instance);
6869 	if (softs == NULL)
6870 		return (ENXIO);
6871 
6872 	return (0);
6873 }
6874 
6875 /*ARGSUSED*/
6876 static int
6877 aac_close(dev_t dev, int flag, int otyp, cred_t *cred)
6878 {
6879 	int minor0, minor;
6880 	int instance;
6881 
6882 	DBCALLED(NULL, 2);
6883 
6884 	if (otyp != OTYP_BLK && otyp != OTYP_CHR)
6885 		return (EINVAL);
6886 
6887 	minor0 = getminor(dev);
6888 	minor = AAC_SCSA_MINOR(minor0);
6889 
6890 	if (AAC_IS_SCSA_NODE(minor))
6891 		return (scsi_hba_close(dev, flag, otyp, cred));
6892 
6893 	instance = MINOR2INST(minor0);
6894 	if (instance >= AAC_MAX_ADAPTERS)
6895 		return (ENXIO);
6896 
6897 	return (0);
6898 }
6899 
6900 static int
6901 aac_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
6902     int *rval_p)
6903 {
6904 	struct aac_softstate *softs;
6905 	int minor0, minor;
6906 	int instance;
6907 
6908 	DBCALLED(NULL, 2);
6909 
6910 	if (drv_priv(cred_p) != 0)
6911 		return (EPERM);
6912 
6913 	minor0 = getminor(dev);
6914 	minor = AAC_SCSA_MINOR(minor0);
6915 
6916 	if (AAC_IS_SCSA_NODE(minor))
6917 		return (scsi_hba_ioctl(dev, cmd, arg, flag, cred_p, rval_p));
6918 
6919 	instance = MINOR2INST(minor0);
6920 	if (instance < AAC_MAX_ADAPTERS) {
6921 		softs = ddi_get_soft_state(aac_softstatep, instance);
6922 		return (aac_do_ioctl(softs, dev, cmd, arg, flag));
6923 	}
6924 	return (ENXIO);
6925 }
6926 
6927 /*
6928  * The IO fault service error handling callback function
6929  */
6930 /*ARGSUSED*/
6931 static int
6932 aac_fm_error_cb(dev_info_t *dip, ddi_fm_error_t *err, const void *impl_data)
6933 {
6934 	/*
6935 	 * as the driver can always deal with an error in any dma or
6936 	 * access handle, we can just return the fme_status value.
6937 	 */
6938 	pci_ereport_post(dip, err, NULL);
6939 	return (err->fme_status);
6940 }
6941 
6942 /*
6943  * aac_fm_init - initialize fma capabilities and register with IO
6944  *               fault services.
6945  */
6946 static void
6947 aac_fm_init(struct aac_softstate *softs)
6948 {
6949 	/*
6950 	 * Need to change iblock to priority for new MSI intr
6951 	 */
6952 	ddi_iblock_cookie_t fm_ibc;
6953 
6954 	softs->fm_capabilities = ddi_getprop(DDI_DEV_T_ANY, softs->devinfo_p,
6955 	    DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
6956 	    DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
6957 	    DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
6958 
6959 	/* Only register with IO Fault Services if we have some capability */
6960 	if (softs->fm_capabilities) {
6961 		/* Adjust access and dma attributes for FMA */
6962 		softs->reg_attr.devacc_attr_access = DDI_FLAGERR_ACC;
6963 		softs->addr_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
6964 		softs->buf_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
6965 
6966 		/*
6967 		 * Register capabilities with IO Fault Services.
6968 		 * fm_capabilities will be updated to indicate
6969 		 * capabilities actually supported (not requested.)
6970 		 */
6971 		ddi_fm_init(softs->devinfo_p, &softs->fm_capabilities, &fm_ibc);
6972 
6973 		/*
6974 		 * Initialize pci ereport capabilities if ereport
6975 		 * capable (should always be.)
6976 		 */
6977 		if (DDI_FM_EREPORT_CAP(softs->fm_capabilities) ||
6978 		    DDI_FM_ERRCB_CAP(softs->fm_capabilities)) {
6979 			pci_ereport_setup(softs->devinfo_p);
6980 		}
6981 
6982 		/*
6983 		 * Register error callback if error callback capable.
6984 		 */
6985 		if (DDI_FM_ERRCB_CAP(softs->fm_capabilities)) {
6986 			ddi_fm_handler_register(softs->devinfo_p,
6987 			    aac_fm_error_cb, (void *) softs);
6988 		}
6989 	}
6990 }
6991 
6992 /*
6993  * aac_fm_fini - Releases fma capabilities and un-registers with IO
6994  *               fault services.
6995  */
6996 static void
6997 aac_fm_fini(struct aac_softstate *softs)
6998 {
6999 	/* Only unregister FMA capabilities if registered */
7000 	if (softs->fm_capabilities) {
7001 		/*
7002 		 * Un-register error callback if error callback capable.
7003 		 */
7004 		if (DDI_FM_ERRCB_CAP(softs->fm_capabilities)) {
7005 			ddi_fm_handler_unregister(softs->devinfo_p);
7006 		}
7007 
7008 		/*
7009 		 * Release any resources allocated by pci_ereport_setup()
7010 		 */
7011 		if (DDI_FM_EREPORT_CAP(softs->fm_capabilities) ||
7012 		    DDI_FM_ERRCB_CAP(softs->fm_capabilities)) {
7013 			pci_ereport_teardown(softs->devinfo_p);
7014 		}
7015 
7016 		/* Unregister from IO Fault Services */
7017 		ddi_fm_fini(softs->devinfo_p);
7018 
7019 		/* Adjust access and dma attributes for FMA */
7020 		softs->reg_attr.devacc_attr_access = DDI_DEFAULT_ACC;
7021 		softs->addr_dma_attr.dma_attr_flags &= ~DDI_DMA_FLAGERR;
7022 		softs->buf_dma_attr.dma_attr_flags &= ~DDI_DMA_FLAGERR;
7023 	}
7024 }
7025 
7026 int
7027 aac_check_acc_handle(ddi_acc_handle_t handle)
7028 {
7029 	ddi_fm_error_t de;
7030 
7031 	ddi_fm_acc_err_get(handle, &de, DDI_FME_VERSION);
7032 	return (de.fme_status);
7033 }
7034 
7035 int
7036 aac_check_dma_handle(ddi_dma_handle_t handle)
7037 {
7038 	ddi_fm_error_t de;
7039 
7040 	ddi_fm_dma_err_get(handle, &de, DDI_FME_VERSION);
7041 	return (de.fme_status);
7042 }
7043 
7044 void
7045 aac_fm_ereport(struct aac_softstate *softs, char *detail)
7046 {
7047 	uint64_t ena;
7048 	char buf[FM_MAX_CLASS];
7049 
7050 	(void) snprintf(buf, FM_MAX_CLASS, "%s.%s", DDI_FM_DEVICE, detail);
7051 	ena = fm_ena_generate(0, FM_ENA_FMT1);
7052 	if (DDI_FM_EREPORT_CAP(softs->fm_capabilities)) {
7053 		ddi_fm_ereport_post(softs->devinfo_p, buf, ena, DDI_NOSLEEP,
7054 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERSION, NULL);
7055 	}
7056 }
7057 
7058 /*
7059  * Autoconfiguration support
7060  */
7061 static int
7062 aac_parse_devname(char *devnm, int *tgt, int *lun)
7063 {
7064 	char devbuf[SCSI_MAXNAMELEN];
7065 	char *addr;
7066 	char *p,  *tp, *lp;
7067 	long num;
7068 
7069 	/* Parse dev name and address */
7070 	(void) strcpy(devbuf, devnm);
7071 	addr = "";
7072 	for (p = devbuf; *p != '\0'; p++) {
7073 		if (*p == '@') {
7074 			addr = p + 1;
7075 			*p = '\0';
7076 		} else if (*p == ':') {
7077 			*p = '\0';
7078 			break;
7079 		}
7080 	}
7081 
7082 	/* Parse taget and lun */
7083 	for (p = tp = addr, lp = NULL; *p != '\0'; p++) {
7084 		if (*p == ',') {
7085 			lp = p + 1;
7086 			*p = '\0';
7087 			break;
7088 		}
7089 	}
7090 	if (tgt && tp) {
7091 		if (ddi_strtol(tp, NULL, 0x10, &num))
7092 			return (AACERR);
7093 		*tgt = (int)num;
7094 	}
7095 	if (lun && lp) {
7096 		if (ddi_strtol(lp, NULL, 0x10, &num))
7097 			return (AACERR);
7098 		*lun = (int)num;
7099 	}
7100 	return (AACOK);
7101 }
7102 
7103 static dev_info_t *
7104 aac_find_child(struct aac_softstate *softs, uint16_t tgt, uint8_t lun)
7105 {
7106 	dev_info_t *child = NULL;
7107 	char addr[SCSI_MAXNAMELEN];
7108 	char tmp[MAXNAMELEN];
7109 
7110 	if (tgt < AAC_MAX_LD) {
7111 		if (lun == 0) {
7112 			struct aac_device *dvp = &softs->containers[tgt].dev;
7113 
7114 			child = dvp->dip;
7115 		}
7116 	} else {
7117 		(void) sprintf(addr, "%x,%x", tgt, lun);
7118 		for (child = ddi_get_child(softs->devinfo_p);
7119 		    child; child = ddi_get_next_sibling(child)) {
7120 			/* We don't care about non-persistent node */
7121 			if (ndi_dev_is_persistent_node(child) == 0)
7122 				continue;
7123 
7124 			if (aac_name_node(child, tmp, MAXNAMELEN) !=
7125 			    DDI_SUCCESS)
7126 				continue;
7127 			if (strcmp(addr, tmp) == 0)
7128 				break;
7129 		}
7130 	}
7131 	return (child);
7132 }
7133 
7134 static int
7135 aac_config_child(struct aac_softstate *softs, struct scsi_device *sd,
7136     dev_info_t **dipp)
7137 {
7138 	char *nodename = NULL;
7139 	char **compatible = NULL;
7140 	int ncompatible = 0;
7141 	char *childname;
7142 	dev_info_t *ldip = NULL;
7143 	int tgt = sd->sd_address.a_target;
7144 	int lun = sd->sd_address.a_lun;
7145 	int dtype = sd->sd_inq->inq_dtype & DTYPE_MASK;
7146 	int rval;
7147 
7148 	DBCALLED(softs, 2);
7149 
7150 	scsi_hba_nodename_compatible_get(sd->sd_inq, NULL, dtype,
7151 	    NULL, &nodename, &compatible, &ncompatible);
7152 	if (nodename == NULL) {
7153 		AACDB_PRINT(softs, CE_WARN,
7154 		    "found no comptible driver for t%dL%d", tgt, lun);
7155 		rval = NDI_FAILURE;
7156 		goto finish;
7157 	}
7158 	childname = (softs->legacy && dtype == DTYPE_DIRECT) ? "sd" : nodename;
7159 
7160 	/* Create dev node */
7161 	rval = ndi_devi_alloc(softs->devinfo_p, childname, DEVI_SID_NODEID,
7162 	    &ldip);
7163 	if (rval == NDI_SUCCESS) {
7164 		if (ndi_prop_update_int(DDI_DEV_T_NONE, ldip, "target", tgt)
7165 		    != DDI_PROP_SUCCESS) {
7166 			AACDB_PRINT(softs, CE_WARN, "unable to create "
7167 			    "property for t%dL%d (target)", tgt, lun);
7168 			rval = NDI_FAILURE;
7169 			goto finish;
7170 		}
7171 		if (ndi_prop_update_int(DDI_DEV_T_NONE, ldip, "lun", lun)
7172 		    != DDI_PROP_SUCCESS) {
7173 			AACDB_PRINT(softs, CE_WARN, "unable to create "
7174 			    "property for t%dL%d (lun)", tgt, lun);
7175 			rval = NDI_FAILURE;
7176 			goto finish;
7177 		}
7178 		if (ndi_prop_update_string_array(DDI_DEV_T_NONE, ldip,
7179 		    "compatible", compatible, ncompatible)
7180 		    != DDI_PROP_SUCCESS) {
7181 			AACDB_PRINT(softs, CE_WARN, "unable to create "
7182 			    "property for t%dL%d (compatible)", tgt, lun);
7183 			rval = NDI_FAILURE;
7184 			goto finish;
7185 		}
7186 
7187 		rval = ndi_devi_online(ldip, NDI_ONLINE_ATTACH);
7188 		if (rval != NDI_SUCCESS) {
7189 			AACDB_PRINT(softs, CE_WARN, "unable to online t%dL%d",
7190 			    tgt, lun);
7191 			ndi_prop_remove_all(ldip);
7192 			(void) ndi_devi_free(ldip);
7193 		}
7194 	}
7195 finish:
7196 	if (dipp)
7197 		*dipp = ldip;
7198 
7199 	scsi_hba_nodename_compatible_free(nodename, compatible);
7200 	return (rval);
7201 }
7202 
7203 /*ARGSUSED*/
7204 static int
7205 aac_probe_lun(struct aac_softstate *softs, struct scsi_device *sd)
7206 {
7207 	int tgt = sd->sd_address.a_target;
7208 	int lun = sd->sd_address.a_lun;
7209 
7210 	DBCALLED(softs, 2);
7211 
7212 	if (tgt < AAC_MAX_LD) {
7213 		enum aac_cfg_event event;
7214 
7215 		if (lun == 0) {
7216 			mutex_enter(&softs->io_lock);
7217 			event = aac_probe_container(softs, tgt);
7218 			mutex_exit(&softs->io_lock);
7219 			if ((event != AAC_CFG_NULL_NOEXIST) &&
7220 			    (event != AAC_CFG_DELETE)) {
7221 				if (scsi_hba_probe(sd, NULL) ==
7222 				    SCSIPROBE_EXISTS)
7223 					return (NDI_SUCCESS);
7224 			}
7225 		}
7226 		return (NDI_FAILURE);
7227 	} else {
7228 		int dtype;
7229 		int qual; /* device qualifier */
7230 
7231 		if (scsi_hba_probe(sd, NULL) != SCSIPROBE_EXISTS)
7232 			return (NDI_FAILURE);
7233 
7234 		dtype = sd->sd_inq->inq_dtype & DTYPE_MASK;
7235 		qual = dtype >> 5;
7236 
7237 		AACDB_PRINT(softs, CE_NOTE,
7238 		    "Phys. device found: tgt %d dtype %d: %s",
7239 		    tgt, dtype, sd->sd_inq->inq_vid);
7240 
7241 		/* Only non-DASD and JBOD mode DASD are allowed exposed */
7242 		if (dtype == DTYPE_RODIRECT /* CDROM */ ||
7243 		    dtype == DTYPE_SEQUENTIAL /* TAPE */ ||
7244 		    dtype == DTYPE_ESI /* SES */) {
7245 			if (!(softs->flags & AAC_FLAGS_NONDASD))
7246 				return (NDI_FAILURE);
7247 			AACDB_PRINT(softs, CE_NOTE, "non-DASD %d found", tgt);
7248 
7249 		} else if (dtype == DTYPE_DIRECT) {
7250 			if (!(softs->flags & AAC_FLAGS_JBOD) || qual != 0)
7251 				return (NDI_FAILURE);
7252 			AACDB_PRINT(softs, CE_NOTE, "JBOD DASD %d found", tgt);
7253 		}
7254 
7255 		mutex_enter(&softs->io_lock);
7256 		softs->nondasds[AAC_PD(tgt)].dev.flags |= AAC_DFLAG_VALID;
7257 		mutex_exit(&softs->io_lock);
7258 		return (NDI_SUCCESS);
7259 	}
7260 }
7261 
7262 static int
7263 aac_config_lun(struct aac_softstate *softs, uint16_t tgt, uint8_t lun,
7264     dev_info_t **ldip)
7265 {
7266 	struct scsi_device sd;
7267 	dev_info_t *child;
7268 	int rval;
7269 
7270 	DBCALLED(softs, 2);
7271 
7272 	if ((child = aac_find_child(softs, tgt, lun)) != NULL) {
7273 		if (ldip)
7274 			*ldip = child;
7275 		return (NDI_SUCCESS);
7276 	}
7277 
7278 	bzero(&sd, sizeof (struct scsi_device));
7279 	sd.sd_address.a_hba_tran = softs->hba_tran;
7280 	sd.sd_address.a_target = (uint16_t)tgt;
7281 	sd.sd_address.a_lun = (uint8_t)lun;
7282 	if ((rval = aac_probe_lun(softs, &sd)) == NDI_SUCCESS)
7283 		rval = aac_config_child(softs, &sd, ldip);
7284 	/* scsi_unprobe is blank now. Free buffer manually */
7285 	if (sd.sd_inq) {
7286 		kmem_free(sd.sd_inq, SUN_INQSIZE);
7287 		sd.sd_inq = (struct scsi_inquiry *)NULL;
7288 	}
7289 	return (rval);
7290 }
7291 
7292 static int
7293 aac_config_tgt(struct aac_softstate *softs, int tgt)
7294 {
7295 	struct scsi_address ap;
7296 	struct buf *bp = NULL;
7297 	int buf_len = AAC_SCSI_RPTLUNS_HEAD_SIZE + AAC_SCSI_RPTLUNS_ADDR_SIZE;
7298 	int list_len = 0;
7299 	int lun_total = 0;
7300 	dev_info_t *ldip;
7301 	int i;
7302 
7303 	ap.a_hba_tran = softs->hba_tran;
7304 	ap.a_target = (uint16_t)tgt;
7305 	ap.a_lun = 0;
7306 
7307 	for (i = 0; i < 2; i++) {
7308 		struct scsi_pkt *pkt;
7309 		uchar_t *cdb;
7310 		uchar_t *p;
7311 		uint32_t data;
7312 
7313 		if (bp == NULL) {
7314 			if ((bp = scsi_alloc_consistent_buf(&ap, NULL,
7315 			    buf_len, B_READ, NULL_FUNC, NULL)) == NULL)
7316 				return (AACERR);
7317 		}
7318 		if ((pkt = scsi_init_pkt(&ap, NULL, bp, CDB_GROUP5,
7319 		    sizeof (struct scsi_arq_status), 0, PKT_CONSISTENT,
7320 		    NULL, NULL)) == NULL) {
7321 			scsi_free_consistent_buf(bp);
7322 			return (AACERR);
7323 		}
7324 		cdb = pkt->pkt_cdbp;
7325 		bzero(cdb, CDB_GROUP5);
7326 		cdb[0] = SCMD_REPORT_LUNS;
7327 
7328 		/* Convert buffer len from local to LE_32 */
7329 		data = buf_len;
7330 		for (p = &cdb[9]; p > &cdb[5]; p--) {
7331 			*p = data & 0xff;
7332 			data >>= 8;
7333 		}
7334 
7335 		if (scsi_poll(pkt) < 0 ||
7336 		    ((struct scsi_status *)pkt->pkt_scbp)->sts_chk) {
7337 			scsi_destroy_pkt(pkt);
7338 			break;
7339 		}
7340 
7341 		/* Convert list_len from LE_32 to local */
7342 		for (p = (uchar_t *)bp->b_un.b_addr;
7343 		    p < (uchar_t *)bp->b_un.b_addr + 4; p++) {
7344 			data <<= 8;
7345 			data |= *p;
7346 		}
7347 		list_len = data;
7348 		if (buf_len < list_len + AAC_SCSI_RPTLUNS_HEAD_SIZE) {
7349 			scsi_free_consistent_buf(bp);
7350 			bp = NULL;
7351 			buf_len = list_len + AAC_SCSI_RPTLUNS_HEAD_SIZE;
7352 		}
7353 		scsi_destroy_pkt(pkt);
7354 	}
7355 	if (i >= 2) {
7356 		uint8_t *buf = (uint8_t *)(bp->b_un.b_addr +
7357 		    AAC_SCSI_RPTLUNS_HEAD_SIZE);
7358 
7359 		for (i = 0; i < (list_len / AAC_SCSI_RPTLUNS_ADDR_SIZE); i++) {
7360 			uint16_t lun;
7361 
7362 			/* Determine report luns addressing type */
7363 			switch (buf[0] & AAC_SCSI_RPTLUNS_ADDR_MASK) {
7364 			/*
7365 			 * Vendors in the field have been found to be
7366 			 * concatenating bus/target/lun to equal the
7367 			 * complete lun value instead of switching to
7368 			 * flat space addressing
7369 			 */
7370 			case AAC_SCSI_RPTLUNS_ADDR_PERIPHERAL:
7371 			case AAC_SCSI_RPTLUNS_ADDR_LOGICAL_UNIT:
7372 			case AAC_SCSI_RPTLUNS_ADDR_FLAT_SPACE:
7373 				lun = ((buf[0] & 0x3f) << 8) | buf[1];
7374 				if (lun > UINT8_MAX) {
7375 					AACDB_PRINT(softs, CE_WARN,
7376 					    "abnormal lun number: %d", lun);
7377 					break;
7378 				}
7379 				if (aac_config_lun(softs, tgt, lun, &ldip) ==
7380 				    NDI_SUCCESS)
7381 					lun_total++;
7382 				break;
7383 			}
7384 
7385 			buf += AAC_SCSI_RPTLUNS_ADDR_SIZE;
7386 		}
7387 	} else {
7388 		/* The target may do not support SCMD_REPORT_LUNS. */
7389 		if (aac_config_lun(softs, tgt, 0, &ldip) == NDI_SUCCESS)
7390 			lun_total++;
7391 	}
7392 	scsi_free_consistent_buf(bp);
7393 	return (lun_total);
7394 }
7395 
7396 static void
7397 aac_devcfg(struct aac_softstate *softs, int tgt, int en)
7398 {
7399 	struct aac_device *dvp;
7400 
7401 	mutex_enter(&softs->io_lock);
7402 	dvp = AAC_DEV(softs, tgt);
7403 	if (en)
7404 		dvp->flags |= AAC_DFLAG_CONFIGURING;
7405 	else
7406 		dvp->flags &= ~AAC_DFLAG_CONFIGURING;
7407 	mutex_exit(&softs->io_lock);
7408 }
7409 
7410 static int
7411 aac_tran_bus_config(dev_info_t *parent, uint_t flags, ddi_bus_config_op_t op,
7412     void *arg, dev_info_t **childp)
7413 {
7414 	struct aac_softstate *softs;
7415 	int circ = 0;
7416 	int rval;
7417 
7418 	if ((softs = ddi_get_soft_state(aac_softstatep,
7419 	    ddi_get_instance(parent))) == NULL)
7420 		return (NDI_FAILURE);
7421 
7422 	/* Commands for bus config should be blocked as the bus is quiesced */
7423 	mutex_enter(&softs->io_lock);
7424 	if (softs->state & AAC_STATE_QUIESCED) {
7425 		AACDB_PRINT(softs, CE_NOTE,
7426 		    "bus_config abroted because bus is quiesced");
7427 		mutex_exit(&softs->io_lock);
7428 		return (NDI_FAILURE);
7429 	}
7430 	mutex_exit(&softs->io_lock);
7431 
7432 	DBCALLED(softs, 1);
7433 
7434 	/* Hold the nexus across the bus_config */
7435 	ndi_devi_enter(parent, &circ);
7436 	switch (op) {
7437 	case BUS_CONFIG_ONE: {
7438 		int tgt, lun;
7439 
7440 		if (aac_parse_devname(arg, &tgt, &lun) != AACOK) {
7441 			rval = NDI_FAILURE;
7442 			break;
7443 		}
7444 		if (tgt >= AAC_MAX_LD) {
7445 			if (tgt >= AAC_MAX_DEV(softs)) {
7446 				rval = NDI_FAILURE;
7447 				break;
7448 			}
7449 		}
7450 
7451 		AAC_DEVCFG_BEGIN(softs, tgt);
7452 		rval = aac_config_lun(softs, tgt, lun, childp);
7453 		AAC_DEVCFG_END(softs, tgt);
7454 		break;
7455 	}
7456 
7457 	case BUS_CONFIG_DRIVER:
7458 	case BUS_CONFIG_ALL: {
7459 		uint32_t bus, tgt;
7460 		int index, total;
7461 
7462 		for (tgt = 0; tgt < AAC_MAX_LD; tgt++) {
7463 			AAC_DEVCFG_BEGIN(softs, tgt);
7464 			(void) aac_config_lun(softs, tgt, 0, NULL);
7465 			AAC_DEVCFG_END(softs, tgt);
7466 		}
7467 
7468 		/* Config the non-DASD devices connected to the card */
7469 		total = 0;
7470 		index = AAC_MAX_LD;
7471 		for (bus = 0; bus < softs->bus_max; bus++) {
7472 			AACDB_PRINT(softs, CE_NOTE, "bus %d:", bus);
7473 			for (tgt = 0; tgt < softs->tgt_max; tgt++, index++) {
7474 				AAC_DEVCFG_BEGIN(softs, index);
7475 				if (aac_config_tgt(softs, index))
7476 					total++;
7477 				AAC_DEVCFG_END(softs, index);
7478 			}
7479 		}
7480 		AACDB_PRINT(softs, CE_CONT,
7481 		    "?Total %d phys. device(s) found", total);
7482 		rval = NDI_SUCCESS;
7483 		break;
7484 	}
7485 	}
7486 
7487 	if (rval == NDI_SUCCESS)
7488 		rval = ndi_busop_bus_config(parent, flags, op, arg, childp, 0);
7489 	ndi_devi_exit(parent, circ);
7490 	return (rval);
7491 }
7492 
7493 /*ARGSUSED*/
7494 static int
7495 aac_handle_dr(struct aac_softstate *softs, int tgt, int lun, int event)
7496 {
7497 	struct aac_device *dvp;
7498 	dev_info_t *dip;
7499 	int valid;
7500 	int circ1 = 0;
7501 
7502 	DBCALLED(softs, 1);
7503 
7504 	/* Hold the nexus across the bus_config */
7505 	dvp = AAC_DEV(softs, tgt);
7506 	valid = AAC_DEV_IS_VALID(dvp);
7507 	dip = dvp->dip;
7508 	if (!(softs->state & AAC_STATE_RUN))
7509 		return (AACERR);
7510 	mutex_exit(&softs->io_lock);
7511 
7512 	switch (event) {
7513 	case AAC_CFG_ADD:
7514 	case AAC_CFG_DELETE:
7515 		/* Device onlined */
7516 		if (dip == NULL && valid) {
7517 			ndi_devi_enter(softs->devinfo_p, &circ1);
7518 			(void) aac_config_lun(softs, tgt, 0, NULL);
7519 			AACDB_PRINT(softs, CE_NOTE, "c%dt%dL%d onlined",
7520 			    softs->instance, tgt, lun);
7521 			ndi_devi_exit(softs->devinfo_p, circ1);
7522 		}
7523 		/* Device offlined */
7524 		if (dip && !valid) {
7525 			mutex_enter(&softs->io_lock);
7526 			(void) aac_do_reset(softs);
7527 			mutex_exit(&softs->io_lock);
7528 
7529 			(void) ndi_devi_offline(dip, NDI_DEVI_REMOVE);
7530 			AACDB_PRINT(softs, CE_NOTE, "c%dt%dL%d offlined",
7531 			    softs->instance, tgt, lun);
7532 		}
7533 		break;
7534 	}
7535 
7536 	mutex_enter(&softs->io_lock);
7537 	return (AACOK);
7538 }
7539 
7540 #ifdef DEBUG
7541 
7542 /* -------------------------debug aid functions-------------------------- */
7543 
7544 #define	AAC_FIB_CMD_KEY_STRINGS \
7545 	TestCommandResponse, "TestCommandResponse", \
7546 	TestAdapterCommand, "TestAdapterCommand", \
7547 	LastTestCommand, "LastTestCommand", \
7548 	ReinitHostNormCommandQueue, "ReinitHostNormCommandQueue", \
7549 	ReinitHostHighCommandQueue, "ReinitHostHighCommandQueue", \
7550 	ReinitHostHighRespQueue, "ReinitHostHighRespQueue", \
7551 	ReinitHostNormRespQueue, "ReinitHostNormRespQueue", \
7552 	ReinitAdapNormCommandQueue, "ReinitAdapNormCommandQueue", \
7553 	ReinitAdapHighCommandQueue, "ReinitAdapHighCommandQueue", \
7554 	ReinitAdapHighRespQueue, "ReinitAdapHighRespQueue", \
7555 	ReinitAdapNormRespQueue, "ReinitAdapNormRespQueue", \
7556 	InterfaceShutdown, "InterfaceShutdown", \
7557 	DmaCommandFib, "DmaCommandFib", \
7558 	StartProfile, "StartProfile", \
7559 	TermProfile, "TermProfile", \
7560 	SpeedTest, "SpeedTest", \
7561 	TakeABreakPt, "TakeABreakPt", \
7562 	RequestPerfData, "RequestPerfData", \
7563 	SetInterruptDefTimer, "SetInterruptDefTimer", \
7564 	SetInterruptDefCount, "SetInterruptDefCount", \
7565 	GetInterruptDefStatus, "GetInterruptDefStatus", \
7566 	LastCommCommand, "LastCommCommand", \
7567 	NuFileSystem, "NuFileSystem", \
7568 	UFS, "UFS", \
7569 	HostFileSystem, "HostFileSystem", \
7570 	LastFileSystemCommand, "LastFileSystemCommand", \
7571 	ContainerCommand, "ContainerCommand", \
7572 	ContainerCommand64, "ContainerCommand64", \
7573 	ClusterCommand, "ClusterCommand", \
7574 	ScsiPortCommand, "ScsiPortCommand", \
7575 	ScsiPortCommandU64, "ScsiPortCommandU64", \
7576 	AifRequest, "AifRequest", \
7577 	CheckRevision, "CheckRevision", \
7578 	FsaHostShutdown, "FsaHostShutdown", \
7579 	RequestAdapterInfo, "RequestAdapterInfo", \
7580 	IsAdapterPaused, "IsAdapterPaused", \
7581 	SendHostTime, "SendHostTime", \
7582 	LastMiscCommand, "LastMiscCommand"
7583 
7584 #define	AAC_CTVM_SUBCMD_KEY_STRINGS \
7585 	VM_Null, "VM_Null", \
7586 	VM_NameServe, "VM_NameServe", \
7587 	VM_ContainerConfig, "VM_ContainerConfig", \
7588 	VM_Ioctl, "VM_Ioctl", \
7589 	VM_FilesystemIoctl, "VM_FilesystemIoctl", \
7590 	VM_CloseAll, "VM_CloseAll", \
7591 	VM_CtBlockRead, "VM_CtBlockRead", \
7592 	VM_CtBlockWrite, "VM_CtBlockWrite", \
7593 	VM_SliceBlockRead, "VM_SliceBlockRead", \
7594 	VM_SliceBlockWrite, "VM_SliceBlockWrite", \
7595 	VM_DriveBlockRead, "VM_DriveBlockRead", \
7596 	VM_DriveBlockWrite, "VM_DriveBlockWrite", \
7597 	VM_EnclosureMgt, "VM_EnclosureMgt", \
7598 	VM_Unused, "VM_Unused", \
7599 	VM_CtBlockVerify, "VM_CtBlockVerify", \
7600 	VM_CtPerf, "VM_CtPerf", \
7601 	VM_CtBlockRead64, "VM_CtBlockRead64", \
7602 	VM_CtBlockWrite64, "VM_CtBlockWrite64", \
7603 	VM_CtBlockVerify64, "VM_CtBlockVerify64", \
7604 	VM_CtHostRead64, "VM_CtHostRead64", \
7605 	VM_CtHostWrite64, "VM_CtHostWrite64", \
7606 	VM_NameServe64, "VM_NameServe64"
7607 
7608 #define	AAC_CT_SUBCMD_KEY_STRINGS \
7609 	CT_Null, "CT_Null", \
7610 	CT_GET_SLICE_COUNT, "CT_GET_SLICE_COUNT", \
7611 	CT_GET_PARTITION_COUNT, "CT_GET_PARTITION_COUNT", \
7612 	CT_GET_PARTITION_INFO, "CT_GET_PARTITION_INFO", \
7613 	CT_GET_CONTAINER_COUNT, "CT_GET_CONTAINER_COUNT", \
7614 	CT_GET_CONTAINER_INFO_OLD, "CT_GET_CONTAINER_INFO_OLD", \
7615 	CT_WRITE_MBR, "CT_WRITE_MBR", \
7616 	CT_WRITE_PARTITION, "CT_WRITE_PARTITION", \
7617 	CT_UPDATE_PARTITION, "CT_UPDATE_PARTITION", \
7618 	CT_UNLOAD_CONTAINER, "CT_UNLOAD_CONTAINER", \
7619 	CT_CONFIG_SINGLE_PRIMARY, "CT_CONFIG_SINGLE_PRIMARY", \
7620 	CT_READ_CONFIG_AGE, "CT_READ_CONFIG_AGE", \
7621 	CT_WRITE_CONFIG_AGE, "CT_WRITE_CONFIG_AGE", \
7622 	CT_READ_SERIAL_NUMBER, "CT_READ_SERIAL_NUMBER", \
7623 	CT_ZERO_PAR_ENTRY, "CT_ZERO_PAR_ENTRY", \
7624 	CT_READ_MBR, "CT_READ_MBR", \
7625 	CT_READ_PARTITION, "CT_READ_PARTITION", \
7626 	CT_DESTROY_CONTAINER, "CT_DESTROY_CONTAINER", \
7627 	CT_DESTROY2_CONTAINER, "CT_DESTROY2_CONTAINER", \
7628 	CT_SLICE_SIZE, "CT_SLICE_SIZE", \
7629 	CT_CHECK_CONFLICTS, "CT_CHECK_CONFLICTS", \
7630 	CT_MOVE_CONTAINER, "CT_MOVE_CONTAINER", \
7631 	CT_READ_LAST_DRIVE, "CT_READ_LAST_DRIVE", \
7632 	CT_WRITE_LAST_DRIVE, "CT_WRITE_LAST_DRIVE", \
7633 	CT_UNMIRROR, "CT_UNMIRROR", \
7634 	CT_MIRROR_DELAY, "CT_MIRROR_DELAY", \
7635 	CT_GEN_MIRROR, "CT_GEN_MIRROR", \
7636 	CT_GEN_MIRROR2, "CT_GEN_MIRROR2", \
7637 	CT_TEST_CONTAINER, "CT_TEST_CONTAINER", \
7638 	CT_MOVE2, "CT_MOVE2", \
7639 	CT_SPLIT, "CT_SPLIT", \
7640 	CT_SPLIT2, "CT_SPLIT2", \
7641 	CT_SPLIT_BROKEN, "CT_SPLIT_BROKEN", \
7642 	CT_SPLIT_BROKEN2, "CT_SPLIT_BROKEN2", \
7643 	CT_RECONFIG, "CT_RECONFIG", \
7644 	CT_BREAK2, "CT_BREAK2", \
7645 	CT_BREAK, "CT_BREAK", \
7646 	CT_MERGE2, "CT_MERGE2", \
7647 	CT_MERGE, "CT_MERGE", \
7648 	CT_FORCE_ERROR, "CT_FORCE_ERROR", \
7649 	CT_CLEAR_ERROR, "CT_CLEAR_ERROR", \
7650 	CT_ASSIGN_FAILOVER, "CT_ASSIGN_FAILOVER", \
7651 	CT_CLEAR_FAILOVER, "CT_CLEAR_FAILOVER", \
7652 	CT_GET_FAILOVER_DATA, "CT_GET_FAILOVER_DATA", \
7653 	CT_VOLUME_ADD, "CT_VOLUME_ADD", \
7654 	CT_VOLUME_ADD2, "CT_VOLUME_ADD2", \
7655 	CT_MIRROR_STATUS, "CT_MIRROR_STATUS", \
7656 	CT_COPY_STATUS, "CT_COPY_STATUS", \
7657 	CT_COPY, "CT_COPY", \
7658 	CT_UNLOCK_CONTAINER, "CT_UNLOCK_CONTAINER", \
7659 	CT_LOCK_CONTAINER, "CT_LOCK_CONTAINER", \
7660 	CT_MAKE_READ_ONLY, "CT_MAKE_READ_ONLY", \
7661 	CT_MAKE_READ_WRITE, "CT_MAKE_READ_WRITE", \
7662 	CT_CLEAN_DEAD, "CT_CLEAN_DEAD", \
7663 	CT_ABORT_MIRROR_COMMAND, "CT_ABORT_MIRROR_COMMAND", \
7664 	CT_SET, "CT_SET", \
7665 	CT_GET, "CT_GET", \
7666 	CT_GET_NVLOG_ENTRY, "CT_GET_NVLOG_ENTRY", \
7667 	CT_GET_DELAY, "CT_GET_DELAY", \
7668 	CT_ZERO_CONTAINER_SPACE, "CT_ZERO_CONTAINER_SPACE", \
7669 	CT_GET_ZERO_STATUS, "CT_GET_ZERO_STATUS", \
7670 	CT_SCRUB, "CT_SCRUB", \
7671 	CT_GET_SCRUB_STATUS, "CT_GET_SCRUB_STATUS", \
7672 	CT_GET_SLICE_INFO, "CT_GET_SLICE_INFO", \
7673 	CT_GET_SCSI_METHOD, "CT_GET_SCSI_METHOD", \
7674 	CT_PAUSE_IO, "CT_PAUSE_IO", \
7675 	CT_RELEASE_IO, "CT_RELEASE_IO", \
7676 	CT_SCRUB2, "CT_SCRUB2", \
7677 	CT_MCHECK, "CT_MCHECK", \
7678 	CT_CORRUPT, "CT_CORRUPT", \
7679 	CT_GET_TASK_COUNT, "CT_GET_TASK_COUNT", \
7680 	CT_PROMOTE, "CT_PROMOTE", \
7681 	CT_SET_DEAD, "CT_SET_DEAD", \
7682 	CT_CONTAINER_OPTIONS, "CT_CONTAINER_OPTIONS", \
7683 	CT_GET_NV_PARAM, "CT_GET_NV_PARAM", \
7684 	CT_GET_PARAM, "CT_GET_PARAM", \
7685 	CT_NV_PARAM_SIZE, "CT_NV_PARAM_SIZE", \
7686 	CT_COMMON_PARAM_SIZE, "CT_COMMON_PARAM_SIZE", \
7687 	CT_PLATFORM_PARAM_SIZE, "CT_PLATFORM_PARAM_SIZE", \
7688 	CT_SET_NV_PARAM, "CT_SET_NV_PARAM", \
7689 	CT_ABORT_SCRUB, "CT_ABORT_SCRUB", \
7690 	CT_GET_SCRUB_ERROR, "CT_GET_SCRUB_ERROR", \
7691 	CT_LABEL_CONTAINER, "CT_LABEL_CONTAINER", \
7692 	CT_CONTINUE_DATA, "CT_CONTINUE_DATA", \
7693 	CT_STOP_DATA, "CT_STOP_DATA", \
7694 	CT_GET_PARTITION_TABLE, "CT_GET_PARTITION_TABLE", \
7695 	CT_GET_DISK_PARTITIONS, "CT_GET_DISK_PARTITIONS", \
7696 	CT_GET_MISC_STATUS, "CT_GET_MISC_STATUS", \
7697 	CT_GET_CONTAINER_PERF_INFO, "CT_GET_CONTAINER_PERF_INFO", \
7698 	CT_GET_TIME, "CT_GET_TIME", \
7699 	CT_READ_DATA, "CT_READ_DATA", \
7700 	CT_CTR, "CT_CTR", \
7701 	CT_CTL, "CT_CTL", \
7702 	CT_DRAINIO, "CT_DRAINIO", \
7703 	CT_RELEASEIO, "CT_RELEASEIO", \
7704 	CT_GET_NVRAM, "CT_GET_NVRAM", \
7705 	CT_GET_MEMORY, "CT_GET_MEMORY", \
7706 	CT_PRINT_CT_LOG, "CT_PRINT_CT_LOG", \
7707 	CT_ADD_LEVEL, "CT_ADD_LEVEL", \
7708 	CT_NV_ZERO, "CT_NV_ZERO", \
7709 	CT_READ_SIGNATURE, "CT_READ_SIGNATURE", \
7710 	CT_THROTTLE_ON, "CT_THROTTLE_ON", \
7711 	CT_THROTTLE_OFF, "CT_THROTTLE_OFF", \
7712 	CT_GET_THROTTLE_STATS, "CT_GET_THROTTLE_STATS", \
7713 	CT_MAKE_SNAPSHOT, "CT_MAKE_SNAPSHOT", \
7714 	CT_REMOVE_SNAPSHOT, "CT_REMOVE_SNAPSHOT", \
7715 	CT_WRITE_USER_FLAGS, "CT_WRITE_USER_FLAGS", \
7716 	CT_READ_USER_FLAGS, "CT_READ_USER_FLAGS", \
7717 	CT_MONITOR, "CT_MONITOR", \
7718 	CT_GEN_MORPH, "CT_GEN_MORPH", \
7719 	CT_GET_SNAPSHOT_INFO, "CT_GET_SNAPSHOT_INFO", \
7720 	CT_CACHE_SET, "CT_CACHE_SET", \
7721 	CT_CACHE_STAT, "CT_CACHE_STAT", \
7722 	CT_TRACE_START, "CT_TRACE_START", \
7723 	CT_TRACE_STOP, "CT_TRACE_STOP", \
7724 	CT_TRACE_ENABLE, "CT_TRACE_ENABLE", \
7725 	CT_TRACE_DISABLE, "CT_TRACE_DISABLE", \
7726 	CT_FORCE_CORE_DUMP, "CT_FORCE_CORE_DUMP", \
7727 	CT_SET_SERIAL_NUMBER, "CT_SET_SERIAL_NUMBER", \
7728 	CT_RESET_SERIAL_NUMBER, "CT_RESET_SERIAL_NUMBER", \
7729 	CT_ENABLE_RAID5, "CT_ENABLE_RAID5", \
7730 	CT_CLEAR_VALID_DUMP_FLAG, "CT_CLEAR_VALID_DUMP_FLAG", \
7731 	CT_GET_MEM_STATS, "CT_GET_MEM_STATS", \
7732 	CT_GET_CORE_SIZE, "CT_GET_CORE_SIZE", \
7733 	CT_CREATE_CONTAINER_OLD, "CT_CREATE_CONTAINER_OLD", \
7734 	CT_STOP_DUMPS, "CT_STOP_DUMPS", \
7735 	CT_PANIC_ON_TAKE_A_BREAK, "CT_PANIC_ON_TAKE_A_BREAK", \
7736 	CT_GET_CACHE_STATS, "CT_GET_CACHE_STATS", \
7737 	CT_MOVE_PARTITION, "CT_MOVE_PARTITION", \
7738 	CT_FLUSH_CACHE, "CT_FLUSH_CACHE", \
7739 	CT_READ_NAME, "CT_READ_NAME", \
7740 	CT_WRITE_NAME, "CT_WRITE_NAME", \
7741 	CT_TOSS_CACHE, "CT_TOSS_CACHE", \
7742 	CT_LOCK_DRAINIO, "CT_LOCK_DRAINIO", \
7743 	CT_CONTAINER_OFFLINE, "CT_CONTAINER_OFFLINE", \
7744 	CT_SET_CACHE_SIZE, "CT_SET_CACHE_SIZE", \
7745 	CT_CLEAN_SHUTDOWN_STATUS, "CT_CLEAN_SHUTDOWN_STATUS", \
7746 	CT_CLEAR_DISKLOG_ON_DISK, "CT_CLEAR_DISKLOG_ON_DISK", \
7747 	CT_CLEAR_ALL_DISKLOG, "CT_CLEAR_ALL_DISKLOG", \
7748 	CT_CACHE_FAVOR, "CT_CACHE_FAVOR", \
7749 	CT_READ_PASSTHRU_MBR, "CT_READ_PASSTHRU_MBR", \
7750 	CT_SCRUB_NOFIX, "CT_SCRUB_NOFIX", \
7751 	CT_SCRUB2_NOFIX, "CT_SCRUB2_NOFIX", \
7752 	CT_FLUSH, "CT_FLUSH", \
7753 	CT_REBUILD, "CT_REBUILD", \
7754 	CT_FLUSH_CONTAINER, "CT_FLUSH_CONTAINER", \
7755 	CT_RESTART, "CT_RESTART", \
7756 	CT_GET_CONFIG_STATUS, "CT_GET_CONFIG_STATUS", \
7757 	CT_TRACE_FLAG, "CT_TRACE_FLAG", \
7758 	CT_RESTART_MORPH, "CT_RESTART_MORPH", \
7759 	CT_GET_TRACE_INFO, "CT_GET_TRACE_INFO", \
7760 	CT_GET_TRACE_ITEM, "CT_GET_TRACE_ITEM", \
7761 	CT_COMMIT_CONFIG, "CT_COMMIT_CONFIG", \
7762 	CT_CONTAINER_EXISTS, "CT_CONTAINER_EXISTS", \
7763 	CT_GET_SLICE_FROM_DEVT, "CT_GET_SLICE_FROM_DEVT", \
7764 	CT_OPEN_READ_WRITE, "CT_OPEN_READ_WRITE", \
7765 	CT_WRITE_MEMORY_BLOCK, "CT_WRITE_MEMORY_BLOCK", \
7766 	CT_GET_CACHE_PARAMS, "CT_GET_CACHE_PARAMS", \
7767 	CT_CRAZY_CACHE, "CT_CRAZY_CACHE", \
7768 	CT_GET_PROFILE_STRUCT, "CT_GET_PROFILE_STRUCT", \
7769 	CT_SET_IO_TRACE_FLAG, "CT_SET_IO_TRACE_FLAG", \
7770 	CT_GET_IO_TRACE_STRUCT, "CT_GET_IO_TRACE_STRUCT", \
7771 	CT_CID_TO_64BITS_UID, "CT_CID_TO_64BITS_UID", \
7772 	CT_64BITS_UID_TO_CID, "CT_64BITS_UID_TO_CID", \
7773 	CT_PAR_TO_64BITS_UID, "CT_PAR_TO_64BITS_UID", \
7774 	CT_CID_TO_32BITS_UID, "CT_CID_TO_32BITS_UID", \
7775 	CT_32BITS_UID_TO_CID, "CT_32BITS_UID_TO_CID", \
7776 	CT_PAR_TO_32BITS_UID, "CT_PAR_TO_32BITS_UID", \
7777 	CT_SET_FAILOVER_OPTION, "CT_SET_FAILOVER_OPTION", \
7778 	CT_GET_FAILOVER_OPTION, "CT_GET_FAILOVER_OPTION", \
7779 	CT_STRIPE_ADD2, "CT_STRIPE_ADD2", \
7780 	CT_CREATE_VOLUME_SET, "CT_CREATE_VOLUME_SET", \
7781 	CT_CREATE_STRIPE_SET, "CT_CREATE_STRIPE_SET", \
7782 	CT_VERIFY_CONTAINER, "CT_VERIFY_CONTAINER", \
7783 	CT_IS_CONTAINER_DEAD, "CT_IS_CONTAINER_DEAD", \
7784 	CT_GET_CONTAINER_OPTION, "CT_GET_CONTAINER_OPTION", \
7785 	CT_GET_SNAPSHOT_UNUSED_STRUCT, "CT_GET_SNAPSHOT_UNUSED_STRUCT", \
7786 	CT_CLEAR_SNAPSHOT_UNUSED_STRUCT, "CT_CLEAR_SNAPSHOT_UNUSED_STRUCT", \
7787 	CT_GET_CONTAINER_INFO, "CT_GET_CONTAINER_INFO", \
7788 	CT_CREATE_CONTAINER, "CT_CREATE_CONTAINER", \
7789 	CT_CHANGE_CREATIONINFO, "CT_CHANGE_CREATIONINFO", \
7790 	CT_CHECK_CONFLICT_UID, "CT_CHECK_CONFLICT_UID", \
7791 	CT_CONTAINER_UID_CHECK, "CT_CONTAINER_UID_CHECK", \
7792 	CT_IS_CONTAINER_MEATADATA_STANDARD, \
7793 	    "CT_IS_CONTAINER_MEATADATA_STANDARD", \
7794 	CT_IS_SLICE_METADATA_STANDARD, "CT_IS_SLICE_METADATA_STANDARD", \
7795 	CT_GET_IMPORT_COUNT, "CT_GET_IMPORT_COUNT", \
7796 	CT_CANCEL_ALL_IMPORTS, "CT_CANCEL_ALL_IMPORTS", \
7797 	CT_GET_IMPORT_INFO, "CT_GET_IMPORT_INFO", \
7798 	CT_IMPORT_ARRAY, "CT_IMPORT_ARRAY", \
7799 	CT_GET_LOG_SIZE, "CT_GET_LOG_SIZE", \
7800 	CT_ALARM_GET_STATE, "CT_ALARM_GET_STATE", \
7801 	CT_ALARM_SET_STATE, "CT_ALARM_SET_STATE", \
7802 	CT_ALARM_ON_OFF, "CT_ALARM_ON_OFF", \
7803 	CT_GET_EE_OEM_ID, "CT_GET_EE_OEM_ID", \
7804 	CT_GET_PPI_HEADERS, "CT_GET_PPI_HEADERS", \
7805 	CT_GET_PPI_DATA, "CT_GET_PPI_DATA", \
7806 	CT_GET_PPI_ENTRIES, "CT_GET_PPI_ENTRIES", \
7807 	CT_DELETE_PPI_BUNDLE, "CT_DELETE_PPI_BUNDLE", \
7808 	CT_GET_PARTITION_TABLE_2, "CT_GET_PARTITION_TABLE_2", \
7809 	CT_GET_PARTITION_INFO_2, "CT_GET_PARTITION_INFO_2", \
7810 	CT_GET_DISK_PARTITIONS_2, "CT_GET_DISK_PARTITIONS_2", \
7811 	CT_QUIESCE_ADAPTER, "CT_QUIESCE_ADAPTER", \
7812 	CT_CLEAR_PPI_TABLE, "CT_CLEAR_PPI_TABLE"
7813 
7814 #define	AAC_CL_SUBCMD_KEY_STRINGS \
7815 	CL_NULL, "CL_NULL", \
7816 	DS_INIT, "DS_INIT", \
7817 	DS_RESCAN, "DS_RESCAN", \
7818 	DS_CREATE, "DS_CREATE", \
7819 	DS_DELETE, "DS_DELETE", \
7820 	DS_ADD_DISK, "DS_ADD_DISK", \
7821 	DS_REMOVE_DISK, "DS_REMOVE_DISK", \
7822 	DS_MOVE_DISK, "DS_MOVE_DISK", \
7823 	DS_TAKE_OWNERSHIP, "DS_TAKE_OWNERSHIP", \
7824 	DS_RELEASE_OWNERSHIP, "DS_RELEASE_OWNERSHIP", \
7825 	DS_FORCE_OWNERSHIP, "DS_FORCE_OWNERSHIP", \
7826 	DS_GET_DISK_SET_PARAM, "DS_GET_DISK_SET_PARAM", \
7827 	DS_GET_DRIVE_PARAM, "DS_GET_DRIVE_PARAM", \
7828 	DS_GET_SLICE_PARAM, "DS_GET_SLICE_PARAM", \
7829 	DS_GET_DISK_SETS, "DS_GET_DISK_SETS", \
7830 	DS_GET_DRIVES, "DS_GET_DRIVES", \
7831 	DS_SET_DISK_SET_PARAM, "DS_SET_DISK_SET_PARAM", \
7832 	DS_ONLINE, "DS_ONLINE", \
7833 	DS_OFFLINE, "DS_OFFLINE", \
7834 	DS_ONLINE_CONTAINERS, "DS_ONLINE_CONTAINERS", \
7835 	DS_FSAPRINT, "DS_FSAPRINT", \
7836 	CL_CFG_SET_HOST_IDS, "CL_CFG_SET_HOST_IDS", \
7837 	CL_CFG_SET_PARTNER_HOST_IDS, "CL_CFG_SET_PARTNER_HOST_IDS", \
7838 	CL_CFG_GET_CLUSTER_CONFIG, "CL_CFG_GET_CLUSTER_CONFIG", \
7839 	CC_CLI_CLEAR_MESSAGE_BUFFER, "CC_CLI_CLEAR_MESSAGE_BUFFER", \
7840 	CC_SRV_CLEAR_MESSAGE_BUFFER, "CC_SRV_CLEAR_MESSAGE_BUFFER", \
7841 	CC_CLI_SHOW_MESSAGE_BUFFER, "CC_CLI_SHOW_MESSAGE_BUFFER", \
7842 	CC_SRV_SHOW_MESSAGE_BUFFER, "CC_SRV_SHOW_MESSAGE_BUFFER", \
7843 	CC_CLI_SEND_MESSAGE, "CC_CLI_SEND_MESSAGE", \
7844 	CC_SRV_SEND_MESSAGE, "CC_SRV_SEND_MESSAGE", \
7845 	CC_CLI_GET_MESSAGE, "CC_CLI_GET_MESSAGE", \
7846 	CC_SRV_GET_MESSAGE, "CC_SRV_GET_MESSAGE", \
7847 	CC_SEND_TEST_MESSAGE, "CC_SEND_TEST_MESSAGE", \
7848 	CC_GET_BUSINFO, "CC_GET_BUSINFO", \
7849 	CC_GET_PORTINFO, "CC_GET_PORTINFO", \
7850 	CC_GET_NAMEINFO, "CC_GET_NAMEINFO", \
7851 	CC_GET_CONFIGINFO, "CC_GET_CONFIGINFO", \
7852 	CQ_QUORUM_OP, "CQ_QUORUM_OP"
7853 
7854 #define	AAC_AIF_SUBCMD_KEY_STRINGS \
7855 	AifCmdEventNotify, "AifCmdEventNotify", \
7856 	AifCmdJobProgress, "AifCmdJobProgress", \
7857 	AifCmdAPIReport, "AifCmdAPIReport", \
7858 	AifCmdDriverNotify, "AifCmdDriverNotify", \
7859 	AifReqJobList, "AifReqJobList", \
7860 	AifReqJobsForCtr, "AifReqJobsForCtr", \
7861 	AifReqJobsForScsi, "AifReqJobsForScsi", \
7862 	AifReqJobReport, "AifReqJobReport", \
7863 	AifReqTerminateJob, "AifReqTerminateJob", \
7864 	AifReqSuspendJob, "AifReqSuspendJob", \
7865 	AifReqResumeJob, "AifReqResumeJob", \
7866 	AifReqSendAPIReport, "AifReqSendAPIReport", \
7867 	AifReqAPIJobStart, "AifReqAPIJobStart", \
7868 	AifReqAPIJobUpdate, "AifReqAPIJobUpdate", \
7869 	AifReqAPIJobFinish, "AifReqAPIJobFinish"
7870 
7871 #define	AAC_IOCTL_SUBCMD_KEY_STRINGS \
7872 	Reserved_IOCTL, "Reserved_IOCTL", \
7873 	GetDeviceHandle, "GetDeviceHandle", \
7874 	BusTargetLun_to_DeviceHandle, "BusTargetLun_to_DeviceHandle", \
7875 	DeviceHandle_to_BusTargetLun, "DeviceHandle_to_BusTargetLun", \
7876 	RescanBus, "RescanBus", \
7877 	GetDeviceProbeInfo, "GetDeviceProbeInfo", \
7878 	GetDeviceCapacity, "GetDeviceCapacity", \
7879 	GetContainerProbeInfo, "GetContainerProbeInfo", \
7880 	GetRequestedMemorySize, "GetRequestedMemorySize", \
7881 	GetBusInfo, "GetBusInfo", \
7882 	GetVendorSpecific, "GetVendorSpecific", \
7883 	EnhancedGetDeviceProbeInfo, "EnhancedGetDeviceProbeInfo", \
7884 	EnhancedGetBusInfo, "EnhancedGetBusInfo", \
7885 	SetupExtendedCounters, "SetupExtendedCounters", \
7886 	GetPerformanceCounters, "GetPerformanceCounters", \
7887 	ResetPerformanceCounters, "ResetPerformanceCounters", \
7888 	ReadModePage, "ReadModePage", \
7889 	WriteModePage, "WriteModePage", \
7890 	ReadDriveParameter, "ReadDriveParameter", \
7891 	WriteDriveParameter, "WriteDriveParameter", \
7892 	ResetAdapter, "ResetAdapter", \
7893 	ResetBus, "ResetBus", \
7894 	ResetBusDevice, "ResetBusDevice", \
7895 	ExecuteSrb, "ExecuteSrb", \
7896 	Create_IO_Task, "Create_IO_Task", \
7897 	Delete_IO_Task, "Delete_IO_Task", \
7898 	Get_IO_Task_Info, "Get_IO_Task_Info", \
7899 	Check_Task_Progress, "Check_Task_Progress", \
7900 	InjectError, "InjectError", \
7901 	GetDeviceDefectCounts, "GetDeviceDefectCounts", \
7902 	GetDeviceDefectInfo, "GetDeviceDefectInfo", \
7903 	GetDeviceStatus, "GetDeviceStatus", \
7904 	ClearDeviceStatus, "ClearDeviceStatus", \
7905 	DiskSpinControl, "DiskSpinControl", \
7906 	DiskSmartControl, "DiskSmartControl", \
7907 	WriteSame, "WriteSame", \
7908 	ReadWriteLong, "ReadWriteLong", \
7909 	FormatUnit, "FormatUnit", \
7910 	TargetDeviceControl, "TargetDeviceControl", \
7911 	TargetChannelControl, "TargetChannelControl", \
7912 	FlashNewCode, "FlashNewCode", \
7913 	DiskCheck, "DiskCheck", \
7914 	RequestSense, "RequestSense", \
7915 	DiskPERControl, "DiskPERControl", \
7916 	Read10, "Read10", \
7917 	Write10, "Write10"
7918 
7919 #define	AAC_AIFEN_KEY_STRINGS \
7920 	AifEnGeneric, "Generic", \
7921 	AifEnTaskComplete, "TaskComplete", \
7922 	AifEnConfigChange, "Config change", \
7923 	AifEnContainerChange, "Container change", \
7924 	AifEnDeviceFailure, "device failed", \
7925 	AifEnMirrorFailover, "Mirror failover", \
7926 	AifEnContainerEvent, "container event", \
7927 	AifEnFileSystemChange, "File system changed", \
7928 	AifEnConfigPause, "Container pause event", \
7929 	AifEnConfigResume, "Container resume event", \
7930 	AifEnFailoverChange, "Failover space assignment changed", \
7931 	AifEnRAID5RebuildDone, "RAID5 rebuild finished", \
7932 	AifEnEnclosureManagement, "Enclosure management event", \
7933 	AifEnBatteryEvent, "battery event", \
7934 	AifEnAddContainer, "Add container", \
7935 	AifEnDeleteContainer, "Delete container", \
7936 	AifEnSMARTEvent, "SMART Event", \
7937 	AifEnBatteryNeedsRecond, "battery needs reconditioning", \
7938 	AifEnClusterEvent, "cluster event", \
7939 	AifEnDiskSetEvent, "disk set event occured", \
7940 	AifDenMorphComplete, "morph operation completed", \
7941 	AifDenVolumeExtendComplete, "VolumeExtendComplete"
7942 
7943 struct aac_key_strings {
7944 	int key;
7945 	char *message;
7946 };
7947 
7948 extern struct scsi_key_strings scsi_cmds[];
7949 
7950 static struct aac_key_strings aac_fib_cmds[] = {
7951 	AAC_FIB_CMD_KEY_STRINGS,
7952 	-1,			NULL
7953 };
7954 
7955 static struct aac_key_strings aac_ctvm_subcmds[] = {
7956 	AAC_CTVM_SUBCMD_KEY_STRINGS,
7957 	-1,			NULL
7958 };
7959 
7960 static struct aac_key_strings aac_ct_subcmds[] = {
7961 	AAC_CT_SUBCMD_KEY_STRINGS,
7962 	-1,			NULL
7963 };
7964 
7965 static struct aac_key_strings aac_cl_subcmds[] = {
7966 	AAC_CL_SUBCMD_KEY_STRINGS,
7967 	-1,			NULL
7968 };
7969 
7970 static struct aac_key_strings aac_aif_subcmds[] = {
7971 	AAC_AIF_SUBCMD_KEY_STRINGS,
7972 	-1,			NULL
7973 };
7974 
7975 static struct aac_key_strings aac_ioctl_subcmds[] = {
7976 	AAC_IOCTL_SUBCMD_KEY_STRINGS,
7977 	-1,			NULL
7978 };
7979 
7980 static struct aac_key_strings aac_aifens[] = {
7981 	AAC_AIFEN_KEY_STRINGS,
7982 	-1,			NULL
7983 };
7984 
7985 /*
7986  * The following function comes from Adaptec:
7987  *
7988  * Get the firmware print buffer parameters from the firmware,
7989  * if the command was successful map in the address.
7990  */
7991 static int
7992 aac_get_fw_debug_buffer(struct aac_softstate *softs)
7993 {
7994 	if (aac_sync_mbcommand(softs, AAC_MONKER_GETDRVPROP,
7995 	    0, 0, 0, 0, NULL) == AACOK) {
7996 		uint32_t mondrv_buf_paddrl = AAC_MAILBOX_GET(softs, 1);
7997 		uint32_t mondrv_buf_paddrh = AAC_MAILBOX_GET(softs, 2);
7998 		uint32_t mondrv_buf_size = AAC_MAILBOX_GET(softs, 3);
7999 		uint32_t mondrv_hdr_size = AAC_MAILBOX_GET(softs, 4);
8000 
8001 		if (mondrv_buf_size) {
8002 			uint32_t offset = mondrv_buf_paddrl - \
8003 			    softs->pci_mem_base_paddr;
8004 
8005 			/*
8006 			 * See if the address is already mapped in, and
8007 			 * if so set it up from the base address
8008 			 */
8009 			if ((mondrv_buf_paddrh == 0) &&
8010 			    (offset + mondrv_buf_size < softs->map_size)) {
8011 				mutex_enter(&aac_prt_mutex);
8012 				softs->debug_buf_offset = offset;
8013 				softs->debug_header_size = mondrv_hdr_size;
8014 				softs->debug_buf_size = mondrv_buf_size;
8015 				softs->debug_fw_flags = 0;
8016 				softs->debug_flags &= ~AACDB_FLAGS_FW_PRINT;
8017 				mutex_exit(&aac_prt_mutex);
8018 
8019 				return (AACOK);
8020 			}
8021 		}
8022 	}
8023 	return (AACERR);
8024 }
8025 
8026 int
8027 aac_dbflag_on(struct aac_softstate *softs, int flag)
8028 {
8029 	int debug_flags = softs ? softs->debug_flags : aac_debug_flags;
8030 
8031 	return ((debug_flags & (AACDB_FLAGS_FW_PRINT | \
8032 	    AACDB_FLAGS_KERNEL_PRINT)) && (debug_flags & flag));
8033 }
8034 
8035 static void
8036 aac_cmn_err(struct aac_softstate *softs, uint_t lev, char sl, int noheader)
8037 {
8038 	if (noheader) {
8039 		if (sl) {
8040 			aac_fmt[0] = sl;
8041 			cmn_err(lev, aac_fmt, aac_prt_buf);
8042 		} else {
8043 			cmn_err(lev, &aac_fmt[1], aac_prt_buf);
8044 		}
8045 	} else {
8046 		if (sl) {
8047 			aac_fmt_header[0] = sl;
8048 			cmn_err(lev, aac_fmt_header,
8049 			    softs->vendor_name, softs->instance,
8050 			    aac_prt_buf);
8051 		} else {
8052 			cmn_err(lev, &aac_fmt_header[1],
8053 			    softs->vendor_name, softs->instance,
8054 			    aac_prt_buf);
8055 		}
8056 	}
8057 }
8058 
8059 /*
8060  * The following function comes from Adaptec:
8061  *
8062  * Format and print out the data passed in to UART or console
8063  * as specified by debug flags.
8064  */
8065 void
8066 aac_printf(struct aac_softstate *softs, uint_t lev, const char *fmt, ...)
8067 {
8068 	va_list args;
8069 	char sl; /* system log character */
8070 
8071 	mutex_enter(&aac_prt_mutex);
8072 	/* Set up parameters and call sprintf function to format the data */
8073 	if (strchr("^!?", fmt[0]) == NULL) {
8074 		sl = 0;
8075 	} else {
8076 		sl = fmt[0];
8077 		fmt++;
8078 	}
8079 	va_start(args, fmt);
8080 	(void) vsprintf(aac_prt_buf, fmt, args);
8081 	va_end(args);
8082 
8083 	/* Make sure the softs structure has been passed in for this section */
8084 	if (softs) {
8085 		if ((softs->debug_flags & AACDB_FLAGS_FW_PRINT) &&
8086 		    /* If we are set up for a Firmware print */
8087 		    (softs->debug_buf_size)) {
8088 			uint32_t count, i;
8089 
8090 			/* Make sure the string size is within boundaries */
8091 			count = strlen(aac_prt_buf);
8092 			if (count > softs->debug_buf_size)
8093 				count = (uint16_t)softs->debug_buf_size;
8094 
8095 			/*
8096 			 * Wait for no more than AAC_PRINT_TIMEOUT for the
8097 			 * previous message length to clear (the handshake).
8098 			 */
8099 			for (i = 0; i < AAC_PRINT_TIMEOUT; i++) {
8100 				if (!PCI_MEM_GET32(softs,
8101 				    softs->debug_buf_offset + \
8102 				    AAC_FW_DBG_STRLEN_OFFSET))
8103 					break;
8104 
8105 				drv_usecwait(1000);
8106 			}
8107 
8108 			/*
8109 			 * If the length is clear, copy over the message, the
8110 			 * flags, and the length. Make sure the length is the
8111 			 * last because that is the signal for the Firmware to
8112 			 * pick it up.
8113 			 */
8114 			if (!PCI_MEM_GET32(softs, softs->debug_buf_offset + \
8115 			    AAC_FW_DBG_STRLEN_OFFSET)) {
8116 				PCI_MEM_REP_PUT8(softs,
8117 				    softs->debug_buf_offset + \
8118 				    softs->debug_header_size,
8119 				    aac_prt_buf, count);
8120 				PCI_MEM_PUT32(softs,
8121 				    softs->debug_buf_offset + \
8122 				    AAC_FW_DBG_FLAGS_OFFSET,
8123 				    softs->debug_fw_flags);
8124 				PCI_MEM_PUT32(softs,
8125 				    softs->debug_buf_offset + \
8126 				    AAC_FW_DBG_STRLEN_OFFSET, count);
8127 			} else {
8128 				cmn_err(CE_WARN, "UART output fail");
8129 				softs->debug_flags &= ~AACDB_FLAGS_FW_PRINT;
8130 			}
8131 		}
8132 
8133 		/*
8134 		 * If the Kernel Debug Print flag is set, send it off
8135 		 * to the Kernel Debugger
8136 		 */
8137 		if (softs->debug_flags & AACDB_FLAGS_KERNEL_PRINT)
8138 			aac_cmn_err(softs, lev, sl,
8139 			    (softs->debug_flags & AACDB_FLAGS_NO_HEADERS));
8140 	} else {
8141 		/* Driver not initialized yet, no firmware or header output */
8142 		if (aac_debug_flags & AACDB_FLAGS_KERNEL_PRINT)
8143 			aac_cmn_err(softs, lev, sl, 1);
8144 	}
8145 	mutex_exit(&aac_prt_mutex);
8146 }
8147 
8148 /*
8149  * Translate command number to description string
8150  */
8151 static char *
8152 aac_cmd_name(int cmd, struct aac_key_strings *cmdlist)
8153 {
8154 	int i;
8155 
8156 	for (i = 0; cmdlist[i].key != -1; i++) {
8157 		if (cmd == cmdlist[i].key)
8158 			return (cmdlist[i].message);
8159 	}
8160 	return (NULL);
8161 }
8162 
8163 static void
8164 aac_print_scmd(struct aac_softstate *softs, struct aac_cmd *acp)
8165 {
8166 	struct scsi_pkt *pkt = acp->pkt;
8167 	struct scsi_address *ap = &pkt->pkt_address;
8168 	int is_pd = 0;
8169 	int ctl = ddi_get_instance(softs->devinfo_p);
8170 	int tgt = ap->a_target;
8171 	int lun = ap->a_lun;
8172 	union scsi_cdb *cdbp = (void *)pkt->pkt_cdbp;
8173 	uchar_t cmd = cdbp->scc_cmd;
8174 	char *desc;
8175 
8176 	if (tgt >= AAC_MAX_LD) {
8177 		is_pd = 1;
8178 		ctl = ((struct aac_nondasd *)acp->dvp)->bus;
8179 		tgt = ((struct aac_nondasd *)acp->dvp)->tid;
8180 		lun = 0;
8181 	}
8182 
8183 	if ((desc = aac_cmd_name(cmd,
8184 	    (struct aac_key_strings *)scsi_cmds)) == NULL) {
8185 		aac_printf(softs, CE_NOTE,
8186 		    "SCMD> Unknown(0x%2x) --> c%dt%dL%d %s",
8187 		    cmd, ctl, tgt, lun, is_pd ? "(pd)" : "");
8188 		return;
8189 	}
8190 
8191 	switch (cmd) {
8192 	case SCMD_READ:
8193 	case SCMD_WRITE:
8194 		aac_printf(softs, CE_NOTE,
8195 		    "SCMD> %s 0x%x[%d] %s --> c%dt%dL%d %s",
8196 		    desc, GETG0ADDR(cdbp), GETG0COUNT(cdbp),
8197 		    (acp->flags & AAC_CMD_NO_INTR) ? "poll" : "intr",
8198 		    ctl, tgt, lun, is_pd ? "(pd)" : "");
8199 		break;
8200 	case SCMD_READ_G1:
8201 	case SCMD_WRITE_G1:
8202 		aac_printf(softs, CE_NOTE,
8203 		    "SCMD> %s 0x%x[%d] %s --> c%dt%dL%d %s",
8204 		    desc, GETG1ADDR(cdbp), GETG1COUNT(cdbp),
8205 		    (acp->flags & AAC_CMD_NO_INTR) ? "poll" : "intr",
8206 		    ctl, tgt, lun, is_pd ? "(pd)" : "");
8207 		break;
8208 	case SCMD_READ_G4:
8209 	case SCMD_WRITE_G4:
8210 		aac_printf(softs, CE_NOTE,
8211 		    "SCMD> %s 0x%x.%08x[%d] %s --> c%dt%dL%d %s",
8212 		    desc, GETG4ADDR(cdbp), GETG4ADDRTL(cdbp),
8213 		    GETG4COUNT(cdbp),
8214 		    (acp->flags & AAC_CMD_NO_INTR) ? "poll" : "intr",
8215 		    ctl, tgt, lun, is_pd ? "(pd)" : "");
8216 		break;
8217 	case SCMD_READ_G5:
8218 	case SCMD_WRITE_G5:
8219 		aac_printf(softs, CE_NOTE,
8220 		    "SCMD> %s 0x%x[%d] %s --> c%dt%dL%d %s",
8221 		    desc, GETG5ADDR(cdbp), GETG5COUNT(cdbp),
8222 		    (acp->flags & AAC_CMD_NO_INTR) ? "poll" : "intr",
8223 		    ctl, tgt, lun, is_pd ? "(pd)" : "");
8224 		break;
8225 	default:
8226 		aac_printf(softs, CE_NOTE, "SCMD> %s --> c%dt%dL%d %s",
8227 		    desc, ctl, tgt, lun, is_pd ? "(pd)" : "");
8228 	}
8229 }
8230 
8231 void
8232 aac_print_fib(struct aac_softstate *softs, struct aac_slot *slotp)
8233 {
8234 	struct aac_cmd *acp = slotp->acp;
8235 	struct aac_fib *fibp = slotp->fibp;
8236 	ddi_acc_handle_t acc = slotp->fib_acc_handle;
8237 	uint16_t fib_size;
8238 	uint32_t fib_cmd, sub_cmd;
8239 	char *cmdstr, *subcmdstr;
8240 	char *caller;
8241 	int i;
8242 
8243 	if (acp) {
8244 		if (!(softs->debug_fib_flags & acp->fib_flags))
8245 			return;
8246 		if (acp->fib_flags & AACDB_FLAGS_FIB_SCMD)
8247 			caller = "SCMD";
8248 		else if (acp->fib_flags & AACDB_FLAGS_FIB_IOCTL)
8249 			caller = "IOCTL";
8250 		else if (acp->fib_flags & AACDB_FLAGS_FIB_SRB)
8251 			caller = "SRB";
8252 		else
8253 			return;
8254 	} else {
8255 		if (!(softs->debug_fib_flags & AACDB_FLAGS_FIB_SYNC))
8256 			return;
8257 		caller = "SYNC";
8258 	}
8259 
8260 	fib_cmd = ddi_get16(acc, &fibp->Header.Command);
8261 	cmdstr = aac_cmd_name(fib_cmd, aac_fib_cmds);
8262 	sub_cmd = (uint32_t)-1;
8263 	subcmdstr = NULL;
8264 
8265 	/* Print FIB header */
8266 	if (softs->debug_fib_flags & AACDB_FLAGS_FIB_HEADER) {
8267 		aac_printf(softs, CE_NOTE, "FIB> from %s", caller);
8268 		aac_printf(softs, CE_NOTE, "     XferState  %d",
8269 		    ddi_get32(acc, &fibp->Header.XferState));
8270 		aac_printf(softs, CE_NOTE, "     Command    %d",
8271 		    ddi_get16(acc, &fibp->Header.Command));
8272 		aac_printf(softs, CE_NOTE, "     StructType %d",
8273 		    ddi_get8(acc, &fibp->Header.StructType));
8274 		aac_printf(softs, CE_NOTE, "     Flags      0x%x",
8275 		    ddi_get8(acc, &fibp->Header.Flags));
8276 		aac_printf(softs, CE_NOTE, "     Size       %d",
8277 		    ddi_get16(acc, &fibp->Header.Size));
8278 		aac_printf(softs, CE_NOTE, "     SenderSize %d",
8279 		    ddi_get16(acc, &fibp->Header.SenderSize));
8280 		aac_printf(softs, CE_NOTE, "     SenderAddr 0x%x",
8281 		    ddi_get32(acc, &fibp->Header.SenderFibAddress));
8282 		aac_printf(softs, CE_NOTE, "     RcvrAddr   0x%x",
8283 		    ddi_get32(acc, &fibp->Header.ReceiverFibAddress));
8284 		aac_printf(softs, CE_NOTE, "     SenderData 0x%x",
8285 		    ddi_get32(acc, &fibp->Header.SenderData));
8286 	}
8287 
8288 	/* Print FIB data */
8289 	switch (fib_cmd) {
8290 	case ContainerCommand:
8291 		sub_cmd = ddi_get32(acc,
8292 		    (void *)&(((uint32_t *)(void *)&fibp->data[0])[0]));
8293 		subcmdstr = aac_cmd_name(sub_cmd, aac_ctvm_subcmds);
8294 		if (subcmdstr == NULL)
8295 			break;
8296 
8297 		switch (sub_cmd) {
8298 		case VM_ContainerConfig: {
8299 			struct aac_Container *pContainer =
8300 			    (struct aac_Container *)fibp->data;
8301 
8302 			fib_cmd = sub_cmd;
8303 			cmdstr = subcmdstr;
8304 			sub_cmd = (uint32_t)-1;
8305 			subcmdstr = NULL;
8306 
8307 			sub_cmd = ddi_get32(acc,
8308 			    &pContainer->CTCommand.command);
8309 			subcmdstr = aac_cmd_name(sub_cmd, aac_ct_subcmds);
8310 			if (subcmdstr == NULL)
8311 				break;
8312 			aac_printf(softs, CE_NOTE, "FIB> %s (0x%x, 0x%x, 0x%x)",
8313 			    subcmdstr,
8314 			    ddi_get32(acc, &pContainer->CTCommand.param[0]),
8315 			    ddi_get32(acc, &pContainer->CTCommand.param[1]),
8316 			    ddi_get32(acc, &pContainer->CTCommand.param[2]));
8317 			return;
8318 		}
8319 
8320 		case VM_Ioctl:
8321 			fib_cmd = sub_cmd;
8322 			cmdstr = subcmdstr;
8323 			sub_cmd = (uint32_t)-1;
8324 			subcmdstr = NULL;
8325 
8326 			sub_cmd = ddi_get32(acc,
8327 			    (void *)&(((uint32_t *)(void *)&fibp->data[0])[4]));
8328 			subcmdstr = aac_cmd_name(sub_cmd, aac_ioctl_subcmds);
8329 			break;
8330 
8331 		case VM_CtBlockRead:
8332 		case VM_CtBlockWrite: {
8333 			struct aac_blockread *br =
8334 			    (struct aac_blockread *)fibp->data;
8335 			struct aac_sg_table *sg = &br->SgMap;
8336 			uint32_t sgcount = ddi_get32(acc, &sg->SgCount);
8337 
8338 			aac_printf(softs, CE_NOTE,
8339 			    "FIB> %s Container %d  0x%x/%d", subcmdstr,
8340 			    ddi_get32(acc, &br->ContainerId),
8341 			    ddi_get32(acc, &br->BlockNumber),
8342 			    ddi_get32(acc, &br->ByteCount));
8343 			for (i = 0; i < sgcount; i++)
8344 				aac_printf(softs, CE_NOTE,
8345 				    "     %d: 0x%08x/%d", i,
8346 				    ddi_get32(acc, &sg->SgEntry[i].SgAddress),
8347 				    ddi_get32(acc, &sg->SgEntry[i]. \
8348 				    SgByteCount));
8349 			return;
8350 		}
8351 		}
8352 		break;
8353 
8354 	case ContainerCommand64: {
8355 		struct aac_blockread64 *br =
8356 		    (struct aac_blockread64 *)fibp->data;
8357 		struct aac_sg_table64 *sg = &br->SgMap64;
8358 		uint32_t sgcount = ddi_get32(acc, &sg->SgCount);
8359 		uint64_t sgaddr;
8360 
8361 		sub_cmd = br->Command;
8362 		subcmdstr = NULL;
8363 		if (sub_cmd == VM_CtHostRead64)
8364 			subcmdstr = "VM_CtHostRead64";
8365 		else if (sub_cmd == VM_CtHostWrite64)
8366 			subcmdstr = "VM_CtHostWrite64";
8367 		else
8368 			break;
8369 
8370 		aac_printf(softs, CE_NOTE,
8371 		    "FIB> %s Container %d  0x%x/%d", subcmdstr,
8372 		    ddi_get16(acc, &br->ContainerId),
8373 		    ddi_get32(acc, &br->BlockNumber),
8374 		    ddi_get16(acc, &br->SectorCount));
8375 		for (i = 0; i < sgcount; i++) {
8376 			sgaddr = ddi_get64(acc,
8377 			    &sg->SgEntry64[i].SgAddress);
8378 			aac_printf(softs, CE_NOTE,
8379 			    "     %d: 0x%08x.%08x/%d", i,
8380 			    AAC_MS32(sgaddr), AAC_LS32(sgaddr),
8381 			    ddi_get32(acc, &sg->SgEntry64[i]. \
8382 			    SgByteCount));
8383 		}
8384 		return;
8385 	}
8386 
8387 	case RawIo: {
8388 		struct aac_raw_io *io = (struct aac_raw_io *)fibp->data;
8389 		struct aac_sg_tableraw *sg = &io->SgMapRaw;
8390 		uint32_t sgcount = ddi_get32(acc, &sg->SgCount);
8391 		uint64_t sgaddr;
8392 
8393 		aac_printf(softs, CE_NOTE,
8394 		    "FIB> RawIo Container %d  0x%llx/%d 0x%x",
8395 		    ddi_get16(acc, &io->ContainerId),
8396 		    ddi_get64(acc, &io->BlockNumber),
8397 		    ddi_get32(acc, &io->ByteCount),
8398 		    ddi_get16(acc, &io->Flags));
8399 		for (i = 0; i < sgcount; i++) {
8400 			sgaddr = ddi_get64(acc, &sg->SgEntryRaw[i].SgAddress);
8401 			aac_printf(softs, CE_NOTE, "     %d: 0x%08x.%08x/%d", i,
8402 			    AAC_MS32(sgaddr), AAC_LS32(sgaddr),
8403 			    ddi_get32(acc, &sg->SgEntryRaw[i].SgByteCount));
8404 		}
8405 		return;
8406 	}
8407 
8408 	case ClusterCommand:
8409 		sub_cmd = ddi_get32(acc,
8410 		    (void *)&(((uint32_t *)(void *)fibp->data)[0]));
8411 		subcmdstr = aac_cmd_name(sub_cmd, aac_cl_subcmds);
8412 		break;
8413 
8414 	case AifRequest:
8415 		sub_cmd = ddi_get32(acc,
8416 		    (void *)&(((uint32_t *)(void *)fibp->data)[0]));
8417 		subcmdstr = aac_cmd_name(sub_cmd, aac_aif_subcmds);
8418 		break;
8419 
8420 	default:
8421 		break;
8422 	}
8423 
8424 	fib_size = ddi_get16(acc, &(fibp->Header.Size));
8425 	if (subcmdstr)
8426 		aac_printf(softs, CE_NOTE, "FIB> %s, sz=%d",
8427 		    subcmdstr, fib_size);
8428 	else if (cmdstr && sub_cmd == (uint32_t)-1)
8429 		aac_printf(softs, CE_NOTE, "FIB> %s, sz=%d",
8430 		    cmdstr, fib_size);
8431 	else if (cmdstr)
8432 		aac_printf(softs, CE_NOTE, "FIB> %s: Unknown(0x%x), sz=%d",
8433 		    cmdstr, sub_cmd, fib_size);
8434 	else
8435 		aac_printf(softs, CE_NOTE, "FIB> Unknown(0x%x), sz=%d",
8436 		    fib_cmd, fib_size);
8437 }
8438 
8439 static void
8440 aac_print_aif(struct aac_softstate *softs, struct aac_aif_command *aif)
8441 {
8442 	int aif_command;
8443 	uint32_t aif_seqnumber;
8444 	int aif_en_type;
8445 	char *str;
8446 
8447 	aif_command = LE_32(aif->command);
8448 	aif_seqnumber = LE_32(aif->seqNumber);
8449 	aif_en_type = LE_32(aif->data.EN.type);
8450 
8451 	switch (aif_command) {
8452 	case AifCmdEventNotify:
8453 		str = aac_cmd_name(aif_en_type, aac_aifens);
8454 		if (str)
8455 			aac_printf(softs, CE_NOTE, "AIF! %s", str);
8456 		else
8457 			aac_printf(softs, CE_NOTE, "AIF! Unknown(0x%x)",
8458 			    aif_en_type);
8459 		break;
8460 
8461 	case AifCmdJobProgress:
8462 		switch (LE_32(aif->data.PR[0].status)) {
8463 		case AifJobStsSuccess:
8464 			str = "success"; break;
8465 		case AifJobStsFinished:
8466 			str = "finished"; break;
8467 		case AifJobStsAborted:
8468 			str = "aborted"; break;
8469 		case AifJobStsFailed:
8470 			str = "failed"; break;
8471 		case AifJobStsSuspended:
8472 			str = "suspended"; break;
8473 		case AifJobStsRunning:
8474 			str = "running"; break;
8475 		default:
8476 			str = "unknown"; break;
8477 		}
8478 		aac_printf(softs, CE_NOTE,
8479 		    "AIF! JobProgress (%d) - %s (%d, %d)",
8480 		    aif_seqnumber, str,
8481 		    LE_32(aif->data.PR[0].currentTick),
8482 		    LE_32(aif->data.PR[0].finalTick));
8483 		break;
8484 
8485 	case AifCmdAPIReport:
8486 		aac_printf(softs, CE_NOTE, "AIF! APIReport (%d)",
8487 		    aif_seqnumber);
8488 		break;
8489 
8490 	case AifCmdDriverNotify:
8491 		aac_printf(softs, CE_NOTE, "AIF! DriverNotify (%d)",
8492 		    aif_seqnumber);
8493 		break;
8494 
8495 	default:
8496 		aac_printf(softs, CE_NOTE, "AIF! AIF %d (%d)",
8497 		    aif_command, aif_seqnumber);
8498 		break;
8499 	}
8500 }
8501 
8502 #endif /* DEBUG */
8503