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