1/*-
2 * Copyright (c) 1999,2000 Michael Smith
3 * Copyright (c) 2000 BSDi
4 * Copyright (c) 2005 Scott Long
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28/*-
29 * Copyright (c) 2002 Eric Moore
30 * Copyright (c) 2002, 2004 LSI Logic Corporation
31 * All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 *    notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 *    notice, this list of conditions and the following disclaimer in the
40 *    documentation and/or other materials provided with the distribution.
41 * 3. The party using or redistributing the source code and binary forms
42 *    agrees to the disclaimer below and the terms and conditions set forth
43 *    herein.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 */
57
58#include <sys/cdefs.h>
59__FBSDID("$FreeBSD$");
60
61/*
62 * Driver for the AMI MegaRaid family of controllers.
63 */
64
65#include <sys/param.h>
66#include <sys/systm.h>
67#include <sys/malloc.h>
68#include <sys/kernel.h>
69#include <sys/proc.h>
70#include <sys/sysctl.h>
71
72#include <sys/bio.h>
73#include <sys/bus.h>
74#include <sys/conf.h>
75#include <sys/stat.h>
76
77#include <machine/bus.h>
78#include <machine/cpu.h>
79#include <machine/resource.h>
80#include <sys/rman.h>
81
82#include <dev/pci/pcireg.h>
83#include <dev/pci/pcivar.h>
84
85#include <dev/amr/amrio.h>
86#include <dev/amr/amrreg.h>
87#include <dev/amr/amrvar.h>
88#define AMR_DEFINE_TABLES
89#include <dev/amr/amr_tables.h>
90
91SYSCTL_NODE(_hw, OID_AUTO, amr, CTLFLAG_RD, 0, "AMR driver parameters");
92
93static d_open_t         amr_open;
94static d_close_t        amr_close;
95static d_ioctl_t        amr_ioctl;
96
97static struct cdevsw amr_cdevsw = {
98	.d_version =	D_VERSION,
99	.d_flags =	D_NEEDGIANT,
100	.d_open =	amr_open,
101	.d_close =	amr_close,
102	.d_ioctl =	amr_ioctl,
103	.d_name =	"amr",
104};
105
106int linux_no_adapter = 0;
107/*
108 * Initialisation, bus interface.
109 */
110static void	amr_startup(void *arg);
111
112/*
113 * Command wrappers
114 */
115static int	amr_query_controller(struct amr_softc *sc);
116static void	*amr_enquiry(struct amr_softc *sc, size_t bufsize,
117			     u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual, int *status);
118static void	amr_completeio(struct amr_command *ac);
119static int	amr_support_ext_cdb(struct amr_softc *sc);
120
121/*
122 * Command buffer allocation.
123 */
124static void	amr_alloccmd_cluster(struct amr_softc *sc);
125static void	amr_freecmd_cluster(struct amr_command_cluster *acc);
126
127/*
128 * Command processing.
129 */
130static int	amr_bio_command(struct amr_softc *sc, struct amr_command **acp);
131static int	amr_wait_command(struct amr_command *ac) __unused;
132static int	amr_mapcmd(struct amr_command *ac);
133static void	amr_unmapcmd(struct amr_command *ac);
134static int	amr_start(struct amr_command *ac);
135static void	amr_complete(void *context, ac_qhead_t *head);
136static void	amr_setup_sg(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
137static void	amr_setup_data(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
138static void	amr_setup_ccb(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
139static void	amr_abort_load(struct amr_command *ac);
140
141/*
142 * Interface-specific shims
143 */
144static int	amr_quartz_submit_command(struct amr_command *ac);
145static int	amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
146static int	amr_quartz_poll_command(struct amr_command *ac);
147static int	amr_quartz_poll_command1(struct amr_softc *sc, struct amr_command *ac);
148
149static int	amr_std_submit_command(struct amr_command *ac);
150static int	amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
151static int	amr_std_poll_command(struct amr_command *ac);
152static void	amr_std_attach_mailbox(struct amr_softc *sc);
153
154#ifdef AMR_BOARD_INIT
155static int	amr_quartz_init(struct amr_softc *sc);
156static int	amr_std_init(struct amr_softc *sc);
157#endif
158
159/*
160 * Debugging
161 */
162static void	amr_describe_controller(struct amr_softc *sc);
163#ifdef AMR_DEBUG
164#if 0
165static void	amr_printcommand(struct amr_command *ac);
166#endif
167#endif
168
169static void	amr_init_sysctl(struct amr_softc *sc);
170static int	amr_linux_ioctl_int(struct cdev *dev, u_long cmd, caddr_t addr,
171		    int32_t flag, struct thread *td);
172
173static MALLOC_DEFINE(M_AMR, "amr", "AMR memory");
174
175/********************************************************************************
176 ********************************************************************************
177                                                                      Inline Glue
178 ********************************************************************************
179 ********************************************************************************/
180
181/********************************************************************************
182 ********************************************************************************
183                                                                Public Interfaces
184 ********************************************************************************
185 ********************************************************************************/
186
187/********************************************************************************
188 * Initialise the controller and softc.
189 */
190int
191amr_attach(struct amr_softc *sc)
192{
193    device_t child;
194
195    debug_called(1);
196
197    /*
198     * Initialise per-controller queues.
199     */
200    amr_init_qhead(&sc->amr_freecmds);
201    amr_init_qhead(&sc->amr_ready);
202    TAILQ_INIT(&sc->amr_cmd_clusters);
203    bioq_init(&sc->amr_bioq);
204
205    debug(2, "queue init done");
206
207    /*
208     * Configure for this controller type.
209     */
210    if (AMR_IS_QUARTZ(sc)) {
211	sc->amr_submit_command = amr_quartz_submit_command;
212	sc->amr_get_work       = amr_quartz_get_work;
213	sc->amr_poll_command   = amr_quartz_poll_command;
214	sc->amr_poll_command1  = amr_quartz_poll_command1;
215    } else {
216	sc->amr_submit_command = amr_std_submit_command;
217	sc->amr_get_work       = amr_std_get_work;
218	sc->amr_poll_command   = amr_std_poll_command;
219	amr_std_attach_mailbox(sc);
220    }
221
222#ifdef AMR_BOARD_INIT
223    if ((AMR_IS_QUARTZ(sc) ? amr_quartz_init(sc) : amr_std_init(sc)))
224	return(ENXIO);
225#endif
226
227    /*
228     * Allocate initial commands.
229     */
230    amr_alloccmd_cluster(sc);
231
232    /*
233     * Quiz controller for features and limits.
234     */
235    if (amr_query_controller(sc))
236	return(ENXIO);
237
238    debug(2, "controller query complete");
239
240    /*
241     * preallocate the remaining commands.
242     */
243    while (sc->amr_nextslot < sc->amr_maxio)
244	amr_alloccmd_cluster(sc);
245
246    /*
247     * Setup sysctls.
248     */
249    amr_init_sysctl(sc);
250
251    /*
252     * Attach our 'real' SCSI channels to CAM.
253     */
254    child = device_add_child(sc->amr_dev, "amrp", -1);
255    sc->amr_pass = child;
256    if (child != NULL) {
257	device_set_softc(child, sc);
258	device_set_desc(child, "SCSI Passthrough Bus");
259	bus_generic_attach(sc->amr_dev);
260    }
261
262    /*
263     * Create the control device.
264     */
265    sc->amr_dev_t = make_dev(&amr_cdevsw, device_get_unit(sc->amr_dev), UID_ROOT, GID_OPERATOR,
266			     S_IRUSR | S_IWUSR, "amr%d", device_get_unit(sc->amr_dev));
267    sc->amr_dev_t->si_drv1 = sc;
268    linux_no_adapter++;
269    if (device_get_unit(sc->amr_dev) == 0)
270	make_dev_alias(sc->amr_dev_t, "megadev0");
271
272    /*
273     * Schedule ourselves to bring the controller up once interrupts are
274     * available.
275     */
276    bzero(&sc->amr_ich, sizeof(struct intr_config_hook));
277    sc->amr_ich.ich_func = amr_startup;
278    sc->amr_ich.ich_arg = sc;
279    if (config_intrhook_establish(&sc->amr_ich) != 0) {
280	device_printf(sc->amr_dev, "can't establish configuration hook\n");
281	return(ENOMEM);
282    }
283
284    /*
285     * Print a little information about the controller.
286     */
287    amr_describe_controller(sc);
288
289    debug(2, "attach complete");
290    return(0);
291}
292
293/********************************************************************************
294 * Locate disk resources and attach children to them.
295 */
296static void
297amr_startup(void *arg)
298{
299    struct amr_softc	*sc = (struct amr_softc *)arg;
300    struct amr_logdrive	*dr;
301    int			i, error;
302
303    debug_called(1);
304
305    /* pull ourselves off the intrhook chain */
306    if (sc->amr_ich.ich_func)
307	config_intrhook_disestablish(&sc->amr_ich);
308    sc->amr_ich.ich_func = NULL;
309
310    /* get up-to-date drive information */
311    if (amr_query_controller(sc)) {
312	device_printf(sc->amr_dev, "can't scan controller for drives\n");
313	return;
314    }
315
316    /* iterate over available drives */
317    for (i = 0, dr = &sc->amr_drive[0]; (i < AMR_MAXLD) && (dr->al_size != 0xffffffff); i++, dr++) {
318	/* are we already attached to this drive? */
319	if (dr->al_disk == 0) {
320	    /* generate geometry information */
321	    if (dr->al_size > 0x200000) {	/* extended translation? */
322		dr->al_heads = 255;
323		dr->al_sectors = 63;
324	    } else {
325		dr->al_heads = 64;
326		dr->al_sectors = 32;
327	    }
328	    dr->al_cylinders = dr->al_size / (dr->al_heads * dr->al_sectors);
329
330	    dr->al_disk = device_add_child(sc->amr_dev, NULL, -1);
331	    if (dr->al_disk == 0)
332		device_printf(sc->amr_dev, "device_add_child failed\n");
333	    device_set_ivars(dr->al_disk, dr);
334	}
335    }
336
337    if ((error = bus_generic_attach(sc->amr_dev)) != 0)
338	device_printf(sc->amr_dev, "bus_generic_attach returned %d\n", error);
339
340    /* mark controller back up */
341    sc->amr_state &= ~AMR_STATE_SHUTDOWN;
342
343    /* interrupts will be enabled before we do anything more */
344    sc->amr_state |= AMR_STATE_INTEN;
345
346    return;
347}
348
349static void
350amr_init_sysctl(struct amr_softc *sc)
351{
352
353    SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->amr_dev),
354	SYSCTL_CHILDREN(device_get_sysctl_tree(sc->amr_dev)),
355	OID_AUTO, "allow_volume_configure", CTLFLAG_RW, &sc->amr_allow_vol_config, 0,
356	"");
357    SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->amr_dev),
358	SYSCTL_CHILDREN(device_get_sysctl_tree(sc->amr_dev)),
359	OID_AUTO, "nextslot", CTLFLAG_RD, &sc->amr_nextslot, 0,
360	"");
361    SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->amr_dev),
362	SYSCTL_CHILDREN(device_get_sysctl_tree(sc->amr_dev)),
363	OID_AUTO, "busyslots", CTLFLAG_RD, &sc->amr_busyslots, 0,
364	"");
365    SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->amr_dev),
366	SYSCTL_CHILDREN(device_get_sysctl_tree(sc->amr_dev)),
367	OID_AUTO, "maxio", CTLFLAG_RD, &sc->amr_maxio, 0,
368	"");
369}
370
371
372/*******************************************************************************
373 * Free resources associated with a controller instance
374 */
375void
376amr_free(struct amr_softc *sc)
377{
378    struct amr_command_cluster	*acc;
379
380    /* detach from CAM */
381    if (sc->amr_pass != NULL)
382	device_delete_child(sc->amr_dev, sc->amr_pass);
383
384    /* throw away any command buffers */
385    while ((acc = TAILQ_FIRST(&sc->amr_cmd_clusters)) != NULL) {
386	TAILQ_REMOVE(&sc->amr_cmd_clusters, acc, acc_link);
387	amr_freecmd_cluster(acc);
388    }
389
390    /* destroy control device */
391    if( sc->amr_dev_t != (struct cdev *)NULL)
392	    destroy_dev(sc->amr_dev_t);
393
394    if (mtx_initialized(&sc->amr_hw_lock))
395	mtx_destroy(&sc->amr_hw_lock);
396
397    if (mtx_initialized(&sc->amr_list_lock))
398	mtx_destroy(&sc->amr_list_lock);
399}
400
401/*******************************************************************************
402 * Receive a bio structure from a child device and queue it on a particular
403 * disk resource, then poke the disk resource to start as much work as it can.
404 */
405int
406amr_submit_bio(struct amr_softc *sc, struct bio *bio)
407{
408    debug_called(2);
409
410    mtx_lock(&sc->amr_list_lock);
411    amr_enqueue_bio(sc, bio);
412    amr_startio(sc);
413    mtx_unlock(&sc->amr_list_lock);
414    return(0);
415}
416
417/********************************************************************************
418 * Accept an open operation on the control device.
419 */
420static int
421amr_open(struct cdev *dev, int flags, int fmt, struct thread *td)
422{
423    int			unit = dev2unit(dev);
424    struct amr_softc	*sc = devclass_get_softc(devclass_find("amr"), unit);
425
426    debug_called(1);
427
428    sc->amr_state |= AMR_STATE_OPEN;
429    return(0);
430}
431
432#ifdef LSI
433static int
434amr_del_ld(struct amr_softc *sc, int drv_no, int status)
435{
436
437    debug_called(1);
438
439    sc->amr_state &= ~AMR_STATE_QUEUE_FRZN;
440    sc->amr_state &= ~AMR_STATE_LD_DELETE;
441    sc->amr_state |= AMR_STATE_REMAP_LD;
442    debug(1, "State Set");
443
444    if (!status) {
445	debug(1, "disk begin destroyed %d",drv_no);
446	if (--amr_disks_registered == 0)
447	    cdevsw_remove(&amrddisk_cdevsw);
448	debug(1, "disk begin destroyed success");
449    }
450    return 0;
451}
452
453static int
454amr_prepare_ld_delete(struct amr_softc *sc)
455{
456
457    debug_called(1);
458    if (sc->ld_del_supported == 0)
459	return(ENOIOCTL);
460
461    sc->amr_state |= AMR_STATE_QUEUE_FRZN;
462    sc->amr_state |= AMR_STATE_LD_DELETE;
463
464    /* 5 minutes for the all the commands to be flushed.*/
465    tsleep((void *)&sc->ld_del_supported, PCATCH | PRIBIO,"delete_logical_drv",hz * 60 * 1);
466    if ( sc->amr_busyslots )
467	return(ENOIOCTL);
468
469    return 0;
470}
471#endif
472
473/********************************************************************************
474 * Accept the last close on the control device.
475 */
476static int
477amr_close(struct cdev *dev, int flags, int fmt, struct thread *td)
478{
479    int			unit = dev2unit(dev);
480    struct amr_softc	*sc = devclass_get_softc(devclass_find("amr"), unit);
481
482    debug_called(1);
483
484    sc->amr_state &= ~AMR_STATE_OPEN;
485    return (0);
486}
487
488/********************************************************************************
489 * Handle controller-specific control operations.
490 */
491static void
492amr_rescan_drives(struct cdev *dev)
493{
494    struct amr_softc	*sc = (struct amr_softc *)dev->si_drv1;
495    int			i, error = 0;
496
497    sc->amr_state |= AMR_STATE_REMAP_LD;
498    while (sc->amr_busyslots) {
499	device_printf(sc->amr_dev, "idle controller\n");
500	amr_done(sc);
501    }
502
503    /* mark ourselves as in-shutdown */
504    sc->amr_state |= AMR_STATE_SHUTDOWN;
505
506    /* flush controller */
507    device_printf(sc->amr_dev, "flushing cache...");
508    printf("%s\n", amr_flush(sc) ? "failed" : "done");
509
510    /* delete all our child devices */
511    for(i = 0 ; i < AMR_MAXLD; i++) {
512	if(sc->amr_drive[i].al_disk != 0) {
513	    if((error = device_delete_child(sc->amr_dev,
514		sc->amr_drive[i].al_disk)) != 0)
515		goto shutdown_out;
516
517	     sc->amr_drive[i].al_disk = 0;
518	}
519    }
520
521shutdown_out:
522    amr_startup(sc);
523}
524
525/*
526 * Bug-for-bug compatibility with Linux!
527 * Some apps will send commands with inlen and outlen set to 0,
528 * even though they expect data to be transferred to them from the
529 * card.  Linux accidentally allows this by allocating a 4KB
530 * buffer for the transfer anyways, but it then throws it away
531 * without copying it back to the app.
532 *
533 * The amr(4) firmware relies on this feature.  In fact, it assumes
534 * the buffer is always a power of 2 up to a max of 64k.  There is
535 * also at least one case where it assumes a buffer less than 16k is
536 * greater than 16k.  However, forcing all buffers to a size of 32k
537 * causes stalls in the firmware.  Force each command smaller than
538 * 64k up to the next power of two except that commands between 8k
539 * and 16k are rounded up to 32k instead of 16k.
540 */
541static unsigned long
542amr_ioctl_buffer_length(unsigned long len)
543{
544
545    if (len <= 4 * 1024)
546	return (4 * 1024);
547    if (len <= 8 * 1024)
548	return (8 * 1024);
549    if (len <= 32 * 1024)
550	return (32 * 1024);
551    if (len <= 64 * 1024)
552	return (64 * 1024);
553    return (len);
554}
555
556int
557amr_linux_ioctl_int(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag,
558    struct thread *td)
559{
560    struct amr_softc		*sc = (struct amr_softc *)dev->si_drv1;
561    struct amr_command		*ac;
562    struct amr_mailbox		*mb;
563    struct amr_linux_ioctl	ali;
564    void			*dp, *temp;
565    int				error;
566    int				len, ac_flags = 0;
567    int				logical_drives_changed = 0;
568    u_int32_t			linux_version = 0x02100000;
569    u_int8_t			status;
570    struct amr_passthrough	*ap;	/* 60 bytes */
571
572    error = 0;
573    dp = NULL;
574    ac = NULL;
575    ap = NULL;
576
577    if ((error = copyin(addr, &ali, sizeof(ali))) != 0)
578	return (error);
579    switch (ali.ui.fcs.opcode) {
580    case 0x82:
581	switch(ali.ui.fcs.subopcode) {
582	case 'e':
583	    copyout(&linux_version, (void *)(uintptr_t)ali.data,
584		sizeof(linux_version));
585	    error = 0;
586	    break;
587
588	case 'm':
589	    copyout(&linux_no_adapter, (void *)(uintptr_t)ali.data,
590		sizeof(linux_no_adapter));
591	    td->td_retval[0] = linux_no_adapter;
592	    error = 0;
593	    break;
594
595	default:
596	    printf("Unknown subopcode\n");
597	    error = ENOIOCTL;
598	    break;
599	}
600    break;
601
602    case 0x80:
603    case 0x81:
604	if (ali.ui.fcs.opcode == 0x80)
605	    len = max(ali.outlen, ali.inlen);
606	else
607	    len = ali.ui.fcs.length;
608
609	mb = (void *)&ali.mbox[0];
610
611	if ((ali.mbox[0] == FC_DEL_LOGDRV  && ali.mbox[2] == OP_DEL_LOGDRV) ||	/* delete */
612	    (ali.mbox[0] == AMR_CMD_CONFIG && ali.mbox[2] == 0x0d)) {		/* create */
613	    if (sc->amr_allow_vol_config == 0) {
614		error = EPERM;
615		break;
616	    }
617	    logical_drives_changed = 1;
618	}
619
620	if (ali.mbox[0] == AMR_CMD_PASS) {
621	    mtx_lock(&sc->amr_list_lock);
622	    while ((ac = amr_alloccmd(sc)) == NULL)
623		msleep(sc, &sc->amr_list_lock, PPAUSE, "amrioc", hz);
624	    mtx_unlock(&sc->amr_list_lock);
625	    ap = &ac->ac_ccb->ccb_pthru;
626
627	    error = copyin((void *)(uintptr_t)mb->mb_physaddr, ap,
628		sizeof(struct amr_passthrough));
629	    if (error)
630		break;
631
632	    if (ap->ap_data_transfer_length)
633		dp = malloc(ap->ap_data_transfer_length, M_AMR,
634		    M_WAITOK | M_ZERO);
635
636	    if (ali.inlen) {
637		error = copyin((void *)(uintptr_t)ap->ap_data_transfer_address,
638		    dp, ap->ap_data_transfer_length);
639		if (error)
640		    break;
641	    }
642
643	    ac_flags = AMR_CMD_DATAIN|AMR_CMD_DATAOUT|AMR_CMD_CCB;
644	    bzero(&ac->ac_mailbox, sizeof(ac->ac_mailbox));
645	    ac->ac_mailbox.mb_command = AMR_CMD_PASS;
646	    ac->ac_flags = ac_flags;
647
648	    ac->ac_data = dp;
649	    ac->ac_length = ap->ap_data_transfer_length;
650	    temp = (void *)(uintptr_t)ap->ap_data_transfer_address;
651
652	    mtx_lock(&sc->amr_list_lock);
653	    error = amr_wait_command(ac);
654	    mtx_unlock(&sc->amr_list_lock);
655	    if (error)
656		break;
657
658	    status = ac->ac_status;
659	    error = copyout(&status, &((struct amr_passthrough *)(uintptr_t)mb->mb_physaddr)->ap_scsi_status, sizeof(status));
660	    if (error)
661		break;
662
663	    if (ali.outlen) {
664		error = copyout(dp, temp, ap->ap_data_transfer_length);
665	        if (error)
666		    break;
667	    }
668	    error = copyout(ap->ap_request_sense_area, ((struct amr_passthrough *)(uintptr_t)mb->mb_physaddr)->ap_request_sense_area, ap->ap_request_sense_length);
669	    if (error)
670		break;
671
672	    error = 0;
673	    break;
674	} else if (ali.mbox[0] == AMR_CMD_PASS_64) {
675	    printf("No AMR_CMD_PASS_64\n");
676	    error = ENOIOCTL;
677	    break;
678	} else if (ali.mbox[0] == AMR_CMD_EXTPASS) {
679	    printf("No AMR_CMD_EXTPASS\n");
680	    error = ENOIOCTL;
681	    break;
682	} else {
683	    len = amr_ioctl_buffer_length(imax(ali.inlen, ali.outlen));
684
685	    dp = malloc(len, M_AMR, M_WAITOK | M_ZERO);
686
687	    if (ali.inlen) {
688		error = copyin((void *)(uintptr_t)mb->mb_physaddr, dp, len);
689		if (error)
690		    break;
691	    }
692
693	    mtx_lock(&sc->amr_list_lock);
694	    while ((ac = amr_alloccmd(sc)) == NULL)
695		msleep(sc, &sc->amr_list_lock, PPAUSE, "amrioc", hz);
696
697	    ac_flags = AMR_CMD_DATAIN|AMR_CMD_DATAOUT;
698	    bzero(&ac->ac_mailbox, sizeof(ac->ac_mailbox));
699	    bcopy(&ali.mbox[0], &ac->ac_mailbox, sizeof(ali.mbox));
700
701	    ac->ac_length = len;
702	    ac->ac_data = dp;
703	    ac->ac_flags = ac_flags;
704
705	    error = amr_wait_command(ac);
706	    mtx_unlock(&sc->amr_list_lock);
707	    if (error)
708		break;
709
710	    status = ac->ac_status;
711	    error = copyout(&status, &((struct amr_mailbox *)&((struct amr_linux_ioctl *)addr)->mbox[0])->mb_status, sizeof(status));
712	    if (ali.outlen) {
713		error = copyout(dp, (void *)(uintptr_t)mb->mb_physaddr, ali.outlen);
714		if (error)
715		    break;
716	    }
717
718	    error = 0;
719	    if (logical_drives_changed)
720		amr_rescan_drives(dev);
721	    break;
722	}
723	break;
724
725    default:
726	debug(1, "unknown linux ioctl 0x%lx", cmd);
727	printf("unknown linux ioctl 0x%lx\n", cmd);
728	error = ENOIOCTL;
729	break;
730    }
731
732    /*
733     * At this point, we know that there is a lock held and that these
734     * objects have been allocated.
735     */
736    mtx_lock(&sc->amr_list_lock);
737    if (ac != NULL)
738	amr_releasecmd(ac);
739    mtx_unlock(&sc->amr_list_lock);
740    if (dp != NULL)
741	free(dp, M_AMR);
742    return(error);
743}
744
745static int
746amr_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, struct thread *td)
747{
748    struct amr_softc		*sc = (struct amr_softc *)dev->si_drv1;
749    union {
750	void			*_p;
751	struct amr_user_ioctl	*au;
752#ifdef AMR_IO_COMMAND32
753	struct amr_user_ioctl32	*au32;
754#endif
755	int			*result;
756    } arg;
757    struct amr_command		*ac;
758    struct amr_mailbox_ioctl	*mbi;
759    void			*dp, *au_buffer;
760    unsigned long		au_length, real_length;
761    unsigned char		*au_cmd;
762    int				*au_statusp;
763    int				error;
764    struct amr_passthrough	*ap;	/* 60 bytes */
765    int				logical_drives_changed = 0;
766
767    debug_called(1);
768
769    arg._p = (void *)addr;
770
771    error = 0;
772    dp = NULL;
773    ac = NULL;
774    ap = NULL;
775
776    switch(cmd) {
777
778    case AMR_IO_VERSION:
779	debug(1, "AMR_IO_VERSION");
780	*arg.result = AMR_IO_VERSION_NUMBER;
781	return(0);
782
783#ifdef AMR_IO_COMMAND32
784    /*
785     * Accept ioctl-s from 32-bit binaries on non-32-bit
786     * platforms, such as AMD. LSI's MEGAMGR utility is
787     * the only example known today...	-mi
788     */
789    case AMR_IO_COMMAND32:
790	debug(1, "AMR_IO_COMMAND32 0x%x", arg.au32->au_cmd[0]);
791	au_cmd = arg.au32->au_cmd;
792	au_buffer = (void *)(u_int64_t)arg.au32->au_buffer;
793	au_length = arg.au32->au_length;
794	au_statusp = &arg.au32->au_status;
795	break;
796#endif
797
798    case AMR_IO_COMMAND:
799	debug(1, "AMR_IO_COMMAND  0x%x", arg.au->au_cmd[0]);
800	au_cmd = arg.au->au_cmd;
801	au_buffer = (void *)arg.au->au_buffer;
802	au_length = arg.au->au_length;
803	au_statusp = &arg.au->au_status;
804	break;
805
806    case 0xc0046d00:
807    case 0xc06e6d00:	/* Linux emulation */
808	{
809	    devclass_t			devclass;
810	    struct amr_linux_ioctl	ali;
811	    int				adapter, error;
812
813	    devclass = devclass_find("amr");
814	    if (devclass == NULL)
815		return (ENOENT);
816
817	    error = copyin(addr, &ali, sizeof(ali));
818	    if (error)
819		return (error);
820	    if (ali.ui.fcs.opcode == 0x82)
821		adapter = 0;
822	    else
823		adapter = (ali.ui.fcs.adapno) ^ 'm' << 8;
824
825	    sc = devclass_get_softc(devclass, adapter);
826	    if (sc == NULL)
827		return (ENOENT);
828
829	    return (amr_linux_ioctl_int(sc->amr_dev_t, cmd, addr, 0, td));
830	}
831    default:
832	debug(1, "unknown ioctl 0x%lx", cmd);
833	return(ENOIOCTL);
834    }
835
836    if ((au_cmd[0] == FC_DEL_LOGDRV && au_cmd[1] == OP_DEL_LOGDRV) ||	/* delete */
837	(au_cmd[0] == AMR_CMD_CONFIG && au_cmd[1] == 0x0d)) {		/* create */
838	if (sc->amr_allow_vol_config == 0) {
839	    error = EPERM;
840	    goto out;
841	}
842	logical_drives_changed = 1;
843#ifdef LSI
844	if ((error = amr_prepare_ld_delete(sc)) != 0)
845	    return (error);
846#endif
847    }
848
849    /* handle inbound data buffer */
850    real_length = amr_ioctl_buffer_length(au_length);
851    dp = malloc(real_length, M_AMR, M_WAITOK|M_ZERO);
852    if (au_length != 0 && au_cmd[0] != 0x06) {
853	if ((error = copyin(au_buffer, dp, au_length)) != 0) {
854	    free(dp, M_AMR);
855	    return (error);
856	}
857	debug(2, "copyin %ld bytes from %p -> %p", au_length, au_buffer, dp);
858    }
859
860    /* Allocate this now before the mutex gets held */
861
862    mtx_lock(&sc->amr_list_lock);
863    while ((ac = amr_alloccmd(sc)) == NULL)
864	msleep(sc, &sc->amr_list_lock, PPAUSE, "amrioc", hz);
865
866    /* handle SCSI passthrough command */
867    if (au_cmd[0] == AMR_CMD_PASS) {
868        int len;
869
870	ap = &ac->ac_ccb->ccb_pthru;
871	bzero(ap, sizeof(struct amr_passthrough));
872
873	/* copy cdb */
874        len = au_cmd[2];
875	ap->ap_cdb_length = len;
876	bcopy(au_cmd + 3, ap->ap_cdb, len);
877
878	/* build passthrough */
879	ap->ap_timeout		= au_cmd[len + 3] & 0x07;
880	ap->ap_ars		= (au_cmd[len + 3] & 0x08) ? 1 : 0;
881	ap->ap_islogical		= (au_cmd[len + 3] & 0x80) ? 1 : 0;
882	ap->ap_logical_drive_no	= au_cmd[len + 4];
883	ap->ap_channel		= au_cmd[len + 5];
884	ap->ap_scsi_id 		= au_cmd[len + 6];
885	ap->ap_request_sense_length	= 14;
886	ap->ap_data_transfer_length	= au_length;
887	/* XXX what about the request-sense area? does the caller want it? */
888
889	/* build command */
890	ac->ac_mailbox.mb_command = AMR_CMD_PASS;
891	ac->ac_flags = AMR_CMD_CCB;
892
893    } else {
894	/* direct command to controller */
895	mbi = (struct amr_mailbox_ioctl *)&ac->ac_mailbox;
896
897	/* copy pertinent mailbox items */
898	mbi->mb_command = au_cmd[0];
899	mbi->mb_channel = au_cmd[1];
900	mbi->mb_param = au_cmd[2];
901	mbi->mb_pad[0] = au_cmd[3];
902	mbi->mb_drive = au_cmd[4];
903	ac->ac_flags = 0;
904    }
905
906    /* build the command */
907    ac->ac_data = dp;
908    ac->ac_length = real_length;
909    ac->ac_flags |= AMR_CMD_DATAIN|AMR_CMD_DATAOUT;
910
911    /* run the command */
912    error = amr_wait_command(ac);
913    mtx_unlock(&sc->amr_list_lock);
914    if (error)
915	goto out;
916
917    /* copy out data and set status */
918    if (au_length != 0) {
919	error = copyout(dp, au_buffer, au_length);
920    }
921    debug(2, "copyout %ld bytes from %p -> %p", au_length, dp, au_buffer);
922    debug(2, "%p status 0x%x", dp, ac->ac_status);
923    *au_statusp = ac->ac_status;
924
925out:
926    /*
927     * At this point, we know that there is a lock held and that these
928     * objects have been allocated.
929     */
930    mtx_lock(&sc->amr_list_lock);
931    if (ac != NULL)
932	amr_releasecmd(ac);
933    mtx_unlock(&sc->amr_list_lock);
934    if (dp != NULL)
935	free(dp, M_AMR);
936
937#ifndef LSI
938    if (logical_drives_changed)
939	amr_rescan_drives(dev);
940#endif
941
942    return(error);
943}
944
945/********************************************************************************
946 ********************************************************************************
947                                                                 Command Wrappers
948 ********************************************************************************
949 ********************************************************************************/
950
951/********************************************************************************
952 * Interrogate the controller for the operational parameters we require.
953 */
954static int
955amr_query_controller(struct amr_softc *sc)
956{
957    struct amr_enquiry3	*aex;
958    struct amr_prodinfo	*ap;
959    struct amr_enquiry	*ae;
960    int			ldrv;
961    int			status;
962
963    /*
964     * Greater than 10 byte cdb support
965     */
966    sc->support_ext_cdb = amr_support_ext_cdb(sc);
967
968    if(sc->support_ext_cdb) {
969	debug(2,"supports extended CDBs.");
970    }
971
972    /*
973     * Try to issue an ENQUIRY3 command
974     */
975    if ((aex = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_ENQ3,
976			   AMR_CONFIG_ENQ3_SOLICITED_FULL, &status)) != NULL) {
977
978	/*
979	 * Fetch current state of logical drives.
980	 */
981	for (ldrv = 0; ldrv < aex->ae_numldrives; ldrv++) {
982	    sc->amr_drive[ldrv].al_size       = aex->ae_drivesize[ldrv];
983	    sc->amr_drive[ldrv].al_state      = aex->ae_drivestate[ldrv];
984	    sc->amr_drive[ldrv].al_properties = aex->ae_driveprop[ldrv];
985	    debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
986		  sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
987	}
988	free(aex, M_AMR);
989
990	/*
991	 * Get product info for channel count.
992	 */
993	if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0, &status)) == NULL) {
994	    device_printf(sc->amr_dev, "can't obtain product data from controller\n");
995	    return(1);
996	}
997	sc->amr_maxdrives = 40;
998	sc->amr_maxchan = ap->ap_nschan;
999	sc->amr_maxio = ap->ap_maxio;
1000	sc->amr_type |= AMR_TYPE_40LD;
1001	free(ap, M_AMR);
1002
1003	ap = amr_enquiry(sc, 0, FC_DEL_LOGDRV, OP_SUP_DEL_LOGDRV, 0, &status);
1004	if (ap != NULL)
1005	    free(ap, M_AMR);
1006	if (!status) {
1007	    sc->amr_ld_del_supported = 1;
1008	    device_printf(sc->amr_dev, "delete logical drives supported by controller\n");
1009	}
1010    } else {
1011
1012	/* failed, try the 8LD ENQUIRY commands */
1013	if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0, &status)) == NULL) {
1014	    if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0, &status)) == NULL) {
1015		device_printf(sc->amr_dev, "can't obtain configuration data from controller\n");
1016		return(1);
1017	    }
1018	    ae->ae_signature = 0;
1019	}
1020
1021	/*
1022	 * Fetch current state of logical drives.
1023	 */
1024	for (ldrv = 0; ldrv < ae->ae_ldrv.al_numdrives; ldrv++) {
1025	    sc->amr_drive[ldrv].al_size       = ae->ae_ldrv.al_size[ldrv];
1026	    sc->amr_drive[ldrv].al_state      = ae->ae_ldrv.al_state[ldrv];
1027	    sc->amr_drive[ldrv].al_properties = ae->ae_ldrv.al_properties[ldrv];
1028	    debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
1029		  sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
1030	}
1031
1032	sc->amr_maxdrives = 8;
1033	sc->amr_maxchan = ae->ae_adapter.aa_channels;
1034	sc->amr_maxio = ae->ae_adapter.aa_maxio;
1035	free(ae, M_AMR);
1036    }
1037
1038    /*
1039     * Mark remaining drives as unused.
1040     */
1041    for (; ldrv < AMR_MAXLD; ldrv++)
1042	sc->amr_drive[ldrv].al_size = 0xffffffff;
1043
1044    /*
1045     * Cap the maximum number of outstanding I/Os.  AMI's Linux driver doesn't trust
1046     * the controller's reported value, and lockups have been seen when we do.
1047     */
1048    sc->amr_maxio = imin(sc->amr_maxio, AMR_LIMITCMD);
1049
1050    return(0);
1051}
1052
1053/********************************************************************************
1054 * Run a generic enquiry-style command.
1055 */
1056static void *
1057amr_enquiry(struct amr_softc *sc, size_t bufsize, u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual, int *status)
1058{
1059    struct amr_command	*ac;
1060    void		*result;
1061    u_int8_t		*mbox;
1062    int			error;
1063
1064    debug_called(1);
1065
1066    error = 1;
1067    result = NULL;
1068
1069    /* get ourselves a command buffer */
1070    mtx_lock(&sc->amr_list_lock);
1071    ac = amr_alloccmd(sc);
1072    mtx_unlock(&sc->amr_list_lock);
1073    if (ac == NULL)
1074	goto out;
1075    /* allocate the response structure */
1076    if ((result = malloc(bufsize, M_AMR, M_ZERO|M_NOWAIT)) == NULL)
1077	goto out;
1078    /* set command flags */
1079
1080    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAIN;
1081
1082    /* point the command at our data */
1083    ac->ac_data = result;
1084    ac->ac_length = bufsize;
1085
1086    /* build the command proper */
1087    mbox = (u_int8_t *)&ac->ac_mailbox;		/* XXX want a real structure for this? */
1088    mbox[0] = cmd;
1089    mbox[2] = cmdsub;
1090    mbox[3] = cmdqual;
1091    *status = 0;
1092
1093    /* can't assume that interrupts are going to work here, so play it safe */
1094    if (sc->amr_poll_command(ac))
1095	goto out;
1096    error = ac->ac_status;
1097    *status = ac->ac_status;
1098
1099 out:
1100    mtx_lock(&sc->amr_list_lock);
1101    if (ac != NULL)
1102	amr_releasecmd(ac);
1103    mtx_unlock(&sc->amr_list_lock);
1104    if ((error != 0) && (result != NULL)) {
1105	free(result, M_AMR);
1106	result = NULL;
1107    }
1108    return(result);
1109}
1110
1111/********************************************************************************
1112 * Flush the controller's internal cache, return status.
1113 */
1114int
1115amr_flush(struct amr_softc *sc)
1116{
1117    struct amr_command	*ac;
1118    int			error;
1119
1120    /* get ourselves a command buffer */
1121    error = 1;
1122    mtx_lock(&sc->amr_list_lock);
1123    ac = amr_alloccmd(sc);
1124    mtx_unlock(&sc->amr_list_lock);
1125    if (ac == NULL)
1126	goto out;
1127    /* set command flags */
1128    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
1129
1130    /* build the command proper */
1131    ac->ac_mailbox.mb_command = AMR_CMD_FLUSH;
1132
1133    /* we have to poll, as the system may be going down or otherwise damaged */
1134    if (sc->amr_poll_command(ac))
1135	goto out;
1136    error = ac->ac_status;
1137
1138 out:
1139    mtx_lock(&sc->amr_list_lock);
1140    if (ac != NULL)
1141	amr_releasecmd(ac);
1142    mtx_unlock(&sc->amr_list_lock);
1143    return(error);
1144}
1145
1146/********************************************************************************
1147 * Detect extented cdb >> greater than 10 byte cdb support
1148 * returns '1' means this support exist
1149 * returns '0' means this support doesn't exist
1150 */
1151static int
1152amr_support_ext_cdb(struct amr_softc *sc)
1153{
1154    struct amr_command	*ac;
1155    u_int8_t		*mbox;
1156    int			error;
1157
1158    /* get ourselves a command buffer */
1159    error = 0;
1160    mtx_lock(&sc->amr_list_lock);
1161    ac = amr_alloccmd(sc);
1162    mtx_unlock(&sc->amr_list_lock);
1163    if (ac == NULL)
1164	goto out;
1165    /* set command flags */
1166    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
1167
1168    /* build the command proper */
1169    mbox = (u_int8_t *)&ac->ac_mailbox;		/* XXX want a real structure for this? */
1170    mbox[0] = 0xA4;
1171    mbox[2] = 0x16;
1172
1173
1174    /* we have to poll, as the system may be going down or otherwise damaged */
1175    if (sc->amr_poll_command(ac))
1176	goto out;
1177    if( ac->ac_status == AMR_STATUS_SUCCESS ) {
1178	    error = 1;
1179    }
1180
1181out:
1182    mtx_lock(&sc->amr_list_lock);
1183    if (ac != NULL)
1184	amr_releasecmd(ac);
1185    mtx_unlock(&sc->amr_list_lock);
1186    return(error);
1187}
1188
1189/********************************************************************************
1190 * Try to find I/O work for the controller from one or more of the work queues.
1191 *
1192 * We make the assumption that if the controller is not ready to take a command
1193 * at some given time, it will generate an interrupt at some later time when
1194 * it is.
1195 */
1196void
1197amr_startio(struct amr_softc *sc)
1198{
1199    struct amr_command	*ac;
1200
1201    /* spin until something prevents us from doing any work */
1202    for (;;) {
1203
1204	/* Don't bother to queue commands no bounce buffers are available. */
1205	if (sc->amr_state & AMR_STATE_QUEUE_FRZN)
1206	    break;
1207
1208	/* try to get a ready command */
1209	ac = amr_dequeue_ready(sc);
1210
1211	/* if that failed, build a command from a bio */
1212	if (ac == NULL)
1213	    (void)amr_bio_command(sc, &ac);
1214
1215	/* if that failed, build a command from a ccb */
1216	if ((ac == NULL) && (sc->amr_cam_command != NULL))
1217	    sc->amr_cam_command(sc, &ac);
1218
1219	/* if we don't have anything to do, give up */
1220	if (ac == NULL)
1221	    break;
1222
1223	/* try to give the command to the controller; if this fails save it for later and give up */
1224	if (amr_start(ac)) {
1225	    debug(2, "controller busy, command deferred");
1226	    amr_requeue_ready(ac);	/* XXX schedule retry very soon? */
1227	    break;
1228	}
1229    }
1230}
1231
1232/********************************************************************************
1233 * Handle completion of an I/O command.
1234 */
1235static void
1236amr_completeio(struct amr_command *ac)
1237{
1238    struct amrd_softc		*sc = ac->ac_bio->bio_disk->d_drv1;
1239    static struct timeval	lastfail;
1240    static int			curfail;
1241
1242    if (ac->ac_status != AMR_STATUS_SUCCESS) {	/* could be more verbose here? */
1243	ac->ac_bio->bio_error = EIO;
1244	ac->ac_bio->bio_flags |= BIO_ERROR;
1245
1246	if (ppsratecheck(&lastfail, &curfail, 1))
1247	    device_printf(sc->amrd_dev, "I/O error - 0x%x\n", ac->ac_status);
1248/*	amr_printcommand(ac);*/
1249    }
1250    amrd_intr(ac->ac_bio);
1251    mtx_lock(&ac->ac_sc->amr_list_lock);
1252    amr_releasecmd(ac);
1253    mtx_unlock(&ac->ac_sc->amr_list_lock);
1254}
1255
1256/********************************************************************************
1257 ********************************************************************************
1258                                                               Command Processing
1259 ********************************************************************************
1260 ********************************************************************************/
1261
1262/********************************************************************************
1263 * Convert a bio off the top of the bio queue into a command.
1264 */
1265static int
1266amr_bio_command(struct amr_softc *sc, struct amr_command **acp)
1267{
1268    struct amr_command	*ac;
1269    struct amrd_softc	*amrd;
1270    struct bio		*bio;
1271    int			error;
1272    int			blkcount;
1273    int			driveno;
1274    int			cmd;
1275
1276    ac = NULL;
1277    error = 0;
1278
1279    /* get a command */
1280    if ((ac = amr_alloccmd(sc)) == NULL)
1281	return (ENOMEM);
1282
1283    /* get a bio to work on */
1284    if ((bio = amr_dequeue_bio(sc)) == NULL) {
1285	amr_releasecmd(ac);
1286	return (0);
1287    }
1288
1289    /* connect the bio to the command */
1290    ac->ac_complete = amr_completeio;
1291    ac->ac_bio = bio;
1292    ac->ac_data = bio->bio_data;
1293    ac->ac_length = bio->bio_bcount;
1294    cmd = 0;
1295    switch (bio->bio_cmd) {
1296    case BIO_READ:
1297	ac->ac_flags |= AMR_CMD_DATAIN;
1298	if (AMR_IS_SG64(sc)) {
1299	    cmd = AMR_CMD_LREAD64;
1300	    ac->ac_flags |= AMR_CMD_SG64;
1301	} else
1302	    cmd = AMR_CMD_LREAD;
1303	break;
1304    case BIO_WRITE:
1305	ac->ac_flags |= AMR_CMD_DATAOUT;
1306	if (AMR_IS_SG64(sc)) {
1307	    cmd = AMR_CMD_LWRITE64;
1308	    ac->ac_flags |= AMR_CMD_SG64;
1309	} else
1310	    cmd = AMR_CMD_LWRITE;
1311	break;
1312    case BIO_FLUSH:
1313	ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
1314	cmd = AMR_CMD_FLUSH;
1315	break;
1316    }
1317    amrd = (struct amrd_softc *)bio->bio_disk->d_drv1;
1318    driveno = amrd->amrd_drive - sc->amr_drive;
1319    blkcount = howmany(bio->bio_bcount, AMR_BLKSIZE);
1320
1321    ac->ac_mailbox.mb_command = cmd;
1322    if (bio->bio_cmd == BIO_READ || bio->bio_cmd == BIO_WRITE) {
1323	ac->ac_mailbox.mb_blkcount = blkcount;
1324	ac->ac_mailbox.mb_lba = bio->bio_pblkno;
1325	if ((bio->bio_pblkno + blkcount) > sc->amr_drive[driveno].al_size) {
1326	    device_printf(sc->amr_dev,
1327			  "I/O beyond end of unit (%lld,%d > %lu)\n",
1328			  (long long)bio->bio_pblkno, blkcount,
1329			  (u_long)sc->amr_drive[driveno].al_size);
1330	}
1331    }
1332    ac->ac_mailbox.mb_drive = driveno;
1333    if (sc->amr_state & AMR_STATE_REMAP_LD)
1334	ac->ac_mailbox.mb_drive |= 0x80;
1335
1336    /* we fill in the s/g related data when the command is mapped */
1337
1338
1339    *acp = ac;
1340    return(error);
1341}
1342
1343/********************************************************************************
1344 * Take a command, submit it to the controller and sleep until it completes
1345 * or fails.  Interrupts must be enabled, returns nonzero on error.
1346 */
1347static int
1348amr_wait_command(struct amr_command *ac)
1349{
1350    int			error = 0;
1351    struct amr_softc	*sc = ac->ac_sc;
1352
1353    debug_called(1);
1354
1355    ac->ac_complete = NULL;
1356    ac->ac_flags |= AMR_CMD_SLEEP;
1357    if ((error = amr_start(ac)) != 0) {
1358	return(error);
1359    }
1360
1361    while ((ac->ac_flags & AMR_CMD_BUSY) && (error != EWOULDBLOCK)) {
1362	error = msleep(ac,&sc->amr_list_lock, PRIBIO, "amrwcmd", 0);
1363    }
1364
1365    return(error);
1366}
1367
1368/********************************************************************************
1369 * Take a command, submit it to the controller and busy-wait for it to return.
1370 * Returns nonzero on error.  Can be safely called with interrupts enabled.
1371 */
1372static int
1373amr_std_poll_command(struct amr_command *ac)
1374{
1375    struct amr_softc	*sc = ac->ac_sc;
1376    int			error, count;
1377
1378    debug_called(2);
1379
1380    ac->ac_complete = NULL;
1381    if ((error = amr_start(ac)) != 0)
1382	return(error);
1383
1384    count = 0;
1385    do {
1386	/*
1387	 * Poll for completion, although the interrupt handler may beat us to it.
1388	 * Note that the timeout here is somewhat arbitrary.
1389	 */
1390	amr_done(sc);
1391	DELAY(1000);
1392    } while ((ac->ac_flags & AMR_CMD_BUSY) && (count++ < 1000));
1393    if (!(ac->ac_flags & AMR_CMD_BUSY)) {
1394	error = 0;
1395    } else {
1396	/* XXX the slot is now marked permanently busy */
1397	error = EIO;
1398	device_printf(sc->amr_dev, "polled command timeout\n");
1399    }
1400    return(error);
1401}
1402
1403static void
1404amr_setup_polled_dmamap(void *arg, bus_dma_segment_t *segs, int nsegs, int err)
1405{
1406    struct amr_command *ac = arg;
1407    struct amr_softc *sc = ac->ac_sc;
1408    int mb_channel;
1409
1410    if (err) {
1411	device_printf(sc->amr_dev, "error %d in %s", err, __FUNCTION__);
1412	ac->ac_status = AMR_STATUS_ABORTED;
1413	return;
1414    }
1415
1416    amr_setup_sg(arg, segs, nsegs, err);
1417
1418    /* for AMR_CMD_CONFIG Read/Write the s/g count goes elsewhere */
1419    mb_channel = ((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_channel;
1420    if (ac->ac_mailbox.mb_command == AMR_CMD_CONFIG &&
1421        ((mb_channel == AMR_CONFIG_READ_NVRAM_CONFIG) ||
1422        (mb_channel == AMR_CONFIG_WRITE_NVRAM_CONFIG)))
1423	((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_param = ac->ac_nsegments;
1424
1425    ac->ac_mailbox.mb_nsgelem = ac->ac_nsegments;
1426    ac->ac_mailbox.mb_physaddr = ac->ac_mb_physaddr;
1427    if (AC_IS_SG64(ac)) {
1428	ac->ac_sg64_hi = 0;
1429	ac->ac_sg64_lo = ac->ac_sgbusaddr;
1430    }
1431
1432    sc->amr_poll_command1(sc, ac);
1433}
1434
1435/********************************************************************************
1436 * Take a command, submit it to the controller and busy-wait for it to return.
1437 * Returns nonzero on error.  Can be safely called with interrupts enabled.
1438 */
1439static int
1440amr_quartz_poll_command(struct amr_command *ac)
1441{
1442    struct amr_softc	*sc = ac->ac_sc;
1443    int			error;
1444
1445    debug_called(2);
1446
1447    error = 0;
1448
1449    if (AC_IS_SG64(ac)) {
1450	ac->ac_tag = sc->amr_buffer64_dmat;
1451	ac->ac_datamap = ac->ac_dma64map;
1452    } else {
1453	ac->ac_tag = sc->amr_buffer_dmat;
1454	ac->ac_datamap = ac->ac_dmamap;
1455    }
1456
1457    /* now we have a slot, we can map the command (unmapped in amr_complete) */
1458    if (ac->ac_data != 0) {
1459	if (bus_dmamap_load(ac->ac_tag, ac->ac_datamap, ac->ac_data,
1460	    ac->ac_length, amr_setup_polled_dmamap, ac, BUS_DMA_NOWAIT) != 0) {
1461	    error = 1;
1462	}
1463    } else {
1464	error = amr_quartz_poll_command1(sc, ac);
1465    }
1466
1467    return (error);
1468}
1469
1470static int
1471amr_quartz_poll_command1(struct amr_softc *sc, struct amr_command *ac)
1472{
1473    int count, error;
1474
1475    mtx_lock(&sc->amr_hw_lock);
1476    if ((sc->amr_state & AMR_STATE_INTEN) == 0) {
1477	count=0;
1478	while (sc->amr_busyslots) {
1479	    msleep(sc, &sc->amr_hw_lock, PRIBIO | PCATCH, "amrpoll", hz);
1480	    if(count++>10) {
1481		break;
1482	    }
1483	}
1484
1485	if(sc->amr_busyslots) {
1486	    device_printf(sc->amr_dev, "adapter is busy\n");
1487	    mtx_unlock(&sc->amr_hw_lock);
1488	    if (ac->ac_data != NULL) {
1489		bus_dmamap_unload(ac->ac_tag, ac->ac_datamap);
1490	    }
1491    	    ac->ac_status=0;
1492	    return(1);
1493	}
1494    }
1495
1496    bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, AMR_MBOX_CMDSIZE);
1497
1498    /* clear the poll/ack fields in the mailbox */
1499    sc->amr_mailbox->mb_ident = 0xFE;
1500    sc->amr_mailbox->mb_nstatus = 0xFF;
1501    sc->amr_mailbox->mb_status = 0xFF;
1502    sc->amr_mailbox->mb_poll = 0;
1503    sc->amr_mailbox->mb_ack = 0;
1504    sc->amr_mailbox->mb_busy = 1;
1505
1506    AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
1507
1508    while(sc->amr_mailbox->mb_nstatus == 0xFF)
1509	DELAY(1);
1510    while(sc->amr_mailbox->mb_status == 0xFF)
1511	DELAY(1);
1512    ac->ac_status=sc->amr_mailbox->mb_status;
1513    error = (ac->ac_status !=AMR_STATUS_SUCCESS) ? 1:0;
1514    while(sc->amr_mailbox->mb_poll != 0x77)
1515	DELAY(1);
1516    sc->amr_mailbox->mb_poll = 0;
1517    sc->amr_mailbox->mb_ack = 0x77;
1518
1519    /* acknowledge that we have the commands */
1520    AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_ACK);
1521    while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK)
1522	DELAY(1);
1523    mtx_unlock(&sc->amr_hw_lock);
1524
1525    /* unmap the command's data buffer */
1526    if (ac->ac_flags & AMR_CMD_DATAIN) {
1527	bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, BUS_DMASYNC_POSTREAD);
1528    }
1529    if (ac->ac_flags & AMR_CMD_DATAOUT) {
1530	bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, BUS_DMASYNC_POSTWRITE);
1531    }
1532    bus_dmamap_unload(ac->ac_tag, ac->ac_datamap);
1533
1534    return(error);
1535}
1536
1537static __inline int
1538amr_freeslot(struct amr_command *ac)
1539{
1540    struct amr_softc *sc = ac->ac_sc;
1541    int			slot;
1542
1543    debug_called(3);
1544
1545    slot = ac->ac_slot;
1546    if (sc->amr_busycmd[slot] == NULL)
1547	panic("amr: slot %d not busy?\n", slot);
1548
1549    sc->amr_busycmd[slot] = NULL;
1550    atomic_subtract_int(&sc->amr_busyslots, 1);
1551
1552    return (0);
1553}
1554
1555/********************************************************************************
1556 * Map/unmap (ac)'s data in the controller's addressable space as required.
1557 *
1558 * These functions may be safely called multiple times on a given command.
1559 */
1560static void
1561amr_setup_sg(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
1562{
1563    struct amr_command	*ac = (struct amr_command *)arg;
1564    struct amr_sgentry	*sg;
1565    struct amr_sg64entry *sg64;
1566    int flags, i;
1567
1568    debug_called(3);
1569
1570    /* get base address of s/g table */
1571    sg = ac->ac_sg.sg32;
1572    sg64 = ac->ac_sg.sg64;
1573
1574    if (AC_IS_SG64(ac)) {
1575	ac->ac_nsegments = nsegments;
1576	ac->ac_mb_physaddr = 0xffffffff;
1577	for (i = 0; i < nsegments; i++, sg64++) {
1578	    sg64->sg_addr = segs[i].ds_addr;
1579	    sg64->sg_count = segs[i].ds_len;
1580	}
1581    } else {
1582	/* decide whether we need to populate the s/g table */
1583	if (nsegments < 2) {
1584	    ac->ac_nsegments = 0;
1585	    ac->ac_mb_physaddr = segs[0].ds_addr;
1586	} else {
1587            ac->ac_nsegments = nsegments;
1588	    ac->ac_mb_physaddr = ac->ac_sgbusaddr;
1589	    for (i = 0; i < nsegments; i++, sg++) {
1590		sg->sg_addr = segs[i].ds_addr;
1591		sg->sg_count = segs[i].ds_len;
1592	    }
1593	}
1594    }
1595
1596    flags = 0;
1597    if (ac->ac_flags & AMR_CMD_DATAIN)
1598	flags |= BUS_DMASYNC_PREREAD;
1599    if (ac->ac_flags & AMR_CMD_DATAOUT)
1600	flags |= BUS_DMASYNC_PREWRITE;
1601    bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, flags);
1602    ac->ac_flags |= AMR_CMD_MAPPED;
1603}
1604
1605static void
1606amr_setup_data(void *arg, bus_dma_segment_t *segs, int nsegs, int err)
1607{
1608    struct amr_command *ac = arg;
1609    struct amr_softc *sc = ac->ac_sc;
1610    int mb_channel;
1611
1612    if (err) {
1613	device_printf(sc->amr_dev, "error %d in %s", err, __FUNCTION__);
1614	amr_abort_load(ac);
1615	return;
1616    }
1617
1618    amr_setup_sg(arg, segs, nsegs, err);
1619
1620    /* for AMR_CMD_CONFIG Read/Write the s/g count goes elsewhere */
1621    mb_channel = ((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_channel;
1622    if (ac->ac_mailbox.mb_command == AMR_CMD_CONFIG &&
1623        ((mb_channel == AMR_CONFIG_READ_NVRAM_CONFIG) ||
1624        (mb_channel == AMR_CONFIG_WRITE_NVRAM_CONFIG)))
1625	((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_param = ac->ac_nsegments;
1626
1627    ac->ac_mailbox.mb_nsgelem = ac->ac_nsegments;
1628    ac->ac_mailbox.mb_physaddr = ac->ac_mb_physaddr;
1629    if (AC_IS_SG64(ac)) {
1630	ac->ac_sg64_hi = 0;
1631	ac->ac_sg64_lo = ac->ac_sgbusaddr;
1632    }
1633
1634    if (sc->amr_submit_command(ac) == EBUSY) {
1635	amr_freeslot(ac);
1636	amr_requeue_ready(ac);
1637    }
1638}
1639
1640static void
1641amr_setup_ccb(void *arg, bus_dma_segment_t *segs, int nsegs, int err)
1642{
1643    struct amr_command *ac = arg;
1644    struct amr_softc *sc = ac->ac_sc;
1645    struct amr_passthrough *ap = &ac->ac_ccb->ccb_pthru;
1646    struct amr_ext_passthrough *aep = &ac->ac_ccb->ccb_epthru;
1647
1648    if (err) {
1649	device_printf(sc->amr_dev, "error %d in %s", err, __FUNCTION__);
1650	amr_abort_load(ac);
1651	return;
1652    }
1653
1654    /* Set up the mailbox portion of the command to point at the ccb */
1655    ac->ac_mailbox.mb_nsgelem = 0;
1656    ac->ac_mailbox.mb_physaddr = ac->ac_ccb_busaddr;
1657
1658    amr_setup_sg(arg, segs, nsegs, err);
1659
1660    switch (ac->ac_mailbox.mb_command) {
1661    case AMR_CMD_EXTPASS:
1662	aep->ap_no_sg_elements = ac->ac_nsegments;
1663	aep->ap_data_transfer_address = ac->ac_mb_physaddr;
1664        break;
1665    case AMR_CMD_PASS:
1666	ap->ap_no_sg_elements = ac->ac_nsegments;
1667	ap->ap_data_transfer_address = ac->ac_mb_physaddr;
1668	break;
1669    default:
1670	panic("Unknown ccb command");
1671    }
1672
1673    if (sc->amr_submit_command(ac) == EBUSY) {
1674	amr_freeslot(ac);
1675	amr_requeue_ready(ac);
1676    }
1677}
1678
1679static int
1680amr_mapcmd(struct amr_command *ac)
1681{
1682    bus_dmamap_callback_t *cb;
1683    struct amr_softc	*sc = ac->ac_sc;
1684
1685    debug_called(3);
1686
1687    if (AC_IS_SG64(ac)) {
1688	ac->ac_tag = sc->amr_buffer64_dmat;
1689	ac->ac_datamap = ac->ac_dma64map;
1690    } else {
1691	ac->ac_tag = sc->amr_buffer_dmat;
1692	ac->ac_datamap = ac->ac_dmamap;
1693    }
1694
1695    if (ac->ac_flags & AMR_CMD_CCB)
1696	cb = amr_setup_ccb;
1697    else
1698	cb = amr_setup_data;
1699
1700    /* if the command involves data at all, and hasn't been mapped */
1701    if ((ac->ac_flags & AMR_CMD_MAPPED) == 0 && (ac->ac_data != NULL)) {
1702	/* map the data buffers into bus space and build the s/g list */
1703	if (bus_dmamap_load(ac->ac_tag, ac->ac_datamap, ac->ac_data,
1704	     ac->ac_length, cb, ac, 0) == EINPROGRESS) {
1705	    sc->amr_state |= AMR_STATE_QUEUE_FRZN;
1706	}
1707   } else {
1708    	if (sc->amr_submit_command(ac) == EBUSY) {
1709	    amr_freeslot(ac);
1710	    amr_requeue_ready(ac);
1711	}
1712   }
1713
1714    return (0);
1715}
1716
1717static void
1718amr_unmapcmd(struct amr_command *ac)
1719{
1720    int			flag;
1721
1722    debug_called(3);
1723
1724    /* if the command involved data at all and was mapped */
1725    if (ac->ac_flags & AMR_CMD_MAPPED) {
1726
1727	if (ac->ac_data != NULL) {
1728
1729	    flag = 0;
1730	    if (ac->ac_flags & AMR_CMD_DATAIN)
1731		flag |= BUS_DMASYNC_POSTREAD;
1732	    if (ac->ac_flags & AMR_CMD_DATAOUT)
1733		flag |= BUS_DMASYNC_POSTWRITE;
1734
1735	    bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, flag);
1736	    bus_dmamap_unload(ac->ac_tag, ac->ac_datamap);
1737	}
1738
1739	ac->ac_flags &= ~AMR_CMD_MAPPED;
1740    }
1741}
1742
1743static void
1744amr_abort_load(struct amr_command *ac)
1745{
1746    ac_qhead_t head;
1747    struct amr_softc *sc = ac->ac_sc;
1748
1749    mtx_assert(&sc->amr_list_lock, MA_OWNED);
1750
1751    ac->ac_status = AMR_STATUS_ABORTED;
1752    amr_init_qhead(&head);
1753    amr_enqueue_completed(ac, &head);
1754
1755    mtx_unlock(&sc->amr_list_lock);
1756    amr_complete(sc, &head);
1757    mtx_lock(&sc->amr_list_lock);
1758}
1759
1760/********************************************************************************
1761 * Take a command and give it to the controller, returns 0 if successful, or
1762 * EBUSY if the command should be retried later.
1763 */
1764static int
1765amr_start(struct amr_command *ac)
1766{
1767    struct amr_softc *sc;
1768    int error = 0;
1769    int slot;
1770
1771    debug_called(3);
1772
1773    /* mark command as busy so that polling consumer can tell */
1774    sc = ac->ac_sc;
1775    ac->ac_flags |= AMR_CMD_BUSY;
1776
1777    /* get a command slot (freed in amr_done) */
1778    slot = ac->ac_slot;
1779    if (sc->amr_busycmd[slot] != NULL)
1780	panic("amr: slot %d busy?\n", slot);
1781    sc->amr_busycmd[slot] = ac;
1782    atomic_add_int(&sc->amr_busyslots, 1);
1783
1784    /* Now we have a slot, we can map the command (unmapped in amr_complete). */
1785    if ((error = amr_mapcmd(ac)) == ENOMEM) {
1786	/*
1787	 * Memory resources are short, so free the slot and let this be tried
1788	 * later.
1789	 */
1790	amr_freeslot(ac);
1791    }
1792
1793    return (error);
1794}
1795
1796/********************************************************************************
1797 * Extract one or more completed commands from the controller (sc)
1798 *
1799 * Returns nonzero if any commands on the work queue were marked as completed.
1800 */
1801
1802int
1803amr_done(struct amr_softc *sc)
1804{
1805    ac_qhead_t		head;
1806    struct amr_command	*ac;
1807    struct amr_mailbox	mbox;
1808    int			i, idx, result;
1809
1810    debug_called(3);
1811
1812    /* See if there's anything for us to do */
1813    result = 0;
1814    amr_init_qhead(&head);
1815
1816    /* loop collecting completed commands */
1817    for (;;) {
1818	/* poll for a completed command's identifier and status */
1819	if (sc->amr_get_work(sc, &mbox)) {
1820	    result = 1;
1821
1822	    /* iterate over completed commands in this result */
1823	    for (i = 0; i < mbox.mb_nstatus; i++) {
1824		/* get pointer to busy command */
1825		idx = mbox.mb_completed[i] - 1;
1826		ac = sc->amr_busycmd[idx];
1827
1828		/* really a busy command? */
1829		if (ac != NULL) {
1830
1831		    /* pull the command from the busy index */
1832		    amr_freeslot(ac);
1833
1834		    /* save status for later use */
1835		    ac->ac_status = mbox.mb_status;
1836		    amr_enqueue_completed(ac, &head);
1837		    debug(3, "completed command with status %x", mbox.mb_status);
1838		} else {
1839		    device_printf(sc->amr_dev, "bad slot %d completed\n", idx);
1840		}
1841	    }
1842	} else
1843	    break;	/* no work */
1844    }
1845
1846    /* handle completion and timeouts */
1847    amr_complete(sc, &head);
1848
1849    return(result);
1850}
1851
1852/********************************************************************************
1853 * Do completion processing on done commands on (sc)
1854 */
1855
1856static void
1857amr_complete(void *context, ac_qhead_t *head)
1858{
1859    struct amr_softc	*sc = (struct amr_softc *)context;
1860    struct amr_command	*ac;
1861
1862    debug_called(3);
1863
1864    /* pull completed commands off the queue */
1865    for (;;) {
1866	ac = amr_dequeue_completed(sc, head);
1867	if (ac == NULL)
1868	    break;
1869
1870	/* unmap the command's data buffer */
1871	amr_unmapcmd(ac);
1872
1873	/*
1874	 * Is there a completion handler?
1875	 */
1876	if (ac->ac_complete != NULL) {
1877	    /* unbusy the command */
1878	    ac->ac_flags &= ~AMR_CMD_BUSY;
1879	    ac->ac_complete(ac);
1880
1881	    /*
1882	     * Is someone sleeping on this one?
1883	     */
1884	} else {
1885	    mtx_lock(&sc->amr_list_lock);
1886	    ac->ac_flags &= ~AMR_CMD_BUSY;
1887	    if (ac->ac_flags & AMR_CMD_SLEEP) {
1888		/* unbusy the command */
1889		wakeup(ac);
1890	    }
1891	    mtx_unlock(&sc->amr_list_lock);
1892	}
1893
1894	if(!sc->amr_busyslots) {
1895	    wakeup(sc);
1896	}
1897    }
1898
1899    mtx_lock(&sc->amr_list_lock);
1900    sc->amr_state &= ~AMR_STATE_QUEUE_FRZN;
1901    amr_startio(sc);
1902    mtx_unlock(&sc->amr_list_lock);
1903}
1904
1905/********************************************************************************
1906 ********************************************************************************
1907                                                        Command Buffer Management
1908 ********************************************************************************
1909 ********************************************************************************/
1910
1911/********************************************************************************
1912 * Get a new command buffer.
1913 *
1914 * This may return NULL in low-memory cases.
1915 *
1916 * If possible, we recycle a command buffer that's been used before.
1917 */
1918struct amr_command *
1919amr_alloccmd(struct amr_softc *sc)
1920{
1921    struct amr_command	*ac;
1922
1923    debug_called(3);
1924
1925    ac = amr_dequeue_free(sc);
1926    if (ac == NULL) {
1927	sc->amr_state |= AMR_STATE_QUEUE_FRZN;
1928	return(NULL);
1929    }
1930
1931    /* clear out significant fields */
1932    ac->ac_status = 0;
1933    bzero(&ac->ac_mailbox, sizeof(struct amr_mailbox));
1934    ac->ac_flags = 0;
1935    ac->ac_bio = NULL;
1936    ac->ac_data = NULL;
1937    ac->ac_complete = NULL;
1938    ac->ac_retries = 0;
1939    ac->ac_tag = NULL;
1940    ac->ac_datamap = NULL;
1941    return(ac);
1942}
1943
1944/********************************************************************************
1945 * Release a command buffer for recycling.
1946 */
1947void
1948amr_releasecmd(struct amr_command *ac)
1949{
1950    debug_called(3);
1951
1952    amr_enqueue_free(ac);
1953}
1954
1955/********************************************************************************
1956 * Allocate a new command cluster and initialise it.
1957 */
1958static void
1959amr_alloccmd_cluster(struct amr_softc *sc)
1960{
1961    struct amr_command_cluster	*acc;
1962    struct amr_command		*ac;
1963    int				i, nextslot;
1964
1965    /*
1966     * If we haven't found the real limit yet, let us have a couple of
1967     * commands in order to be able to probe.
1968     */
1969    if (sc->amr_maxio == 0)
1970	sc->amr_maxio = 2;
1971
1972    if (sc->amr_nextslot > sc->amr_maxio)
1973	return;
1974    acc = malloc(AMR_CMD_CLUSTERSIZE, M_AMR, M_NOWAIT | M_ZERO);
1975    if (acc != NULL) {
1976	nextslot = sc->amr_nextslot;
1977	mtx_lock(&sc->amr_list_lock);
1978	TAILQ_INSERT_TAIL(&sc->amr_cmd_clusters, acc, acc_link);
1979	mtx_unlock(&sc->amr_list_lock);
1980	for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++) {
1981	    ac = &acc->acc_command[i];
1982	    ac->ac_sc = sc;
1983	    ac->ac_slot = nextslot;
1984
1985	    /*
1986	     * The SG table for each slot is a fixed size and is assumed to
1987	     * to hold 64-bit s/g objects when the driver is configured to do
1988	     * 64-bit DMA.  32-bit DMA commands still use the same table, but
1989	     * cast down to 32-bit objects.
1990	     */
1991	    if (AMR_IS_SG64(sc)) {
1992		ac->ac_sgbusaddr = sc->amr_sgbusaddr +
1993		    (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sg64entry));
1994	        ac->ac_sg.sg64 = sc->amr_sg64table + (ac->ac_slot * AMR_NSEG);
1995	    } else {
1996		ac->ac_sgbusaddr = sc->amr_sgbusaddr +
1997		    (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
1998	        ac->ac_sg.sg32 = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
1999	    }
2000
2001	    ac->ac_ccb = sc->amr_ccb + ac->ac_slot;
2002	    ac->ac_ccb_busaddr = sc->amr_ccb_busaddr +
2003		(ac->ac_slot * sizeof(union amr_ccb));
2004
2005	    if (bus_dmamap_create(sc->amr_buffer_dmat, 0, &ac->ac_dmamap))
2006		break;
2007	    if (AMR_IS_SG64(sc) &&
2008		(bus_dmamap_create(sc->amr_buffer64_dmat, 0,&ac->ac_dma64map)))
2009		break;
2010	    amr_releasecmd(ac);
2011	    if (++nextslot > sc->amr_maxio)
2012		break;
2013	}
2014	sc->amr_nextslot = nextslot;
2015    }
2016}
2017
2018/********************************************************************************
2019 * Free a command cluster
2020 */
2021static void
2022amr_freecmd_cluster(struct amr_command_cluster *acc)
2023{
2024    struct amr_softc	*sc = acc->acc_command[0].ac_sc;
2025    int			i;
2026
2027    for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++) {
2028	if (acc->acc_command[i].ac_sc == NULL)
2029	    break;
2030	bus_dmamap_destroy(sc->amr_buffer_dmat, acc->acc_command[i].ac_dmamap);
2031	if (AMR_IS_SG64(sc))
2032		bus_dmamap_destroy(sc->amr_buffer64_dmat, acc->acc_command[i].ac_dma64map);
2033    }
2034    free(acc, M_AMR);
2035}
2036
2037/********************************************************************************
2038 ********************************************************************************
2039                                                         Interface-specific Shims
2040 ********************************************************************************
2041 ********************************************************************************/
2042
2043/********************************************************************************
2044 * Tell the controller that the mailbox contains a valid command
2045 */
2046static int
2047amr_quartz_submit_command(struct amr_command *ac)
2048{
2049    struct amr_softc	*sc = ac->ac_sc;
2050    static struct timeval lastfail;
2051    static int		curfail;
2052    int			i = 0;
2053
2054    mtx_lock(&sc->amr_hw_lock);
2055    while (sc->amr_mailbox->mb_busy && (i++ < 10)) {
2056        DELAY(1);
2057	/* This is a no-op read that flushes pending mailbox updates */
2058	AMR_QGET_ODB(sc);
2059    }
2060    if (sc->amr_mailbox->mb_busy) {
2061	mtx_unlock(&sc->amr_hw_lock);
2062	if (ac->ac_retries++ > 1000) {
2063	    if (ppsratecheck(&lastfail, &curfail, 1))
2064		device_printf(sc->amr_dev, "Too many retries on command %p.  "
2065			      "Controller is likely dead\n", ac);
2066	    ac->ac_retries = 0;
2067	}
2068	return (EBUSY);
2069    }
2070
2071    /*
2072     * Save the slot number so that we can locate this command when complete.
2073     * Note that ident = 0 seems to be special, so we don't use it.
2074     */
2075    ac->ac_mailbox.mb_ident = ac->ac_slot + 1; /* will be coppied into mbox */
2076    bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, 14);
2077    sc->amr_mailbox->mb_busy = 1;
2078    sc->amr_mailbox->mb_poll = 0;
2079    sc->amr_mailbox->mb_ack  = 0;
2080    sc->amr_mailbox64->sg64_hi = ac->ac_sg64_hi;
2081    sc->amr_mailbox64->sg64_lo = ac->ac_sg64_lo;
2082
2083    AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
2084    mtx_unlock(&sc->amr_hw_lock);
2085    return(0);
2086}
2087
2088static int
2089amr_std_submit_command(struct amr_command *ac)
2090{
2091    struct amr_softc	*sc = ac->ac_sc;
2092    static struct timeval lastfail;
2093    static int		curfail;
2094
2095    mtx_lock(&sc->amr_hw_lock);
2096    if (AMR_SGET_MBSTAT(sc) & AMR_SMBOX_BUSYFLAG) {
2097	mtx_unlock(&sc->amr_hw_lock);
2098	if (ac->ac_retries++ > 1000) {
2099	    if (ppsratecheck(&lastfail, &curfail, 1))
2100		device_printf(sc->amr_dev, "Too many retries on command %p.  "
2101			      "Controller is likely dead\n", ac);
2102	    ac->ac_retries = 0;
2103	}
2104	return (EBUSY);
2105    }
2106
2107    /*
2108     * Save the slot number so that we can locate this command when complete.
2109     * Note that ident = 0 seems to be special, so we don't use it.
2110     */
2111    ac->ac_mailbox.mb_ident = ac->ac_slot + 1; /* will be coppied into mbox */
2112    bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, 14);
2113    sc->amr_mailbox->mb_busy = 1;
2114    sc->amr_mailbox->mb_poll = 0;
2115    sc->amr_mailbox->mb_ack  = 0;
2116
2117    AMR_SPOST_COMMAND(sc);
2118    mtx_unlock(&sc->amr_hw_lock);
2119    return(0);
2120}
2121
2122/********************************************************************************
2123 * Claim any work that the controller has completed; acknowledge completion,
2124 * save details of the completion in (mbsave)
2125 */
2126static int
2127amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
2128{
2129    int		worked, i;
2130    u_int32_t	outd;
2131    u_int8_t	nstatus;
2132    u_int8_t	completed[46];
2133
2134    debug_called(3);
2135
2136    worked = 0;
2137
2138    /* work waiting for us? */
2139    if ((outd = AMR_QGET_ODB(sc)) == AMR_QODB_READY) {
2140
2141	/* acknowledge interrupt */
2142	AMR_QPUT_ODB(sc, AMR_QODB_READY);
2143
2144	while ((nstatus = sc->amr_mailbox->mb_nstatus) == 0xff)
2145	    DELAY(1);
2146	sc->amr_mailbox->mb_nstatus = 0xff;
2147
2148	/* wait until fw wrote out all completions */
2149	for (i = 0; i < nstatus; i++) {
2150	    while ((completed[i] = sc->amr_mailbox->mb_completed[i]) == 0xff)
2151		DELAY(1);
2152	    sc->amr_mailbox->mb_completed[i] = 0xff;
2153	}
2154
2155	/* Save information for later processing */
2156	mbsave->mb_nstatus = nstatus;
2157	mbsave->mb_status = sc->amr_mailbox->mb_status;
2158	sc->amr_mailbox->mb_status = 0xff;
2159
2160	for (i = 0; i < nstatus; i++)
2161	    mbsave->mb_completed[i] = completed[i];
2162
2163	/* acknowledge that we have the commands */
2164	AMR_QPUT_IDB(sc, AMR_QIDB_ACK);
2165
2166#if 0
2167#ifndef AMR_QUARTZ_GOFASTER
2168	/*
2169	 * This waits for the controller to notice that we've taken the
2170	 * command from it.  It's very inefficient, and we shouldn't do it,
2171	 * but if we remove this code, we stop completing commands under
2172	 * load.
2173	 *
2174	 * Peter J says we shouldn't do this.  The documentation says we
2175	 * should.  Who is right?
2176	 */
2177	while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK)
2178	    ;				/* XXX aiee! what if it dies? */
2179#endif
2180#endif
2181
2182	worked = 1;			/* got some work */
2183    }
2184
2185    return(worked);
2186}
2187
2188static int
2189amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
2190{
2191    int		worked;
2192    u_int8_t	istat;
2193
2194    debug_called(3);
2195
2196    worked = 0;
2197
2198    /* check for valid interrupt status */
2199    istat = AMR_SGET_ISTAT(sc);
2200    if ((istat & AMR_SINTR_VALID) != 0) {
2201	AMR_SPUT_ISTAT(sc, istat);	/* ack interrupt status */
2202
2203	/* save mailbox, which contains a list of completed commands */
2204	bcopy((void *)(uintptr_t)(volatile void *)sc->amr_mailbox, mbsave, sizeof(*mbsave));
2205
2206	AMR_SACK_INTERRUPT(sc);		/* acknowledge we have the mailbox */
2207	worked = 1;
2208    }
2209
2210    return(worked);
2211}
2212
2213/********************************************************************************
2214 * Notify the controller of the mailbox location.
2215 */
2216static void
2217amr_std_attach_mailbox(struct amr_softc *sc)
2218{
2219
2220    /* program the mailbox physical address */
2221    AMR_SBYTE_SET(sc, AMR_SMBOX_0, sc->amr_mailboxphys         & 0xff);
2222    AMR_SBYTE_SET(sc, AMR_SMBOX_1, (sc->amr_mailboxphys >>  8) & 0xff);
2223    AMR_SBYTE_SET(sc, AMR_SMBOX_2, (sc->amr_mailboxphys >> 16) & 0xff);
2224    AMR_SBYTE_SET(sc, AMR_SMBOX_3, (sc->amr_mailboxphys >> 24) & 0xff);
2225    AMR_SBYTE_SET(sc, AMR_SMBOX_ENABLE, AMR_SMBOX_ADDR);
2226
2227    /* clear any outstanding interrupt and enable interrupts proper */
2228    AMR_SACK_INTERRUPT(sc);
2229    AMR_SENABLE_INTR(sc);
2230}
2231
2232#ifdef AMR_BOARD_INIT
2233/********************************************************************************
2234 * Initialise the controller
2235 */
2236static int
2237amr_quartz_init(struct amr_softc *sc)
2238{
2239    int		status, ostatus;
2240
2241    device_printf(sc->amr_dev, "initial init status %x\n", AMR_QGET_INITSTATUS(sc));
2242
2243    AMR_QRESET(sc);
2244
2245    ostatus = 0xff;
2246    while ((status = AMR_QGET_INITSTATUS(sc)) != AMR_QINIT_DONE) {
2247	if (status != ostatus) {
2248	    device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_qinit, status));
2249	    ostatus = status;
2250	}
2251	switch (status) {
2252	case AMR_QINIT_NOMEM:
2253	    return(ENOMEM);
2254
2255	case AMR_QINIT_SCAN:
2256	    /* XXX we could print channel/target here */
2257	    break;
2258	}
2259    }
2260    return(0);
2261}
2262
2263static int
2264amr_std_init(struct amr_softc *sc)
2265{
2266    int		status, ostatus;
2267
2268    device_printf(sc->amr_dev, "initial init status %x\n", AMR_SGET_INITSTATUS(sc));
2269
2270    AMR_SRESET(sc);
2271
2272    ostatus = 0xff;
2273    while ((status = AMR_SGET_INITSTATUS(sc)) != AMR_SINIT_DONE) {
2274	if (status != ostatus) {
2275	    device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_sinit, status));
2276	    ostatus = status;
2277	}
2278	switch (status) {
2279	case AMR_SINIT_NOMEM:
2280	    return(ENOMEM);
2281
2282	case AMR_SINIT_INPROG:
2283	    /* XXX we could print channel/target here? */
2284	    break;
2285	}
2286    }
2287    return(0);
2288}
2289#endif
2290
2291/********************************************************************************
2292 ********************************************************************************
2293                                                                        Debugging
2294 ********************************************************************************
2295 ********************************************************************************/
2296
2297/********************************************************************************
2298 * Identify the controller and print some information about it.
2299 */
2300static void
2301amr_describe_controller(struct amr_softc *sc)
2302{
2303    struct amr_prodinfo	*ap;
2304    struct amr_enquiry	*ae;
2305    char		*prod;
2306    int			status;
2307
2308    /*
2309     * Try to get 40LD product info, which tells us what the card is labelled as.
2310     */
2311    if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0, &status)) != NULL) {
2312	device_printf(sc->amr_dev, "<LSILogic %.80s> Firmware %.16s, BIOS %.16s, %dMB RAM\n",
2313		      ap->ap_product, ap->ap_firmware, ap->ap_bios,
2314		      ap->ap_memsize);
2315
2316	free(ap, M_AMR);
2317	return;
2318    }
2319
2320    /*
2321     * Try 8LD extended ENQUIRY to get controller signature, and use lookup table.
2322     */
2323    if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0, &status)) != NULL) {
2324	prod = amr_describe_code(amr_table_adaptertype, ae->ae_signature);
2325
2326    } else if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0, &status)) != NULL) {
2327
2328	/*
2329	 * Try to work it out based on the PCI signatures.
2330	 */
2331	switch (pci_get_device(sc->amr_dev)) {
2332	case 0x9010:
2333	    prod = "Series 428";
2334	    break;
2335	case 0x9060:
2336	    prod = "Series 434";
2337	    break;
2338	default:
2339	    prod = "unknown controller";
2340	    break;
2341	}
2342    } else {
2343	device_printf(sc->amr_dev, "<unsupported controller>\n");
2344	return;
2345    }
2346
2347    /*
2348     * HP NetRaid controllers have a special encoding of the firmware and
2349     * BIOS versions. The AMI version seems to have it as strings whereas
2350     * the HP version does it with a leading uppercase character and two
2351     * binary numbers.
2352     */
2353
2354    if(ae->ae_adapter.aa_firmware[2] >= 'A' &&
2355       ae->ae_adapter.aa_firmware[2] <= 'Z' &&
2356       ae->ae_adapter.aa_firmware[1] <  ' ' &&
2357       ae->ae_adapter.aa_firmware[0] <  ' ' &&
2358       ae->ae_adapter.aa_bios[2] >= 'A'     &&
2359       ae->ae_adapter.aa_bios[2] <= 'Z'     &&
2360       ae->ae_adapter.aa_bios[1] <  ' '     &&
2361       ae->ae_adapter.aa_bios[0] <  ' ') {
2362
2363	/* this looks like we have an HP NetRaid version of the MegaRaid */
2364
2365    	if(ae->ae_signature == AMR_SIG_438) {
2366    		/* the AMI 438 is a NetRaid 3si in HP-land */
2367    		prod = "HP NetRaid 3si";
2368    	}
2369
2370	device_printf(sc->amr_dev, "<%s> Firmware %c.%02d.%02d, BIOS %c.%02d.%02d, %dMB RAM\n",
2371		      prod, ae->ae_adapter.aa_firmware[2],
2372		      ae->ae_adapter.aa_firmware[1],
2373		      ae->ae_adapter.aa_firmware[0],
2374		      ae->ae_adapter.aa_bios[2],
2375		      ae->ae_adapter.aa_bios[1],
2376		      ae->ae_adapter.aa_bios[0],
2377		      ae->ae_adapter.aa_memorysize);
2378    } else {
2379	device_printf(sc->amr_dev, "<%s> Firmware %.4s, BIOS %.4s, %dMB RAM\n",
2380		      prod, ae->ae_adapter.aa_firmware, ae->ae_adapter.aa_bios,
2381		      ae->ae_adapter.aa_memorysize);
2382    }
2383    free(ae, M_AMR);
2384}
2385
2386int
2387amr_dump_blocks(struct amr_softc *sc, int unit, u_int32_t lba, void *data, int blks)
2388{
2389    struct amr_command	*ac;
2390    int			error = EIO;
2391
2392    debug_called(1);
2393
2394    sc->amr_state |= AMR_STATE_INTEN;
2395
2396    /* get ourselves a command buffer */
2397    if ((ac = amr_alloccmd(sc)) == NULL)
2398	goto out;
2399    /* set command flags */
2400    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
2401
2402    /* point the command at our data */
2403    ac->ac_data = data;
2404    ac->ac_length = blks * AMR_BLKSIZE;
2405
2406    /* build the command proper */
2407    ac->ac_mailbox.mb_command 	= AMR_CMD_LWRITE;
2408    ac->ac_mailbox.mb_blkcount	= blks;
2409    ac->ac_mailbox.mb_lba	= lba;
2410    ac->ac_mailbox.mb_drive	= unit;
2411
2412    /* can't assume that interrupts are going to work here, so play it safe */
2413    if (sc->amr_poll_command(ac))
2414	goto out;
2415    error = ac->ac_status;
2416
2417 out:
2418    if (ac != NULL)
2419	amr_releasecmd(ac);
2420
2421    sc->amr_state &= ~AMR_STATE_INTEN;
2422    return (error);
2423}
2424
2425
2426
2427#ifdef AMR_DEBUG
2428/********************************************************************************
2429 * Print the command (ac) in human-readable format
2430 */
2431#if 0
2432static void
2433amr_printcommand(struct amr_command *ac)
2434{
2435    struct amr_softc	*sc = ac->ac_sc;
2436    struct amr_sgentry	*sg;
2437    int			i;
2438
2439    device_printf(sc->amr_dev, "cmd %x  ident %d  drive %d\n",
2440		  ac->ac_mailbox.mb_command, ac->ac_mailbox.mb_ident, ac->ac_mailbox.mb_drive);
2441    device_printf(sc->amr_dev, "blkcount %d  lba %d\n",
2442		  ac->ac_mailbox.mb_blkcount, ac->ac_mailbox.mb_lba);
2443    device_printf(sc->amr_dev, "virtaddr %p  length %lu\n", ac->ac_data, (unsigned long)ac->ac_length);
2444    device_printf(sc->amr_dev, "sg physaddr %08x  nsg %d\n",
2445		  ac->ac_mailbox.mb_physaddr, ac->ac_mailbox.mb_nsgelem);
2446    device_printf(sc->amr_dev, "ccb %p  bio %p\n", ac->ac_ccb_data, ac->ac_bio);
2447
2448    /* get base address of s/g table */
2449    sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
2450    for (i = 0; i < ac->ac_mailbox.mb_nsgelem; i++, sg++)
2451	device_printf(sc->amr_dev, "  %x/%d\n", sg->sg_addr, sg->sg_count);
2452}
2453#endif
2454#endif
2455