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