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