xref: /netbsd-src/sys/dev/pci/amr.c (revision 8ac07aec990b9d2e483062509d0a9fa5b4f57cf2)
1 /*	$NetBSD: amr.c,v 1.47 2008/04/10 19:13:36 cegger 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.47 2008/04/10 19:13:36 cegger 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 #include <sys/kauth.h>
87 
88 #include <uvm/uvm_extern.h>
89 
90 #include <machine/endian.h>
91 #include <sys/bus.h>
92 
93 #include <dev/pci/pcidevs.h>
94 #include <dev/pci/pcivar.h>
95 #include <dev/pci/amrreg.h>
96 #include <dev/pci/amrvar.h>
97 #include <dev/pci/amrio.h>
98 
99 #include "locators.h"
100 
101 static void	amr_attach(struct device *, struct device *, void *);
102 static void	amr_ccb_dump(struct amr_softc *, struct amr_ccb *);
103 static void	*amr_enquire(struct amr_softc *, u_int8_t, u_int8_t, u_int8_t,
104 			     void *);
105 static int	amr_init(struct amr_softc *, const char *,
106 			 struct pci_attach_args *pa);
107 static int	amr_intr(void *);
108 static int	amr_match(struct device *, struct cfdata *, void *);
109 static int	amr_print(void *, const char *);
110 static void	amr_shutdown(void *);
111 static void	amr_teardown(struct amr_softc *);
112 static void	amr_thread(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, struct cfdata *match,
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, 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 precedes 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_dev(&amr->amr_dv, "unable to allocate buffer, rv = %d\n",
362 		    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 	    (void **)&amr->amr_mbox,
370 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
371 		aprint_error_dev(&amr->amr_dv, "unable to map buffer, rv = %d\n",
372 		    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_dev(&amr->amr_dv, "unable to create buffer DMA map, rv = %d\n",
381 		    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_dev(&amr->amr_dv, "unable to load buffer DMA map, rv = %d\n",
390 		    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 *)((char *)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_dev(&amr->amr_dv, "memory exhausted\n");
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 		rv = kthread_create(PRI_NONE, 0, NULL, amr_thread, amr,
495 		    &amr->amr_thread, "%s", device_xname(&amr->amr_dv));
496  		if (rv != 0)
497 			aprint_error_dev(&amr->amr_dv, "unable to create thread (%d)",
498  			    rv);
499  		else
500  			amr->amr_flags |= AMRF_THREAD;
501 	}
502 }
503 
504 /*
505  * Free up resources.
506  */
507 static void
508 amr_teardown(struct amr_softc *amr)
509 {
510 	struct amr_ccb *ac;
511 	int fl;
512 
513 	fl = amr->amr_flags;
514 
515 	if ((fl & AMRF_THREAD) != 0) {
516 		amr->amr_flags |= AMRF_THREAD_EXIT;
517 		wakeup(amr_thread);
518 		while ((amr->amr_flags & AMRF_THREAD_EXIT) != 0)
519 			tsleep(&amr->amr_flags, PWAIT, "amrexit", 0);
520 	}
521 	if ((fl & AMRF_CCBS) != 0) {
522 		SLIST_FOREACH(ac, &amr->amr_ccb_freelist, ac_chain.slist) {
523 			bus_dmamap_destroy(amr->amr_dmat, ac->ac_xfer_map);
524 		}
525 		free(amr->amr_ccbs, M_DEVBUF);
526 	}
527 	if ((fl & AMRF_ENQBUF) != 0)
528 		free(amr->amr_enqbuf, M_DEVBUF);
529 	if ((fl & AMRF_DMA_LOAD) != 0)
530 		bus_dmamap_unload(amr->amr_dmat, amr->amr_dmamap);
531 	if ((fl & AMRF_DMA_MAP) != 0)
532 		bus_dmamem_unmap(amr->amr_dmat, (void *)amr->amr_mbox,
533 		    amr->amr_dmasize);
534 	if ((fl & AMRF_DMA_ALLOC) != 0)
535 		bus_dmamem_free(amr->amr_dmat, &amr->amr_dmaseg, 1);
536 	if ((fl & AMRF_DMA_CREATE) != 0)
537 		bus_dmamap_destroy(amr->amr_dmat, amr->amr_dmamap);
538 	if ((fl & AMRF_PCI_INTR) != 0)
539 		pci_intr_disestablish(amr->amr_pc, amr->amr_ih);
540 	if ((fl & AMRF_PCI_REGS) != 0)
541 		bus_space_unmap(amr->amr_iot, amr->amr_ioh, amr->amr_ios);
542 }
543 
544 /*
545  * Print autoconfiguration message for a sub-device.
546  */
547 static int
548 amr_print(void *aux, const char *pnp)
549 {
550 	struct amr_attach_args *amra;
551 
552 	amra = (struct amr_attach_args *)aux;
553 
554 	if (pnp != NULL)
555 		aprint_normal("block device at %s", pnp);
556 	aprint_normal(" unit %d", amra->amra_unit);
557 	return (UNCONF);
558 }
559 
560 /*
561  * Retrieve operational parameters and describe the controller.
562  */
563 static int
564 amr_init(struct amr_softc *amr, const char *intrstr,
565 	 struct pci_attach_args *pa)
566 {
567 	struct amr_adapter_info *aa;
568 	struct amr_prodinfo *ap;
569 	struct amr_enquiry *ae;
570 	struct amr_enquiry3 *aex;
571 	const char *prodstr;
572 	u_int i, sig, ishp;
573 	char sbuf[64];
574 
575 	/*
576 	 * Try to get 40LD product info, which tells us what the card is
577 	 * labelled as.
578 	 */
579 	ap = amr_enquire(amr, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0,
580 	    amr->amr_enqbuf);
581 	if (ap != NULL) {
582 		aprint_normal("<%.80s>\n", ap->ap_product);
583 		if (intrstr != NULL)
584 			aprint_normal_dev(&amr->amr_dv, "interrupting at %s\n",
585 			    intrstr);
586 		aprint_normal_dev(&amr->amr_dv, "firmware %.16s, BIOS %.16s, %dMB RAM\n",
587 		    ap->ap_firmware, ap->ap_bios,
588 		    le16toh(ap->ap_memsize));
589 
590 		amr->amr_maxqueuecnt = ap->ap_maxio;
591 
592 		/*
593 		 * Fetch and record state of logical drives.
594 		 */
595 		aex = amr_enquire(amr, AMR_CMD_CONFIG, AMR_CONFIG_ENQ3,
596 		    AMR_CONFIG_ENQ3_SOLICITED_FULL, amr->amr_enqbuf);
597 		if (aex == NULL) {
598 			aprint_error_dev(&amr->amr_dv, "ENQUIRY3 failed\n");
599 			return (-1);
600 		}
601 
602 		if (aex->ae_numldrives > __arraycount(aex->ae_drivestate)) {
603 			aprint_error_dev(&amr->amr_dv, "Inquiry returned more drives (%d)"
604 			   " than the array can handle (%zu)\n",
605 			   aex->ae_numldrives,
606 			   __arraycount(aex->ae_drivestate));
607 			aex->ae_numldrives = __arraycount(aex->ae_drivestate);
608 		}
609 		if (aex->ae_numldrives > AMR_MAX_UNITS) {
610 			aprint_error_dev(&amr->amr_dv,
611 			    "adjust AMR_MAX_UNITS to %d (currently %d)"
612 			    "\n", AMR_MAX_UNITS,
613 			    amr->amr_numdrives);
614 			amr->amr_numdrives = AMR_MAX_UNITS;
615 		} else
616 			amr->amr_numdrives = aex->ae_numldrives;
617 
618 		for (i = 0; i < amr->amr_numdrives; i++) {
619 			amr->amr_drive[i].al_size =
620 			    le32toh(aex->ae_drivesize[i]);
621 			amr->amr_drive[i].al_state = aex->ae_drivestate[i];
622 			amr->amr_drive[i].al_properties = aex->ae_driveprop[i];
623 		}
624 
625 		return (0);
626 	}
627 
628 	/*
629 	 * Try 8LD extended ENQUIRY to get the controller signature.  Once
630 	 * found, search for a product description.
631 	 */
632 	ae = amr_enquire(amr, AMR_CMD_EXT_ENQUIRY2, 0, 0, amr->amr_enqbuf);
633 	if (ae != NULL) {
634 		i = 0;
635 		sig = le32toh(ae->ae_signature);
636 
637 		while (i < sizeof(amr_typestr) / sizeof(amr_typestr[0])) {
638 			if (amr_typestr[i].at_sig == sig)
639 				break;
640 			i++;
641 		}
642 		if (i == sizeof(amr_typestr) / sizeof(amr_typestr[0])) {
643 			snprintf(sbuf, sizeof(sbuf),
644 			    "unknown ENQUIRY2 sig (0x%08x)", sig);
645 			prodstr = sbuf;
646 		} else
647 			prodstr = amr_typestr[i].at_str;
648 	} else {
649 		ae = amr_enquire(amr, AMR_CMD_ENQUIRY, 0, 0, amr->amr_enqbuf);
650 		if (ae == NULL) {
651 			aprint_error_dev(&amr->amr_dv, "unsupported controller\n");
652 			return (-1);
653 		}
654 
655 		switch (PCI_PRODUCT(pa->pa_id)) {
656 		case PCI_PRODUCT_AMI_MEGARAID:
657 			prodstr = "Series 428";
658 			break;
659 		case PCI_PRODUCT_AMI_MEGARAID2:
660 			prodstr = "Series 434";
661 			break;
662 		default:
663 			snprintf(sbuf, sizeof(sbuf), "unknown PCI dev (0x%04x)",
664 			    PCI_PRODUCT(pa->pa_id));
665 			prodstr = sbuf;
666 			break;
667 		}
668 	}
669 
670 	/*
671 	 * HP NetRaid controllers have a special encoding of the firmware
672 	 * and BIOS versions.  The AMI version seems to have it as strings
673 	 * whereas the HP version does it with a leading uppercase character
674 	 * and two binary numbers.
675 	*/
676 	aa = &ae->ae_adapter;
677 
678 	if (aa->aa_firmware[2] >= 'A' && aa->aa_firmware[2] <= 'Z' &&
679 	    aa->aa_firmware[1] <  ' ' && aa->aa_firmware[0] <  ' ' &&
680 	    aa->aa_bios[2] >= 'A' && aa->aa_bios[2] <= 'Z' &&
681 	    aa->aa_bios[1] <  ' ' && aa->aa_bios[0] <  ' ') {
682 		if (le32toh(ae->ae_signature) == AMR_SIG_438) {
683 			/* The AMI 438 is a NetRaid 3si in HP-land. */
684 			prodstr = "HP NetRaid 3si";
685 		}
686 		ishp = 1;
687 	} else
688 		ishp = 0;
689 
690 	aprint_normal("<%s>\n", prodstr);
691 	if (intrstr != NULL)
692 		aprint_normal_dev(&amr->amr_dv, "interrupting at %s\n",
693 		    intrstr);
694 
695 	if (ishp)
696 		aprint_normal_dev(&amr->amr_dv, "firmware <%c.%02d.%02d>, BIOS <%c.%02d.%02d>"
697 		    ", %dMB RAM\n", aa->aa_firmware[2],
698 		     aa->aa_firmware[1], aa->aa_firmware[0], aa->aa_bios[2],
699 		     aa->aa_bios[1], aa->aa_bios[0], aa->aa_memorysize);
700 	else
701 		aprint_normal_dev(&amr->amr_dv, "firmware <%.4s>, BIOS <%.4s>, %dMB RAM\n",
702 		    aa->aa_firmware, aa->aa_bios,
703 		    aa->aa_memorysize);
704 
705 	amr->amr_maxqueuecnt = aa->aa_maxio;
706 
707 	/*
708 	 * Record state of logical drives.
709 	 */
710 	if (ae->ae_ldrv.al_numdrives > __arraycount(ae->ae_ldrv.al_size)) {
711 		aprint_error_dev(&amr->amr_dv, "Inquiry returned more drives (%d)"
712 		   " than the array can handle (%zu)\n",
713 		   ae->ae_ldrv.al_numdrives,
714 		   __arraycount(ae->ae_ldrv.al_size));
715 		ae->ae_ldrv.al_numdrives = __arraycount(ae->ae_ldrv.al_size);
716 	}
717 	if (ae->ae_ldrv.al_numdrives > AMR_MAX_UNITS) {
718 		aprint_error_dev(&amr->amr_dv, "adjust AMR_MAX_UNITS to %d (currently %d)\n",
719 		    ae->ae_ldrv.al_numdrives,
720 		    AMR_MAX_UNITS);
721 		amr->amr_numdrives = AMR_MAX_UNITS;
722 	} else
723 		amr->amr_numdrives = ae->ae_ldrv.al_numdrives;
724 
725 	for (i = 0; i < amr->amr_numdrives; i++) {
726 		amr->amr_drive[i].al_size = le32toh(ae->ae_ldrv.al_size[i]);
727 		amr->amr_drive[i].al_state = ae->ae_ldrv.al_state[i];
728 		amr->amr_drive[i].al_properties = ae->ae_ldrv.al_properties[i];
729 	}
730 
731 	return (0);
732 }
733 
734 /*
735  * Flush the internal cache on each configured controller.  Called at
736  * shutdown time.
737  */
738 static void
739 amr_shutdown(void *cookie)
740 {
741 	extern struct cfdriver amr_cd;
742 	struct amr_softc *amr;
743 	struct amr_ccb *ac;
744 	int i, rv, s;
745 
746 	for (i = 0; i < amr_cd.cd_ndevs; i++) {
747 		if ((amr = device_lookup(&amr_cd, i)) == NULL)
748 			continue;
749 
750 		if ((rv = amr_ccb_alloc(amr, &ac)) == 0) {
751 			ac->ac_cmd.mb_command = AMR_CMD_FLUSH;
752 			s = splbio();
753 			rv = amr_ccb_poll(amr, ac, 30000);
754 			splx(s);
755 			amr_ccb_free(amr, ac);
756 		}
757 		if (rv != 0)
758 			aprint_error_dev(&amr->amr_dv, "unable to flush cache (%d)\n", rv);
759 	}
760 }
761 
762 /*
763  * Interrupt service routine.
764  */
765 static int
766 amr_intr(void *cookie)
767 {
768 	struct amr_softc *amr;
769 	struct amr_ccb *ac;
770 	struct amr_mailbox_resp mbox;
771 	u_int i, forus, idx;
772 
773 	amr = cookie;
774 	forus = 0;
775 
776 	while ((*amr->amr_get_work)(amr, &mbox) == 0) {
777 		/* Iterate over completed commands in this result. */
778 		for (i = 0; i < mbox.mb_nstatus; i++) {
779 			idx = mbox.mb_completed[i] - 1;
780 			ac = amr->amr_ccbs + idx;
781 
782 			if (idx >= amr->amr_maxqueuecnt) {
783 				printf("%s: bad status (bogus ID: %u=%u)\n",
784 				    device_xname(&amr->amr_dv), i, idx);
785 				continue;
786 			}
787 
788 			if ((ac->ac_flags & AC_ACTIVE) == 0) {
789 				printf("%s: bad status (not active; 0x04%x)\n",
790 				    device_xname(&amr->amr_dv), ac->ac_flags);
791 				continue;
792 			}
793 
794 			ac->ac_status = mbox.mb_status;
795 			ac->ac_flags = (ac->ac_flags & ~AC_ACTIVE) |
796 			    AC_COMPLETE;
797 			TAILQ_REMOVE(&amr->amr_ccb_active, ac, ac_chain.tailq);
798 
799 			if ((ac->ac_flags & AC_MOAN) != 0)
800 				printf("%s: ccb %d completed\n",
801 				    device_xname(&amr->amr_dv), ac->ac_ident);
802 
803 			/* Pass notification to upper layers. */
804 			if (ac->ac_handler != NULL)
805 				(*ac->ac_handler)(ac);
806 			else
807 				wakeup(ac);
808 		}
809 		forus = 1;
810 	}
811 
812 	if (forus)
813 		amr_ccb_enqueue(amr, NULL);
814 
815 	return (forus);
816 }
817 
818 /*
819  * Watchdog thread.
820  */
821 static void
822 amr_thread(void *cookie)
823 {
824 	struct amr_softc *amr;
825 	struct amr_ccb *ac;
826 	struct amr_logdrive *al;
827 	struct amr_enquiry *ae;
828 	int rv, i, s;
829 
830 	amr = cookie;
831 	ae = amr->amr_enqbuf;
832 
833 	for (;;) {
834 		tsleep(amr_thread, PWAIT, "amrwdog", AMR_WDOG_TICKS);
835 
836 		if ((amr->amr_flags & AMRF_THREAD_EXIT) != 0) {
837 			amr->amr_flags ^= AMRF_THREAD_EXIT;
838 			wakeup(&amr->amr_flags);
839 			kthread_exit(0);
840 		}
841 
842 		s = splbio();
843 		amr_intr(cookie);
844 		ac = TAILQ_FIRST(&amr->amr_ccb_active);
845 		while (ac != NULL) {
846 			if (ac->ac_start_time + AMR_TIMEOUT > time_uptime)
847 				break;
848 			if ((ac->ac_flags & AC_MOAN) == 0) {
849 				printf("%s: ccb %d timed out; mailbox:\n",
850 				    device_xname(&amr->amr_dv), ac->ac_ident);
851 				amr_ccb_dump(amr, ac);
852 				ac->ac_flags |= AC_MOAN;
853 			}
854 			ac = TAILQ_NEXT(ac, ac_chain.tailq);
855 		}
856 		splx(s);
857 
858 		if ((rv = amr_ccb_alloc(amr, &ac)) != 0) {
859 			printf("%s: ccb_alloc failed (%d)\n",
860  			    device_xname(&amr->amr_dv), rv);
861 			continue;
862 		}
863 
864 		ac->ac_cmd.mb_command = AMR_CMD_ENQUIRY;
865 
866 		rv = amr_ccb_map(amr, ac, amr->amr_enqbuf,
867 		    AMR_ENQUIRY_BUFSIZE, AC_XFER_IN);
868 		if (rv != 0) {
869 			aprint_error_dev(&amr->amr_dv, "ccb_map failed (%d)\n",
870  			    rv);
871 			amr_ccb_free(amr, ac);
872 			continue;
873 		}
874 
875 		rv = amr_ccb_wait(amr, ac);
876 		amr_ccb_unmap(amr, ac);
877 		if (rv != 0) {
878 			aprint_error_dev(&amr->amr_dv, "enquiry failed (st=%d)\n",
879  			    ac->ac_status);
880 			continue;
881 		}
882 		amr_ccb_free(amr, ac);
883 
884 		al = amr->amr_drive;
885 		for (i = 0; i < __arraycount(ae->ae_ldrv.al_state); i++, al++) {
886 			if (al->al_dv == NULL)
887 				continue;
888 			if (al->al_state == ae->ae_ldrv.al_state[i])
889 				continue;
890 
891 			printf("%s: state changed: %s -> %s\n",
892 			    device_xname(al->al_dv),
893 			    amr_drive_state(al->al_state, NULL),
894 			    amr_drive_state(ae->ae_ldrv.al_state[i], NULL));
895 
896 			al->al_state = ae->ae_ldrv.al_state[i];
897 		}
898 	}
899 }
900 
901 /*
902  * Return a text description of a logical drive's current state.
903  */
904 const char *
905 amr_drive_state(int state, int *happy)
906 {
907 	const char *str;
908 
909 	state = AMR_DRV_CURSTATE(state);
910 	if (state >= sizeof(amr_dstate) / sizeof(amr_dstate[0])) {
911 		if (happy)
912 			*happy = 1;
913 		str = "status unknown";
914 	} else {
915 		if (happy)
916 			*happy = amr_dstate[state].ds_happy;
917 		str = amr_dstate[state].ds_descr;
918 	}
919 
920 	return (str);
921 }
922 
923 /*
924  * Run a generic enquiry-style command.
925  */
926 static void *
927 amr_enquire(struct amr_softc *amr, u_int8_t cmd, u_int8_t cmdsub,
928 	    u_int8_t cmdqual, void *sbuf)
929 {
930 	struct amr_ccb *ac;
931 	u_int8_t *mb;
932 	int rv;
933 
934 	if (amr_ccb_alloc(amr, &ac) != 0)
935 		return (NULL);
936 
937 	/* Build the command proper. */
938 	mb = (u_int8_t *)&ac->ac_cmd;
939 	mb[0] = cmd;
940 	mb[2] = cmdsub;
941 	mb[3] = cmdqual;
942 
943 	rv = amr_ccb_map(amr, ac, sbuf, AMR_ENQUIRY_BUFSIZE, AC_XFER_IN);
944 	if (rv == 0) {
945 		rv = amr_ccb_poll(amr, ac, 2000);
946 		amr_ccb_unmap(amr, ac);
947 	}
948 	amr_ccb_free(amr, ac);
949 
950 	return (rv ? NULL : sbuf);
951 }
952 
953 /*
954  * Allocate and initialise a CCB.
955  */
956 int
957 amr_ccb_alloc(struct amr_softc *amr, struct amr_ccb **acp)
958 {
959 	int s;
960 
961 	s = splbio();
962 	if ((*acp = SLIST_FIRST(&amr->amr_ccb_freelist)) == NULL) {
963 		splx(s);
964 		return (EAGAIN);
965 	}
966 	SLIST_REMOVE_HEAD(&amr->amr_ccb_freelist, ac_chain.slist);
967 	splx(s);
968 
969 	return (0);
970 }
971 
972 /*
973  * Free a CCB.
974  */
975 void
976 amr_ccb_free(struct amr_softc *amr, struct amr_ccb *ac)
977 {
978 	int s;
979 
980 	memset(&ac->ac_cmd, 0, sizeof(ac->ac_cmd));
981 	ac->ac_cmd.mb_ident = ac->ac_ident + 1;
982 	ac->ac_cmd.mb_busy = 1;
983 	ac->ac_handler = NULL;
984 	ac->ac_flags = 0;
985 
986 	s = splbio();
987 	SLIST_INSERT_HEAD(&amr->amr_ccb_freelist, ac, ac_chain.slist);
988 	splx(s);
989 }
990 
991 /*
992  * If a CCB is specified, enqueue it.  Pull CCBs off the software queue in
993  * the order that they were enqueued and try to submit their command blocks
994  * to the controller for execution.
995  */
996 void
997 amr_ccb_enqueue(struct amr_softc *amr, struct amr_ccb *ac)
998 {
999 	int s;
1000 
1001 	s = splbio();
1002 
1003 	if (ac != NULL)
1004 		SIMPLEQ_INSERT_TAIL(&amr->amr_ccb_queue, ac, ac_chain.simpleq);
1005 
1006 	while ((ac = SIMPLEQ_FIRST(&amr->amr_ccb_queue)) != NULL) {
1007 		if ((*amr->amr_submit)(amr, ac) != 0)
1008 			break;
1009 		SIMPLEQ_REMOVE_HEAD(&amr->amr_ccb_queue, ac_chain.simpleq);
1010 		TAILQ_INSERT_TAIL(&amr->amr_ccb_active, ac, ac_chain.tailq);
1011 	}
1012 
1013 	splx(s);
1014 }
1015 
1016 /*
1017  * Map the specified CCB's data buffer onto the bus, and fill the
1018  * scatter-gather list.
1019  */
1020 int
1021 amr_ccb_map(struct amr_softc *amr, struct amr_ccb *ac, void *data, int size,
1022 	    int tflag)
1023 {
1024 	struct amr_sgentry *sge;
1025 	struct amr_mailbox_cmd *mb;
1026 	int nsegs, i, rv, sgloff;
1027 	bus_dmamap_t xfer;
1028 	int dmaflag = 0;
1029 
1030 	xfer = ac->ac_xfer_map;
1031 
1032 	rv = bus_dmamap_load(amr->amr_dmat, xfer, data, size, NULL,
1033 	    BUS_DMA_NOWAIT);
1034 	if (rv != 0)
1035 		return (rv);
1036 
1037 	mb = &ac->ac_cmd;
1038 	ac->ac_xfer_size = size;
1039 	ac->ac_flags |= (tflag & (AC_XFER_OUT | AC_XFER_IN));
1040 	sgloff = AMR_SGL_SIZE * ac->ac_ident;
1041 
1042 	if (tflag & AC_XFER_OUT)
1043 		dmaflag |= BUS_DMASYNC_PREWRITE;
1044 	if (tflag & AC_XFER_IN)
1045 		dmaflag |= BUS_DMASYNC_PREREAD;
1046 
1047 	/* We don't need to use a scatter/gather list for just 1 segment. */
1048 	nsegs = xfer->dm_nsegs;
1049 	if (nsegs == 1) {
1050 		mb->mb_nsgelem = 0;
1051 		mb->mb_physaddr = htole32(xfer->dm_segs[0].ds_addr);
1052 		ac->ac_flags |= AC_NOSGL;
1053 	} else {
1054 		mb->mb_nsgelem = nsegs;
1055 		mb->mb_physaddr = htole32(amr->amr_sgls_paddr + sgloff);
1056 
1057 		sge = (struct amr_sgentry *)((char *)amr->amr_sgls + sgloff);
1058 		for (i = 0; i < nsegs; i++, sge++) {
1059 			sge->sge_addr = htole32(xfer->dm_segs[i].ds_addr);
1060 			sge->sge_count = htole32(xfer->dm_segs[i].ds_len);
1061 		}
1062 	}
1063 
1064 	bus_dmamap_sync(amr->amr_dmat, xfer, 0, ac->ac_xfer_size, dmaflag);
1065 
1066 	if ((ac->ac_flags & AC_NOSGL) == 0)
1067 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, sgloff,
1068 		    AMR_SGL_SIZE, BUS_DMASYNC_PREWRITE);
1069 
1070 	return (0);
1071 }
1072 
1073 /*
1074  * Unmap the specified CCB's data buffer.
1075  */
1076 void
1077 amr_ccb_unmap(struct amr_softc *amr, struct amr_ccb *ac)
1078 {
1079 	int dmaflag = 0;
1080 
1081 	if (ac->ac_flags & AC_XFER_IN)
1082 		dmaflag |= BUS_DMASYNC_POSTREAD;
1083 	if (ac->ac_flags & AC_XFER_OUT)
1084 		dmaflag |= BUS_DMASYNC_POSTWRITE;
1085 
1086 	if ((ac->ac_flags & AC_NOSGL) == 0)
1087 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap,
1088 		    AMR_SGL_SIZE * ac->ac_ident, AMR_SGL_SIZE,
1089 		    BUS_DMASYNC_POSTWRITE);
1090 	bus_dmamap_sync(amr->amr_dmat, ac->ac_xfer_map, 0, ac->ac_xfer_size,
1091 	    dmaflag);
1092 	bus_dmamap_unload(amr->amr_dmat, ac->ac_xfer_map);
1093 }
1094 
1095 /*
1096  * Submit a command to the controller and poll on completion.  Return
1097  * non-zero on timeout or error.  Must be called with interrupts blocked.
1098  */
1099 int
1100 amr_ccb_poll(struct amr_softc *amr, struct amr_ccb *ac, int timo)
1101 {
1102 	int rv;
1103 
1104 	if ((rv = (*amr->amr_submit)(amr, ac)) != 0)
1105 		return (rv);
1106 	TAILQ_INSERT_TAIL(&amr->amr_ccb_active, ac, ac_chain.tailq);
1107 
1108 	for (timo *= 10; timo != 0; timo--) {
1109 		amr_intr(amr);
1110 		if ((ac->ac_flags & AC_COMPLETE) != 0)
1111 			break;
1112 		DELAY(100);
1113 	}
1114 
1115 	return (timo == 0 || ac->ac_status != 0 ? EIO : 0);
1116 }
1117 
1118 /*
1119  * Submit a command to the controller and sleep on completion.  Return
1120  * non-zero on error.
1121  */
1122 int
1123 amr_ccb_wait(struct amr_softc *amr, struct amr_ccb *ac)
1124 {
1125 	int s;
1126 
1127 	s = splbio();
1128 	amr_ccb_enqueue(amr, ac);
1129 	tsleep(ac, PRIBIO, "amrcmd", 0);
1130 	splx(s);
1131 
1132 	return (ac->ac_status != 0 ? EIO : 0);
1133 }
1134 
1135 #if 0
1136 /*
1137  * Wait for the mailbox to become available.
1138  */
1139 static int
1140 amr_mbox_wait(struct amr_softc *amr)
1141 {
1142 	int timo;
1143 
1144 	for (timo = 10000; timo != 0; timo--) {
1145 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1146 		    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1147 		if (amr->amr_mbox->mb_cmd.mb_busy == 0)
1148 			break;
1149 		DELAY(100);
1150 	}
1151 
1152 	if (timo == 0)
1153 		printf("%s: controller wedged\n", device_xname(&amr->amr_dv));
1154 
1155 	return (timo != 0 ? 0 : EAGAIN);
1156 }
1157 #endif
1158 
1159 /*
1160  * Tell the controller that the mailbox contains a valid command.  Must be
1161  * called with interrupts blocked.
1162  */
1163 static int
1164 amr_quartz_submit(struct amr_softc *amr, struct amr_ccb *ac)
1165 {
1166 	u_int32_t v;
1167 
1168 	amr->amr_mbox->mb_poll = 0;
1169 	amr->amr_mbox->mb_ack = 0;
1170 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1171 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1172 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1173 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1174 	if (amr->amr_mbox->mb_cmd.mb_busy != 0)
1175 		return (EAGAIN);
1176 
1177 	v = amr_inl(amr, AMR_QREG_IDB);
1178 	if ((v & AMR_QIDB_SUBMIT) != 0) {
1179 		amr->amr_mbox->mb_cmd.mb_busy = 0;
1180 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1181 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1182 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1183 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1184 		return (EAGAIN);
1185 	}
1186 
1187 	amr->amr_mbox->mb_segment = 0;
1188 	memcpy(&amr->amr_mbox->mb_cmd, &ac->ac_cmd, sizeof(ac->ac_cmd));
1189 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1190 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1191 
1192 	ac->ac_start_time = time_uptime;
1193 	ac->ac_flags |= AC_ACTIVE;
1194 	amr_outl(amr, AMR_QREG_IDB,
1195 	    (amr->amr_mbox_paddr + 16) | AMR_QIDB_SUBMIT);
1196 	return (0);
1197 }
1198 
1199 static int
1200 amr_std_submit(struct amr_softc *amr, struct amr_ccb *ac)
1201 {
1202 
1203 	amr->amr_mbox->mb_poll = 0;
1204 	amr->amr_mbox->mb_ack = 0;
1205 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1206 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1207 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1208 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1209 	if (amr->amr_mbox->mb_cmd.mb_busy != 0)
1210 		return (EAGAIN);
1211 
1212 	if ((amr_inb(amr, AMR_SREG_MBOX_BUSY) & AMR_SMBOX_BUSY_FLAG) != 0) {
1213 		amr->amr_mbox->mb_cmd.mb_busy = 0;
1214 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1215 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1216 		bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1217 		    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1218 		return (EAGAIN);
1219 	}
1220 
1221 	amr->amr_mbox->mb_segment = 0;
1222 	memcpy(&amr->amr_mbox->mb_cmd, &ac->ac_cmd, sizeof(ac->ac_cmd));
1223 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1224 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREWRITE);
1225 
1226 	ac->ac_start_time = time_uptime;
1227 	ac->ac_flags |= AC_ACTIVE;
1228 	amr_outb(amr, AMR_SREG_CMD, AMR_SCMD_POST);
1229 	return (0);
1230 }
1231 
1232 /*
1233  * Claim any work that the controller has completed; acknowledge completion,
1234  * save details of the completion in (mbsave).  Must be called with
1235  * interrupts blocked.
1236  */
1237 static int
1238 amr_quartz_get_work(struct amr_softc *amr, struct amr_mailbox_resp *mbsave)
1239 {
1240 
1241 	/* Work waiting for us? */
1242 	if (amr_inl(amr, AMR_QREG_ODB) != AMR_QODB_READY)
1243 		return (-1);
1244 
1245 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1246 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1247 
1248 	/* Save the mailbox, which contains a list of completed commands. */
1249 	memcpy(mbsave, &amr->amr_mbox->mb_resp, sizeof(*mbsave));
1250 
1251 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1252 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1253 
1254 	/* Ack the interrupt and mailbox transfer. */
1255 	amr_outl(amr, AMR_QREG_ODB, AMR_QODB_READY);
1256 	amr_outl(amr, AMR_QREG_IDB, (amr->amr_mbox_paddr+16) | AMR_QIDB_ACK);
1257 
1258 	/*
1259 	 * This waits for the controller to notice that we've taken the
1260 	 * command from it.  It's very inefficient, and we shouldn't do it,
1261 	 * but if we remove this code, we stop completing commands under
1262 	 * load.
1263 	 *
1264 	 * Peter J says we shouldn't do this.  The documentation says we
1265 	 * should.  Who is right?
1266 	 */
1267 	while ((amr_inl(amr, AMR_QREG_IDB) & AMR_QIDB_ACK) != 0)
1268 		DELAY(10);
1269 
1270 	return (0);
1271 }
1272 
1273 static int
1274 amr_std_get_work(struct amr_softc *amr, struct amr_mailbox_resp *mbsave)
1275 {
1276 	u_int8_t istat;
1277 
1278 	/* Check for valid interrupt status. */
1279 	if (((istat = amr_inb(amr, AMR_SREG_INTR)) & AMR_SINTR_VALID) == 0)
1280 		return (-1);
1281 
1282 	/* Ack the interrupt. */
1283 	amr_outb(amr, AMR_SREG_INTR, istat);
1284 
1285 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1286 	    sizeof(struct amr_mailbox), BUS_DMASYNC_POSTREAD);
1287 
1288 	/* Save mailbox, which contains a list of completed commands. */
1289 	memcpy(mbsave, &amr->amr_mbox->mb_resp, sizeof(*mbsave));
1290 
1291 	bus_dmamap_sync(amr->amr_dmat, amr->amr_dmamap, 0,
1292 	    sizeof(struct amr_mailbox), BUS_DMASYNC_PREREAD);
1293 
1294 	/* Ack mailbox transfer. */
1295 	amr_outb(amr, AMR_SREG_CMD, AMR_SCMD_ACKINTR);
1296 
1297 	return (0);
1298 }
1299 
1300 static void
1301 amr_ccb_dump(struct amr_softc *amr, struct amr_ccb *ac)
1302 {
1303 	int i;
1304 
1305 	printf("%s: ", device_xname(&amr->amr_dv));
1306 	for (i = 0; i < 4; i++)
1307 		printf("%08x ", ((u_int32_t *)&ac->ac_cmd)[i]);
1308 	printf("\n");
1309 }
1310 
1311 static int
1312 amropen(dev_t dev, int flag, int mode, struct lwp *l)
1313 {
1314 	struct amr_softc *amr;
1315 
1316 	if ((amr = device_lookup(&amr_cd, minor(dev))) == NULL)
1317 		return (ENXIO);
1318 	if ((amr->amr_flags & AMRF_OPEN) != 0)
1319 		return (EBUSY);
1320 
1321 	amr->amr_flags |= AMRF_OPEN;
1322 	return (0);
1323 }
1324 
1325 static int
1326 amrclose(dev_t dev, int flag, int mode, struct lwp *l)
1327 {
1328 	struct amr_softc *amr;
1329 
1330 	amr = device_lookup(&amr_cd, minor(dev));
1331 	amr->amr_flags &= ~AMRF_OPEN;
1332 	return (0);
1333 }
1334 
1335 static int
1336 amrioctl(dev_t dev, u_long cmd, void *data, int flag,
1337     struct lwp *l)
1338 {
1339 	struct amr_softc *amr;
1340 	struct amr_user_ioctl *au;
1341 	struct amr_ccb *ac;
1342 	struct amr_mailbox_ioctl *mbi;
1343 	unsigned long au_length;
1344 	uint8_t *au_cmd;
1345 	int error;
1346 	void *dp = NULL, *au_buffer;
1347 
1348 	amr = device_lookup(&amr_cd, minor(dev));
1349 
1350 	/* This should be compatible with the FreeBSD interface */
1351 
1352 	switch (cmd) {
1353 	case AMR_IO_VERSION:
1354 		*(int *)data = AMR_IO_VERSION_NUMBER;
1355 		return 0;
1356 	case AMR_IO_COMMAND:
1357 		error = kauth_authorize_device_passthru(l->l_cred, dev,
1358 		    KAUTH_REQ_DEVICE_RAWIO_PASSTHRU_ALL, data);
1359 		if (error)
1360 			return (error);
1361 
1362 		au = (struct amr_user_ioctl *)data;
1363 		au_cmd = au->au_cmd;
1364 		au_buffer = au->au_buffer;
1365 		au_length = au->au_length;
1366 		break;
1367 	default:
1368 		return ENOTTY;
1369 	}
1370 
1371 	if (au_cmd[0] == AMR_CMD_PASS) {
1372 		/* not yet */
1373 		return EOPNOTSUPP;
1374 	}
1375 
1376 	if (au_length <= 0 || au_length > MAXPHYS || au_cmd[0] == 0x06)
1377 		return (EINVAL);
1378 
1379 	/*
1380 	 * allocate kernel memory for data, doing I/O directly to user
1381 	 * buffer isn't that easy.
1382 	 */
1383 	dp = malloc(au_length, M_DEVBUF, M_WAITOK|M_ZERO);
1384 	if (dp == NULL)
1385 		return ENOMEM;
1386 	if ((error = copyin(au_buffer, dp, au_length)) != 0)
1387 		goto out;
1388 
1389 	/* direct command to controller */
1390 	while (amr_ccb_alloc(amr, &ac) != 0) {
1391 		error = tsleep(NULL, PRIBIO | PCATCH, "armmbx", hz);
1392 		if (error == EINTR)
1393 			goto out;
1394 	}
1395 
1396 	mbi = (struct amr_mailbox_ioctl *)&ac->ac_cmd;
1397 	mbi->mb_command = au_cmd[0];
1398 	mbi->mb_channel = au_cmd[1];
1399 	mbi->mb_param = au_cmd[2];
1400 	mbi->mb_pad[0] = au_cmd[3];
1401 	mbi->mb_drive = au_cmd[4];
1402 	error = amr_ccb_map(amr, ac, dp, (int)au_length,
1403 	    AC_XFER_IN | AC_XFER_OUT);
1404 	if (error == 0) {
1405 		error = amr_ccb_wait(amr, ac);
1406 		amr_ccb_unmap(amr, ac);
1407 		if (error == 0)
1408 			error = copyout(dp, au_buffer, au_length);
1409 
1410 	}
1411 	amr_ccb_free(amr, ac);
1412 out:
1413 	free(dp, M_DEVBUF);
1414 	return (error);
1415 }
1416