amr.c revision 125594
1/*-
2 * Copyright (c) 1999,2000 Michael Smith
3 * Copyright (c) 2000 BSDi
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27/*
28 * Copyright (c) 2002 Eric Moore
29 * Copyright (c) 2002 LSI Logic Corporation
30 * All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 *    notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 *    notice, this list of conditions and the following disclaimer in the
39 *    documentation and/or other materials provided with the distribution.
40 * 3. The party using or redistributing the source code and binary forms
41 *    agrees to the disclaimer below and the terms and conditions set forth
42 *    herein.
43 *
44 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
45 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
47 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
48 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
50 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
53 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * SUCH DAMAGE.
55 */
56
57#include <sys/cdefs.h>
58__FBSDID("$FreeBSD: head/sys/dev/amr/amr.c 125594 2004-02-08 16:07:22Z scottl $");
59
60/*
61 * Driver for the AMI MegaRaid family of controllers.
62 */
63
64#include <sys/param.h>
65#include <sys/systm.h>
66#include <sys/malloc.h>
67#include <sys/kernel.h>
68
69#include <dev/amr/amr_compat.h>
70#include <sys/bus.h>
71#include <sys/conf.h>
72#include <sys/stat.h>
73
74#include <machine/bus_memio.h>
75#include <machine/bus_pio.h>
76#include <machine/bus.h>
77#include <machine/resource.h>
78#include <sys/rman.h>
79
80#include <dev/pci/pcireg.h>
81#include <dev/pci/pcivar.h>
82
83#include <dev/amr/amrio.h>
84#include <dev/amr/amrreg.h>
85#include <dev/amr/amrvar.h>
86#define AMR_DEFINE_TABLES
87#include <dev/amr/amr_tables.h>
88
89static d_open_t         amr_open;
90static d_close_t        amr_close;
91static d_ioctl_t        amr_ioctl;
92
93static struct cdevsw amr_cdevsw = {
94	.d_open =	amr_open,
95	.d_close =	amr_close,
96	.d_ioctl =	amr_ioctl,
97	.d_name =	"amr",
98};
99
100/*
101 * Initialisation, bus interface.
102 */
103static void	amr_startup(void *arg);
104
105/*
106 * Command wrappers
107 */
108static int	amr_query_controller(struct amr_softc *sc);
109static void	*amr_enquiry(struct amr_softc *sc, size_t bufsize,
110			     u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual);
111static void	amr_completeio(struct amr_command *ac);
112static int	amr_support_ext_cdb(struct amr_softc *sc);
113
114/*
115 * Command buffer allocation.
116 */
117static void	amr_alloccmd_cluster(struct amr_softc *sc);
118static void	amr_freecmd_cluster(struct amr_command_cluster *acc);
119
120/*
121 * Command processing.
122 */
123static int	amr_bio_command(struct amr_softc *sc, struct amr_command **acp);
124static int	amr_wait_command(struct amr_command *ac);
125static int	amr_getslot(struct amr_command *ac);
126static void	amr_mapcmd(struct amr_command *ac);
127static void	amr_unmapcmd(struct amr_command *ac);
128static int	amr_start(struct amr_command *ac);
129static void	amr_complete(void *context, int pending);
130
131/*
132 * Status monitoring
133 */
134static void	amr_periodic(void *data);
135
136/*
137 * Interface-specific shims
138 */
139static int	amr_quartz_submit_command(struct amr_softc *sc);
140static int	amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
141static int	amr_quartz_poll_command(struct amr_command *ac);
142
143static int	amr_std_submit_command(struct amr_softc *sc);
144static int	amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
145static int	amr_std_poll_command(struct amr_command *ac);
146static void	amr_std_attach_mailbox(struct amr_softc *sc);
147
148#ifdef AMR_BOARD_INIT
149static int	amr_quartz_init(struct amr_softc *sc);
150static int	amr_std_init(struct amr_softc *sc);
151#endif
152
153/*
154 * Debugging
155 */
156static void	amr_describe_controller(struct amr_softc *sc);
157#ifdef AMR_DEBUG
158#if 0
159static void	amr_printcommand(struct amr_command *ac);
160#endif
161#endif
162
163/********************************************************************************
164 ********************************************************************************
165                                                                      Inline Glue
166 ********************************************************************************
167 ********************************************************************************/
168
169/********************************************************************************
170 ********************************************************************************
171                                                                Public Interfaces
172 ********************************************************************************
173 ********************************************************************************/
174
175/********************************************************************************
176 * Initialise the controller and softc.
177 */
178int
179amr_attach(struct amr_softc *sc)
180{
181
182    debug_called(1);
183
184    /*
185     * Initialise per-controller queues.
186     */
187    TAILQ_INIT(&sc->amr_completed);
188    TAILQ_INIT(&sc->amr_freecmds);
189    TAILQ_INIT(&sc->amr_cmd_clusters);
190    TAILQ_INIT(&sc->amr_ready);
191    bioq_init(&sc->amr_bioq);
192
193#if __FreeBSD_version >= 500005
194    /*
195     * Initialise command-completion task.
196     */
197    TASK_INIT(&sc->amr_task_complete, 0, amr_complete, sc);
198#endif
199
200    debug(2, "queue init done");
201
202    /*
203     * Configure for this controller type.
204     */
205    if (AMR_IS_QUARTZ(sc)) {
206	sc->amr_submit_command = amr_quartz_submit_command;
207	sc->amr_get_work       = amr_quartz_get_work;
208	sc->amr_poll_command   = amr_quartz_poll_command;
209    } else {
210	sc->amr_submit_command = amr_std_submit_command;
211	sc->amr_get_work       = amr_std_get_work;
212	sc->amr_poll_command   = amr_std_poll_command;
213	amr_std_attach_mailbox(sc);;
214    }
215
216#ifdef AMR_BOARD_INIT
217    if ((AMR_IS_QUARTZ(sc) ? amr_quartz_init(sc) : amr_std_init(sc))))
218	return(ENXIO);
219#endif
220
221    /*
222     * Quiz controller for features and limits.
223     */
224    if (amr_query_controller(sc))
225	return(ENXIO);
226
227    debug(2, "controller query complete");
228
229    /*
230     * Attach our 'real' SCSI channels to CAM.
231     */
232    if (amr_cam_attach(sc))
233	return(ENXIO);
234    debug(2, "CAM attach done");
235
236    /*
237     * Create the control device.
238     */
239    sc->amr_dev_t = make_dev(&amr_cdevsw, device_get_unit(sc->amr_dev), UID_ROOT, GID_OPERATOR,
240			     S_IRUSR | S_IWUSR, "amr%d", device_get_unit(sc->amr_dev));
241    sc->amr_dev_t->si_drv1 = sc;
242
243    /*
244     * Schedule ourselves to bring the controller up once interrupts are
245     * available.
246     */
247    bzero(&sc->amr_ich, sizeof(struct intr_config_hook));
248    sc->amr_ich.ich_func = amr_startup;
249    sc->amr_ich.ich_arg = sc;
250    if (config_intrhook_establish(&sc->amr_ich) != 0) {
251	device_printf(sc->amr_dev, "can't establish configuration hook\n");
252	return(ENOMEM);
253    }
254
255    /*
256     * Print a little information about the controller.
257     */
258    amr_describe_controller(sc);
259
260    debug(2, "attach complete");
261    return(0);
262}
263
264/********************************************************************************
265 * Locate disk resources and attach children to them.
266 */
267static void
268amr_startup(void *arg)
269{
270    struct amr_softc	*sc = (struct amr_softc *)arg;
271    struct amr_logdrive	*dr;
272    int			i, error;
273
274    debug_called(1);
275
276    /* pull ourselves off the intrhook chain */
277    config_intrhook_disestablish(&sc->amr_ich);
278
279    /* get up-to-date drive information */
280    if (amr_query_controller(sc)) {
281	device_printf(sc->amr_dev, "can't scan controller for drives\n");
282	return;
283    }
284
285    /* iterate over available drives */
286    for (i = 0, dr = &sc->amr_drive[0]; (i < AMR_MAXLD) && (dr->al_size != 0xffffffff); i++, dr++) {
287	/* are we already attached to this drive? */
288	if (dr->al_disk == 0) {
289	    /* generate geometry information */
290	    if (dr->al_size > 0x200000) {	/* extended translation? */
291		dr->al_heads = 255;
292		dr->al_sectors = 63;
293	    } else {
294		dr->al_heads = 64;
295		dr->al_sectors = 32;
296	    }
297	    dr->al_cylinders = dr->al_size / (dr->al_heads * dr->al_sectors);
298
299	    dr->al_disk = device_add_child(sc->amr_dev, NULL, -1);
300	    if (dr->al_disk == 0)
301		device_printf(sc->amr_dev, "device_add_child failed\n");
302	    device_set_ivars(dr->al_disk, dr);
303	}
304    }
305
306    if ((error = bus_generic_attach(sc->amr_dev)) != 0)
307	device_printf(sc->amr_dev, "bus_generic_attach returned %d\n", error);
308
309    /* mark controller back up */
310    sc->amr_state &= ~AMR_STATE_SHUTDOWN;
311
312    /* interrupts will be enabled before we do anything more */
313    sc->amr_state |= AMR_STATE_INTEN;
314
315    /*
316     * Start the timeout routine.
317     */
318/*    sc->amr_timeout = timeout(amr_periodic, sc, hz);*/
319
320    return;
321}
322
323/*******************************************************************************
324 * Free resources associated with a controller instance
325 */
326void
327amr_free(struct amr_softc *sc)
328{
329    struct amr_command_cluster	*acc;
330
331    /* detach from CAM */
332    amr_cam_detach(sc);
333
334    /* cancel status timeout */
335    untimeout(amr_periodic, sc, sc->amr_timeout);
336
337    /* throw away any command buffers */
338    while ((acc = TAILQ_FIRST(&sc->amr_cmd_clusters)) != NULL) {
339	TAILQ_REMOVE(&sc->amr_cmd_clusters, acc, acc_link);
340	amr_freecmd_cluster(acc);
341    }
342
343    /* destroy control device */
344    if( sc->amr_dev_t != (dev_t)NULL)
345	    destroy_dev(sc->amr_dev_t);
346}
347
348/*******************************************************************************
349 * Receive a bio structure from a child device and queue it on a particular
350 * disk resource, then poke the disk resource to start as much work as it can.
351 */
352int
353amr_submit_bio(struct amr_softc *sc, struct bio *bio)
354{
355    debug_called(2);
356
357    amr_enqueue_bio(sc, bio);
358    amr_startio(sc);
359    return(0);
360}
361
362/********************************************************************************
363 * Accept an open operation on the control device.
364 */
365static int
366amr_open(dev_t dev, int flags, int fmt, d_thread_t *td)
367{
368    int			unit = minor(dev);
369    struct amr_softc	*sc = devclass_get_softc(devclass_find("amr"), unit);
370
371    debug_called(1);
372
373    sc->amr_state |= AMR_STATE_OPEN;
374    return(0);
375}
376
377/********************************************************************************
378 * Accept the last close on the control device.
379 */
380static int
381amr_close(dev_t dev, int flags, int fmt, d_thread_t *td)
382{
383    int			unit = minor(dev);
384    struct amr_softc	*sc = devclass_get_softc(devclass_find("amr"), unit);
385
386    debug_called(1);
387
388    sc->amr_state &= ~AMR_STATE_OPEN;
389    return (0);
390}
391
392/********************************************************************************
393 * Handle controller-specific control operations.
394 */
395static int
396amr_ioctl(dev_t dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *td)
397{
398    struct amr_softc		*sc = (struct amr_softc *)dev->si_drv1;
399    int				*arg = (int *)addr;
400    struct amr_user_ioctl	*au = (struct amr_user_ioctl *)addr;
401    struct amr_command		*ac;
402    struct amr_mailbox_ioctl	*mbi;
403    struct amr_passthrough	*ap;
404    void			*dp;
405    int				error;
406
407    debug_called(1);
408
409    error = 0;
410    dp = NULL;
411    ap = NULL;
412    ac = NULL;
413    switch(cmd) {
414
415    case AMR_IO_VERSION:
416	debug(1, "AMR_IO_VERSION");
417	*arg = AMR_IO_VERSION_NUMBER;
418	break;
419
420    case AMR_IO_COMMAND:
421	debug(1, "AMR_IO_COMMAND  0x%x", au->au_cmd[0]);
422	/* handle inbound data buffer */
423	if (au->au_length != 0) {
424	    if ((dp = malloc(au->au_length, M_DEVBUF, M_WAITOK)) == NULL) {
425		error = ENOMEM;
426		break;
427	    }
428	    if ((error = copyin(au->au_buffer, dp, au->au_length)) != 0)
429		break;
430	    debug(2, "copyin %ld bytes from %p -> %p", au->au_length, au->au_buffer, dp);
431	}
432
433	if ((ac = amr_alloccmd(sc)) == NULL) {
434	    error = ENOMEM;
435	    break;
436	}
437
438	/* handle SCSI passthrough command */
439	if (au->au_cmd[0] == AMR_CMD_PASS) {
440	    if ((ap = malloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO)) == NULL) {
441		error = ENOMEM;
442		break;
443	    }
444
445	    /* copy cdb */
446	    ap->ap_cdb_length = au->au_cmd[2];
447	    bcopy(&au->au_cmd[3], &ap->ap_cdb[0], ap->ap_cdb_length);
448
449	    /* build passthrough */
450	    ap->ap_timeout		= au->au_cmd[ap->ap_cdb_length + 3] & 0x07;
451	    ap->ap_ars			= (au->au_cmd[ap->ap_cdb_length + 3] & 0x08) ? 1 : 0;
452	    ap->ap_islogical		= (au->au_cmd[ap->ap_cdb_length + 3] & 0x80) ? 1 : 0;
453	    ap->ap_logical_drive_no	= au->au_cmd[ap->ap_cdb_length + 4];
454	    ap->ap_channel		= au->au_cmd[ap->ap_cdb_length + 5];
455	    ap->ap_scsi_id 		= au->au_cmd[ap->ap_cdb_length + 6];
456	    ap->ap_request_sense_length	= 14;
457	    ap->ap_data_transfer_length = au->au_length;
458	    /* XXX what about the request-sense area? does the caller want it? */
459
460	    /* build command */
461	    ac->ac_data = ap;
462	    ac->ac_length = sizeof(*ap);
463	    ac->ac_flags |= AMR_CMD_DATAOUT;
464	    ac->ac_ccb_data = dp;
465	    ac->ac_ccb_length = au->au_length;
466	    if (au->au_direction & AMR_IO_READ)
467		ac->ac_flags |= AMR_CMD_CCB_DATAIN;
468	    if (au->au_direction & AMR_IO_WRITE)
469		ac->ac_flags |= AMR_CMD_CCB_DATAOUT;
470
471	    ac->ac_mailbox.mb_command = AMR_CMD_PASS;
472
473	} else {
474	    /* direct command to controller */
475	    mbi = (struct amr_mailbox_ioctl *)&ac->ac_mailbox;
476
477	    /* copy pertinent mailbox items */
478	    mbi->mb_command = au->au_cmd[0];
479	    mbi->mb_channel = au->au_cmd[1];
480	    mbi->mb_param = au->au_cmd[2];
481	    mbi->mb_pad[0] = au->au_cmd[3];
482	    mbi->mb_drive = au->au_cmd[4];
483
484	    /* build the command */
485	    ac->ac_data = dp;
486	    ac->ac_length = au->au_length;
487	    if (au->au_direction & AMR_IO_READ)
488		ac->ac_flags |= AMR_CMD_DATAIN;
489	    if (au->au_direction & AMR_IO_WRITE)
490		ac->ac_flags |= AMR_CMD_DATAOUT;
491	}
492
493	/* run the command */
494	if ((error = amr_wait_command(ac)) != 0)
495	    break;
496
497	/* copy out data and set status */
498	if (au->au_length != 0)
499	    error = copyout(dp, au->au_buffer, au->au_length);
500	debug(2, "copyout %ld bytes from %p -> %p", au->au_length, dp, au->au_buffer);
501	if (dp != NULL)
502	    debug(2, "%16d", (int)dp);
503	au->au_status = ac->ac_status;
504	break;
505
506    default:
507	debug(1, "unknown ioctl 0x%lx", cmd);
508	error = ENOIOCTL;
509	break;
510    }
511
512    if (dp != NULL)
513	free(dp, M_DEVBUF);
514    if (ap != NULL)
515	free(ap, M_DEVBUF);
516    if (ac != NULL)
517	amr_releasecmd(ac);
518    return(error);
519}
520
521/********************************************************************************
522 ********************************************************************************
523                                                                Status Monitoring
524 ********************************************************************************
525 ********************************************************************************/
526
527/********************************************************************************
528 * Perform a periodic check of the controller status
529 */
530static void
531amr_periodic(void *data)
532{
533    struct amr_softc	*sc = (struct amr_softc *)data;
534
535    debug_called(2);
536
537    /* XXX perform periodic status checks here */
538
539    /* compensate for missed interrupts */
540    amr_done(sc);
541
542    /* reschedule */
543    sc->amr_timeout = timeout(amr_periodic, sc, hz);
544}
545
546/********************************************************************************
547 ********************************************************************************
548                                                                 Command Wrappers
549 ********************************************************************************
550 ********************************************************************************/
551
552/********************************************************************************
553 * Interrogate the controller for the operational parameters we require.
554 */
555static int
556amr_query_controller(struct amr_softc *sc)
557{
558    struct amr_enquiry3	*aex;
559    struct amr_prodinfo	*ap;
560    struct amr_enquiry	*ae;
561    int			ldrv;
562
563    /*
564     * If we haven't found the real limit yet, let us have a couple of commands in
565     * order to be able to probe.
566     */
567    if (sc->amr_maxio == 0)
568	sc->amr_maxio = 2;
569
570    /*
571     * Greater than 10 byte cdb support
572     */
573    sc->support_ext_cdb = amr_support_ext_cdb(sc);
574
575    if(sc->support_ext_cdb) {
576	debug(2,"supports extended CDBs.");
577    }
578
579    /*
580     * Try to issue an ENQUIRY3 command
581     */
582    if ((aex = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_ENQ3,
583			   AMR_CONFIG_ENQ3_SOLICITED_FULL)) != NULL) {
584
585	/*
586	 * Fetch current state of logical drives.
587	 */
588	for (ldrv = 0; ldrv < aex->ae_numldrives; ldrv++) {
589	    sc->amr_drive[ldrv].al_size       = aex->ae_drivesize[ldrv];
590	    sc->amr_drive[ldrv].al_state      = aex->ae_drivestate[ldrv];
591	    sc->amr_drive[ldrv].al_properties = aex->ae_driveprop[ldrv];
592	    debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
593		  sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
594	}
595	free(aex, M_DEVBUF);
596
597	/*
598	 * Get product info for channel count.
599	 */
600	if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0)) == NULL) {
601	    device_printf(sc->amr_dev, "can't obtain product data from controller\n");
602	    return(1);
603	}
604	sc->amr_maxdrives = 40;
605	sc->amr_maxchan = ap->ap_nschan;
606	sc->amr_maxio = ap->ap_maxio;
607	sc->amr_type |= AMR_TYPE_40LD;
608	free(ap, M_DEVBUF);
609
610    } else {
611
612	/* failed, try the 8LD ENQUIRY commands */
613	if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0)) == NULL) {
614	    if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0)) == NULL) {
615		device_printf(sc->amr_dev, "can't obtain configuration data from controller\n");
616		return(1);
617	    }
618	    ae->ae_signature = 0;
619	}
620
621	/*
622	 * Fetch current state of logical drives.
623	 */
624	for (ldrv = 0; ldrv < ae->ae_ldrv.al_numdrives; ldrv++) {
625	    sc->amr_drive[ldrv].al_size       = ae->ae_ldrv.al_size[ldrv];
626	    sc->amr_drive[ldrv].al_state      = ae->ae_ldrv.al_state[ldrv];
627	    sc->amr_drive[ldrv].al_properties = ae->ae_ldrv.al_properties[ldrv];
628	    debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
629		  sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
630	}
631
632	sc->amr_maxdrives = 8;
633	sc->amr_maxchan = ae->ae_adapter.aa_channels;
634	sc->amr_maxio = ae->ae_adapter.aa_maxio;
635	free(ae, M_DEVBUF);
636    }
637
638    /*
639     * Mark remaining drives as unused.
640     */
641    for (; ldrv < AMR_MAXLD; ldrv++)
642	sc->amr_drive[ldrv].al_size = 0xffffffff;
643
644    /*
645     * Cap the maximum number of outstanding I/Os.  AMI's Linux driver doesn't trust
646     * the controller's reported value, and lockups have been seen when we do.
647     */
648    sc->amr_maxio = imin(sc->amr_maxio, AMR_LIMITCMD);
649
650    return(0);
651}
652
653/********************************************************************************
654 * Run a generic enquiry-style command.
655 */
656static void *
657amr_enquiry(struct amr_softc *sc, size_t bufsize, u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual)
658{
659    struct amr_command	*ac;
660    void		*result;
661    u_int8_t		*mbox;
662    int			error;
663
664    debug_called(1);
665
666    error = 1;
667    result = NULL;
668
669    /* get ourselves a command buffer */
670    if ((ac = amr_alloccmd(sc)) == NULL)
671	goto out;
672    /* allocate the response structure */
673    if ((result = malloc(bufsize, M_DEVBUF, M_NOWAIT)) == NULL)
674	goto out;
675    /* set command flags */
676    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
677
678    /* point the command at our data */
679    ac->ac_data = result;
680    ac->ac_length = bufsize;
681
682    /* build the command proper */
683    mbox = (u_int8_t *)&ac->ac_mailbox;		/* XXX want a real structure for this? */
684    mbox[0] = cmd;
685    mbox[2] = cmdsub;
686    mbox[3] = cmdqual;
687
688    /* can't assume that interrupts are going to work here, so play it safe */
689    if (sc->amr_poll_command(ac))
690	goto out;
691    error = ac->ac_status;
692
693 out:
694    if (ac != NULL)
695	amr_releasecmd(ac);
696    if ((error != 0) && (result != NULL)) {
697	free(result, M_DEVBUF);
698	result = NULL;
699    }
700    return(result);
701}
702
703/********************************************************************************
704 * Flush the controller's internal cache, return status.
705 */
706int
707amr_flush(struct amr_softc *sc)
708{
709    struct amr_command	*ac;
710    int			error;
711
712    /* get ourselves a command buffer */
713    error = 1;
714    if ((ac = amr_alloccmd(sc)) == NULL)
715	goto out;
716    /* set command flags */
717    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
718
719    /* build the command proper */
720    ac->ac_mailbox.mb_command = AMR_CMD_FLUSH;
721
722    /* we have to poll, as the system may be going down or otherwise damaged */
723    if (sc->amr_poll_command(ac))
724	goto out;
725    error = ac->ac_status;
726
727 out:
728    if (ac != NULL)
729	amr_releasecmd(ac);
730    return(error);
731}
732
733/********************************************************************************
734 * Detect extented cdb >> greater than 10 byte cdb support
735 * returns '1' means this support exist
736 * returns '0' means this support doesn't exist
737 */
738static int
739amr_support_ext_cdb(struct amr_softc *sc)
740{
741    struct amr_command	*ac;
742    u_int8_t		*mbox;
743    int			error;
744
745    /* get ourselves a command buffer */
746    error = 0;
747    if ((ac = amr_alloccmd(sc)) == NULL)
748	goto out;
749    /* set command flags */
750    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
751
752    /* build the command proper */
753    mbox = (u_int8_t *)&ac->ac_mailbox;		/* XXX want a real structure for this? */
754    mbox[0] = 0xA4;
755    mbox[2] = 0x16;
756
757
758    /* we have to poll, as the system may be going down or otherwise damaged */
759    if (sc->amr_poll_command(ac))
760	goto out;
761    if( ac->ac_status == AMR_STATUS_SUCCESS ) {
762	    error = 1;
763    }
764
765out:
766    if (ac != NULL)
767	amr_releasecmd(ac);
768    return(error);
769}
770
771/********************************************************************************
772 * Try to find I/O work for the controller from one or more of the work queues.
773 *
774 * We make the assumption that if the controller is not ready to take a command
775 * at some given time, it will generate an interrupt at some later time when
776 * it is.
777 */
778void
779amr_startio(struct amr_softc *sc)
780{
781    struct amr_command	*ac;
782
783    /* spin until something prevents us from doing any work */
784    for (;;) {
785
786	/* try to get a ready command */
787	ac = amr_dequeue_ready(sc);
788
789	/* if that failed, build a command from a bio */
790	if (ac == NULL)
791	    (void)amr_bio_command(sc, &ac);
792
793	/* if that failed, build a command from a ccb */
794	if (ac == NULL)
795	    (void)amr_cam_command(sc, &ac);
796
797	/* if we don't have anything to do, give up */
798	if (ac == NULL)
799	    break;
800
801	/* try to give the command to the controller; if this fails save it for later and give up */
802	if (amr_start(ac)) {
803	    debug(2, "controller busy, command deferred");
804	    amr_requeue_ready(ac);	/* XXX schedule retry very soon? */
805	    break;
806	}
807    }
808}
809
810/********************************************************************************
811 * Handle completion of an I/O command.
812 */
813static void
814amr_completeio(struct amr_command *ac)
815{
816    struct amr_softc	*sc = ac->ac_sc;
817
818    if (ac->ac_status != AMR_STATUS_SUCCESS) {	/* could be more verbose here? */
819	ac->ac_bio->bio_error = EIO;
820	ac->ac_bio->bio_flags |= BIO_ERROR;
821
822	device_printf(sc->amr_dev, "I/O error - 0x%x\n", ac->ac_status);
823/*	amr_printcommand(ac);*/
824    }
825    amrd_intr(ac->ac_bio);
826    amr_releasecmd(ac);
827}
828
829/********************************************************************************
830 ********************************************************************************
831                                                               Command Processing
832 ********************************************************************************
833 ********************************************************************************/
834
835/********************************************************************************
836 * Convert a bio off the top of the bio queue into a command.
837 */
838static int
839amr_bio_command(struct amr_softc *sc, struct amr_command **acp)
840{
841    struct amr_command	*ac;
842    struct amrd_softc	*amrd;
843    struct bio		*bio;
844    int			error;
845    int			blkcount;
846    int			driveno;
847    int			cmd;
848
849    ac = NULL;
850    error = 0;
851
852    /* get a bio to work on */
853    if ((bio = amr_dequeue_bio(sc)) == NULL)
854	goto out;
855
856    /* get a command */
857    if ((ac = amr_alloccmd(sc)) == NULL) {
858	error = ENOMEM;
859	goto out;
860    }
861
862    /* connect the bio to the command */
863    ac->ac_complete = amr_completeio;
864    ac->ac_bio = bio;
865    ac->ac_data = bio->bio_data;
866    ac->ac_length = bio->bio_bcount;
867    if (BIO_IS_READ(bio)) {
868	ac->ac_flags |= AMR_CMD_DATAIN;
869	cmd = AMR_CMD_LREAD;
870    } else {
871	ac->ac_flags |= AMR_CMD_DATAOUT;
872	cmd = AMR_CMD_LWRITE;
873    }
874    amrd = (struct amrd_softc *)bio->bio_disk->d_drv1;
875    driveno = amrd->amrd_drive - sc->amr_drive;
876    blkcount = (bio->bio_bcount + AMR_BLKSIZE - 1) / AMR_BLKSIZE;
877
878    ac->ac_mailbox.mb_command = cmd;
879    ac->ac_mailbox.mb_blkcount = blkcount;
880    ac->ac_mailbox.mb_lba = bio->bio_pblkno;
881    ac->ac_mailbox.mb_drive = driveno;
882    /* we fill in the s/g related data when the command is mapped */
883
884    if ((bio->bio_pblkno + blkcount) > sc->amr_drive[driveno].al_size)
885	device_printf(sc->amr_dev, "I/O beyond end of unit (%lld,%d > %lu)\n",
886		      (long long)bio->bio_pblkno, blkcount,
887		      (u_long)sc->amr_drive[driveno].al_size);
888
889out:
890    if (error != 0) {
891	if (ac != NULL)
892	    amr_releasecmd(ac);
893	if (bio != NULL)			/* this breaks ordering... */
894	    amr_enqueue_bio(sc, bio);
895    }
896    *acp = ac;
897    return(error);
898}
899
900/********************************************************************************
901 * Take a command, submit it to the controller and sleep until it completes
902 * or fails.  Interrupts must be enabled, returns nonzero on error.
903 */
904static int
905amr_wait_command(struct amr_command *ac)
906{
907    int			error, count;
908
909    debug_called(1);
910
911    ac->ac_complete = NULL;
912    ac->ac_flags |= AMR_CMD_SLEEP;
913    if ((error = amr_start(ac)) != 0)
914	return(error);
915
916    count = 0;
917    /* XXX better timeout? */
918    while ((ac->ac_flags & AMR_CMD_BUSY) && (count < 30)) {
919	tsleep(ac, PRIBIO | PCATCH, "amrwcmd", hz);
920    }
921    return(0);
922}
923
924/********************************************************************************
925 * Take a command, submit it to the controller and busy-wait for it to return.
926 * Returns nonzero on error.  Can be safely called with interrupts enabled.
927 */
928static int
929amr_std_poll_command(struct amr_command *ac)
930{
931    struct amr_softc	*sc = ac->ac_sc;
932    int			error, count;
933
934    debug_called(2);
935
936    ac->ac_complete = NULL;
937    if ((error = amr_start(ac)) != 0)
938	return(error);
939
940    count = 0;
941    do {
942	/*
943	 * Poll for completion, although the interrupt handler may beat us to it.
944	 * Note that the timeout here is somewhat arbitrary.
945	 */
946	amr_done(sc);
947	DELAY(1000);
948    } while ((ac->ac_flags & AMR_CMD_BUSY) && (count++ < 1000));
949    if (!(ac->ac_flags & AMR_CMD_BUSY)) {
950	error = 0;
951    } else {
952	/* XXX the slot is now marked permanently busy */
953	error = EIO;
954	device_printf(sc->amr_dev, "polled command timeout\n");
955    }
956    return(error);
957}
958
959/********************************************************************************
960 * Take a command, submit it to the controller and busy-wait for it to return.
961 * Returns nonzero on error.  Can be safely called with interrupts enabled.
962 */
963static int
964amr_quartz_poll_command(struct amr_command *ac)
965{
966    struct amr_softc	*sc = ac->ac_sc;
967    int			s;
968    int			error,count;
969
970    debug_called(2);
971
972    /* now we have a slot, we can map the command (unmapped in amr_complete) */
973    amr_mapcmd(ac);
974
975    s = splbio();
976
977    if (sc->amr_state & AMR_STATE_INTEN) {
978	count=0;
979	while (sc->amr_busyslots) {
980	    tsleep(sc, PRIBIO | PCATCH, "amrpoll", hz);
981	    if(count++>10) {
982		break;
983	    }
984	}
985
986	if(sc->amr_busyslots) {
987	    device_printf(sc->amr_dev, "adapter is busy\n");
988	    splx(s);
989	    amr_unmapcmd(ac);
990    	    ac->ac_status=0;
991	    return(1);
992	}
993    }
994
995    bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, AMR_MBOX_CMDSIZE);
996
997    /* clear the poll/ack fields in the mailbox */
998    sc->amr_mailbox->mb_ident = 0xFE;
999    sc->amr_mailbox->mb_nstatus = 0xFF;
1000    sc->amr_mailbox->mb_status = 0xFF;
1001    sc->amr_mailbox->mb_poll = 0;
1002    sc->amr_mailbox->mb_ack = 0;
1003    sc->amr_mailbox->mb_busy = 1;
1004
1005    AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
1006
1007    while(sc->amr_mailbox->mb_nstatus == 0xFF);
1008    while(sc->amr_mailbox->mb_status == 0xFF);
1009    ac->ac_status=sc->amr_mailbox->mb_status;
1010    error = (ac->ac_status !=AMR_STATUS_SUCCESS) ? 1:0;
1011    while(sc->amr_mailbox->mb_poll != 0x77);
1012    sc->amr_mailbox->mb_poll = 0;
1013    sc->amr_mailbox->mb_ack = 0x77;
1014
1015    /* acknowledge that we have the commands */
1016    AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_ACK);
1017    while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK);
1018
1019    splx(s);
1020
1021    /* unmap the command's data buffer */
1022    amr_unmapcmd(ac);
1023
1024    return(error);
1025}
1026
1027/********************************************************************************
1028 * Get a free command slot for a command if it doesn't already have one.
1029 *
1030 * May be safely called multiple times for a given command.
1031 */
1032static int
1033amr_getslot(struct amr_command *ac)
1034{
1035    struct amr_softc	*sc = ac->ac_sc;
1036    int			s, slot, limit, error;
1037
1038    debug_called(3);
1039
1040    /* if the command already has a slot, don't try to give it another one */
1041    if (ac->ac_slot != 0)
1042	return(0);
1043
1044    /* enforce slot usage limit */
1045    limit = (ac->ac_flags & AMR_CMD_PRIORITY) ? sc->amr_maxio : sc->amr_maxio - 4;
1046    if (sc->amr_busyslots > limit)
1047	return(EBUSY);
1048
1049    /*
1050     * Allocate a slot.  XXX linear scan is slow
1051     */
1052    error = EBUSY;
1053    s = splbio();
1054    for (slot = 0; slot < sc->amr_maxio; slot++) {
1055	if (sc->amr_busycmd[slot] == NULL) {
1056	    sc->amr_busycmd[slot] = ac;
1057	    sc->amr_busyslots++;
1058	    ac->ac_slot = slot;
1059	    error = 0;
1060	    break;
1061	}
1062    }
1063    splx(s);
1064
1065    return(error);
1066}
1067
1068/********************************************************************************
1069 * Map/unmap (ac)'s data in the controller's addressable space as required.
1070 *
1071 * These functions may be safely called multiple times on a given command.
1072 */
1073static void
1074amr_setup_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
1075{
1076    struct amr_command	*ac = (struct amr_command *)arg;
1077    struct amr_softc	*sc = ac->ac_sc;
1078    struct amr_sgentry	*sg;
1079    int			i;
1080    u_int8_t		*sgc;
1081
1082    debug_called(3);
1083
1084    /* get base address of s/g table */
1085    sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
1086
1087    /* save data physical address */
1088    ac->ac_dataphys = segs[0].ds_addr;
1089
1090    /* for AMR_CMD_CONFIG the s/g count goes elsewhere */
1091    if (ac->ac_mailbox.mb_command == AMR_CMD_CONFIG) {
1092	sgc = &(((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_param);
1093    } else {
1094	sgc = &ac->ac_mailbox.mb_nsgelem;
1095    }
1096
1097    /* decide whether we need to populate the s/g table */
1098    if (nsegments < 2) {
1099	*sgc = 0;
1100	ac->ac_mailbox.mb_nsgelem = 0;
1101	ac->ac_mailbox.mb_physaddr = ac->ac_dataphys;
1102    } else {
1103        ac->ac_mailbox.mb_nsgelem = nsegments;
1104	*sgc = nsegments;
1105	ac->ac_mailbox.mb_physaddr = sc->amr_sgbusaddr + (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
1106	for (i = 0; i < nsegments; i++, sg++) {
1107	    sg->sg_addr = segs[i].ds_addr;
1108	    sg->sg_count = segs[i].ds_len;
1109	}
1110    }
1111}
1112
1113static void
1114amr_setup_ccbmap(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
1115{
1116    struct amr_command          *ac = (struct amr_command *)arg;
1117    struct amr_softc            *sc = ac->ac_sc;
1118    struct amr_sgentry          *sg;
1119    struct amr_passthrough      *ap = (struct amr_passthrough *)ac->ac_data;
1120    struct amr_ext_passthrough	*aep = (struct amr_ext_passthrough *)ac->ac_data;
1121    int                         i;
1122
1123    /* get base address of s/g table */
1124    sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
1125
1126    /* decide whether we need to populate the s/g table */
1127    if( ac->ac_mailbox.mb_command == AMR_CMD_EXTPASS ) {
1128	if (nsegments < 2) {
1129	    aep->ap_no_sg_elements = 0;
1130	    aep->ap_data_transfer_address =  segs[0].ds_addr;
1131	} else {
1132	    /* save s/g table information in passthrough */
1133	    aep->ap_no_sg_elements = nsegments;
1134	    aep->ap_data_transfer_address = sc->amr_sgbusaddr + (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
1135	    /* populate s/g table (overwrites previous call which mapped the passthrough) */
1136	    for (i = 0; i < nsegments; i++, sg++) {
1137		sg->sg_addr = segs[i].ds_addr;
1138		sg->sg_count = segs[i].ds_len;
1139		debug(3, " %d: 0x%x/%d", i, sg->sg_addr, sg->sg_count);
1140	    }
1141	}
1142	debug(3, "slot %d  %d segments at 0x%x, passthrough at 0x%x", ac->ac_slot,
1143	    aep->ap_no_sg_elements, aep->ap_data_transfer_address, ac->ac_dataphys);
1144    } else {
1145	if (nsegments < 2) {
1146	    ap->ap_no_sg_elements = 0;
1147	    ap->ap_data_transfer_address =  segs[0].ds_addr;
1148	} else {
1149	    /* save s/g table information in passthrough */
1150	    ap->ap_no_sg_elements = nsegments;
1151	    ap->ap_data_transfer_address = sc->amr_sgbusaddr + (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
1152	    /* populate s/g table (overwrites previous call which mapped the passthrough) */
1153	    for (i = 0; i < nsegments; i++, sg++) {
1154		sg->sg_addr = segs[i].ds_addr;
1155		sg->sg_count = segs[i].ds_len;
1156		debug(3, " %d: 0x%x/%d", i, sg->sg_addr, sg->sg_count);
1157	    }
1158	}
1159	debug(3, "slot %d  %d segments at 0x%x, passthrough at 0x%x", ac->ac_slot,
1160	    ap->ap_no_sg_elements, ap->ap_data_transfer_address, ac->ac_dataphys);
1161    }
1162}
1163
1164static void
1165amr_mapcmd(struct amr_command *ac)
1166{
1167    struct amr_softc	*sc = ac->ac_sc;
1168
1169    debug_called(3);
1170
1171    /* if the command involves data at all, and hasn't been mapped */
1172    if (!(ac->ac_flags & AMR_CMD_MAPPED)) {
1173
1174	if (ac->ac_data != NULL) {
1175	    /* map the data buffers into bus space and build the s/g list */
1176	    bus_dmamap_load(sc->amr_buffer_dmat, ac->ac_dmamap, ac->ac_data, ac->ac_length,
1177			    amr_setup_dmamap, ac, 0);
1178	    if (ac->ac_flags & AMR_CMD_DATAIN)
1179		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_PREREAD);
1180	    if (ac->ac_flags & AMR_CMD_DATAOUT)
1181		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_PREWRITE);
1182	}
1183
1184	if (ac->ac_ccb_data != NULL) {
1185	    bus_dmamap_load(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, ac->ac_ccb_data, ac->ac_ccb_length,
1186			    amr_setup_ccbmap, ac, 0);
1187	    if (ac->ac_flags & AMR_CMD_CCB_DATAIN)
1188		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_PREREAD);
1189	    if (ac->ac_flags & AMR_CMD_CCB_DATAOUT)
1190		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_PREWRITE);
1191	}
1192	ac->ac_flags |= AMR_CMD_MAPPED;
1193    }
1194}
1195
1196static void
1197amr_unmapcmd(struct amr_command *ac)
1198{
1199    struct amr_softc	*sc = ac->ac_sc;
1200
1201    debug_called(3);
1202
1203    /* if the command involved data at all and was mapped */
1204    if (ac->ac_flags & AMR_CMD_MAPPED) {
1205
1206	if (ac->ac_data != NULL) {
1207	    if (ac->ac_flags & AMR_CMD_DATAIN)
1208		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_POSTREAD);
1209	    if (ac->ac_flags & AMR_CMD_DATAOUT)
1210		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_POSTWRITE);
1211	    bus_dmamap_unload(sc->amr_buffer_dmat, ac->ac_dmamap);
1212	}
1213
1214	if (ac->ac_ccb_data != NULL) {
1215	    if (ac->ac_flags & AMR_CMD_CCB_DATAIN)
1216		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_POSTREAD);
1217	    if (ac->ac_flags & AMR_CMD_CCB_DATAOUT)
1218		bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_POSTWRITE);
1219	    bus_dmamap_unload(sc->amr_buffer_dmat, ac->ac_ccb_dmamap);
1220	}
1221	ac->ac_flags &= ~AMR_CMD_MAPPED;
1222    }
1223}
1224
1225/********************************************************************************
1226 * Take a command and give it to the controller, returns 0 if successful, or
1227 * EBUSY if the command should be retried later.
1228 */
1229static int
1230amr_start(struct amr_command *ac)
1231{
1232    struct amr_softc	*sc = ac->ac_sc;
1233    int			done, s, i;
1234
1235    debug_called(3);
1236
1237    /* mark command as busy so that polling consumer can tell */
1238    ac->ac_flags |= AMR_CMD_BUSY;
1239
1240    /* get a command slot (freed in amr_done) */
1241    if (amr_getslot(ac))
1242	return(EBUSY);
1243
1244    /* now we have a slot, we can map the command (unmapped in amr_complete) */
1245    amr_mapcmd(ac);
1246
1247    /* mark the new mailbox we are going to copy in as busy */
1248    ac->ac_mailbox.mb_busy = 1;
1249
1250    /* clear the poll/ack fields in the mailbox */
1251    sc->amr_mailbox->mb_poll = 0;
1252    sc->amr_mailbox->mb_ack = 0;
1253
1254    /*
1255     * Save the slot number so that we can locate this command when complete.
1256     * Note that ident = 0 seems to be special, so we don't use it.
1257     */
1258    ac->ac_mailbox.mb_ident = ac->ac_slot + 1;
1259
1260    /*
1261     * Spin waiting for the mailbox, give up after ~1 second.  We expect the
1262     * controller to be able to handle our I/O.
1263     *
1264     * XXX perhaps we should wait for less time, and count on the deferred command
1265     * handling to deal with retries?
1266     */
1267    debug(4, "wait for mailbox");
1268    for (i = 10000, done = 0; (i > 0) && !done; i--) {
1269	s = splbio();
1270
1271	/* is the mailbox free? */
1272	if (sc->amr_mailbox->mb_busy == 0) {
1273	    debug(4, "got mailbox");
1274	    sc->amr_mailbox64->mb64_segment = 0;
1275	    bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, AMR_MBOX_CMDSIZE);
1276	    done = 1;
1277
1278	    /* not free, spin waiting */
1279	} else {
1280	    debug(4, "busy flag %x\n", sc->amr_mailbox->mb_busy);
1281	    /* this is somewhat ugly */
1282	    DELAY(100);
1283	}
1284	splx(s);	/* drop spl to allow completion interrupts */
1285    }
1286
1287    /*
1288     * Now give the command to the controller
1289     */
1290    if (done) {
1291	if (sc->amr_submit_command(sc)) {
1292	    /* the controller wasn't ready to take the command, forget that we tried to post it */
1293	    sc->amr_mailbox->mb_busy = 0;
1294	    return(EBUSY);
1295	}
1296	debug(3, "posted command");
1297	return(0);
1298    }
1299
1300    /*
1301     * The controller wouldn't take the command.  Return the command as busy
1302     * so that it is retried later.
1303     */
1304    return(EBUSY);
1305}
1306
1307/********************************************************************************
1308 * Extract one or more completed commands from the controller (sc)
1309 *
1310 * Returns nonzero if any commands on the work queue were marked as completed.
1311 */
1312int
1313amr_done(struct amr_softc *sc)
1314{
1315    struct amr_command	*ac;
1316    struct amr_mailbox	mbox;
1317    int			i, idx, result;
1318
1319    debug_called(3);
1320
1321    /* See if there's anything for us to do */
1322    result = 0;
1323
1324    /* loop collecting completed commands */
1325    for (;;) {
1326	/* poll for a completed command's identifier and status */
1327	if (sc->amr_get_work(sc, &mbox)) {
1328	    result = 1;
1329
1330	    /* iterate over completed commands in this result */
1331	    for (i = 0; i < mbox.mb_nstatus; i++) {
1332		/* get pointer to busy command */
1333		idx = mbox.mb_completed[i] - 1;
1334		ac = sc->amr_busycmd[idx];
1335
1336		/* really a busy command? */
1337		if (ac != NULL) {
1338
1339		    /* pull the command from the busy index */
1340		    sc->amr_busycmd[idx] = NULL;
1341		    sc->amr_busyslots--;
1342
1343		    /* save status for later use */
1344		    ac->ac_status = mbox.mb_status;
1345		    amr_enqueue_completed(ac);
1346		    debug(3, "completed command with status %x", mbox.mb_status);
1347		} else {
1348		    device_printf(sc->amr_dev, "bad slot %d completed\n", idx);
1349		}
1350	    }
1351	} else {
1352	    break;	/* no work */
1353	}
1354    }
1355
1356    /* if we've completed any commands, try posting some more */
1357    if (result)
1358	amr_startio(sc);
1359
1360    /* handle completion and timeouts */
1361#if __FreeBSD_version >= 500005
1362    if (sc->amr_state & AMR_STATE_INTEN)
1363	taskqueue_enqueue(taskqueue_swi_giant, &sc->amr_task_complete);
1364    else
1365#endif
1366	amr_complete(sc, 0);
1367
1368    return(result);
1369}
1370
1371/********************************************************************************
1372 * Do completion processing on done commands on (sc)
1373 */
1374static void
1375amr_complete(void *context, int pending)
1376{
1377    struct amr_softc	*sc = (struct amr_softc *)context;
1378    struct amr_command	*ac;
1379
1380    debug_called(3);
1381
1382    /* pull completed commands off the queue */
1383    for (;;) {
1384	ac = amr_dequeue_completed(sc);
1385	if (ac == NULL)
1386	    break;
1387
1388	/* unmap the command's data buffer */
1389	amr_unmapcmd(ac);
1390
1391	/* unbusy the command */
1392	ac->ac_flags &= ~AMR_CMD_BUSY;
1393
1394	/*
1395	 * Is there a completion handler?
1396	 */
1397	if (ac->ac_complete != NULL) {
1398	    ac->ac_complete(ac);
1399
1400	    /*
1401	     * Is someone sleeping on this one?
1402	     */
1403	} else if (ac->ac_flags & AMR_CMD_SLEEP) {
1404	    wakeup(ac);
1405	}
1406
1407	if(!sc->amr_busyslots) {
1408	    wakeup(sc);
1409	}
1410    }
1411}
1412
1413/********************************************************************************
1414 ********************************************************************************
1415                                                        Command Buffer Management
1416 ********************************************************************************
1417 ********************************************************************************/
1418
1419/********************************************************************************
1420 * Get a new command buffer.
1421 *
1422 * This may return NULL in low-memory cases.
1423 *
1424 * If possible, we recycle a command buffer that's been used before.
1425 */
1426struct amr_command *
1427amr_alloccmd(struct amr_softc *sc)
1428{
1429    struct amr_command	*ac;
1430
1431    debug_called(3);
1432
1433    ac = amr_dequeue_free(sc);
1434    if (ac == NULL) {
1435	amr_alloccmd_cluster(sc);
1436	ac = amr_dequeue_free(sc);
1437    }
1438    if (ac == NULL)
1439	return(NULL);
1440
1441    /* clear out significant fields */
1442    ac->ac_slot = 0;
1443    ac->ac_status = 0;
1444    bzero(&ac->ac_mailbox, sizeof(struct amr_mailbox));
1445    ac->ac_flags = 0;
1446    ac->ac_bio = NULL;
1447    ac->ac_data = NULL;
1448    ac->ac_ccb_data = NULL;
1449    ac->ac_complete = NULL;
1450    return(ac);
1451}
1452
1453/********************************************************************************
1454 * Release a command buffer for recycling.
1455 */
1456void
1457amr_releasecmd(struct amr_command *ac)
1458{
1459    debug_called(3);
1460
1461    amr_enqueue_free(ac);
1462}
1463
1464/********************************************************************************
1465 * Allocate a new command cluster and initialise it.
1466 */
1467static void
1468amr_alloccmd_cluster(struct amr_softc *sc)
1469{
1470    struct amr_command_cluster	*acc;
1471    struct amr_command		*ac;
1472    int				s, i;
1473
1474    acc = malloc(AMR_CMD_CLUSTERSIZE, M_DEVBUF, M_NOWAIT);
1475    if (acc != NULL) {
1476	s = splbio();
1477	TAILQ_INSERT_TAIL(&sc->amr_cmd_clusters, acc, acc_link);
1478	splx(s);
1479	for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++) {
1480	    ac = &acc->acc_command[i];
1481	    bzero(ac, sizeof(*ac));
1482	    ac->ac_sc = sc;
1483	    if (!bus_dmamap_create(sc->amr_buffer_dmat, 0, &ac->ac_dmamap) &&
1484		!bus_dmamap_create(sc->amr_buffer_dmat, 0, &ac->ac_ccb_dmamap))
1485		amr_releasecmd(ac);
1486	}
1487    }
1488}
1489
1490/********************************************************************************
1491 * Free a command cluster
1492 */
1493static void
1494amr_freecmd_cluster(struct amr_command_cluster *acc)
1495{
1496    struct amr_softc	*sc = acc->acc_command[0].ac_sc;
1497    int			i;
1498
1499    for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++)
1500	bus_dmamap_destroy(sc->amr_buffer_dmat, acc->acc_command[i].ac_dmamap);
1501    free(acc, M_DEVBUF);
1502}
1503
1504/********************************************************************************
1505 ********************************************************************************
1506                                                         Interface-specific Shims
1507 ********************************************************************************
1508 ********************************************************************************/
1509
1510/********************************************************************************
1511 * Tell the controller that the mailbox contains a valid command
1512 */
1513static int
1514amr_quartz_submit_command(struct amr_softc *sc)
1515{
1516    debug_called(3);
1517
1518    if (AMR_QGET_IDB(sc) & AMR_QIDB_SUBMIT)
1519	return(EBUSY);
1520    AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
1521    return(0);
1522}
1523
1524static int
1525amr_std_submit_command(struct amr_softc *sc)
1526{
1527    debug_called(3);
1528
1529    if (AMR_SGET_MBSTAT(sc) & AMR_SMBOX_BUSYFLAG)
1530	return(EBUSY);
1531    AMR_SPOST_COMMAND(sc);
1532    return(0);
1533}
1534
1535/********************************************************************************
1536 * Claim any work that the controller has completed; acknowledge completion,
1537 * save details of the completion in (mbsave)
1538 */
1539static int
1540amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
1541{
1542    int		s, worked;
1543    u_int32_t	outd;
1544
1545    debug_called(3);
1546
1547    worked = 0;
1548    s = splbio();
1549
1550    /* work waiting for us? */
1551    if ((outd = AMR_QGET_ODB(sc)) == AMR_QODB_READY) {
1552
1553	/* save mailbox, which contains a list of completed commands */
1554	bcopy((void *)(uintptr_t)(volatile void *)sc->amr_mailbox, mbsave, sizeof(*mbsave));
1555
1556	/* acknowledge interrupt */
1557	AMR_QPUT_ODB(sc, AMR_QODB_READY);
1558
1559	/* acknowledge that we have the commands */
1560	AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_ACK);
1561
1562#ifndef AMR_QUARTZ_GOFASTER
1563	/*
1564	 * This waits for the controller to notice that we've taken the
1565	 * command from it.  It's very inefficient, and we shouldn't do it,
1566	 * but if we remove this code, we stop completing commands under
1567	 * load.
1568	 *
1569	 * Peter J says we shouldn't do this.  The documentation says we
1570	 * should.  Who is right?
1571	 */
1572	while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK)
1573	    ;				/* XXX aiee! what if it dies? */
1574#endif
1575
1576	worked = 1;			/* got some work */
1577    }
1578
1579    splx(s);
1580    return(worked);
1581}
1582
1583static int
1584amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
1585{
1586    int		s, worked;
1587    u_int8_t	istat;
1588
1589    debug_called(3);
1590
1591    worked = 0;
1592    s = splbio();
1593
1594    /* check for valid interrupt status */
1595    istat = AMR_SGET_ISTAT(sc);
1596    if ((istat & AMR_SINTR_VALID) != 0) {
1597	AMR_SPUT_ISTAT(sc, istat);	/* ack interrupt status */
1598
1599	/* save mailbox, which contains a list of completed commands */
1600	bcopy((void *)(uintptr_t)(volatile void *)sc->amr_mailbox, mbsave, sizeof(*mbsave));
1601
1602	AMR_SACK_INTERRUPT(sc);		/* acknowledge we have the mailbox */
1603	worked = 1;
1604    }
1605
1606    splx(s);
1607    return(worked);
1608}
1609
1610/********************************************************************************
1611 * Notify the controller of the mailbox location.
1612 */
1613static void
1614amr_std_attach_mailbox(struct amr_softc *sc)
1615{
1616
1617    /* program the mailbox physical address */
1618    AMR_SBYTE_SET(sc, AMR_SMBOX_0, sc->amr_mailboxphys         & 0xff);
1619    AMR_SBYTE_SET(sc, AMR_SMBOX_1, (sc->amr_mailboxphys >>  8) & 0xff);
1620    AMR_SBYTE_SET(sc, AMR_SMBOX_2, (sc->amr_mailboxphys >> 16) & 0xff);
1621    AMR_SBYTE_SET(sc, AMR_SMBOX_3, (sc->amr_mailboxphys >> 24) & 0xff);
1622    AMR_SBYTE_SET(sc, AMR_SMBOX_ENABLE, AMR_SMBOX_ADDR);
1623
1624    /* clear any outstanding interrupt and enable interrupts proper */
1625    AMR_SACK_INTERRUPT(sc);
1626    AMR_SENABLE_INTR(sc);
1627}
1628
1629#ifdef AMR_BOARD_INIT
1630/********************************************************************************
1631 * Initialise the controller
1632 */
1633static int
1634amr_quartz_init(struct amr_softc *sc)
1635{
1636    int		status, ostatus;
1637
1638    device_printf(sc->amr_dev, "initial init status %x\n", AMR_QGET_INITSTATUS(sc));
1639
1640    AMR_QRESET(sc);
1641
1642    ostatus = 0xff;
1643    while ((status = AMR_QGET_INITSTATUS(sc)) != AMR_QINIT_DONE) {
1644	if (status != ostatus) {
1645	    device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_qinit, status));
1646	    ostatus = status;
1647	}
1648	switch (status) {
1649	case AMR_QINIT_NOMEM:
1650	    return(ENOMEM);
1651
1652	case AMR_QINIT_SCAN:
1653	    /* XXX we could print channel/target here */
1654	    break;
1655	}
1656    }
1657    return(0);
1658}
1659
1660static int
1661amr_std_init(struct amr_softc *sc)
1662{
1663    int		status, ostatus;
1664
1665    device_printf(sc->amr_dev, "initial init status %x\n", AMR_SGET_INITSTATUS(sc));
1666
1667    AMR_SRESET(sc);
1668
1669    ostatus = 0xff;
1670    while ((status = AMR_SGET_INITSTATUS(sc)) != AMR_SINIT_DONE) {
1671	if (status != ostatus) {
1672	    device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_sinit, status));
1673	    ostatus = status;
1674	}
1675	switch (status) {
1676	case AMR_SINIT_NOMEM:
1677	    return(ENOMEM);
1678
1679	case AMR_SINIT_INPROG:
1680	    /* XXX we could print channel/target here? */
1681	    break;
1682	}
1683    }
1684    return(0);
1685}
1686#endif
1687
1688/********************************************************************************
1689 ********************************************************************************
1690                                                                        Debugging
1691 ********************************************************************************
1692 ********************************************************************************/
1693
1694/********************************************************************************
1695 * Identify the controller and print some information about it.
1696 */
1697static void
1698amr_describe_controller(struct amr_softc *sc)
1699{
1700    struct amr_prodinfo	*ap;
1701    struct amr_enquiry	*ae;
1702    char		*prod;
1703
1704    /*
1705     * Try to get 40LD product info, which tells us what the card is labelled as.
1706     */
1707    if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0)) != NULL) {
1708	device_printf(sc->amr_dev, "<LSILogic %.80s> Firmware %.16s, BIOS %.16s, %dMB RAM\n",
1709		      ap->ap_product, ap->ap_firmware, ap->ap_bios,
1710		      ap->ap_memsize);
1711
1712	free(ap, M_DEVBUF);
1713	return;
1714    }
1715
1716    /*
1717     * Try 8LD extended ENQUIRY to get controller signature, and use lookup table.
1718     */
1719    if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0)) != NULL) {
1720	prod = amr_describe_code(amr_table_adaptertype, ae->ae_signature);
1721
1722    } else if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0)) != NULL) {
1723
1724	/*
1725	 * Try to work it out based on the PCI signatures.
1726	 */
1727	switch (pci_get_device(sc->amr_dev)) {
1728	case 0x9010:
1729	    prod = "Series 428";
1730	    break;
1731	case 0x9060:
1732	    prod = "Series 434";
1733	    break;
1734	default:
1735	    prod = "unknown controller";
1736	    break;
1737	}
1738    } else {
1739	prod = "unsupported controller";
1740    }
1741
1742    /*
1743     * HP NetRaid controllers have a special encoding of the firmware and
1744     * BIOS versions. The AMI version seems to have it as strings whereas
1745     * the HP version does it with a leading uppercase character and two
1746     * binary numbers.
1747     */
1748
1749    if(ae->ae_adapter.aa_firmware[2] >= 'A' &&
1750       ae->ae_adapter.aa_firmware[2] <= 'Z' &&
1751       ae->ae_adapter.aa_firmware[1] <  ' ' &&
1752       ae->ae_adapter.aa_firmware[0] <  ' ' &&
1753       ae->ae_adapter.aa_bios[2] >= 'A'     &&
1754       ae->ae_adapter.aa_bios[2] <= 'Z'     &&
1755       ae->ae_adapter.aa_bios[1] <  ' '     &&
1756       ae->ae_adapter.aa_bios[0] <  ' ') {
1757
1758	/* this looks like we have an HP NetRaid version of the MegaRaid */
1759
1760    	if(ae->ae_signature == AMR_SIG_438) {
1761    		/* the AMI 438 is a NetRaid 3si in HP-land */
1762    		prod = "HP NetRaid 3si";
1763    	}
1764
1765	device_printf(sc->amr_dev, "<%s> Firmware %c.%02d.%02d, BIOS %c.%02d.%02d, %dMB RAM\n",
1766		      prod, ae->ae_adapter.aa_firmware[2],
1767		      ae->ae_adapter.aa_firmware[1],
1768		      ae->ae_adapter.aa_firmware[0],
1769		      ae->ae_adapter.aa_bios[2],
1770		      ae->ae_adapter.aa_bios[1],
1771		      ae->ae_adapter.aa_bios[0],
1772		      ae->ae_adapter.aa_memorysize);
1773    } else {
1774	device_printf(sc->amr_dev, "<%s> Firmware %.4s, BIOS %.4s, %dMB RAM\n",
1775		      prod, ae->ae_adapter.aa_firmware, ae->ae_adapter.aa_bios,
1776		      ae->ae_adapter.aa_memorysize);
1777    }
1778    free(ae, M_DEVBUF);
1779}
1780
1781int
1782amr_dump_blocks(struct amr_softc *sc, int unit, u_int32_t lba, void *data, int blks)
1783{
1784    struct amr_command	*ac;
1785    int			error = EIO;
1786
1787    debug_called(1);
1788
1789    sc->amr_state &= ~AMR_STATE_INTEN;
1790
1791    /* get ourselves a command buffer */
1792    if ((ac = amr_alloccmd(sc)) == NULL)
1793	goto out;
1794    /* set command flags */
1795    ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
1796
1797    /* point the command at our data */
1798    ac->ac_data = data;
1799    ac->ac_length = blks * AMR_BLKSIZE;
1800
1801    /* build the command proper */
1802    ac->ac_mailbox.mb_command 	= AMR_CMD_LWRITE;
1803    ac->ac_mailbox.mb_blkcount	= blks;
1804    ac->ac_mailbox.mb_lba	= lba;
1805    ac->ac_mailbox.mb_drive	= unit;
1806
1807    /* can't assume that interrupts are going to work here, so play it safe */
1808    if (sc->amr_poll_command(ac))
1809	goto out;
1810    error = ac->ac_status;
1811
1812 out:
1813    if (ac != NULL)
1814	amr_releasecmd(ac);
1815
1816    sc->amr_state |= AMR_STATE_INTEN;
1817    return (error);
1818}
1819
1820
1821
1822#ifdef AMR_DEBUG
1823/********************************************************************************
1824 * Print the command (ac) in human-readable format
1825 */
1826#if 0
1827static void
1828amr_printcommand(struct amr_command *ac)
1829{
1830    struct amr_softc	*sc = ac->ac_sc;
1831    struct amr_sgentry	*sg;
1832    int			i;
1833
1834    device_printf(sc->amr_dev, "cmd %x  ident %d  drive %d\n",
1835		  ac->ac_mailbox.mb_command, ac->ac_mailbox.mb_ident, ac->ac_mailbox.mb_drive);
1836    device_printf(sc->amr_dev, "blkcount %d  lba %d\n",
1837		  ac->ac_mailbox.mb_blkcount, ac->ac_mailbox.mb_lba);
1838    device_printf(sc->amr_dev, "virtaddr %p  length %lu\n", ac->ac_data, (unsigned long)ac->ac_length);
1839    device_printf(sc->amr_dev, "sg physaddr %08x  nsg %d\n",
1840		  ac->ac_mailbox.mb_physaddr, ac->ac_mailbox.mb_nsgelem);
1841    device_printf(sc->amr_dev, "ccb %p  bio %p\n", ac->ac_ccb_data, ac->ac_bio);
1842
1843    /* get base address of s/g table */
1844    sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
1845    for (i = 0; i < ac->ac_mailbox.mb_nsgelem; i++, sg++)
1846	device_printf(sc->amr_dev, "  %x/%d\n", sg->sg_addr, sg->sg_count);
1847}
1848#endif
1849#endif
1850