xref: /netbsd-src/sys/dev/pci/amr.c (revision ce2c90c7c172d95d2402a5b3d96d8f8e6d138a21)
1 /*	$NetBSD: amr.c,v 1.39 2006/10/12 01:31:28 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 2002, 2003 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*-
40  * Copyright (c) 1999,2000 Michael Smith
41  * Copyright (c) 2000 BSDi
42  * All rights reserved.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  * from FreeBSD: amr_pci.c,v 1.5 2000/08/30 07:52:40 msmith Exp
66  * from FreeBSD: amr.c,v 1.16 2000/08/30 07:52:40 msmith Exp
67  */
68 
69 /*
70  * Driver for AMI RAID controllers.
71  */
72 
73 #include <sys/cdefs.h>
74 __KERNEL_RCSID(0, "$NetBSD: amr.c,v 1.39 2006/10/12 01:31:28 christos Exp $");
75 
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/kernel.h>
79 #include <sys/device.h>
80 #include <sys/queue.h>
81 #include <sys/proc.h>
82 #include <sys/buf.h>
83 #include <sys/malloc.h>
84 #include <sys/conf.h>
85 #include <sys/kthread.h>
86 
87 #include <uvm/uvm_extern.h>
88 
89 #include <machine/endian.h>
90 #include <machine/bus.h>
91 
92 #include <dev/pci/pcidevs.h>
93 #include <dev/pci/pcivar.h>
94 #include <dev/pci/amrreg.h>
95 #include <dev/pci/amrvar.h>
96 #include <dev/pci/amrio.h>
97 
98 #include "locators.h"
99 
100 static void	amr_attach(struct device *, struct device *, void *);
101 static void	amr_ccb_dump(struct amr_softc *, struct amr_ccb *);
102 static void	*amr_enquire(struct amr_softc *, u_int8_t, u_int8_t, u_int8_t,
103 			     void *);
104 static int	amr_init(struct amr_softc *, const char *,
105 			 struct pci_attach_args *pa);
106 static int	amr_intr(void *);
107 static int	amr_match(struct device *, struct cfdata *, void *);
108 static int	amr_print(void *, const char *);
109 static void	amr_shutdown(void *);
110 static void	amr_teardown(struct amr_softc *);
111 static void	amr_thread(void *);
112 static void	amr_thread_create(void *);
113 
114 static int	amr_quartz_get_work(struct amr_softc *,
115 				    struct amr_mailbox_resp *);
116 static int	amr_quartz_submit(struct amr_softc *, struct amr_ccb *);
117 static int	amr_std_get_work(struct amr_softc *, struct amr_mailbox_resp *);
118 static int	amr_std_submit(struct amr_softc *, struct amr_ccb *);
119 
120 static dev_type_open(amropen);
121 static dev_type_close(amrclose);
122 static dev_type_ioctl(amrioctl);
123 
124 CFATTACH_DECL(amr, sizeof(struct amr_softc),
125     amr_match, amr_attach, NULL, NULL);
126 
127 const struct cdevsw amr_cdevsw = {
128 	amropen, amrclose, noread, nowrite, amrioctl,
129 	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER
130 };
131 
132 extern struct   cfdriver amr_cd;
133 
134 #define AT_QUARTZ	0x01	/* `Quartz' chipset */
135 #define	AT_SIG		0x02	/* Check for signature */
136 
137 static struct amr_pci_type {
138 	u_short	apt_vendor;
139 	u_short	apt_product;
140 	u_short	apt_flags;
141 } const amr_pci_type[] = {
142 	{ PCI_VENDOR_AMI,   PCI_PRODUCT_AMI_MEGARAID,  0 },
143 	{ PCI_VENDOR_AMI,   PCI_PRODUCT_AMI_MEGARAID2, 0 },
144 	{ PCI_VENDOR_AMI,   PCI_PRODUCT_AMI_MEGARAID3, AT_QUARTZ },
145 	{ PCI_VENDOR_SYMBIOS, PCI_PRODUCT_AMI_MEGARAID3, AT_QUARTZ },
146 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_AMI_MEGARAID3, AT_QUARTZ | AT_SIG },
147 	{ PCI_VENDOR_INTEL,  PCI_PRODUCT_SYMBIOS_MEGARAID_320X, AT_QUARTZ },
148 	{ PCI_VENDOR_INTEL,  PCI_PRODUCT_SYMBIOS_MEGARAID_320E, AT_QUARTZ },
149 	{ PCI_VENDOR_SYMBIOS,  PCI_PRODUCT_SYMBIOS_MEGARAID_300X, AT_QUARTZ },
150 	{ PCI_VENDOR_DELL,  PCI_PRODUCT_DELL_PERC_4DI, AT_QUARTZ },
151 	{ PCI_VENDOR_DELL,  PCI_PRODUCT_DELL_PERC_4DI_2, AT_QUARTZ },
152 	{ PCI_VENDOR_DELL,  PCI_PRODUCT_DELL_PERC_4ESI, AT_QUARTZ },
153 	{ PCI_VENDOR_SYMBIOS,  PCI_PRODUCT_SYMBIOS_PERC_4SC, AT_QUARTZ },
154 	{ PCI_VENDOR_SYMBIOS,  PCI_PRODUCT_SYMBIOS_MEGARAID_320X, AT_QUARTZ },
155 	{ PCI_VENDOR_SYMBIOS,  PCI_PRODUCT_SYMBIOS_MEGARAID_320E, AT_QUARTZ },
156 	{ PCI_VENDOR_SYMBIOS,  PCI_PRODUCT_SYMBIOS_MEGARAID_300X, AT_QUARTZ },
157 };
158 
159 static struct amr_typestr {
160 	const char	*at_str;
161 	int		at_sig;
162 } const amr_typestr[] = {
163 	{ "Series 431",			AMR_SIG_431 },
164 	{ "Series 438",			AMR_SIG_438 },
165 	{ "Series 466",			AMR_SIG_466 },
166 	{ "Series 467",			AMR_SIG_467 },
167 	{ "Series 490",			AMR_SIG_490 },
168 	{ "Series 762",			AMR_SIG_762 },
169 	{ "HP NetRAID (T5)",		AMR_SIG_T5 },
170 	{ "HP NetRAID (T7)",		AMR_SIG_T7 },
171 };
172 
173 static struct {
174 	const char	*ds_descr;
175 	int	ds_happy;
176 } const amr_dstate[] = {
177 	{ "offline",	0 },
178 	{ "degraded",	1 },
179 	{ "optimal",	1 },
180 	{ "online",	1 },
181 	{ "failed",	0 },
182 	{ "rebuilding",	1 },
183 	{ "hotspare",	0 },
184 };
185 
186 static void	*amr_sdh;
187 
188 static int	amr_max_segs;
189 int		amr_max_xfer;
190 
191 static inline u_int8_t
192 amr_inb(struct amr_softc *amr, int off)
193 {
194 
195 	bus_space_barrier(amr->amr_iot, amr->amr_ioh, off, 1,
196 	    BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ);
197 	return (bus_space_read_1(amr->amr_iot, amr->amr_ioh, off));
198 }
199 
200 static inline u_int32_t
201 amr_inl(struct amr_softc *amr, int off)
202 {
203 
204 	bus_space_barrier(amr->amr_iot, amr->amr_ioh, off, 4,
205 	    BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ);
206 	return (bus_space_read_4(amr->amr_iot, amr->amr_ioh, off));
207 }
208 
209 static inline void
210 amr_outb(struct amr_softc *amr, int off, u_int8_t val)
211 {
212 
213 	bus_space_write_1(amr->amr_iot, amr->amr_ioh, off, val);
214 	bus_space_barrier(amr->amr_iot, amr->amr_ioh, off, 1,
215 	    BUS_SPACE_BARRIER_WRITE);
216 }
217 
218 static inline void
219 amr_outl(struct amr_softc *amr, int off, u_int32_t val)
220 {
221 
222 	bus_space_write_4(amr->amr_iot, amr->amr_ioh, off, val);
223 	bus_space_barrier(amr->amr_iot, amr->amr_ioh, off, 4,
224 	    BUS_SPACE_BARRIER_WRITE);
225 }
226 
227 /*
228  * Match a supported device.
229  */
230 static int
231 amr_match(struct device *parent __unused, struct cfdata *match __unused,
232     void *aux)
233 {
234 	struct pci_attach_args *pa;
235 	pcireg_t s;
236 	int i;
237 
238 	pa = (struct pci_attach_args *)aux;
239 
240 	/*
241 	 * Don't match the device if it's operating in I2O mode.  In this
242 	 * case it should be handled by the `iop' driver.
243 	 */
244 	if (PCI_CLASS(pa->pa_class) == PCI_CLASS_I2O)
245 		return (0);
246 
247 	for (i = 0; i < sizeof(amr_pci_type) / sizeof(amr_pci_type[0]); i++)
248 		if (PCI_VENDOR(pa->pa_id) == amr_pci_type[i].apt_vendor &&
249 		    PCI_PRODUCT(pa->pa_id) == amr_pci_type[i].apt_product)
250 		    	break;
251 
252 	if (i == sizeof(amr_pci_type) / sizeof(amr_pci_type[0]))
253 		return (0);
254 
255 	if ((amr_pci_type[i].apt_flags & AT_SIG) == 0)
256 		return (1);
257 
258 	s = pci_conf_read(pa->pa_pc, pa->pa_tag, AMR_QUARTZ_SIG_REG) & 0xffff;
259 	return (s == AMR_QUARTZ_SIG0 || s == AMR_QUARTZ_SIG1);
260 }
261 
262 /*
263  * Attach a supported device.
264  */
265 static void
266 amr_attach(struct device *parent __unused, struct device *self, void *aux)
267 {
268 	struct pci_attach_args *pa;
269 	struct amr_attach_args amra;
270 	const struct amr_pci_type *apt;
271 	struct amr_softc *amr;
272 	pci_chipset_tag_t pc;
273 	pci_intr_handle_t ih;
274 	const char *intrstr;
275 	pcireg_t reg;
276 	int rseg, i, j, size, rv, memreg, ioreg;
277 	struct amr_ccb *ac;
278 	int locs[AMRCF_NLOCS];
279 
280 	aprint_naive(": RAID controller\n");
281 
282 	amr = (struct amr_softc *)self;
283 	pa = (struct pci_attach_args *)aux;
284 	pc = pa->pa_pc;
285 
286 	for (i = 0; i < sizeof(amr_pci_type) / sizeof(amr_pci_type[0]); i++)
287 		if (PCI_VENDOR(pa->pa_id) == amr_pci_type[i].apt_vendor &&
288 		    PCI_PRODUCT(pa->pa_id) == amr_pci_type[i].apt_product)
289 			break;
290 	apt = amr_pci_type + i;
291 
292 	memreg = ioreg = 0;
293 	for (i = 0x10; i <= 0x14; i += 4) {
294 		reg = pci_conf_read(pc, pa->pa_tag, i);
295 		switch (PCI_MAPREG_TYPE(reg)) {
296 		case PCI_MAPREG_TYPE_MEM:
297 			if (PCI_MAPREG_MEM_SIZE(reg) != 0)
298 				memreg = i;
299 			break;
300 		case PCI_MAPREG_TYPE_IO:
301 			if (PCI_MAPREG_IO_SIZE(reg) != 0)
302 				ioreg = i;
303 			break;
304 
305 		}
306 	}
307 
308 	if (memreg && pci_mapreg_map(pa, memreg, PCI_MAPREG_TYPE_MEM, 0,
309 	    &amr->amr_iot, &amr->amr_ioh, NULL, &amr->amr_ios) == 0)
310 		;
311 	else if (ioreg && pci_mapreg_map(pa, ioreg, PCI_MAPREG_TYPE_IO, 0,
312 	    &amr->amr_iot, &amr->amr_ioh, NULL, &amr->amr_ios) == 0)
313 		;
314 	else {
315 		aprint_error("can't map control registers\n");
316 		amr_teardown(amr);
317 		return;
318 	}
319 
320 	amr->amr_flags |= AMRF_PCI_REGS;
321 	amr->amr_dmat = pa->pa_dmat;
322 	amr->amr_pc = pa->pa_pc;
323 
324 	/* Enable the device. */
325 	reg = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG);
326 	pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
327 	    reg | PCI_COMMAND_MASTER_ENABLE);
328 
329 	/* Map and establish the interrupt. */
330 	if (pci_intr_map(pa, &ih)) {
331 		aprint_error("can't map interrupt\n");
332 		amr_teardown(amr);
333 		return;
334 	}
335 	intrstr = pci_intr_string(pc, ih);
336 	amr->amr_ih = pci_intr_establish(pc, ih, IPL_BIO, amr_intr, amr);
337 	if (amr->amr_ih == NULL) {
338 		aprint_error("can't establish interrupt");
339 		if (intrstr != NULL)
340 			aprint_normal(" at %s", intrstr);
341 		aprint_normal("\n");
342 		amr_teardown(amr);
343 		return;
344 	}
345 	amr->amr_flags |= AMRF_PCI_INTR;
346 
347 	/*
348 	 * Allocate space for the mailbox and S/G lists.  Some controllers
349 	 * don't like S/G lists to be located below 0x2000, so we allocate
350 	 * enough slop to enable us to compensate.
351 	 *
352 	 * The standard mailbox structure needs to be aligned on a 16-byte
353 	 * boundary.  The 64-bit mailbox has one extra field, 4 bytes in
354 	 * size, which preceeds the standard mailbox.
355 	 */
356 	size = AMR_SGL_SIZE * AMR_MAX_CMDS + 0x2000;
357 	amr->amr_dmasize = size;
358 
359 	if ((rv = bus_dmamem_alloc(amr->amr_dmat, size, PAGE_SIZE, 0,
360 	    &amr->amr_dmaseg, 1, &rseg, BUS_DMA_NOWAIT)) != 0) {
361 		aprint_error("%s: unable to allocate buffer, rv = %d\n",
362 		    amr->amr_dv.dv_xname, rv);
363 		amr_teardown(amr);
364 		return;
365 	}
366 	amr->amr_flags |= AMRF_DMA_ALLOC;
367 
368 	if ((rv = bus_dmamem_map(amr->amr_dmat, &amr->amr_dmaseg, rseg, size,
369 	    (caddr_t *)&amr->amr_mbox,
370 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
371 		aprint_error("%s: unable to map buffer, rv = %d\n",
372 		    amr->amr_dv.dv_xname, rv);
373 		amr_teardown(amr);
374 		return;
375 	}
376 	amr->amr_flags |= AMRF_DMA_MAP;
377 
378 	if ((rv = bus_dmamap_create(amr->amr_dmat, size, 1, size, 0,
379 	    BUS_DMA_NOWAIT, &amr->amr_dmamap)) != 0) {
380 		aprint_error("%s: unable to create buffer DMA map, rv = %d\n",
381 		    amr->amr_dv.dv_xname, rv);
382 		amr_teardown(amr);
383 		return;
384 	}
385 	amr->amr_flags |= AMRF_DMA_CREATE;
386 
387 	if ((rv = bus_dmamap_load(amr->amr_dmat, amr->amr_dmamap,
388 	    amr->amr_mbox, size, NULL, BUS_DMA_NOWAIT)) != 0) {
389 		aprint_error("%s: unable to load buffer DMA map, rv = %d\n",
390 		    amr->amr_dv.dv_xname, rv);
391 		amr_teardown(amr);
392 		return;
393 	}
394 	amr->amr_flags |= AMRF_DMA_LOAD;
395 
396 	memset(amr->amr_mbox, 0, size);
397 
398 	amr->amr_mbox_paddr = amr->amr_dmamap->dm_segs[0].ds_addr;
399 	amr->amr_sgls_paddr = (amr->amr_mbox_paddr + 0x1fff) & ~0x1fff;
400 	amr->amr_sgls = (struct amr_sgentry *)((caddr_t)amr->amr_mbox +
401 	    amr->amr_sgls_paddr - amr->amr_dmamap->dm_segs[0].ds_addr);
402 
403 	/*
404 	 * Allocate and initalise the command control blocks.
405 	 */
406 	ac = malloc(sizeof(*ac) * AMR_MAX_CMDS, M_DEVBUF, M_NOWAIT | M_ZERO);
407 	amr->amr_ccbs = ac;
408 	SLIST_INIT(&amr->amr_ccb_freelist);
409 	TAILQ_INIT(&amr->amr_ccb_active);
410 	amr->amr_flags |= AMRF_CCBS;
411 
412 	if (amr_max_xfer == 0) {
413 		amr_max_xfer = min(((AMR_MAX_SEGS - 1) * PAGE_SIZE), MAXPHYS);
414 		amr_max_segs = (amr_max_xfer + (PAGE_SIZE * 2) - 1) / PAGE_SIZE;
415 	}
416 
417 	for (i = 0; i < AMR_MAX_CMDS; i++, ac++) {
418 		rv = bus_dmamap_create(amr->amr_dmat, amr_max_xfer,
419 		    amr_max_segs, amr_max_xfer, 0,
420 		    BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &ac->ac_xfer_map);
421 		if (rv != 0)
422 			break;
423 
424 		ac->ac_ident = i;
425 		amr_ccb_free(amr, ac);
426 	}
427 	if (i != AMR_MAX_CMDS) {
428 		aprint_error("%s: memory exhausted\n", amr->amr_dv.dv_xname);
429 		amr_teardown(amr);
430 		return;
431 	}
432 
433 	/*
434 	 * Take care of model-specific tasks.
435 	 */
436 	if ((apt->apt_flags & AT_QUARTZ) != 0) {
437 		amr->amr_submit = amr_quartz_submit;
438 		amr->amr_get_work = amr_quartz_get_work;
439 	} else {
440 		amr->amr_submit = amr_std_submit;
441 		amr->amr_get_work = amr_std_get_work;
442 
443 		/* Notify the controller of the mailbox location. */
444 		amr_outl(amr, AMR_SREG_MBOX, (u_int32_t)amr->amr_mbox_paddr + 16);
445 		amr_outb(amr, AMR_SREG_MBOX_ENABLE, AMR_SMBOX_ENABLE_ADDR);
446 
447 		/* Clear outstanding interrupts and enable interrupts. */
448 		amr_outb(amr, AMR_SREG_CMD, AMR_SCMD_ACKINTR);
449 		amr_outb(amr, AMR_SREG_TOGL,
450 		    amr_inb(amr, AMR_SREG_TOGL) | AMR_STOGL_ENABLE);
451 	}
452 
453 	/*
454 	 * Retrieve parameters, and tell the world about us.
455 	 */
456 	amr->amr_enqbuf = malloc(AMR_ENQUIRY_BUFSIZE, M_DEVBUF, M_NOWAIT);
457 	amr->amr_flags |= AMRF_ENQBUF;
458 	amr->amr_maxqueuecnt = i;
459 	aprint_normal(": AMI RAID ");
460 	if (amr_init(amr, intrstr, pa) != 0) {
461 		amr_teardown(amr);
462 		return;
463 	}
464 
465 	/*
466 	 * Cap the maximum number of outstanding commands.  AMI's Linux
467 	 * driver doesn't trust the controller's reported value, and lockups
468 	 * have been seen when we do.
469 	 */
470 	amr->amr_maxqueuecnt = min(amr->amr_maxqueuecnt, AMR_MAX_CMDS);
471 	if (amr->amr_maxqueuecnt > i)
472 		amr->amr_maxqueuecnt = i;
473 
474 	/* Set our `shutdownhook' before we start any device activity. */
475 	if (amr_sdh == NULL)
476 		amr_sdh = shutdownhook_establish(amr_shutdown, NULL);
477 
478 	/* Attach sub-devices. */
479 	for (j = 0; j < amr->amr_numdrives; j++) {
480 		if (amr->amr_drive[j].al_size == 0)
481 			continue;
482 		amra.amra_unit = j;
483 
484 		locs[AMRCF_UNIT] = j;
485 
486 		amr->amr_drive[j].al_dv = config_found_sm_loc(&amr->amr_dv,
487 			"amr", locs, &amra, amr_print, config_stdsubmatch);
488 	}
489 
490 	SIMPLEQ_INIT(&amr->amr_ccb_queue);
491 
492 	/* XXX This doesn't work for newer boards yet. */
493 	if ((apt->apt_flags & AT_QUARTZ) == 0)
494 		kthread_create(amr_thread_create, amr);
495 }
496 
497 /*
498  * Free up resources.
499  */
500 static void
501 amr_teardown(struct amr_softc *amr)
502 {
503 	struct amr_ccb *ac;
504 	int fl;
505 
506 	fl = amr->amr_flags;
507 
508 	if ((fl & AMRF_THREAD) != 0) {
509 		amr->amr_flags |= AMRF_THREAD_EXIT;
510 		wakeup(amr_thread);
511 		while ((amr->amr_flags & AMRF_THREAD_EXIT) != 0)
512 			tsleep(&amr->amr_flags, PWAIT, "amrexit", 0);
513 	}
514 	if ((fl & AMRF_CCBS) != 0) {
515 		SLIST_FOREACH(ac, &amr->amr_ccb_freelist, ac_chain.slist) {
516 			bus_dmamap_destroy(amr->amr_dmat, ac->ac_xfer_map);
517 		}
518 		free(amr->amr_ccbs, M_DEVBUF);
519 	}
520 	if ((fl & AMRF_ENQBUF) != 0)
521 		free(amr->amr_enqbuf, M_DEVBUF);
522 	if ((fl & AMRF_DMA_LOAD) != 0)
523 		bus_dmamap_unload(amr->amr_dmat, amr->amr_dmamap);
524 	if ((fl & AMRF_DMA_MAP) != 0)
525 		bus_dmamem_unmap(amr->amr_dmat, (caddr_t)amr->amr_mbox,
526 		    amr->amr_dmasize);
527 	if ((fl & AMRF_DMA_ALLOC) != 0)
528 		bus_dmamem_free(amr->amr_dmat, &amr->amr_dmaseg, 1);
529 	if ((fl & AMRF_DMA_CREATE) != 0)
530 		bus_dmamap_destroy(amr->amr_dmat, amr->amr_dmamap);
531 	if ((fl & AMRF_PCI_INTR) != 0)
532 		pci_intr_disestablish(amr->amr_pc, amr->amr_ih);
533 	if ((fl & AMRF_PCI_REGS) != 0)
534 		bus_space_unmap(amr->amr_iot, amr->amr_ioh, amr->amr_ios);
535 }
536 
537 /*
538  * Print autoconfiguration message for a sub-device.
539  */
540 static int
541 amr_print(void *aux, const char *pnp)
542 {
543 	struct amr_attach_args *amra;
544 
545 	amra = (struct amr_attach_args *)aux;
546 
547 	if (pnp != NULL)
548 		aprint_normal("block device at %s", pnp);
549 	aprint_normal(" unit %d", amra->amra_unit);
550 	return (UNCONF);
551 }
552 
553 /*
554  * Retrieve operational parameters and describe the controller.
555  */
556 static int
557 amr_init(struct amr_softc *amr, const char *intrstr,
558 	 struct pci_attach_args *pa)
559 {
560 	struct amr_adapter_info *aa;
561 	struct amr_prodinfo *ap;
562 	struct amr_enquiry *ae;
563 	struct amr_enquiry3 *aex;
564 	const char *prodstr;
565 	u_int i, sig, ishp;
566 	char sbuf[64];
567 
568 	/*
569 	 * Try to get 40LD product info, which tells us what the card is
570 	 * labelled as.
571 	 */
572 	ap = amr_enquire(amr, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0,
573 	    amr->amr_enqbuf);
574 	if (ap != NULL) {
575 		aprint_normal("<%.80s>\n", ap->ap_product);
576 		if (intrstr != NULL)
577 			aprint_normal("%s: interrupting at %s\n",
578 			    amr->amr_dv.dv_xname, intrstr);
579 		aprint_normal("%s: firmware %.16s, BIOS %.16s, %dMB RAM\n",
580 		    amr->amr_dv.dv_xname, ap->ap_firmware, ap->ap_bios,
581 		    le16toh(ap->ap_memsize));
582 
583 		amr->amr_maxqueuecnt = ap->ap_maxio;
584 
585 		/*
586 		 * Fetch and record state of logical drives.
587 		 */
588 		aex = amr_enquire(amr, AMR_CMD_CONFIG, AMR_CONFIG_ENQ3,
589 		    AMR_CONFIG_ENQ3_SOLICITED_FULL, amr->amr_enqbuf);
590 		if (aex == NULL) {
591 			aprint_error("%s ENQUIRY3 failed\n",
592 			    amr->amr_dv.dv_xname);
593 			return (-1);
594 		}
595 
596 		if (aex->ae_numldrives > __arraycount(aex->ae_drivestate)) {
597 			aprint_error("%s: Inquiry returned more drives (%d)"
598 			   " than the array can handle (%zu)\n",
599 			   amr->amr_dv.dv_xname, aex->ae_numldrives,
600 			   __arraycount(aex->ae_drivestate));
601 			aex->ae_numldrives = __arraycount(aex->ae_drivestate);
602 		}
603 		if (aex->ae_numldrives > AMR_MAX_UNITS) {
604 			aprint_error(
605 			    "%s: adjust AMR_MAX_UNITS to %d (currently %d)"
606 			    "\n", amr->amr_dv.dv_xname, AMR_MAX_UNITS,
607 			    amr->amr_numdrives);
608 			amr->amr_numdrives = AMR_MAX_UNITS;
609 		} else
610 			amr->amr_numdrives = aex->ae_numldrives;
611 
612 		for (i = 0; i < amr->amr_numdrives; i++) {
613 			amr->amr_drive[i].al_size =
614 			    le32toh(aex->ae_drivesize[i]);
615 			amr->amr_drive[i].al_state = aex->ae_drivestate[i];
616 			amr->amr_drive[i].al_properties = aex->ae_driveprop[i];
617 		}
618 
619 		return (0);
620 	}
621 
622 	/*
623 	 * Try 8LD extended ENQUIRY to get the controller signature.  Once
624 	 * found, search for a product description.
625 	 */
626 	ae = amr_enquire(amr, AMR_CMD_EXT_ENQUIRY2, 0, 0, amr->amr_enqbuf);
627 	if (ae != NULL) {
628 		i = 0;
629 		sig = le32toh(ae->ae_signature);
630 
631 		while (i < sizeof(amr_typestr) / sizeof(amr_typestr[0])) {
632 			if (amr_typestr[i].at_sig == sig)
633 				break;
634 			i++;
635 		}
636 		if (i == sizeof(amr_typestr) / sizeof(amr_typestr[0])) {
637 			snprintf(sbuf, sizeof(sbuf),
638 			    "unknown ENQUIRY2 sig (0x%08x)", sig);
639 			prodstr = sbuf;
640 		} else
641 			prodstr = amr_typestr[i].at_str;
642 	} else {
643 		ae = amr_enquire(amr, AMR_CMD_ENQUIRY, 0, 0, amr->amr_enqbuf);
644 		if (ae == NULL) {
645 			aprint_error("%s: unsupported controller\n",
646 			    amr->amr_dv.dv_xname);
647 			return (-1);
648 		}
649 
650 		switch (PCI_PRODUCT(pa->pa_id)) {
651 		case PCI_PRODUCT_AMI_MEGARAID:
652 			prodstr = "Series 428";
653 			break;
654 		case PCI_PRODUCT_AMI_MEGARAID2:
655 			prodstr = "Series 434";
656 			break;
657 		default:
658 			snprintf(sbuf, sizeof(sbuf), "unknown PCI dev (0x%04x)",
659 			    PCI_PRODUCT(pa->pa_id));
660 			prodstr = sbuf;
661 			break;
662 		}
663 	}
664 
665 	/*
666 	 * HP NetRaid controllers have a special encoding of the firmware
667 	 * and BIOS versions.  The AMI version seems to have it as strings
668 	 * whereas the HP version does it with a leading uppercase character
669 	 * and two binary numbers.
670 	*/
671 	aa = &ae->ae_adapter;
672 
673 	if (aa->aa_firmware[2] >= 'A' && aa->aa_firmware[2] <= 'Z' &&
674 	    aa->aa_firmware[1] <  ' ' && aa->aa_firmware[0] <  ' ' &&
675 	    aa->aa_bios[2] >= 'A' && aa->aa_bios[2] <= 'Z' &&
676 	    aa->aa_bios[1] <  ' ' && aa->aa_bios[0] <  ' ') {
677 		if (le32toh(ae->ae_signature) == AMR_SIG_438) {
678 			/* The AMI 438 is a NetRaid 3si in HP-land. */
679 			prodstr = "HP NetRaid 3si";
680 		}
681 		ishp = 1;
682 	} else
683 		ishp = 0;
684 
685 	aprint_normal("<%s>\n", prodstr);
686 	if (intrstr != NULL)
687 		aprint_normal("%s: interrupting at %s\n", amr->amr_dv.dv_xname,
688 		    intrstr);
689 
690 	if (ishp)
691 		aprint_normal("%s: firmware <%c.%02d.%02d>, BIOS <%c.%02d.%02d>"
692 		    ", %dMB RAM\n", amr->amr_dv.dv_xname, aa->aa_firmware[2],
693 		     aa->aa_firmware[1], aa->aa_firmware[0], aa->aa_bios[2],
694 		     aa->aa_bios[1], aa->aa_bios[0], aa->aa_memorysize);
695 	else
696 		aprint_normal("%s: firmware <%.4s>, BIOS <%.4s>, %dMB RAM\n",
697 		    amr->amr_dv.dv_xname, aa->aa_firmware, aa->aa_bios,
698 		    aa->aa_memorysize);
699 
700 	amr->amr_maxqueuecnt = aa->aa_maxio;
701 
702 	/*
703 	 * Record state of logical drives.
704 	 */
705 	if (ae->ae_ldrv.al_numdrives > __arraycount(ae->ae_ldrv.al_size)) {
706 		aprint_error("%s: Inquiry returned more drives (%d)"
707 		   " than the array can handle (%zu)\n",
708 		   amr->amr_dv.dv_xname, ae->ae_ldrv.al_numdrives,
709 		   __arraycount(ae->ae_ldrv.al_size));
710 		ae->ae_ldrv.al_numdrives = __arraycount(ae->ae_ldrv.al_size);
711 	}
712 	if (ae->ae_ldrv.al_numdrives > AMR_MAX_UNITS) {
713 		aprint_error("%s: adjust AMR_MAX_UNITS to %d (currently %d)\n",
714 		    amr->amr_dv.dv_xname, ae->ae_ldrv.al_numdrives,
715 		    AMR_MAX_UNITS);
716 		amr->amr_numdrives = AMR_MAX_UNITS;
717 	} else
718 		amr->amr_numdrives = ae->ae_ldrv.al_numdrives;
719 
720 	for (i = 0; i < amr->amr_numdrives; i++) {
721 		amr->amr_drive[i].al_size = le32toh(ae->ae_ldrv.al_size[i]);
722 		amr->amr_drive[i].al_state = ae->ae_ldrv.al_state[i];
723 		amr->amr_drive[i].al_properties = ae->ae_ldrv.al_properties[i];
724 	}
725 
726 	return (0);
727 }
728 
729 /*
730  * Flush the internal cache on each configured controller.  Called at
731  * shutdown time.
732  */
733 static void
734 amr_shutdown(void *cookie __unused)
735 {
736 	extern struct cfdriver amr_cd;
737 	struct amr_softc *amr;
738 	struct amr_ccb *ac;
739 	int i, rv, s;
740 
741 	for (i = 0; i < amr_cd.cd_ndevs; i++) {
742 		if ((amr = device_lookup(&amr_cd, i)) == NULL)
743 			continue;
744 
745 		if ((rv = amr_ccb_alloc(amr, &ac)) == 0) {
746 			ac->ac_cmd.mb_command = AMR_CMD_FLUSH;
747 			s = splbio();
748 			rv = amr_ccb_poll(amr, ac, 30000);
749 			splx(s);
750 			amr_ccb_free(amr, ac);
751 		}
752 		if (rv != 0)
753 			printf("%s: unable to flush cache (%d)\n",
754 			    amr->amr_dv.dv_xname, rv);
755 	}
756 }
757 
758 /*
759  * Interrupt service routine.
760  */
761 static int
762 amr_intr(void *cookie)
763 {
764 	struct amr_softc *amr;
765 	struct amr_ccb *ac;
766 	struct amr_mailbox_resp mbox;
767 	u_int i, forus, idx;
768 
769 	amr = cookie;
770 	forus = 0;
771 
772 	while ((*amr->amr_get_work)(amr, &mbox) == 0) {
773 		/* Iterate over completed commands in this result. */
774 		for (i = 0; i < mbox.mb_nstatus; i++) {
775 			idx = mbox.mb_completed[i] - 1;
776 			ac = amr->amr_ccbs + idx;
777 
778 			if (idx >= amr->amr_maxqueuecnt) {
779 				printf("%s: bad status (bogus ID: %u=%u)\n",
780 				    amr->amr_dv.dv_xname, i, idx);
781 				continue;
782 			}
783 
784 			if ((ac->ac_flags & AC_ACTIVE) == 0) {
785 				printf("%s: bad status (not active; 0x04%x)\n",
786 				    amr->amr_dv.dv_xname, ac->ac_flags);
787 				continue;
788 			}
789 
790 			ac->ac_status = mbox.mb_status;
791 			ac->ac_flags = (ac->ac_flags & ~AC_ACTIVE) |
792 			    AC_COMPLETE;
793 			TAILQ_REMOVE(&amr->amr_ccb_active, ac, ac_chain.tailq);
794 
795 			if ((ac->ac_flags & AC_MOAN) != 0)
796 				printf("%s: ccb %d completed\n",
797 				    amr->amr_dv.dv_xname, ac->ac_ident);
798 
799 			/* Pass notification to upper layers. */
800 			if (ac->ac_handler != NULL)
801 				(*ac->ac_handler)(ac);
802 			else
803 				wakeup(ac);
804 		}
805 		forus = 1;
806 	}
807 
808 	if (forus)
809 		amr_ccb_enqueue(amr, NULL);
810 
811 	return (forus);
812 }
813 
814 /*
815  * Create the watchdog thread.
816  */
817 static void
818 amr_thread_create(void *cookie)
819 {
820 	struct amr_softc *amr;
821 	int rv;
822 
823 	amr = cookie;
824 
825 	if ((amr->amr_flags & AMRF_THREAD_EXIT) != 0) {
826 		amr->amr_flags ^= AMRF_THREAD_EXIT;
827 		wakeup(&amr->amr_flags);
828 		return;
829 	}
830 
831 	rv = kthread_create1(amr_thread, amr, &amr->amr_thread, "%s",
832 	    amr->amr_dv.dv_xname);
833  	if (rv != 0)
834 		aprint_error("%s: unable to create thread (%d)",
835  		    amr->amr_dv.dv_xname, rv);
836  	else
837  		amr->amr_flags |= AMRF_THREAD;
838 }
839 
840 /*
841  * Watchdog thread.
842  */
843 static void
844 amr_thread(void *cookie)
845 {
846 	struct amr_softc *amr;
847 	struct amr_ccb *ac;
848 	struct amr_logdrive *al;
849 	struct amr_enquiry *ae;
850 	int rv, i, s;
851 
852 	amr = cookie;
853 	ae = amr->amr_enqbuf;
854 
855 	for (;;) {
856 		tsleep(amr_thread, PWAIT, "amrwdog", AMR_WDOG_TICKS);
857 
858 		if ((amr->amr_flags & AMRF_THREAD_EXIT) != 0) {
859 			amr->amr_flags ^= AMRF_THREAD_EXIT;
860 			wakeup(&amr->amr_flags);
861 			kthread_exit(0);
862 		}
863 
864 		s = splbio();
865 		amr_intr(cookie);
866 		ac = TAILQ_FIRST(&amr->amr_ccb_active);
867 		while (ac != NULL) {
868 			if (ac->ac_start_time + AMR_TIMEOUT > time_uptime)
869 				break;
870 			if ((ac->ac_flags & AC_MOAN) == 0) {
871 				printf("%s: ccb %d timed out; mailbox:\n",
872 				    amr->amr_dv.dv_xname, ac->ac_ident);
873 				amr_ccb_dump(amr, ac);
874 				ac->ac_flags |= AC_MOAN;
875 			}
876 			ac = TAILQ_NEXT(ac, ac_chain.tailq);
877 		}
878 		splx(s);
879 
880 		if ((rv = amr_ccb_alloc(amr, &ac)) != 0) {
881 			printf("%s: ccb_alloc failed (%d)\n",
882  			    amr->amr_dv.dv_xname, rv);
883 			continue;
884 		}
885 
886 		ac->ac_cmd.mb_command = AMR_CMD_ENQUIRY;
887 
888 		rv = amr_ccb_map(amr, ac, amr->amr_enqbuf,
889 		    AMR_ENQUIRY_BUFSIZE, AC_XFER_IN);
890 		if (rv != 0) {
891 			printf("%s: ccb_map failed (%d)\n",
892  			    amr->amr_dv.dv_xname, rv);
893 			amr_ccb_free(amr, ac);
894 			continue;
895 		}
896 
897 		rv = amr_ccb_wait(amr, ac);
898 		amr_ccb_unmap(amr, ac);
899 		if (rv != 0) {
900 			printf("%s: enquiry failed (st=%d)\n",
901  			    amr->amr_dv.dv_xname, ac->ac_status);
902 			continue;
903 		}
904 		amr_ccb_free(amr, ac);
905 
906 		al = amr->amr_drive;
907 		for (i = 0; i < __arraycount(ae->ae_ldrv.al_state); i++, al++) {
908 			if (al->al_dv == NULL)
909 				continue;
910 			if (al->al_state == ae->ae_ldrv.al_state[i])
911 				continue;
912 
913 			printf("%s: state changed: %s -> %s\n",
914 			    al->al_dv->dv_xname,
915 			    amr_drive_state(al->al_state, NULL),
916 			    amr_drive_state(ae->ae_ldrv.al_state[i], NULL));
917 
918 			al->al_state = ae->ae_ldrv.al_state[i];
919 		}
920 	}
921 }
922 
923 /*
924  * Return a text description of a logical drive's current state.
925  */
926 const char *
927 amr_drive_state(int state, int *happy)
928 {
929 	const char *str;
930 
931 	state = AMR_DRV_CURSTATE(state);
932 	if (state >= sizeof(amr_dstate) / sizeof(amr_dstate[0])) {
933 		if (happy)
934 			*happy = 1;
935 		str = "status unknown";
936 	} else {
937 		if (happy)
938 			*happy = amr_dstate[state].ds_happy;
939 		str = amr_dstate[state].ds_descr;
940 	}
941 
942 	return (str);
943 }
944 
945 /*
946  * Run a generic enquiry-style command.
947  */
948 static void *
949 amr_enquire(struct amr_softc *amr, u_int8_t cmd, u_int8_t cmdsub,
950 	    u_int8_t cmdqual, void *sbuf)
951 {
952 	struct amr_ccb *ac;
953 	u_int8_t *mb;
954 	int rv;
955 
956 	if (amr_ccb_alloc(amr, &ac) != 0)
957 		return (NULL);
958 
959 	/* Build the command proper. */
960 	mb = (u_int8_t *)&ac->ac_cmd;
961 	mb[0] = cmd;
962 	mb[2] = cmdsub;
963 	mb[3] = cmdqual;
964 
965 	rv = amr_ccb_map(amr, ac, sbuf, AMR_ENQUIRY_BUFSIZE, AC_XFER_IN);
966 	if (rv == 0) {
967 		rv = amr_ccb_poll(amr, ac, 2000);
968 		amr_ccb_unmap(amr, ac);
969 	}
970 	amr_ccb_free(amr, ac);
971 
972 	return (rv ? NULL : sbuf);
973 }
974 
975 /*
976  * Allocate and initialise a CCB.
977  */
978 int
979 amr_ccb_alloc(struct amr_softc *amr, struct amr_ccb **acp)
980 {
981 	int s;
982 
983 	s = splbio();
984 	if ((*acp = SLIST_FIRST(&amr->amr_ccb_freelist)) == NULL) {
985 		splx(s);
986 		return (EAGAIN);
987 	}
988 	SLIST_REMOVE_HEAD(&amr->amr_ccb_freelist, ac_chain.slist);
989 	splx(s);
990 
991 	return (0);
992 }
993 
994 /*
995  * Free a CCB.
996  */
997 void
998 amr_ccb_free(struct amr_softc *amr, struct amr_ccb *ac)
999 {
1000 	int s;
1001 
1002 	memset(&ac->ac_cmd, 0, sizeof(ac->ac_cmd));
1003 	ac->ac_cmd.mb_ident = ac->ac_ident + 1;
1004 	ac->ac_cmd.mb_busy = 1;
1005 	ac->ac_handler = NULL;
1006 	ac->ac_flags = 0;
1007 
1008 	s = splbio();
1009 	SLIST_INSERT_HEAD(&amr->amr_ccb_freelist, ac, ac_chain.slist);
1010 	splx(s);
1011 }
1012 
1013 /*
1014  * If a CCB is specified, enqueue it.  Pull CCBs off the software queue in
1015  * the order that they were enqueued and try to submit their command blocks
1016  * to the controller for execution.
1017  */
1018 void
1019 amr_ccb_enqueue(struct amr_softc *amr, struct amr_ccb *ac)
1020 {
1021 	int s;
1022 
1023 	s = splbio();
1024 
1025 	if (ac != NULL)
1026 		SIMPLEQ_INSERT_TAIL(&amr->amr_ccb_queue, ac, ac_chain.simpleq);
1027 
1028 	while ((ac = SIMPLEQ_FIRST(&amr->amr_ccb_queue)) != NULL) {
1029 		if ((*amr->amr_submit)(amr, ac) != 0)
1030 			break;
1031 		SIMPLEQ_REMOVE_HEAD(&amr->amr_ccb_queue, ac_chain.simpleq);
1032 		TAILQ_INSERT_TAIL(&amr->amr_ccb_active, ac, ac_chain.tailq);
1033 	}
1034 
1035 	splx(s);
1036 }
1037 
1038 /*
1039  * Map the specified CCB's data buffer onto the bus, and fill the
1040  * scatter-gather list.
1041  */
1042 int
1043 amr_ccb_map(struct amr_softc *amr, struct amr_ccb *ac, void *data, int size,
1044 	    int tflag)
1045 {
1046 	struct amr_sgentry *sge;
1047 	struct amr_mailbox_cmd *mb;
1048 	int nsegs, i, rv, sgloff;
1049 	bus_dmamap_t xfer;
1050 	int dmaflag = 0;
1051 
1052 	xfer = ac->ac_xfer_map;
1053 
1054 	rv = bus_dmamap_load(amr->amr_dmat, xfer, data, size, NULL,
1055 	    BUS_DMA_NOWAIT);
1056 	if (rv != 0)
1057 		return (rv);
1058 
1059 	mb = &ac->ac_cmd;
1060 	ac->ac_xfer_size = size;
1061 	ac->ac_flags |= (tflag & (AC_XFER_OUT | AC_XFER_IN));
1062 	sgloff = AMR_SGL_SIZE * ac->ac_ident;
1063 
1064 	if (tflag & AC_XFER_OUT)
1065 		dmaflag |= BUS_DMASYNC_PREWRITE;
1066 	if (tflag & AC_XFER_IN)
1067 		dmaflag |= BUS_DMASYNC_PREREAD;
1068 
1069 	/* We don't need to use a scatter/gather list for just 1 segment. */
1070 	nsegs = xfer->dm_nsegs;
1071 	if (nsegs == 1) {
1072 		mb->mb_nsgelem = 0;
1073 		mb->mb_physaddr = htole32(xfer->dm_segs[0].ds_addr);
1074 		ac->ac_flags |= AC_NOSGL;
1075 	} else {
1076 		mb->mb_nsgelem = nsegs;
1077 		mb->mb_physaddr = htole32(amr->amr_sgls_paddr + sgloff);
1078 
1079 		sge = (struct amr_sgentry *)((caddr_t)amr->amr_sgls + sgloff);
1080 		for (i = 0; i < nsegs; i++, sge++) {
1081 			sge->sge_addr = htole32(xfer->dm_segs[i].ds_addr);
1082 			sge->sge_count = htole32(xfer->dm_segs[i].ds_len);
1083 		}
1084 	}
1085 
1086 	bus_dmamap_sync(amr->amr_dmat, xfer, 0, ac->ac_xfer_size, dmaflag);
1087 
1088 	if ((ac->ac_flags & AC_NOSGL) == 0)
1089 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, sgloff,
1090 		    AMR_SGL_SIZE, BUS_DMASYNC_PREWRITE);
1091 
1092 	return (0);
1093 }
1094 
1095 /*
1096  * Unmap the specified CCB's data buffer.
1097  */
1098 void
1099 amr_ccb_unmap(struct amr_softc *amr, struct amr_ccb *ac)
1100 {
1101 	int dmaflag = 0;
1102 
1103 	if (ac->ac_flags & AC_XFER_IN)
1104 		dmaflag |= BUS_DMASYNC_POSTREAD;
1105 	if (ac->ac_flags & AC_XFER_OUT)
1106 		dmaflag |= BUS_DMASYNC_POSTWRITE;
1107 
1108 	if ((ac->ac_flags & AC_NOSGL) == 0)
1109 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap,
1110 		    AMR_SGL_SIZE * ac->ac_ident, AMR_SGL_SIZE,
1111 		    BUS_DMASYNC_POSTWRITE);
1112 	bus_dmamap_sync(amr->amr_dmat, ac->ac_xfer_map, 0, ac->ac_xfer_size,
1113 	    dmaflag);
1114 	bus_dmamap_unload(amr->amr_dmat, ac->ac_xfer_map);
1115 }
1116 
1117 /*
1118  * Submit a command to the controller and poll on completion.  Return
1119  * non-zero on timeout or error.  Must be called with interrupts blocked.
1120  */
1121 int
1122 amr_ccb_poll(struct amr_softc *amr, struct amr_ccb *ac, int timo)
1123 {
1124 	int rv;
1125 
1126 	if ((rv = (*amr->amr_submit)(amr, ac)) != 0)
1127 		return (rv);
1128 	TAILQ_INSERT_TAIL(&amr->amr_ccb_active, ac, ac_chain.tailq);
1129 
1130 	for (timo *= 10; timo != 0; timo--) {
1131 		amr_intr(amr);
1132 		if ((ac->ac_flags & AC_COMPLETE) != 0)
1133 			break;
1134 		DELAY(100);
1135 	}
1136 
1137 	return (timo == 0 || ac->ac_status != 0 ? EIO : 0);
1138 }
1139 
1140 /*
1141  * Submit a command to the controller and sleep on completion.  Return
1142  * non-zero on error.
1143  */
1144 int
1145 amr_ccb_wait(struct amr_softc *amr, struct amr_ccb *ac)
1146 {
1147 	int s;
1148 
1149 	s = splbio();
1150 	amr_ccb_enqueue(amr, ac);
1151 	tsleep(ac, PRIBIO, "amrcmd", 0);
1152 	splx(s);
1153 
1154 	return (ac->ac_status != 0 ? EIO : 0);
1155 }
1156 
1157 #if 0
1158 /*
1159  * Wait for the mailbox to become available.
1160  */
1161 static int
1162 amr_mbox_wait(struct amr_softc *amr)
1163 {
1164 	int timo;
1165 
1166 	for (timo = 10000; timo != 0; timo--) {
1167 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1168 		    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1169 		if (amr->amr_mbox->mb_cmd.mb_busy == 0)
1170 			break;
1171 		DELAY(100);
1172 	}
1173 
1174 	if (timo == 0)
1175 		printf("%s: controller wedged\n", amr->amr_dv.dv_xname);
1176 
1177 	return (timo != 0 ? 0 : EAGAIN);
1178 }
1179 #endif
1180 
1181 /*
1182  * Tell the controller that the mailbox contains a valid command.  Must be
1183  * called with interrupts blocked.
1184  */
1185 static int
1186 amr_quartz_submit(struct amr_softc *amr, struct amr_ccb *ac)
1187 {
1188 	u_int32_t v;
1189 
1190 	amr->amr_mbox->mb_poll = 0;
1191 	amr->amr_mbox->mb_ack = 0;
1192 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1193 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1194 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1195 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1196 	if (amr->amr_mbox->mb_cmd.mb_busy != 0)
1197 		return (EAGAIN);
1198 
1199 	v = amr_inl(amr, AMR_QREG_IDB);
1200 	if ((v & AMR_QIDB_SUBMIT) != 0) {
1201 		amr->amr_mbox->mb_cmd.mb_busy = 0;
1202 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1203 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1204 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1205 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1206 		return (EAGAIN);
1207 	}
1208 
1209 	amr->amr_mbox->mb_segment = 0;
1210 	memcpy(&amr->amr_mbox->mb_cmd, &ac->ac_cmd, sizeof(ac->ac_cmd));
1211 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1212 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1213 
1214 	ac->ac_start_time = time_uptime;
1215 	ac->ac_flags |= AC_ACTIVE;
1216 	amr_outl(amr, AMR_QREG_IDB,
1217 	    (amr->amr_mbox_paddr + 16) | AMR_QIDB_SUBMIT);
1218 	return (0);
1219 }
1220 
1221 static int
1222 amr_std_submit(struct amr_softc *amr, struct amr_ccb *ac)
1223 {
1224 
1225 	amr->amr_mbox->mb_poll = 0;
1226 	amr->amr_mbox->mb_ack = 0;
1227 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1228 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1229 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1230 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1231 	if (amr->amr_mbox->mb_cmd.mb_busy != 0)
1232 		return (EAGAIN);
1233 
1234 	if ((amr_inb(amr, AMR_SREG_MBOX_BUSY) & AMR_SMBOX_BUSY_FLAG) != 0) {
1235 		amr->amr_mbox->mb_cmd.mb_busy = 0;
1236 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1237 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1238 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1239 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1240 		return (EAGAIN);
1241 	}
1242 
1243 	amr->amr_mbox->mb_segment = 0;
1244 	memcpy(&amr->amr_mbox->mb_cmd, &ac->ac_cmd, sizeof(ac->ac_cmd));
1245 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1246 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1247 
1248 	ac->ac_start_time = time_uptime;
1249 	ac->ac_flags |= AC_ACTIVE;
1250 	amr_outb(amr, AMR_SREG_CMD, AMR_SCMD_POST);
1251 	return (0);
1252 }
1253 
1254 /*
1255  * Claim any work that the controller has completed; acknowledge completion,
1256  * save details of the completion in (mbsave).  Must be called with
1257  * interrupts blocked.
1258  */
1259 static int
1260 amr_quartz_get_work(struct amr_softc *amr, struct amr_mailbox_resp *mbsave)
1261 {
1262 
1263 	/* Work waiting for us? */
1264 	if (amr_inl(amr, AMR_QREG_ODB) != AMR_QODB_READY)
1265 		return (-1);
1266 
1267 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1268 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1269 
1270 	/* Save the mailbox, which contains a list of completed commands. */
1271 	memcpy(mbsave, &amr->amr_mbox->mb_resp, sizeof(*mbsave));
1272 
1273 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1274 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1275 
1276 	/* Ack the interrupt and mailbox transfer. */
1277 	amr_outl(amr, AMR_QREG_ODB, AMR_QODB_READY);
1278 	amr_outl(amr, AMR_QREG_IDB, (amr->amr_mbox_paddr+16) | AMR_QIDB_ACK);
1279 
1280 	/*
1281 	 * This waits for the controller to notice that we've taken the
1282 	 * command from it.  It's very inefficient, and we shouldn't do it,
1283 	 * but if we remove this code, we stop completing commands under
1284 	 * load.
1285 	 *
1286 	 * Peter J says we shouldn't do this.  The documentation says we
1287 	 * should.  Who is right?
1288 	 */
1289 	while ((amr_inl(amr, AMR_QREG_IDB) & AMR_QIDB_ACK) != 0)
1290 		DELAY(10);
1291 
1292 	return (0);
1293 }
1294 
1295 static int
1296 amr_std_get_work(struct amr_softc *amr, struct amr_mailbox_resp *mbsave)
1297 {
1298 	u_int8_t istat;
1299 
1300 	/* Check for valid interrupt status. */
1301 	if (((istat = amr_inb(amr, AMR_SREG_INTR)) & AMR_SINTR_VALID) == 0)
1302 		return (-1);
1303 
1304 	/* Ack the interrupt. */
1305 	amr_outb(amr, AMR_SREG_INTR, istat);
1306 
1307 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1308 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1309 
1310 	/* Save mailbox, which contains a list of completed commands. */
1311 	memcpy(mbsave, &amr->amr_mbox->mb_resp, sizeof(*mbsave));
1312 
1313 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1314 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1315 
1316 	/* Ack mailbox transfer. */
1317 	amr_outb(amr, AMR_SREG_CMD, AMR_SCMD_ACKINTR);
1318 
1319 	return (0);
1320 }
1321 
1322 static void
1323 amr_ccb_dump(struct amr_softc *amr, struct amr_ccb *ac)
1324 {
1325 	int i;
1326 
1327 	printf("%s: ", amr->amr_dv.dv_xname);
1328 	for (i = 0; i < 4; i++)
1329 		printf("%08x ", ((u_int32_t *)&ac->ac_cmd)[i]);
1330 	printf("\n");
1331 }
1332 
1333 static int
1334 amropen(dev_t dev, int flag __unused, int mode __unused, struct lwp *l __unused)
1335 {
1336 	struct amr_softc *amr;
1337 
1338 	if ((amr = device_lookup(&amr_cd, minor(dev))) == NULL)
1339 		return (ENXIO);
1340 	if ((amr->amr_flags & AMRF_OPEN) != 0)
1341 		return (EBUSY);
1342 
1343 	amr->amr_flags |= AMRF_OPEN;
1344 	return (0);
1345 }
1346 
1347 static int
1348 amrclose(dev_t dev, int flag __unused, int mode __unused, struct lwp *l __unused)
1349 {
1350 	struct amr_softc *amr;
1351 
1352 	amr = device_lookup(&amr_cd, minor(dev));
1353 	amr->amr_flags &= ~AMRF_OPEN;
1354 	return (0);
1355 }
1356 
1357 static int
1358 amrioctl(dev_t dev, u_long cmd, caddr_t data, int flag __unused,
1359     struct lwp *l __unused)
1360 {
1361 	struct amr_softc *amr;
1362 	struct amr_user_ioctl *au;
1363 	struct amr_ccb *ac;
1364 	struct amr_mailbox_ioctl *mbi;
1365 	unsigned long au_length;
1366 	uint8_t *au_cmd;
1367 	int error;
1368 	void *dp = NULL, *au_buffer;
1369 
1370 	amr = device_lookup(&amr_cd, minor(dev));
1371 
1372 	/* This should be compatible with the FreeBSD interface */
1373 
1374 	switch (cmd) {
1375 	case AMR_IO_VERSION:
1376 		*(int *)data = AMR_IO_VERSION_NUMBER;
1377 		return 0;
1378 	case AMR_IO_COMMAND:
1379 		if (securelevel >= 2)
1380 			return (EPERM);
1381 
1382 		au = (struct amr_user_ioctl *)data;
1383 		au_cmd = au->au_cmd;
1384 		au_buffer = au->au_buffer;
1385 		au_length = au->au_length;
1386 		break;
1387 	default:
1388 		return ENOTTY;
1389 	}
1390 
1391 	if (au_cmd[0] == AMR_CMD_PASS) {
1392 		/* not yet */
1393 		return EOPNOTSUPP;
1394 	}
1395 
1396 	if (au_length <= 0 || au_length > MAXPHYS || au_cmd[0] == 0x06)
1397 		return (EINVAL);
1398 
1399 	/*
1400 	 * allocate kernel memory for data, doing I/O directly to user
1401 	 * buffer isn't that easy.
1402 	 */
1403 	dp = malloc(au_length, M_DEVBUF, M_WAITOK|M_ZERO);
1404 	if (dp == NULL)
1405 		return ENOMEM;
1406 	if ((error = copyin(au_buffer, dp, au_length)) != 0)
1407 		goto out;
1408 
1409 	/* direct command to controller */
1410 	while (amr_ccb_alloc(amr, &ac) != 0) {
1411 		error = tsleep(NULL, PRIBIO | PCATCH, "armmbx", hz);
1412 		if (error == EINTR)
1413 			goto out;
1414 	}
1415 
1416 	mbi = (struct amr_mailbox_ioctl *)&ac->ac_cmd;
1417 	mbi->mb_command = au_cmd[0];
1418 	mbi->mb_channel = au_cmd[1];
1419 	mbi->mb_param = au_cmd[2];
1420 	mbi->mb_pad[0] = au_cmd[3];
1421 	mbi->mb_drive = au_cmd[4];
1422 	error = amr_ccb_map(amr, ac, dp, (int)au_length,
1423 	    AC_XFER_IN | AC_XFER_OUT);
1424 	if (error == 0) {
1425 		error = amr_ccb_wait(amr, ac);
1426 		amr_ccb_unmap(amr, ac);
1427 		if (error == 0)
1428 			error = copyout(dp, au_buffer, au_length);
1429 
1430 	}
1431 	amr_ccb_free(amr, ac);
1432 out:
1433 	free(dp, M_DEVBUF);
1434 	return (error);
1435 }
1436