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