xref: /freebsd/sys/dev/aac/aac.c (revision 538015aa3b16b2819401ed2b6cebdd459affc7d4)
1 /*-
2  * Copyright (c) 2000 Michael Smith
3  * Copyright (c) 2001 Scott Long
4  * Copyright (c) 2000 BSDi
5  * Copyright (c) 2001 Adaptec, Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	$FreeBSD$
30  */
31 
32 /*
33  * Driver for the Adaptec 'FSA' family of PCI/SCSI RAID adapters.
34  */
35 
36 #include "opt_aac.h"
37 
38 /* #include <stddef.h> */
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/malloc.h>
42 #include <sys/kernel.h>
43 #include <sys/kthread.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/sysctl.h>
47 #include <sys/poll.h>
48 #if __FreeBSD_version >= 500005
49 #include <sys/selinfo.h>
50 #else
51 #include <sys/select.h>
52 #endif
53 
54 #include <dev/aac/aac_compat.h>
55 
56 #include <sys/bus.h>
57 #include <sys/conf.h>
58 #include <sys/devicestat.h>
59 #include <sys/disk.h>
60 #include <sys/signalvar.h>
61 #include <sys/time.h>
62 #include <sys/eventhandler.h>
63 
64 #include <machine/bus_memio.h>
65 #include <machine/bus.h>
66 #include <machine/resource.h>
67 
68 #include <dev/aac/aacreg.h>
69 #include <dev/aac/aac_ioctl.h>
70 #include <dev/aac/aacvar.h>
71 #include <dev/aac/aac_tables.h>
72 #include <dev/aac/aac_cam.h>
73 
74 static void	aac_startup(void *arg);
75 static void	aac_add_container(struct aac_softc *sc,
76 				  struct aac_mntinforesp *mir, int f);
77 static void	aac_get_bus_info(struct aac_softc *sc);
78 
79 /* Command Processing */
80 static void	aac_timeout(struct aac_softc *sc);
81 static int	aac_start(struct aac_command *cm);
82 static void	aac_complete(void *context, int pending);
83 static int	aac_bio_command(struct aac_softc *sc, struct aac_command **cmp);
84 static void	aac_bio_complete(struct aac_command *cm);
85 static int	aac_wait_command(struct aac_command *cm, int timeout);
86 static void	aac_host_command(struct aac_softc *sc);
87 static void	aac_host_response(struct aac_softc *sc);
88 
89 /* Command Buffer Management */
90 static void	aac_map_command_helper(void *arg, bus_dma_segment_t *segs,
91 				       int nseg, int error);
92 static int	aac_alloc_commands(struct aac_softc *sc);
93 static void	aac_free_commands(struct aac_softc *sc);
94 static void	aac_map_command(struct aac_command *cm);
95 static void	aac_unmap_command(struct aac_command *cm);
96 
97 /* Hardware Interface */
98 static void	aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg,
99 			       int error);
100 static int	aac_check_firmware(struct aac_softc *sc);
101 static int	aac_init(struct aac_softc *sc);
102 static int	aac_sync_command(struct aac_softc *sc, u_int32_t command,
103 				 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2,
104 				 u_int32_t arg3, u_int32_t *sp);
105 static int	aac_enqueue_fib(struct aac_softc *sc, int queue,
106 				struct aac_command *cm);
107 static int	aac_dequeue_fib(struct aac_softc *sc, int queue,
108 				u_int32_t *fib_size, struct aac_fib **fib_addr);
109 static int	aac_enqueue_response(struct aac_softc *sc, int queue,
110 				     struct aac_fib *fib);
111 
112 /* Falcon/PPC interface */
113 static int	aac_fa_get_fwstatus(struct aac_softc *sc);
114 static void	aac_fa_qnotify(struct aac_softc *sc, int qbit);
115 static int	aac_fa_get_istatus(struct aac_softc *sc);
116 static void	aac_fa_clear_istatus(struct aac_softc *sc, int mask);
117 static void	aac_fa_set_mailbox(struct aac_softc *sc, u_int32_t command,
118 				   u_int32_t arg0, u_int32_t arg1,
119 				   u_int32_t arg2, u_int32_t arg3);
120 static int	aac_fa_get_mailboxstatus(struct aac_softc *sc);
121 static void	aac_fa_set_interrupts(struct aac_softc *sc, int enable);
122 
123 struct aac_interface aac_fa_interface = {
124 	aac_fa_get_fwstatus,
125 	aac_fa_qnotify,
126 	aac_fa_get_istatus,
127 	aac_fa_clear_istatus,
128 	aac_fa_set_mailbox,
129 	aac_fa_get_mailboxstatus,
130 	aac_fa_set_interrupts
131 };
132 
133 /* StrongARM interface */
134 static int	aac_sa_get_fwstatus(struct aac_softc *sc);
135 static void	aac_sa_qnotify(struct aac_softc *sc, int qbit);
136 static int	aac_sa_get_istatus(struct aac_softc *sc);
137 static void	aac_sa_clear_istatus(struct aac_softc *sc, int mask);
138 static void	aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
139 				   u_int32_t arg0, u_int32_t arg1,
140 				   u_int32_t arg2, u_int32_t arg3);
141 static int	aac_sa_get_mailboxstatus(struct aac_softc *sc);
142 static void	aac_sa_set_interrupts(struct aac_softc *sc, int enable);
143 
144 struct aac_interface aac_sa_interface = {
145 	aac_sa_get_fwstatus,
146 	aac_sa_qnotify,
147 	aac_sa_get_istatus,
148 	aac_sa_clear_istatus,
149 	aac_sa_set_mailbox,
150 	aac_sa_get_mailboxstatus,
151 	aac_sa_set_interrupts
152 };
153 
154 /* i960Rx interface */
155 static int	aac_rx_get_fwstatus(struct aac_softc *sc);
156 static void	aac_rx_qnotify(struct aac_softc *sc, int qbit);
157 static int	aac_rx_get_istatus(struct aac_softc *sc);
158 static void	aac_rx_clear_istatus(struct aac_softc *sc, int mask);
159 static void	aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
160 				   u_int32_t arg0, u_int32_t arg1,
161 				   u_int32_t arg2, u_int32_t arg3);
162 static int	aac_rx_get_mailboxstatus(struct aac_softc *sc);
163 static void	aac_rx_set_interrupts(struct aac_softc *sc, int enable);
164 
165 struct aac_interface aac_rx_interface = {
166 	aac_rx_get_fwstatus,
167 	aac_rx_qnotify,
168 	aac_rx_get_istatus,
169 	aac_rx_clear_istatus,
170 	aac_rx_set_mailbox,
171 	aac_rx_get_mailboxstatus,
172 	aac_rx_set_interrupts
173 };
174 
175 /* Debugging and Diagnostics */
176 static void	aac_describe_controller(struct aac_softc *sc);
177 static char	*aac_describe_code(struct aac_code_lookup *table,
178 				   u_int32_t code);
179 
180 /* Management Interface */
181 static d_open_t		aac_open;
182 static d_close_t	aac_close;
183 static d_ioctl_t	aac_ioctl;
184 static d_poll_t		aac_poll;
185 static int		aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib);
186 static void		aac_handle_aif(struct aac_softc *sc,
187 					   struct aac_fib *fib);
188 static int		aac_rev_check(struct aac_softc *sc, caddr_t udata);
189 static int		aac_getnext_aif(struct aac_softc *sc, caddr_t arg);
190 static int		aac_return_aif(struct aac_softc *sc, caddr_t uptr);
191 static int		aac_query_disk(struct aac_softc *sc, caddr_t uptr);
192 
193 #define AAC_CDEV_MAJOR	150
194 
195 static struct cdevsw aac_cdevsw = {
196 	aac_open,		/* open */
197 	aac_close,		/* close */
198 	noread,			/* read */
199 	nowrite,		/* write */
200 	aac_ioctl,		/* ioctl */
201 	aac_poll,		/* poll */
202 	nommap,			/* mmap */
203 	nostrategy,		/* strategy */
204 	"aac",			/* name */
205 	AAC_CDEV_MAJOR,		/* major */
206 	nodump,			/* dump */
207 	nopsize,		/* psize */
208 	0,			/* flags */
209 #if __FreeBSD_version < 500005
210 	-1,			/* bmaj */
211 #endif
212 };
213 
214 MALLOC_DEFINE(M_AACBUF, "aacbuf", "Buffers for the AAC driver");
215 
216 /* sysctl node */
217 SYSCTL_NODE(_hw, OID_AUTO, aac, CTLFLAG_RD, 0, "AAC driver parameters");
218 
219 /*
220  * Device Interface
221  */
222 
223 /*
224  * Initialise the controller and softc
225  */
226 int
227 aac_attach(struct aac_softc *sc)
228 {
229 	int error, unit;
230 
231 	debug_called(1);
232 
233 	/*
234 	 * Initialise per-controller queues.
235 	 */
236 	aac_initq_free(sc);
237 	aac_initq_ready(sc);
238 	aac_initq_busy(sc);
239 	aac_initq_complete(sc);
240 	aac_initq_bio(sc);
241 
242 #if __FreeBSD_version >= 500005
243 	/*
244 	 * Initialise command-completion task.
245 	 */
246 	TASK_INIT(&sc->aac_task_complete, 0, aac_complete, sc);
247 #endif
248 
249 	/* disable interrupts before we enable anything */
250 	AAC_MASK_INTERRUPTS(sc);
251 
252 	/* mark controller as suspended until we get ourselves organised */
253 	sc->aac_state |= AAC_STATE_SUSPEND;
254 
255 	/*
256 	 * Check that the firmware on the card is supported.
257 	 */
258 	if ((error = aac_check_firmware(sc)) != 0)
259 		return(error);
260 
261 	/*
262 	 * Allocate command structures.  This must be done before aac_init()
263 	 * in order to work around a 2120/2200 bug.
264 	 */
265 	if ((error = aac_alloc_commands(sc)) != 0)
266 		return(error);
267 
268 	/* Init the sync fib lock */
269 	AAC_LOCK_INIT(&sc->aac_sync_lock, "AAC sync FIB lock");
270 
271 	/*
272 	 * Initialise the adapter.
273 	 */
274 	if ((error = aac_init(sc)) != 0)
275 		return(error);
276 
277 	/*
278 	 * Print a little information about the controller.
279 	 */
280 	aac_describe_controller(sc);
281 
282 	/*
283 	 * Register to probe our containers later.
284 	 */
285 	TAILQ_INIT(&sc->aac_container_tqh);
286 	AAC_LOCK_INIT(&sc->aac_container_lock, "AAC container lock");
287 
288 	/*
289 	 * Lock for the AIF queue
290 	 */
291 	AAC_LOCK_INIT(&sc->aac_aifq_lock, "AAC AIF lock");
292 
293 	sc->aac_ich.ich_func = aac_startup;
294 	sc->aac_ich.ich_arg = sc;
295 	if (config_intrhook_establish(&sc->aac_ich) != 0) {
296 		device_printf(sc->aac_dev,
297 			      "can't establish configuration hook\n");
298 		return(ENXIO);
299 	}
300 
301 	/*
302 	 * Make the control device.
303 	 */
304 	unit = device_get_unit(sc->aac_dev);
305 	sc->aac_dev_t = make_dev(&aac_cdevsw, unit, UID_ROOT, GID_OPERATOR,
306 				 0640, "aac%d", unit);
307 #if __FreeBSD_version > 500005
308 	(void)make_dev_alias(sc->aac_dev_t, "afa%d", unit);
309 	(void)make_dev_alias(sc->aac_dev_t, "hpn%d", unit);
310 #endif
311 	sc->aac_dev_t->si_drv1 = sc;
312 
313 	/* Create the AIF thread */
314 #if __FreeBSD_version > 500005
315 	if (kthread_create((void(*)(void *))aac_host_command, sc,
316 			   &sc->aifthread, 0, 0, "aac%daif", unit))
317 #else
318 	if (kthread_create((void(*)(void *))aac_host_command, sc,
319 			   &sc->aifthread, "aac%daif", unit))
320 #endif
321 		panic("Could not create AIF thread\n");
322 
323 	/* Register the shutdown method to only be called post-dump */
324 	if ((EVENTHANDLER_REGISTER(shutdown_final, aac_shutdown, sc->aac_dev,
325 				   SHUTDOWN_PRI_DEFAULT)) == NULL)
326 	device_printf(sc->aac_dev, "shutdown event registration failed\n");
327 
328 	/* Register with CAM for the non-DASD devices */
329 	if (!(sc->quirks & AAC_QUIRK_NOCAM))
330 		aac_get_bus_info(sc);
331 
332 	return(0);
333 }
334 
335 /*
336  * Probe for containers, create disks.
337  */
338 static void
339 aac_startup(void *arg)
340 {
341 	struct aac_softc *sc;
342 	struct aac_fib *fib;
343 	struct aac_mntinfo *mi;
344 	struct aac_mntinforesp *mir = NULL;
345 	int i = 0;
346 
347 	debug_called(1);
348 
349 	sc = (struct aac_softc *)arg;
350 
351 	/* disconnect ourselves from the intrhook chain */
352 	config_intrhook_disestablish(&sc->aac_ich);
353 
354 	aac_alloc_sync_fib(sc, &fib, 0);
355 	mi = (struct aac_mntinfo *)&fib->data[0];
356 
357 	/* loop over possible containers */
358 	do {
359 		/* request information on this container */
360 		bzero(mi, sizeof(struct aac_mntinfo));
361 		mi->Command = VM_NameServe;
362 		mi->MntType = FT_FILESYS;
363 		mi->MntCount = i;
364 		if (aac_sync_fib(sc, ContainerCommand, 0, fib,
365 				 sizeof(struct aac_mntinfo))) {
366 			debug(2, "error probing container %d", i);
367 			continue;
368 		}
369 
370 		mir = (struct aac_mntinforesp *)&fib->data[0];
371 		aac_add_container(sc, mir, 0);
372 		i++;
373 	} while ((i < mir->MntRespCount) && (i < AAC_MAX_CONTAINERS));
374 
375 	aac_release_sync_fib(sc);
376 
377 	/* poke the bus to actually attach the child devices */
378 	if (bus_generic_attach(sc->aac_dev))
379 		device_printf(sc->aac_dev, "bus_generic_attach failed\n");
380 
381 	/* mark the controller up */
382 	sc->aac_state &= ~AAC_STATE_SUSPEND;
383 
384 	/* enable interrupts now */
385 	AAC_UNMASK_INTERRUPTS(sc);
386 
387 	/* enable the timeout watchdog */
388 	timeout((timeout_t*)aac_timeout, sc, AAC_PERIODIC_INTERVAL * hz);
389 }
390 
391 /*
392  * Create a device to respresent a new container
393  */
394 static void
395 aac_add_container(struct aac_softc *sc, struct aac_mntinforesp *mir, int f)
396 {
397 	struct aac_container *co;
398 	device_t child;
399 
400 	/*
401 	 * Check container volume type for validity.  Note that many of
402 	 * the possible types may never show up.
403 	 */
404 	if ((mir->Status == ST_OK) && (mir->MntTable[0].VolType != CT_NONE)) {
405 		MALLOC(co, struct aac_container *, sizeof *co, M_AACBUF,
406 		       M_NOWAIT);
407 		if (co == NULL)
408 			panic("Out of memory?!\n");
409 		debug(1, "id %x  name '%.16s'  size %u  type %d",
410 		      mir->MntTable[0].ObjectId,
411 		      mir->MntTable[0].FileSystemName,
412 		      mir->MntTable[0].Capacity, mir->MntTable[0].VolType);
413 
414 		if ((child = device_add_child(sc->aac_dev, "aacd", -1)) == NULL)
415 			device_printf(sc->aac_dev, "device_add_child failed\n");
416 		else
417 			device_set_ivars(child, co);
418 		device_set_desc(child, aac_describe_code(aac_container_types,
419 				mir->MntTable[0].VolType));
420 		co->co_disk = child;
421 		co->co_found = f;
422 		bcopy(&mir->MntTable[0], &co->co_mntobj,
423 		      sizeof(struct aac_mntobj));
424 		AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
425 		TAILQ_INSERT_TAIL(&sc->aac_container_tqh, co, co_link);
426 		AAC_LOCK_RELEASE(&sc->aac_container_lock);
427 	}
428 }
429 
430 /*
431  * Free all of the resources associated with (sc)
432  *
433  * Should not be called if the controller is active.
434  */
435 void
436 aac_free(struct aac_softc *sc)
437 {
438 	debug_called(1);
439 
440 	/* remove the control device */
441 	if (sc->aac_dev_t != NULL)
442 		destroy_dev(sc->aac_dev_t);
443 
444 	/* throw away any FIB buffers, discard the FIB DMA tag */
445 	if (sc->aac_fibs != NULL)
446 		aac_free_commands(sc);
447 	if (sc->aac_fib_dmat)
448 		bus_dma_tag_destroy(sc->aac_fib_dmat);
449 
450 	/* destroy the common area */
451 	if (sc->aac_common) {
452 		bus_dmamap_unload(sc->aac_common_dmat, sc->aac_common_dmamap);
453 		bus_dmamem_free(sc->aac_common_dmat, sc->aac_common,
454 				sc->aac_common_dmamap);
455 	}
456 	if (sc->aac_common_dmat)
457 		bus_dma_tag_destroy(sc->aac_common_dmat);
458 
459 	/* disconnect the interrupt handler */
460 	if (sc->aac_intr)
461 		bus_teardown_intr(sc->aac_dev, sc->aac_irq, sc->aac_intr);
462 	if (sc->aac_irq != NULL)
463 		bus_release_resource(sc->aac_dev, SYS_RES_IRQ, sc->aac_irq_rid,
464 				     sc->aac_irq);
465 
466 	/* destroy data-transfer DMA tag */
467 	if (sc->aac_buffer_dmat)
468 		bus_dma_tag_destroy(sc->aac_buffer_dmat);
469 
470 	/* destroy the parent DMA tag */
471 	if (sc->aac_parent_dmat)
472 		bus_dma_tag_destroy(sc->aac_parent_dmat);
473 
474 	/* release the register window mapping */
475 	if (sc->aac_regs_resource != NULL)
476 		bus_release_resource(sc->aac_dev, SYS_RES_MEMORY,
477 				     sc->aac_regs_rid, sc->aac_regs_resource);
478 }
479 
480 /*
481  * Disconnect from the controller completely, in preparation for unload.
482  */
483 int
484 aac_detach(device_t dev)
485 {
486 	struct aac_softc *sc;
487 #if AAC_BROKEN
488 	int error;
489 #endif
490 
491 	debug_called(1);
492 
493 	sc = device_get_softc(dev);
494 
495 	if (sc->aac_state & AAC_STATE_OPEN)
496 	return(EBUSY);
497 
498 #if AAC_BROKEN
499 	if (sc->aifflags & AAC_AIFFLAGS_RUNNING) {
500 		sc->aifflags |= AAC_AIFFLAGS_EXIT;
501 		wakeup(sc->aifthread);
502 		tsleep(sc->aac_dev, PUSER | PCATCH, "aacdch", 30 * hz);
503 	}
504 
505 	if (sc->aifflags & AAC_AIFFLAGS_RUNNING)
506 		panic("Cannot shutdown AIF thread\n");
507 
508 	if ((error = aac_shutdown(dev)))
509 		return(error);
510 
511 	aac_free(sc);
512 
513 	return(0);
514 #else
515 	return (EBUSY);
516 #endif
517 }
518 
519 /*
520  * Bring the controller down to a dormant state and detach all child devices.
521  *
522  * This function is called before detach or system shutdown.
523  *
524  * Note that we can assume that the bioq on the controller is empty, as we won't
525  * allow shutdown if any device is open.
526  */
527 int
528 aac_shutdown(device_t dev)
529 {
530 	struct aac_softc *sc;
531 	struct aac_fib *fib;
532 	struct aac_close_command *cc;
533 	int s;
534 
535 	debug_called(1);
536 
537 	sc = device_get_softc(dev);
538 
539 	s = splbio();
540 
541 	sc->aac_state |= AAC_STATE_SUSPEND;
542 
543 	/*
544 	 * Send a Container shutdown followed by a HostShutdown FIB to the
545 	 * controller to convince it that we don't want to talk to it anymore.
546 	 * We've been closed and all I/O completed already
547 	 */
548 	device_printf(sc->aac_dev, "shutting down controller...");
549 
550 	aac_alloc_sync_fib(sc, &fib, AAC_SYNC_LOCK_FORCE);
551 	cc = (struct aac_close_command *)&fib->data[0];
552 
553 	bzero(cc, sizeof(struct aac_close_command));
554 	cc->Command = VM_CloseAll;
555 	cc->ContainerId = 0xffffffff;
556 	if (aac_sync_fib(sc, ContainerCommand, 0, fib,
557 	    sizeof(struct aac_close_command)))
558 		printf("FAILED.\n");
559 	else {
560 		fib->data[0] = 0;
561 		/*
562 		 * XXX Issuing this command to the controller makes it shut down
563 		 * but also keeps it from coming back up without a reset of the
564 		 * PCI bus.  This is not desirable if you are just unloading the
565 		 * driver module with the intent to reload it later.
566 		 */
567 		if (aac_sync_fib(sc, FsaHostShutdown, AAC_FIBSTATE_SHUTDOWN,
568 		    fib, 1)) {
569 			printf("FAILED.\n");
570 		} else {
571 			printf("done.\n");
572 		}
573 	}
574 
575 	AAC_MASK_INTERRUPTS(sc);
576 
577 	splx(s);
578 	return(0);
579 }
580 
581 /*
582  * Bring the controller to a quiescent state, ready for system suspend.
583  */
584 int
585 aac_suspend(device_t dev)
586 {
587 	struct aac_softc *sc;
588 	int s;
589 
590 	debug_called(1);
591 
592 	sc = device_get_softc(dev);
593 
594 	s = splbio();
595 
596 	sc->aac_state |= AAC_STATE_SUSPEND;
597 
598 	AAC_MASK_INTERRUPTS(sc);
599 	splx(s);
600 	return(0);
601 }
602 
603 /*
604  * Bring the controller back to a state ready for operation.
605  */
606 int
607 aac_resume(device_t dev)
608 {
609 	struct aac_softc *sc;
610 
611 	debug_called(1);
612 
613 	sc = device_get_softc(dev);
614 
615 	sc->aac_state &= ~AAC_STATE_SUSPEND;
616 	AAC_UNMASK_INTERRUPTS(sc);
617 	return(0);
618 }
619 
620 /*
621  * Take an interrupt.
622  */
623 void
624 aac_intr(void *arg)
625 {
626 	struct aac_softc *sc;
627 	u_int16_t reason;
628 	u_int32_t *resp_queue;
629 
630 	debug_called(2);
631 
632 	sc = (struct aac_softc *)arg;
633 
634 	/*
635 	 * Optimize the common case of adapter response interrupts.
636 	 * We must read from the card prior to processing the responses
637 	 * to ensure the clear is flushed prior to accessing the queues.
638 	 * Reading the queues from local memory might save us a PCI read.
639 	 */
640 	resp_queue = sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE];
641 	if (resp_queue[AAC_PRODUCER_INDEX] != resp_queue[AAC_CONSUMER_INDEX])
642 		reason = AAC_DB_RESPONSE_READY;
643 	else
644 		reason = AAC_GET_ISTATUS(sc);
645 	AAC_CLEAR_ISTATUS(sc, reason);
646 	(void)AAC_GET_ISTATUS(sc);
647 
648 	/* It's not ok to return here because of races with the previous step */
649 	if (reason & AAC_DB_RESPONSE_READY)
650 		aac_host_response(sc);
651 
652 	/* controller wants to talk to the log */
653 	if (reason & AAC_DB_PRINTF)
654 		aac_print_printf(sc);
655 
656 	/* controller has a message for us? */
657 	if (reason & AAC_DB_COMMAND_READY) {
658 		/* XXX What happens if the thread is already awake? */
659 		if (sc->aifflags & AAC_AIFFLAGS_RUNNING) {
660 			sc->aifflags |= AAC_AIFFLAGS_PENDING;
661 			wakeup(sc->aifthread);
662 		}
663 	}
664 }
665 
666 /*
667  * Command Processing
668  */
669 
670 /*
671  * Start as much queued I/O as possible on the controller
672  */
673 void
674 aac_startio(struct aac_softc *sc)
675 {
676 	struct aac_command *cm;
677 
678 	debug_called(2);
679 
680 	for (;;) {
681 		/*
682 		 * Try to get a command that's been put off for lack of
683 		 * resources
684 		 */
685 		cm = aac_dequeue_ready(sc);
686 
687 		/*
688 		 * Try to build a command off the bio queue (ignore error
689 		 * return)
690 		 */
691 		if (cm == NULL)
692 			aac_bio_command(sc, &cm);
693 
694 		/* nothing to do? */
695 		if (cm == NULL)
696 			break;
697 
698 		/* try to give the command to the controller */
699 		if (aac_start(cm) == EBUSY) {
700 			/* put it on the ready queue for later */
701 			aac_requeue_ready(cm);
702 			break;
703 		}
704 	}
705 }
706 
707 /*
708  * Deliver a command to the controller; allocate controller resources at the
709  * last moment when possible.
710  */
711 static int
712 aac_start(struct aac_command *cm)
713 {
714 	struct aac_softc *sc;
715 	int error;
716 
717 	debug_called(2);
718 
719 	sc = cm->cm_sc;
720 
721 	/* get the command mapped */
722 	aac_map_command(cm);
723 
724 	/* fix up the address values in the FIB */
725 	cm->cm_fib->Header.SenderFibAddress = (u_int32_t)cm->cm_fib;
726 	cm->cm_fib->Header.ReceiverFibAddress = cm->cm_fibphys;
727 
728 	/* save a pointer to the command for speedy reverse-lookup */
729 	cm->cm_fib->Header.SenderData = (u_int32_t)cm;	/* XXX 64-bit physical
730 							 * address issue */
731 	/* put the FIB on the outbound queue */
732 	error = aac_enqueue_fib(sc, cm->cm_queue, cm);
733 	return(error);
734 }
735 
736 /*
737  * Handle notification of one or more FIBs coming from the controller.
738  */
739 static void
740 aac_host_command(struct aac_softc *sc)
741 {
742 	struct aac_fib *fib;
743 	u_int32_t fib_size;
744 	int size;
745 
746 	debug_called(2);
747 
748 	sc->aifflags |= AAC_AIFFLAGS_RUNNING;
749 
750 	while (!(sc->aifflags & AAC_AIFFLAGS_EXIT)) {
751 		if (!(sc->aifflags & AAC_AIFFLAGS_PENDING))
752 			tsleep(sc->aifthread, PRIBIO, "aifthd", 15 * hz);
753 
754 		sc->aifflags &= ~AAC_AIFFLAGS_PENDING;
755 		for (;;) {
756 			if (aac_dequeue_fib(sc, AAC_HOST_NORM_CMD_QUEUE,
757 					    &fib_size, &fib))
758 				break;	/* nothing to do */
759 
760 			AAC_PRINT_FIB(sc, fib);
761 
762 			switch (fib->Header.Command) {
763 			case AifRequest:
764 				aac_handle_aif(sc, fib);
765 				break;
766 			default:
767 				device_printf(sc->aac_dev, "unknown command "
768 					      "from controller\n");
769 				break;
770 			}
771 
772 			/* Return the AIF to the controller. */
773 			if ((fib->Header.XferState == 0) ||
774 			    (fib->Header.StructType != AAC_FIBTYPE_TFIB))
775 				break;
776 
777 			if (fib->Header.XferState & AAC_FIBSTATE_FROMADAP) {
778 				fib->Header.XferState |= AAC_FIBSTATE_DONEHOST;
779 				*(AAC_FSAStatus*)fib->data = ST_OK;
780 
781 				/* XXX Compute the Size field? */
782 				size = fib->Header.Size;
783 				if (size > sizeof(struct aac_fib)) {
784 					size = sizeof(struct aac_fib);
785 					fib->Header.Size = size;
786 				}
787 				/*
788 				 * Since we did not generate this command, it
789 				 * cannot go through the normal
790 				 * enqueue->startio chain.
791 				 */
792 				aac_enqueue_response(sc,
793 						     AAC_ADAP_NORM_RESP_QUEUE,
794 						     fib);
795 			}
796 		}
797 	}
798 	sc->aifflags &= ~AAC_AIFFLAGS_RUNNING;
799 	wakeup(sc->aac_dev);
800 
801 #if __FreeBSD_version > 500005
802 	mtx_lock(&Giant);
803 #endif
804 	kthread_exit(0);
805 }
806 
807 /*
808  * Handle notification of one or more FIBs completed by the controller
809  */
810 static void
811 aac_host_response(struct aac_softc *sc)
812 {
813 	struct aac_command *cm;
814 	struct aac_fib *fib;
815 	u_int32_t fib_size;
816 
817 	debug_called(2);
818 
819 	for (;;) {
820 		/* look for completed FIBs on our queue */
821 		if (aac_dequeue_fib(sc, AAC_HOST_NORM_RESP_QUEUE, &fib_size,
822 				    &fib))
823 			break;	/* nothing to do */
824 
825 		/* get the command, unmap and queue for later processing */
826 		cm = (struct aac_command *)fib->Header.SenderData;
827 		if (cm == NULL) {
828 			AAC_PRINT_FIB(sc, fib);
829 		} else {
830 			aac_remove_busy(cm);
831 			aac_unmap_command(cm);		/* XXX defer? */
832 			aac_enqueue_complete(cm);
833 		}
834 	}
835 
836 	/* handle completion processing */
837 #if __FreeBSD_version >= 500005
838 	taskqueue_enqueue(taskqueue_swi, &sc->aac_task_complete);
839 #else
840 	aac_complete(sc, 0);
841 #endif
842 }
843 
844 /*
845  * Process completed commands.
846  */
847 static void
848 aac_complete(void *context, int pending)
849 {
850 	struct aac_softc *sc;
851 	struct aac_command *cm;
852 
853 	debug_called(2);
854 
855 	sc = (struct aac_softc *)context;
856 
857 	/* pull completed commands off the queue */
858 	for (;;) {
859 		cm = aac_dequeue_complete(sc);
860 		if (cm == NULL)
861 			break;
862 		cm->cm_flags |= AAC_CMD_COMPLETED;
863 
864 		/* is there a completion handler? */
865 		if (cm->cm_complete != NULL) {
866 			cm->cm_complete(cm);
867 		} else {
868 			/* assume that someone is sleeping on this command */
869 			wakeup(cm);
870 		}
871 	}
872 
873 	/* see if we can start some more I/O */
874 	aac_startio(sc);
875 }
876 
877 /*
878  * Handle a bio submitted from a disk device.
879  */
880 void
881 aac_submit_bio(struct bio *bp)
882 {
883 	struct aac_disk *ad;
884 	struct aac_softc *sc;
885 
886 	debug_called(2);
887 
888 	ad = (struct aac_disk *)bp->bio_dev->si_drv1;
889 	sc = ad->ad_controller;
890 
891 	/* queue the BIO and try to get some work done */
892 	aac_enqueue_bio(sc, bp);
893 	aac_startio(sc);
894 }
895 
896 /*
897  * Get a bio and build a command to go with it.
898  */
899 static int
900 aac_bio_command(struct aac_softc *sc, struct aac_command **cmp)
901 {
902 	struct aac_command *cm;
903 	struct aac_fib *fib;
904 	struct aac_blockread *br;
905 	struct aac_blockwrite *bw;
906 	struct aac_disk *ad;
907 	struct bio *bp;
908 
909 	debug_called(2);
910 
911 	/* get the resources we will need */
912 	cm = NULL;
913 	if ((bp = aac_dequeue_bio(sc)) == NULL)
914 		goto fail;
915 	if (aac_alloc_command(sc, &cm))	/* get a command */
916 		goto fail;
917 
918 	/* fill out the command */
919 	cm->cm_data = (void *)bp->bio_data;
920 	cm->cm_datalen = bp->bio_bcount;
921 	cm->cm_complete = aac_bio_complete;
922 	cm->cm_private = bp;
923 	cm->cm_timestamp = time_second;
924 	cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
925 
926 	/* build the FIB */
927 	fib = cm->cm_fib;
928 	fib->Header.XferState =
929 		AAC_FIBSTATE_HOSTOWNED   |
930 		AAC_FIBSTATE_INITIALISED |
931 		AAC_FIBSTATE_EMPTY	 |
932 		AAC_FIBSTATE_FROMHOST	 |
933 		AAC_FIBSTATE_REXPECTED   |
934 		AAC_FIBSTATE_NORM	 |
935 		AAC_FIBSTATE_ASYNC	 |
936 		AAC_FIBSTATE_FAST_RESPONSE;
937 	fib->Header.Command = ContainerCommand;
938 	fib->Header.Size = sizeof(struct aac_fib_header);
939 
940 	/* build the read/write request */
941 	ad = (struct aac_disk *)bp->bio_dev->si_drv1;
942 	if (BIO_IS_READ(bp)) {
943 		br = (struct aac_blockread *)&fib->data[0];
944 		br->Command = VM_CtBlockRead;
945 		br->ContainerId = ad->ad_container->co_mntobj.ObjectId;
946 		br->BlockNumber = bp->bio_pblkno;
947 		br->ByteCount = bp->bio_bcount;
948 		fib->Header.Size += sizeof(struct aac_blockread);
949 		cm->cm_sgtable = &br->SgMap;
950 		cm->cm_flags |= AAC_CMD_DATAIN;
951 	} else {
952 		bw = (struct aac_blockwrite *)&fib->data[0];
953 		bw->Command = VM_CtBlockWrite;
954 		bw->ContainerId = ad->ad_container->co_mntobj.ObjectId;
955 		bw->BlockNumber = bp->bio_pblkno;
956 		bw->ByteCount = bp->bio_bcount;
957 		bw->Stable = CUNSTABLE;	/* XXX what's appropriate here? */
958 		fib->Header.Size += sizeof(struct aac_blockwrite);
959 		cm->cm_flags |= AAC_CMD_DATAOUT;
960 		cm->cm_sgtable = &bw->SgMap;
961 	}
962 
963 	*cmp = cm;
964 	return(0);
965 
966 fail:
967 	if (bp != NULL)
968 		aac_enqueue_bio(sc, bp);
969 	if (cm != NULL)
970 		aac_release_command(cm);
971 	return(ENOMEM);
972 }
973 
974 /*
975  * Handle a bio-instigated command that has been completed.
976  */
977 static void
978 aac_bio_complete(struct aac_command *cm)
979 {
980 	struct aac_blockread_response *brr;
981 	struct aac_blockwrite_response *bwr;
982 	struct bio *bp;
983 	AAC_FSAStatus status;
984 
985 	/* fetch relevant status and then release the command */
986 	bp = (struct bio *)cm->cm_private;
987 	if (BIO_IS_READ(bp)) {
988 		brr = (struct aac_blockread_response *)&cm->cm_fib->data[0];
989 		status = brr->Status;
990 	} else {
991 		bwr = (struct aac_blockwrite_response *)&cm->cm_fib->data[0];
992 		status = bwr->Status;
993 	}
994 	aac_release_command(cm);
995 
996 	/* fix up the bio based on status */
997 	if (status == ST_OK) {
998 		bp->bio_resid = 0;
999 	} else {
1000 		bp->bio_error = EIO;
1001 		bp->bio_flags |= BIO_ERROR;
1002 		/* pass an error string out to the disk layer */
1003 		bp->bio_driver1 = aac_describe_code(aac_command_status_table,
1004 						    status);
1005 	}
1006 	aac_biodone(bp);
1007 }
1008 
1009 /*
1010  * Submit a command to the controller, return when it completes.
1011  * XXX This is very dangerous!  If the card has gone out to lunch, we could
1012  *     be stuck here forever.  At the same time, signals are not caught
1013  *     because there is a risk that a signal could wakeup the tsleep before
1014  *     the card has a chance to complete the command.  The passed in timeout
1015  *     is ignored for the same reason.  Since there is no way to cancel a
1016  *     command in progress, we should probably create a 'dead' queue where
1017  *     commands go that have been interrupted/timed-out/etc, that keeps them
1018  *     out of the free pool.  That way, if the card is just slow, it won't
1019  *     spam the memory of a command that has been recycled.
1020  */
1021 static int
1022 aac_wait_command(struct aac_command *cm, int timeout)
1023 {
1024 	int s, error = 0;
1025 
1026 	debug_called(2);
1027 
1028 	/* Put the command on the ready queue and get things going */
1029 	cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
1030 	aac_enqueue_ready(cm);
1031 	aac_startio(cm->cm_sc);
1032 	s = splbio();
1033 	while (!(cm->cm_flags & AAC_CMD_COMPLETED) && (error != EWOULDBLOCK)) {
1034 		error = tsleep(cm, PRIBIO, "aacwait", 0);
1035 	}
1036 	splx(s);
1037 	return(error);
1038 }
1039 
1040 /*
1041  *Command Buffer Management
1042  */
1043 
1044 /*
1045  * Allocate a command.
1046  */
1047 int
1048 aac_alloc_command(struct aac_softc *sc, struct aac_command **cmp)
1049 {
1050 	struct aac_command *cm;
1051 
1052 	debug_called(3);
1053 
1054 	if ((cm = aac_dequeue_free(sc)) == NULL)
1055 		return(ENOMEM);
1056 
1057 	*cmp = cm;
1058 	return(0);
1059 }
1060 
1061 /*
1062  * Release a command back to the freelist.
1063  */
1064 void
1065 aac_release_command(struct aac_command *cm)
1066 {
1067 	debug_called(3);
1068 
1069 	/* (re)initialise the command/FIB */
1070 	cm->cm_sgtable = NULL;
1071 	cm->cm_flags = 0;
1072 	cm->cm_complete = NULL;
1073 	cm->cm_private = NULL;
1074 	cm->cm_fib->Header.XferState = AAC_FIBSTATE_EMPTY;
1075 	cm->cm_fib->Header.StructType = AAC_FIBTYPE_TFIB;
1076 	cm->cm_fib->Header.Flags = 0;
1077 	cm->cm_fib->Header.SenderSize = sizeof(struct aac_fib);
1078 
1079 	/*
1080 	 * These are duplicated in aac_start to cover the case where an
1081 	 * intermediate stage may have destroyed them.  They're left
1082 	 * initialised here for debugging purposes only.
1083 	 */
1084 	cm->cm_fib->Header.SenderFibAddress = (u_int32_t)cm->cm_fib;
1085 	cm->cm_fib->Header.ReceiverFibAddress = (u_int32_t)cm->cm_fibphys;
1086 	cm->cm_fib->Header.SenderData = 0;
1087 
1088 	aac_enqueue_free(cm);
1089 }
1090 
1091 /*
1092  * Map helper for command/FIB allocation.
1093  */
1094 static void
1095 aac_map_command_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1096 {
1097 	struct aac_softc *sc;
1098 
1099 	sc = (struct aac_softc *)arg;
1100 
1101 	debug_called(3);
1102 
1103 	sc->aac_fibphys = segs[0].ds_addr;
1104 }
1105 
1106 /*
1107  * Allocate and initialise commands/FIBs for this adapter.
1108  */
1109 static int
1110 aac_alloc_commands(struct aac_softc *sc)
1111 {
1112 	struct aac_command *cm;
1113 	int i;
1114 
1115 	debug_called(1);
1116 
1117 	/* allocate the FIBs in DMAable memory and load them */
1118 	if (bus_dmamem_alloc(sc->aac_fib_dmat, (void **)&sc->aac_fibs,
1119 			     BUS_DMA_NOWAIT, &sc->aac_fibmap)) {
1120 		printf("Not enough contiguous memory available.\n");
1121 		return (ENOMEM);
1122 	}
1123 
1124 	/*
1125 	 * Work around a bug in the 2120 and 2200 that cannot DMA commands
1126 	 * below address 8192 in physical memory.
1127 	 * XXX If the padding is not needed, can it be put to use instead
1128 	 * of ignored?
1129 	 */
1130 	bus_dmamap_load(sc->aac_fib_dmat, sc->aac_fibmap, sc->aac_fibs,
1131 			8192 + AAC_FIB_COUNT * sizeof(struct aac_fib),
1132 			aac_map_command_helper, sc, 0);
1133 
1134 	if (sc->aac_fibphys < 8192) {
1135 		sc->aac_fibs += (8192 / sizeof(struct aac_fib));
1136 		sc->aac_fibphys += 8192;
1137 	}
1138 
1139 	/* initialise constant fields in the command structure */
1140 	bzero(sc->aac_fibs, AAC_FIB_COUNT * sizeof(struct aac_fib));
1141 	for (i = 0; i < AAC_FIB_COUNT; i++) {
1142 		cm = &sc->aac_command[i];
1143 		cm->cm_sc = sc;
1144 		cm->cm_fib = sc->aac_fibs + i;
1145 		cm->cm_fibphys = sc->aac_fibphys + (i * sizeof(struct aac_fib));
1146 
1147 		if (!bus_dmamap_create(sc->aac_buffer_dmat, 0, &cm->cm_datamap))
1148 			aac_release_command(cm);
1149 	}
1150 	return (0);
1151 }
1152 
1153 /*
1154  * Free FIBs owned by this adapter.
1155  */
1156 static void
1157 aac_free_commands(struct aac_softc *sc)
1158 {
1159 	int i;
1160 
1161 	debug_called(1);
1162 
1163 	for (i = 0; i < AAC_FIB_COUNT; i++)
1164 		bus_dmamap_destroy(sc->aac_buffer_dmat,
1165 				   sc->aac_command[i].cm_datamap);
1166 
1167 	bus_dmamap_unload(sc->aac_fib_dmat, sc->aac_fibmap);
1168 	bus_dmamem_free(sc->aac_fib_dmat, sc->aac_fibs, sc->aac_fibmap);
1169 }
1170 
1171 /*
1172  * Command-mapping helper function - populate this command's s/g table.
1173  */
1174 static void
1175 aac_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1176 {
1177 	struct aac_command *cm;
1178 	struct aac_fib *fib;
1179 	struct aac_sg_table *sg;
1180 	int i;
1181 
1182 	debug_called(3);
1183 
1184 	cm = (struct aac_command *)arg;
1185 	fib = cm->cm_fib;
1186 
1187 	/* find the s/g table */
1188 	sg = cm->cm_sgtable;
1189 
1190 	/* copy into the FIB */
1191 	if (sg != NULL) {
1192 		sg->SgCount = nseg;
1193 		for (i = 0; i < nseg; i++) {
1194 			sg->SgEntry[i].SgAddress = segs[i].ds_addr;
1195 			sg->SgEntry[i].SgByteCount = segs[i].ds_len;
1196 		}
1197 		/* update the FIB size for the s/g count */
1198 		fib->Header.Size += nseg * sizeof(struct aac_sg_entry);
1199 	}
1200 
1201 }
1202 
1203 /*
1204  * Map a command into controller-visible space.
1205  */
1206 static void
1207 aac_map_command(struct aac_command *cm)
1208 {
1209 	struct aac_softc *sc;
1210 
1211 	debug_called(2);
1212 
1213 	sc = cm->cm_sc;
1214 
1215 	/* don't map more than once */
1216 	if (cm->cm_flags & AAC_CMD_MAPPED)
1217 		return;
1218 
1219 	if (cm->cm_datalen != 0) {
1220 		bus_dmamap_load(sc->aac_buffer_dmat, cm->cm_datamap,
1221 				cm->cm_data, cm->cm_datalen,
1222 				aac_map_command_sg, cm, 0);
1223 
1224 		if (cm->cm_flags & AAC_CMD_DATAIN)
1225 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1226 					BUS_DMASYNC_PREREAD);
1227 		if (cm->cm_flags & AAC_CMD_DATAOUT)
1228 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1229 					BUS_DMASYNC_PREWRITE);
1230 	}
1231 	cm->cm_flags |= AAC_CMD_MAPPED;
1232 }
1233 
1234 /*
1235  * Unmap a command from controller-visible space.
1236  */
1237 static void
1238 aac_unmap_command(struct aac_command *cm)
1239 {
1240 	struct aac_softc *sc;
1241 
1242 	debug_called(2);
1243 
1244 	sc = cm->cm_sc;
1245 
1246 	if (!(cm->cm_flags & AAC_CMD_MAPPED))
1247 		return;
1248 
1249 	if (cm->cm_datalen != 0) {
1250 		if (cm->cm_flags & AAC_CMD_DATAIN)
1251 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1252 					BUS_DMASYNC_POSTREAD);
1253 		if (cm->cm_flags & AAC_CMD_DATAOUT)
1254 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1255 					BUS_DMASYNC_POSTWRITE);
1256 
1257 		bus_dmamap_unload(sc->aac_buffer_dmat, cm->cm_datamap);
1258 	}
1259 	cm->cm_flags &= ~AAC_CMD_MAPPED;
1260 }
1261 
1262 /*
1263  * Hardware Interface
1264  */
1265 
1266 /*
1267  * Initialise the adapter.
1268  */
1269 static void
1270 aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1271 {
1272 	struct aac_softc *sc;
1273 
1274 	debug_called(1);
1275 
1276 	sc = (struct aac_softc *)arg;
1277 
1278 	sc->aac_common_busaddr = segs[0].ds_addr;
1279 }
1280 
1281 /*
1282  * Retrieve the firmware version numbers.  Dell PERC2/QC cards with
1283  * firmware version 1.x are not compatible with this driver.
1284  */
1285 static int
1286 aac_check_firmware(struct aac_softc *sc)
1287 {
1288 	u_int32_t major, minor;
1289 
1290 	debug_called(1);
1291 
1292 	if (sc->quirks & AAC_QUIRK_PERC2QC) {
1293 		if (aac_sync_command(sc, AAC_MONKER_GETKERNVER, 0, 0, 0, 0,
1294 				     NULL)) {
1295 			device_printf(sc->aac_dev,
1296 				      "Error reading firmware version\n");
1297 			return (EIO);
1298 		}
1299 
1300 		/* These numbers are stored as ASCII! */
1301 		major = (AAC_GETREG4(sc, AAC_SA_MAILBOX + 4) & 0xff) - 0x30;
1302 		minor = (AAC_GETREG4(sc, AAC_SA_MAILBOX + 8) & 0xff) - 0x30;
1303 		if (major == 1) {
1304 			device_printf(sc->aac_dev,
1305 			    "Firmware version %d.%d is not supported.\n",
1306 			    major, minor);
1307 			return (EINVAL);
1308 		}
1309 	}
1310 
1311 	return (0);
1312 }
1313 
1314 static int
1315 aac_init(struct aac_softc *sc)
1316 {
1317 	struct aac_adapter_init	*ip;
1318 	time_t then;
1319 	u_int32_t code;
1320 	u_int8_t *qaddr;
1321 
1322 	debug_called(1);
1323 
1324 	/*
1325 	 * First wait for the adapter to come ready.
1326 	 */
1327 	then = time_second;
1328 	do {
1329 		code = AAC_GET_FWSTATUS(sc);
1330 		if (code & AAC_SELF_TEST_FAILED) {
1331 			device_printf(sc->aac_dev, "FATAL: selftest failed\n");
1332 			return(ENXIO);
1333 		}
1334 		if (code & AAC_KERNEL_PANIC) {
1335 			device_printf(sc->aac_dev,
1336 				      "FATAL: controller kernel panic\n");
1337 			return(ENXIO);
1338 		}
1339 		if (time_second > (then + AAC_BOOT_TIMEOUT)) {
1340 			device_printf(sc->aac_dev,
1341 				      "FATAL: controller not coming ready, "
1342 					   "status %x\n", code);
1343 			return(ENXIO);
1344 		}
1345 	} while (!(code & AAC_UP_AND_RUNNING));
1346 
1347 	/*
1348 	 * Create DMA tag for the common structure and allocate it.
1349 	 */
1350 	if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1351 			       1, 0,			/* algnmnt, boundary */
1352 			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1353 			       BUS_SPACE_MAXADDR, 	/* highaddr */
1354 			       NULL, NULL, 		/* filter, filterarg */
1355 			       sizeof(struct aac_common), /* maxsize */
1356 			       1,			/* nsegments */
1357 			       BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1358 			       0,			/* flags */
1359 			       &sc->aac_common_dmat)) {
1360 		device_printf(sc->aac_dev,
1361 			      "can't allocate common structure DMA tag\n");
1362 		return(ENOMEM);
1363 	}
1364 	if (bus_dmamem_alloc(sc->aac_common_dmat, (void **)&sc->aac_common,
1365 			     BUS_DMA_NOWAIT, &sc->aac_common_dmamap)) {
1366 		device_printf(sc->aac_dev, "can't allocate common structure\n");
1367 		return(ENOMEM);
1368 	}
1369 	bus_dmamap_load(sc->aac_common_dmat, sc->aac_common_dmamap,
1370 			sc->aac_common, sizeof(*sc->aac_common), aac_common_map,
1371 			sc, 0);
1372 	bzero(sc->aac_common, sizeof(*sc->aac_common));
1373 
1374 	/*
1375 	 * Fill in the init structure.  This tells the adapter about the
1376 	 * physical location of various important shared data structures.
1377 	 */
1378 	ip = &sc->aac_common->ac_init;
1379 	ip->InitStructRevision = AAC_INIT_STRUCT_REVISION;
1380 	ip->MiniPortRevision = AAC_INIT_STRUCT_MINIPORT_REVISION;
1381 
1382 	ip->AdapterFibsPhysicalAddress = sc->aac_common_busaddr +
1383 					 offsetof(struct aac_common, ac_fibs);
1384 	ip->AdapterFibsVirtualAddress = (u_int32_t)&sc->aac_common->ac_fibs[0];
1385 	ip->AdapterFibsSize = AAC_ADAPTER_FIBS * sizeof(struct aac_fib);
1386 	ip->AdapterFibAlign = sizeof(struct aac_fib);
1387 
1388 	ip->PrintfBufferAddress = sc->aac_common_busaddr +
1389 				  offsetof(struct aac_common, ac_printf);
1390 	ip->PrintfBufferSize = AAC_PRINTF_BUFSIZE;
1391 
1392 	/* The adapter assumes that pages are 4K in size */
1393 	ip->HostPhysMemPages = ctob(physmem) / AAC_PAGE_SIZE;
1394 	ip->HostElapsedSeconds = time_second;	/* reset later if invalid */
1395 
1396 	/*
1397 	 * Initialise FIB queues.  Note that it appears that the layout of the
1398 	 * indexes and the segmentation of the entries may be mandated by the
1399 	 * adapter, which is only told about the base of the queue index fields.
1400 	 *
1401 	 * The initial values of the indices are assumed to inform the adapter
1402 	 * of the sizes of the respective queues, and theoretically it could
1403 	 * work out the entire layout of the queue structures from this.  We
1404 	 * take the easy route and just lay this area out like everyone else
1405 	 * does.
1406 	 *
1407 	 * The Linux driver uses a much more complex scheme whereby several
1408 	 * header records are kept for each queue.  We use a couple of generic
1409 	 * list manipulation functions which 'know' the size of each list by
1410 	 * virtue of a table.
1411 	 */
1412 	qaddr = &sc->aac_common->ac_qbuf[0] + AAC_QUEUE_ALIGN;
1413 	qaddr -= (u_int32_t)qaddr % AAC_QUEUE_ALIGN;
1414 	sc->aac_queues = (struct aac_queue_table *)qaddr;
1415 	ip->CommHeaderAddress = sc->aac_common_busaddr +
1416 				((u_int32_t)sc->aac_queues -
1417 				(u_int32_t)sc->aac_common);
1418 
1419 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1420 		AAC_HOST_NORM_CMD_ENTRIES;
1421 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1422 		AAC_HOST_NORM_CMD_ENTRIES;
1423 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1424 		AAC_HOST_HIGH_CMD_ENTRIES;
1425 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1426 		AAC_HOST_HIGH_CMD_ENTRIES;
1427 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1428 		AAC_ADAP_NORM_CMD_ENTRIES;
1429 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1430 		AAC_ADAP_NORM_CMD_ENTRIES;
1431 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1432 		AAC_ADAP_HIGH_CMD_ENTRIES;
1433 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1434 		AAC_ADAP_HIGH_CMD_ENTRIES;
1435 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1436 		AAC_HOST_NORM_RESP_ENTRIES;
1437 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1438 		AAC_HOST_NORM_RESP_ENTRIES;
1439 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1440 		AAC_HOST_HIGH_RESP_ENTRIES;
1441 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1442 		AAC_HOST_HIGH_RESP_ENTRIES;
1443 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1444 		AAC_ADAP_NORM_RESP_ENTRIES;
1445 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1446 		AAC_ADAP_NORM_RESP_ENTRIES;
1447 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1448 		AAC_ADAP_HIGH_RESP_ENTRIES;
1449 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1450 		AAC_ADAP_HIGH_RESP_ENTRIES;
1451 	sc->aac_qentries[AAC_HOST_NORM_CMD_QUEUE] =
1452 		&sc->aac_queues->qt_HostNormCmdQueue[0];
1453 	sc->aac_qentries[AAC_HOST_HIGH_CMD_QUEUE] =
1454 		&sc->aac_queues->qt_HostHighCmdQueue[0];
1455 	sc->aac_qentries[AAC_ADAP_NORM_CMD_QUEUE] =
1456 		&sc->aac_queues->qt_AdapNormCmdQueue[0];
1457 	sc->aac_qentries[AAC_ADAP_HIGH_CMD_QUEUE] =
1458 		&sc->aac_queues->qt_AdapHighCmdQueue[0];
1459 	sc->aac_qentries[AAC_HOST_NORM_RESP_QUEUE] =
1460 		&sc->aac_queues->qt_HostNormRespQueue[0];
1461 	sc->aac_qentries[AAC_HOST_HIGH_RESP_QUEUE] =
1462 		&sc->aac_queues->qt_HostHighRespQueue[0];
1463 	sc->aac_qentries[AAC_ADAP_NORM_RESP_QUEUE] =
1464 		&sc->aac_queues->qt_AdapNormRespQueue[0];
1465 	sc->aac_qentries[AAC_ADAP_HIGH_RESP_QUEUE] =
1466 		&sc->aac_queues->qt_AdapHighRespQueue[0];
1467 
1468 	/*
1469 	 * Do controller-type-specific initialisation
1470 	 */
1471 	switch (sc->aac_hwif) {
1472 	case AAC_HWIF_I960RX:
1473 		AAC_SETREG4(sc, AAC_RX_ODBR, ~0);
1474 		break;
1475 	}
1476 
1477 	/*
1478 	 * Give the init structure to the controller.
1479 	 */
1480 	if (aac_sync_command(sc, AAC_MONKER_INITSTRUCT,
1481 			     sc->aac_common_busaddr +
1482 			     offsetof(struct aac_common, ac_init), 0, 0, 0,
1483 			     NULL)) {
1484 		device_printf(sc->aac_dev,
1485 			      "error establishing init structure\n");
1486 		return(EIO);
1487 	}
1488 
1489 	return(0);
1490 }
1491 
1492 /*
1493  * Send a synchronous command to the controller and wait for a result.
1494  */
1495 static int
1496 aac_sync_command(struct aac_softc *sc, u_int32_t command,
1497 		 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3,
1498 		 u_int32_t *sp)
1499 {
1500 	time_t then;
1501 	u_int32_t status;
1502 
1503 	debug_called(3);
1504 
1505 	/* populate the mailbox */
1506 	AAC_SET_MAILBOX(sc, command, arg0, arg1, arg2, arg3);
1507 
1508 	/* ensure the sync command doorbell flag is cleared */
1509 	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1510 
1511 	/* then set it to signal the adapter */
1512 	AAC_QNOTIFY(sc, AAC_DB_SYNC_COMMAND);
1513 
1514 	/* spin waiting for the command to complete */
1515 	then = time_second;
1516 	do {
1517 		if (time_second > (then + AAC_IMMEDIATE_TIMEOUT)) {
1518 			debug(2, "timed out");
1519 			return(EIO);
1520 		}
1521 	} while (!(AAC_GET_ISTATUS(sc) & AAC_DB_SYNC_COMMAND));
1522 
1523 	/* clear the completion flag */
1524 	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1525 
1526 	/* get the command status */
1527 	status = AAC_GET_MAILBOXSTATUS(sc);
1528 	if (sp != NULL)
1529 		*sp = status;
1530 	return(0);
1531 }
1532 
1533 /*
1534  * Grab the sync fib area.
1535  */
1536 int
1537 aac_alloc_sync_fib(struct aac_softc *sc, struct aac_fib **fib, int flags)
1538 {
1539 
1540 	/*
1541 	 * If the force flag is set, the system is shutting down, or in
1542 	 * trouble.  Ignore the mutex.
1543 	 */
1544 	if (!(flags & AAC_SYNC_LOCK_FORCE))
1545 		AAC_LOCK_ACQUIRE(&sc->aac_sync_lock);
1546 
1547 	*fib = &sc->aac_common->ac_sync_fib;
1548 
1549 	return (1);
1550 }
1551 
1552 /*
1553  * Release the sync fib area.
1554  */
1555 void
1556 aac_release_sync_fib(struct aac_softc *sc)
1557 {
1558 
1559 	AAC_LOCK_RELEASE(&sc->aac_sync_lock);
1560 }
1561 
1562 /*
1563  * Send a synchronous FIB to the controller and wait for a result.
1564  */
1565 int
1566 aac_sync_fib(struct aac_softc *sc, u_int32_t command, u_int32_t xferstate,
1567 		 struct aac_fib *fib, u_int16_t datasize)
1568 {
1569 	debug_called(3);
1570 
1571 	if (datasize > AAC_FIB_DATASIZE)
1572 		return(EINVAL);
1573 
1574 	/*
1575 	 * Set up the sync FIB
1576 	 */
1577 	fib->Header.XferState = AAC_FIBSTATE_HOSTOWNED |
1578 				AAC_FIBSTATE_INITIALISED |
1579 				AAC_FIBSTATE_EMPTY;
1580 	fib->Header.XferState |= xferstate;
1581 	fib->Header.Command = command;
1582 	fib->Header.StructType = AAC_FIBTYPE_TFIB;
1583 	fib->Header.Size = sizeof(struct aac_fib) + datasize;
1584 	fib->Header.SenderSize = sizeof(struct aac_fib);
1585 	fib->Header.SenderFibAddress = (u_int32_t)fib;
1586 	fib->Header.ReceiverFibAddress = sc->aac_common_busaddr +
1587 					 offsetof(struct aac_common,
1588 						  ac_sync_fib);
1589 
1590 	/*
1591 	 * Give the FIB to the controller, wait for a response.
1592 	 */
1593 	if (aac_sync_command(sc, AAC_MONKER_SYNCFIB,
1594 			     fib->Header.ReceiverFibAddress, 0, 0, 0, NULL)) {
1595 		debug(2, "IO error");
1596 		return(EIO);
1597 	}
1598 
1599 	return (0);
1600 }
1601 
1602 /*
1603  * Adapter-space FIB queue manipulation
1604  *
1605  * Note that the queue implementation here is a little funky; neither the PI or
1606  * CI will ever be zero.  This behaviour is a controller feature.
1607  */
1608 static struct {
1609 	int		size;
1610 	int		notify;
1611 } aac_qinfo[] = {
1612 	{AAC_HOST_NORM_CMD_ENTRIES, AAC_DB_COMMAND_NOT_FULL},
1613 	{AAC_HOST_HIGH_CMD_ENTRIES, 0},
1614 	{AAC_ADAP_NORM_CMD_ENTRIES, AAC_DB_COMMAND_READY},
1615 	{AAC_ADAP_HIGH_CMD_ENTRIES, 0},
1616 	{AAC_HOST_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_NOT_FULL},
1617 	{AAC_HOST_HIGH_RESP_ENTRIES, 0},
1618 	{AAC_ADAP_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_READY},
1619 	{AAC_ADAP_HIGH_RESP_ENTRIES, 0}
1620 };
1621 
1622 /*
1623  * Atomically insert an entry into the nominated queue, returns 0 on success or
1624  * EBUSY if the queue is full.
1625  *
1626  * Note: it would be more efficient to defer notifying the controller in
1627  *	 the case where we may be inserting several entries in rapid succession,
1628  *	 but implementing this usefully may be difficult (it would involve a
1629  *	 separate queue/notify interface).
1630  */
1631 static int
1632 aac_enqueue_fib(struct aac_softc *sc, int queue, struct aac_command *cm)
1633 {
1634 	u_int32_t pi, ci;
1635 	int s, error;
1636 	u_int32_t fib_size;
1637 	u_int32_t fib_addr;
1638 
1639 	debug_called(3);
1640 
1641 	fib_size = cm->cm_fib->Header.Size;
1642 	fib_addr = cm->cm_fib->Header.ReceiverFibAddress;
1643 
1644 	s = splbio();
1645 
1646 	/* get the producer/consumer indices */
1647 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1648 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1649 
1650 	/* wrap the queue? */
1651 	if (pi >= aac_qinfo[queue].size)
1652 		pi = 0;
1653 
1654 	/* check for queue full */
1655 	if ((pi + 1) == ci) {
1656 		error = EBUSY;
1657 		goto out;
1658 	}
1659 
1660 	/* populate queue entry */
1661 	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1662 	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1663 
1664 	/* update producer index */
1665 	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1666 
1667 	/*
1668 	 * To avoid a race with its completion interrupt, place this command on
1669 	 * the busy queue prior to advertising it to the controller.
1670 	 */
1671 	aac_enqueue_busy(cm);
1672 
1673 	/* notify the adapter if we know how */
1674 	if (aac_qinfo[queue].notify != 0)
1675 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1676 
1677 	error = 0;
1678 
1679 out:
1680 	splx(s);
1681 	return(error);
1682 }
1683 
1684 /*
1685  * Atomically remove one entry from the nominated queue, returns 0 on
1686  * success or ENOENT if the queue is empty.
1687  */
1688 static int
1689 aac_dequeue_fib(struct aac_softc *sc, int queue, u_int32_t *fib_size,
1690 		struct aac_fib **fib_addr)
1691 {
1692 	u_int32_t pi, ci;
1693 	int s, error;
1694 	int notify;
1695 
1696 	debug_called(3);
1697 
1698 	s = splbio();
1699 
1700 	/* get the producer/consumer indices */
1701 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1702 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1703 
1704 	/* check for queue empty */
1705 	if (ci == pi) {
1706 		error = ENOENT;
1707 		goto out;
1708 	}
1709 
1710 	notify = 0;
1711 	if (ci == pi + 1)
1712 		notify++;
1713 
1714 	/* wrap the queue? */
1715 	if (ci >= aac_qinfo[queue].size)
1716 		ci = 0;
1717 
1718 	/* fetch the entry */
1719 	*fib_size = (sc->aac_qentries[queue] + ci)->aq_fib_size;
1720 	*fib_addr = (struct aac_fib *)(sc->aac_qentries[queue] +
1721 				       ci)->aq_fib_addr;
1722 
1723 	/*
1724 	 * Is this a fast response? If it is, update the fib fields in
1725 	 * local memory so the whole fib doesn't have to be DMA'd back up.
1726 	 */
1727 	if (*(uintptr_t *)fib_addr & 0x01) {
1728 		*(uintptr_t *)fib_addr &= ~0x01;
1729 		(*fib_addr)->Header.XferState |= AAC_FIBSTATE_DONEADAP;
1730 		*((u_int32_t*)((*fib_addr)->data)) = AAC_ERROR_NORMAL;
1731 	}
1732 	/* update consumer index */
1733 	sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX] = ci + 1;
1734 
1735 	/* if we have made the queue un-full, notify the adapter */
1736 	if (notify && (aac_qinfo[queue].notify != 0))
1737 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1738 	error = 0;
1739 
1740 out:
1741 	splx(s);
1742 	return(error);
1743 }
1744 
1745 /*
1746  * Put our response to an Adapter Initialed Fib on the response queue
1747  */
1748 static int
1749 aac_enqueue_response(struct aac_softc *sc, int queue, struct aac_fib *fib)
1750 {
1751 	u_int32_t pi, ci;
1752 	int s, error;
1753 	u_int32_t fib_size;
1754 	u_int32_t fib_addr;
1755 
1756 	debug_called(1);
1757 
1758 	/* Tell the adapter where the FIB is */
1759 	fib_size = fib->Header.Size;
1760 	fib_addr = fib->Header.SenderFibAddress;
1761 	fib->Header.ReceiverFibAddress = fib_addr;
1762 
1763 	s = splbio();
1764 
1765 	/* get the producer/consumer indices */
1766 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1767 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1768 
1769 	/* wrap the queue? */
1770 	if (pi >= aac_qinfo[queue].size)
1771 		pi = 0;
1772 
1773 	/* check for queue full */
1774 	if ((pi + 1) == ci) {
1775 		error = EBUSY;
1776 		goto out;
1777 	}
1778 
1779 	/* populate queue entry */
1780 	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1781 	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1782 
1783 	/* update producer index */
1784 	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1785 
1786 	/* notify the adapter if we know how */
1787 	if (aac_qinfo[queue].notify != 0)
1788 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1789 
1790 	error = 0;
1791 
1792 out:
1793 	splx(s);
1794 	return(error);
1795 }
1796 
1797 /*
1798  * Check for commands that have been outstanding for a suspiciously long time,
1799  * and complain about them.
1800  */
1801 static void
1802 aac_timeout(struct aac_softc *sc)
1803 {
1804 	int s;
1805 	struct aac_command *cm;
1806 	time_t deadline;
1807 
1808 #if 0
1809 	/* simulate an interrupt to handle possibly-missed interrupts */
1810 	/*
1811 	 * XXX This was done to work around another bug which has since been
1812 	 * fixed.  It is dangerous anyways because you don't want multiple
1813 	 * threads in the interrupt handler at the same time!  If calling
1814 	 * is deamed neccesary in the future, proper mutexes must be used.
1815 	 */
1816 	s = splbio();
1817 	aac_intr(sc);
1818 	splx(s);
1819 
1820 	/* kick the I/O queue to restart it in the case of deadlock */
1821 	aac_startio(sc);
1822 #endif
1823 
1824 	/*
1825 	 * traverse the busy command list, bitch about late commands once
1826 	 * only.
1827 	 */
1828 	deadline = time_second - AAC_CMD_TIMEOUT;
1829 	s = splbio();
1830 	TAILQ_FOREACH(cm, &sc->aac_busy, cm_link) {
1831 		if ((cm->cm_timestamp  < deadline)
1832 			/* && !(cm->cm_flags & AAC_CMD_TIMEDOUT) */) {
1833 			cm->cm_flags |= AAC_CMD_TIMEDOUT;
1834 			device_printf(sc->aac_dev,
1835 				      "COMMAND %p TIMEOUT AFTER %d SECONDS\n",
1836 				      cm, (int)(time_second-cm->cm_timestamp));
1837 			AAC_PRINT_FIB(sc, cm->cm_fib);
1838 		}
1839 	}
1840 	splx(s);
1841 
1842 	/* reset the timer for next time */
1843 	timeout((timeout_t*)aac_timeout, sc, AAC_PERIODIC_INTERVAL * hz);
1844 	return;
1845 }
1846 
1847 /*
1848  * Interface Function Vectors
1849  */
1850 
1851 /*
1852  * Read the current firmware status word.
1853  */
1854 static int
1855 aac_sa_get_fwstatus(struct aac_softc *sc)
1856 {
1857 	debug_called(3);
1858 
1859 	return(AAC_GETREG4(sc, AAC_SA_FWSTATUS));
1860 }
1861 
1862 static int
1863 aac_rx_get_fwstatus(struct aac_softc *sc)
1864 {
1865 	debug_called(3);
1866 
1867 	return(AAC_GETREG4(sc, AAC_RX_FWSTATUS));
1868 }
1869 
1870 static int
1871 aac_fa_get_fwstatus(struct aac_softc *sc)
1872 {
1873 	int val;
1874 
1875 	debug_called(3);
1876 
1877 	val = AAC_GETREG4(sc, AAC_FA_FWSTATUS);
1878 	return (val);
1879 }
1880 
1881 /*
1882  * Notify the controller of a change in a given queue
1883  */
1884 
1885 static void
1886 aac_sa_qnotify(struct aac_softc *sc, int qbit)
1887 {
1888 	debug_called(3);
1889 
1890 	AAC_SETREG2(sc, AAC_SA_DOORBELL1_SET, qbit);
1891 }
1892 
1893 static void
1894 aac_rx_qnotify(struct aac_softc *sc, int qbit)
1895 {
1896 	debug_called(3);
1897 
1898 	AAC_SETREG4(sc, AAC_RX_IDBR, qbit);
1899 }
1900 
1901 static void
1902 aac_fa_qnotify(struct aac_softc *sc, int qbit)
1903 {
1904 	debug_called(3);
1905 
1906 	AAC_SETREG2(sc, AAC_FA_DOORBELL1, qbit);
1907 	AAC_FA_HACK(sc);
1908 }
1909 
1910 /*
1911  * Get the interrupt reason bits
1912  */
1913 static int
1914 aac_sa_get_istatus(struct aac_softc *sc)
1915 {
1916 	debug_called(3);
1917 
1918 	return(AAC_GETREG2(sc, AAC_SA_DOORBELL0));
1919 }
1920 
1921 static int
1922 aac_rx_get_istatus(struct aac_softc *sc)
1923 {
1924 	debug_called(3);
1925 
1926 	return(AAC_GETREG4(sc, AAC_RX_ODBR));
1927 }
1928 
1929 static int
1930 aac_fa_get_istatus(struct aac_softc *sc)
1931 {
1932 	int val;
1933 
1934 	debug_called(3);
1935 
1936 	val = AAC_GETREG2(sc, AAC_FA_DOORBELL0);
1937 	return (val);
1938 }
1939 
1940 /*
1941  * Clear some interrupt reason bits
1942  */
1943 static void
1944 aac_sa_clear_istatus(struct aac_softc *sc, int mask)
1945 {
1946 	debug_called(3);
1947 
1948 	AAC_SETREG2(sc, AAC_SA_DOORBELL0_CLEAR, mask);
1949 }
1950 
1951 static void
1952 aac_rx_clear_istatus(struct aac_softc *sc, int mask)
1953 {
1954 	debug_called(3);
1955 
1956 	AAC_SETREG4(sc, AAC_RX_ODBR, mask);
1957 }
1958 
1959 static void
1960 aac_fa_clear_istatus(struct aac_softc *sc, int mask)
1961 {
1962 	debug_called(3);
1963 
1964 	AAC_SETREG2(sc, AAC_FA_DOORBELL0_CLEAR, mask);
1965 	AAC_FA_HACK(sc);
1966 }
1967 
1968 /*
1969  * Populate the mailbox and set the command word
1970  */
1971 static void
1972 aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
1973 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
1974 {
1975 	debug_called(4);
1976 
1977 	AAC_SETREG4(sc, AAC_SA_MAILBOX, command);
1978 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 4, arg0);
1979 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 8, arg1);
1980 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 12, arg2);
1981 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 16, arg3);
1982 }
1983 
1984 static void
1985 aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
1986 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
1987 {
1988 	debug_called(4);
1989 
1990 	AAC_SETREG4(sc, AAC_RX_MAILBOX, command);
1991 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 4, arg0);
1992 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 8, arg1);
1993 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 12, arg2);
1994 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 16, arg3);
1995 }
1996 
1997 static void
1998 aac_fa_set_mailbox(struct aac_softc *sc, u_int32_t command,
1999 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2000 {
2001 	debug_called(4);
2002 
2003 	AAC_SETREG4(sc, AAC_FA_MAILBOX, command);
2004 	AAC_FA_HACK(sc);
2005 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 4, arg0);
2006 	AAC_FA_HACK(sc);
2007 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 8, arg1);
2008 	AAC_FA_HACK(sc);
2009 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 12, arg2);
2010 	AAC_FA_HACK(sc);
2011 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 16, arg3);
2012 	AAC_FA_HACK(sc);
2013 }
2014 
2015 /*
2016  * Fetch the immediate command status word
2017  */
2018 static int
2019 aac_sa_get_mailboxstatus(struct aac_softc *sc)
2020 {
2021 	debug_called(4);
2022 
2023 	return(AAC_GETREG4(sc, AAC_SA_MAILBOX));
2024 }
2025 
2026 static int
2027 aac_rx_get_mailboxstatus(struct aac_softc *sc)
2028 {
2029 	debug_called(4);
2030 
2031 	return(AAC_GETREG4(sc, AAC_RX_MAILBOX));
2032 }
2033 
2034 static int
2035 aac_fa_get_mailboxstatus(struct aac_softc *sc)
2036 {
2037 	int val;
2038 
2039 	debug_called(4);
2040 
2041 	val = AAC_GETREG4(sc, AAC_FA_MAILBOX);
2042 	return (val);
2043 }
2044 
2045 /*
2046  * Set/clear interrupt masks
2047  */
2048 static void
2049 aac_sa_set_interrupts(struct aac_softc *sc, int enable)
2050 {
2051 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2052 
2053 	if (enable) {
2054 		AAC_SETREG2((sc), AAC_SA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2055 	} else {
2056 		AAC_SETREG2((sc), AAC_SA_MASK0_SET, ~0);
2057 	}
2058 }
2059 
2060 static void
2061 aac_rx_set_interrupts(struct aac_softc *sc, int enable)
2062 {
2063 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2064 
2065 	if (enable) {
2066 		AAC_SETREG4(sc, AAC_RX_OIMR, ~AAC_DB_INTERRUPTS);
2067 	} else {
2068 		AAC_SETREG4(sc, AAC_RX_OIMR, ~0);
2069 	}
2070 }
2071 
2072 static void
2073 aac_fa_set_interrupts(struct aac_softc *sc, int enable)
2074 {
2075 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2076 
2077 	if (enable) {
2078 		AAC_SETREG2((sc), AAC_FA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2079 		AAC_FA_HACK(sc);
2080 	} else {
2081 		AAC_SETREG2((sc), AAC_FA_MASK0, ~0);
2082 		AAC_FA_HACK(sc);
2083 	}
2084 }
2085 
2086 /*
2087  * Debugging and Diagnostics
2088  */
2089 
2090 /*
2091  * Print some information about the controller.
2092  */
2093 static void
2094 aac_describe_controller(struct aac_softc *sc)
2095 {
2096 	struct aac_fib *fib;
2097 	struct aac_adapter_info	*info;
2098 
2099 	debug_called(2);
2100 
2101 	aac_alloc_sync_fib(sc, &fib, 0);
2102 
2103 	fib->data[0] = 0;
2104 	if (aac_sync_fib(sc, RequestAdapterInfo, 0, fib, 1)) {
2105 		device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
2106 		aac_release_sync_fib(sc);
2107 		return;
2108 	}
2109 	info = (struct aac_adapter_info *)&fib->data[0];
2110 
2111 	device_printf(sc->aac_dev, "%s %dMHz, %dMB cache memory, %s\n",
2112 		      aac_describe_code(aac_cpu_variant, info->CpuVariant),
2113 		      info->ClockSpeed, info->BufferMem / (1024 * 1024),
2114 		      aac_describe_code(aac_battery_platform,
2115 					info->batteryPlatform));
2116 
2117 	/* save the kernel revision structure for later use */
2118 	sc->aac_revision = info->KernelRevision;
2119 	device_printf(sc->aac_dev, "Kernel %d.%d-%d, Build %d, S/N %6X\n",
2120 		      info->KernelRevision.external.comp.major,
2121 		      info->KernelRevision.external.comp.minor,
2122 		      info->KernelRevision.external.comp.dash,
2123 		      info->KernelRevision.buildNumber,
2124 		      (u_int32_t)(info->SerialNumber & 0xffffff));
2125 
2126 	aac_release_sync_fib(sc);
2127 }
2128 
2129 /*
2130  * Look up a text description of a numeric error code and return a pointer to
2131  * same.
2132  */
2133 static char *
2134 aac_describe_code(struct aac_code_lookup *table, u_int32_t code)
2135 {
2136 	int i;
2137 
2138 	for (i = 0; table[i].string != NULL; i++)
2139 		if (table[i].code == code)
2140 			return(table[i].string);
2141 	return(table[i + 1].string);
2142 }
2143 
2144 /*
2145  * Management Interface
2146  */
2147 
2148 static int
2149 aac_open(dev_t dev, int flags, int fmt, d_thread_t *td)
2150 {
2151 	struct aac_softc *sc;
2152 
2153 	debug_called(2);
2154 
2155 	sc = dev->si_drv1;
2156 
2157 	/* Check to make sure the device isn't already open */
2158 	if (sc->aac_state & AAC_STATE_OPEN) {
2159 		return EBUSY;
2160 	}
2161 	sc->aac_state |= AAC_STATE_OPEN;
2162 
2163 	return 0;
2164 }
2165 
2166 static int
2167 aac_close(dev_t dev, int flags, int fmt, d_thread_t *td)
2168 {
2169 	struct aac_softc *sc;
2170 
2171 	debug_called(2);
2172 
2173 	sc = dev->si_drv1;
2174 
2175 	/* Mark this unit as no longer open  */
2176 	sc->aac_state &= ~AAC_STATE_OPEN;
2177 
2178 	return 0;
2179 }
2180 
2181 static int
2182 aac_ioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, d_thread_t *td)
2183 {
2184 	union aac_statrequest *as;
2185 	struct aac_softc *sc;
2186 	int error = 0;
2187 	int i;
2188 
2189 	debug_called(2);
2190 
2191 	as = (union aac_statrequest *)arg;
2192 	sc = dev->si_drv1;
2193 
2194 	switch (cmd) {
2195 	case AACIO_STATS:
2196 		switch (as->as_item) {
2197 		case AACQ_FREE:
2198 		case AACQ_BIO:
2199 		case AACQ_READY:
2200 		case AACQ_BUSY:
2201 		case AACQ_COMPLETE:
2202 			bcopy(&sc->aac_qstat[as->as_item], &as->as_qstat,
2203 			      sizeof(struct aac_qstat));
2204 			break;
2205 		default:
2206 			error = ENOENT;
2207 			break;
2208 		}
2209 	break;
2210 
2211 	case FSACTL_SENDFIB:
2212 		arg = *(caddr_t*)arg;
2213 	case FSACTL_LNX_SENDFIB:
2214 		debug(1, "FSACTL_SENDFIB");
2215 		error = aac_ioctl_sendfib(sc, arg);
2216 		break;
2217 	case FSACTL_AIF_THREAD:
2218 	case FSACTL_LNX_AIF_THREAD:
2219 		debug(1, "FSACTL_AIF_THREAD");
2220 		error = EINVAL;
2221 		break;
2222 	case FSACTL_OPEN_GET_ADAPTER_FIB:
2223 		arg = *(caddr_t*)arg;
2224 	case FSACTL_LNX_OPEN_GET_ADAPTER_FIB:
2225 		debug(1, "FSACTL_OPEN_GET_ADAPTER_FIB");
2226 		/*
2227 		 * Pass the caller out an AdapterFibContext.
2228 		 *
2229 		 * Note that because we only support one opener, we
2230 		 * basically ignore this.  Set the caller's context to a magic
2231 		 * number just in case.
2232 		 *
2233 		 * The Linux code hands the driver a pointer into kernel space,
2234 		 * and then trusts it when the caller hands it back.  Aiee!
2235 		 * Here, we give it the proc pointer of the per-adapter aif
2236 		 * thread. It's only used as a sanity check in other calls.
2237 		 */
2238 		i = (int)sc->aifthread;
2239 		error = copyout(&i, arg, sizeof(i));
2240 		break;
2241 	case FSACTL_GET_NEXT_ADAPTER_FIB:
2242 		arg = *(caddr_t*)arg;
2243 	case FSACTL_LNX_GET_NEXT_ADAPTER_FIB:
2244 		debug(1, "FSACTL_GET_NEXT_ADAPTER_FIB");
2245 		error = aac_getnext_aif(sc, arg);
2246 		break;
2247 	case FSACTL_CLOSE_GET_ADAPTER_FIB:
2248 	case FSACTL_LNX_CLOSE_GET_ADAPTER_FIB:
2249 		debug(1, "FSACTL_CLOSE_GET_ADAPTER_FIB");
2250 		/* don't do anything here */
2251 		break;
2252 	case FSACTL_MINIPORT_REV_CHECK:
2253 		arg = *(caddr_t*)arg;
2254 	case FSACTL_LNX_MINIPORT_REV_CHECK:
2255 		debug(1, "FSACTL_MINIPORT_REV_CHECK");
2256 		error = aac_rev_check(sc, arg);
2257 		break;
2258 	case FSACTL_QUERY_DISK:
2259 		arg = *(caddr_t*)arg;
2260 	case FSACTL_LNX_QUERY_DISK:
2261 		debug(1, "FSACTL_QUERY_DISK");
2262 		error = aac_query_disk(sc, arg);
2263 			break;
2264 	case FSACTL_DELETE_DISK:
2265 	case FSACTL_LNX_DELETE_DISK:
2266 		/*
2267 		 * We don't trust the underland to tell us when to delete a
2268 		 * container, rather we rely on an AIF coming from the
2269 		 * controller
2270 		 */
2271 		error = 0;
2272 		break;
2273 	default:
2274 		debug(1, "unsupported cmd 0x%lx\n", cmd);
2275 		error = EINVAL;
2276 		break;
2277 	}
2278 	return(error);
2279 }
2280 
2281 static int
2282 aac_poll(dev_t dev, int poll_events, d_thread_t *td)
2283 {
2284 	struct aac_softc *sc;
2285 	int revents;
2286 
2287 	sc = dev->si_drv1;
2288 	revents = 0;
2289 
2290 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2291 	if ((poll_events & (POLLRDNORM | POLLIN)) != 0) {
2292 		if (sc->aac_aifq_tail != sc->aac_aifq_head)
2293 			revents |= poll_events & (POLLIN | POLLRDNORM);
2294 	}
2295 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2296 
2297 	if (revents == 0) {
2298 		if (poll_events & (POLLIN | POLLRDNORM))
2299 			selrecord(td, &sc->rcv_select);
2300 	}
2301 
2302 	return (revents);
2303 }
2304 
2305 /*
2306  * Send a FIB supplied from userspace
2307  */
2308 static int
2309 aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib)
2310 {
2311 	struct aac_command *cm;
2312 	int size, error;
2313 
2314 	debug_called(2);
2315 
2316 	cm = NULL;
2317 
2318 	/*
2319 	 * Get a command
2320 	 */
2321 	if (aac_alloc_command(sc, &cm)) {
2322 		error = EBUSY;
2323 		goto out;
2324 	}
2325 
2326 	/*
2327 	 * Fetch the FIB header, then re-copy to get data as well.
2328 	 */
2329 	if ((error = copyin(ufib, cm->cm_fib,
2330 			    sizeof(struct aac_fib_header))) != 0)
2331 		goto out;
2332 	size = cm->cm_fib->Header.Size + sizeof(struct aac_fib_header);
2333 	if (size > sizeof(struct aac_fib)) {
2334 		device_printf(sc->aac_dev, "incoming FIB oversized (%d > %d)\n",
2335 			      size, sizeof(struct aac_fib));
2336 		size = sizeof(struct aac_fib);
2337 	}
2338 	if ((error = copyin(ufib, cm->cm_fib, size)) != 0)
2339 		goto out;
2340 	cm->cm_fib->Header.Size = size;
2341 	cm->cm_timestamp = time_second;
2342 
2343 	/*
2344 	 * Pass the FIB to the controller, wait for it to complete.
2345 	 */
2346 	if ((error = aac_wait_command(cm, 30)) != 0) {	/* XXX user timeout? */
2347 		printf("aac_wait_command return %d\n", error);
2348 		goto out;
2349 	}
2350 
2351 	/*
2352 	 * Copy the FIB and data back out to the caller.
2353 	 */
2354 	size = cm->cm_fib->Header.Size;
2355 	if (size > sizeof(struct aac_fib)) {
2356 		device_printf(sc->aac_dev, "outbound FIB oversized (%d > %d)\n",
2357 			      size, sizeof(struct aac_fib));
2358 		size = sizeof(struct aac_fib);
2359 	}
2360 	error = copyout(cm->cm_fib, ufib, size);
2361 
2362 out:
2363 	if (cm != NULL) {
2364 		aac_release_command(cm);
2365 	}
2366 	return(error);
2367 }
2368 
2369 /*
2370  * Handle an AIF sent to us by the controller; queue it for later reference.
2371  * If the queue fills up, then drop the older entries.
2372  */
2373 static void
2374 aac_handle_aif(struct aac_softc *sc, struct aac_fib *fib)
2375 {
2376 	struct aac_aif_command *aif;
2377 	struct aac_container *co, *co_next;
2378 	struct aac_mntinfo *mi;
2379 	struct aac_mntinforesp *mir = NULL;
2380 	u_int16_t rsize;
2381 	int next, found;
2382 	int added = 0, i = 0;
2383 
2384 	debug_called(2);
2385 
2386 	aif = (struct aac_aif_command*)&fib->data[0];
2387 	aac_print_aif(sc, aif);
2388 
2389 	/* Is it an event that we should care about? */
2390 	switch (aif->command) {
2391 	case AifCmdEventNotify:
2392 		switch (aif->data.EN.type) {
2393 		case AifEnAddContainer:
2394 		case AifEnDeleteContainer:
2395 			/*
2396 			 * A container was added or deleted, but the message
2397 			 * doesn't tell us anything else!  Re-enumerate the
2398 			 * containers and sort things out.
2399 			 */
2400 			aac_alloc_sync_fib(sc, &fib, 0);
2401 			mi = (struct aac_mntinfo *)&fib->data[0];
2402 			do {
2403 				/*
2404 				 * Ask the controller for its containers one at
2405 				 * a time.
2406 				 * XXX What if the controller's list changes
2407 				 * midway through this enumaration?
2408 				 * XXX This should be done async.
2409 				 */
2410 				bzero(mi, sizeof(struct aac_mntinfo));
2411 				mi->Command = VM_NameServe;
2412 				mi->MntType = FT_FILESYS;
2413 				mi->MntCount = i;
2414 				rsize = sizeof(mir);
2415 				if (aac_sync_fib(sc, ContainerCommand, 0, fib,
2416 						 sizeof(struct aac_mntinfo))) {
2417 					debug(2, "Error probing container %d\n",
2418 					      i);
2419 					continue;
2420 				}
2421 				mir = (struct aac_mntinforesp *)&fib->data[0];
2422 				/*
2423 				 * Check the container against our list.
2424 				 * co->co_found was already set to 0 in a
2425 				 * previous run.
2426 				 */
2427 				if ((mir->Status == ST_OK) &&
2428 				    (mir->MntTable[0].VolType != CT_NONE)) {
2429 					found = 0;
2430 					TAILQ_FOREACH(co,
2431 						      &sc->aac_container_tqh,
2432 						      co_link) {
2433 						if (co->co_mntobj.ObjectId ==
2434 						    mir->MntTable[0].ObjectId) {
2435 							co->co_found = 1;
2436 							found = 1;
2437 							break;
2438 						}
2439 					}
2440 					/*
2441 					 * If the container matched, continue
2442 					 * in the list.
2443 					 */
2444 					if (found) {
2445 						i++;
2446 						continue;
2447 					}
2448 
2449 					/*
2450 					 * This is a new container.  Do all the
2451 					 * appropriate things to set it up.						 */
2452 					aac_add_container(sc, mir, 1);
2453 					added = 1;
2454 				}
2455 				i++;
2456 			} while ((i < mir->MntRespCount) &&
2457 				 (i < AAC_MAX_CONTAINERS));
2458 			aac_release_sync_fib(sc);
2459 
2460 			/*
2461 			 * Go through our list of containers and see which ones
2462 			 * were not marked 'found'.  Since the controller didn't
2463 			 * list them they must have been deleted.  Do the
2464 			 * appropriate steps to destroy the device.  Also reset
2465 			 * the co->co_found field.
2466 			 */
2467 			co = TAILQ_FIRST(&sc->aac_container_tqh);
2468 			while (co != NULL) {
2469 				if (co->co_found == 0) {
2470 					device_delete_child(sc->aac_dev,
2471 							    co->co_disk);
2472 					co_next = TAILQ_NEXT(co, co_link);
2473 					AAC_LOCK_ACQUIRE(&sc->
2474 							aac_container_lock);
2475 					TAILQ_REMOVE(&sc->aac_container_tqh, co,
2476 						     co_link);
2477 					AAC_LOCK_RELEASE(&sc->
2478 							 aac_container_lock);
2479 					FREE(co, M_AACBUF);
2480 					co = co_next;
2481 				} else {
2482 					co->co_found = 0;
2483 					co = TAILQ_NEXT(co, co_link);
2484 				}
2485 			}
2486 
2487 			/* Attach the newly created containers */
2488 			if (added)
2489 				bus_generic_attach(sc->aac_dev);
2490 
2491 			break;
2492 
2493 		default:
2494 			break;
2495 		}
2496 
2497 	default:
2498 		break;
2499 	}
2500 
2501 	/* Copy the AIF data to the AIF queue for ioctl retrieval */
2502 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2503 	next = (sc->aac_aifq_head + 1) % AAC_AIFQ_LENGTH;
2504 	if (next != sc->aac_aifq_tail) {
2505 		bcopy(aif, &sc->aac_aifq[next], sizeof(struct aac_aif_command));
2506 		sc->aac_aifq_head = next;
2507 
2508 		/* On the off chance that someone is sleeping for an aif... */
2509 		if (sc->aac_state & AAC_STATE_AIF_SLEEPER)
2510 			wakeup(sc->aac_aifq);
2511 		/* Wakeup any poll()ers */
2512 		selwakeup(&sc->rcv_select);
2513 	}
2514 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2515 
2516 	return;
2517 }
2518 
2519 /*
2520  * Return the Revision of the driver to userspace and check to see if the
2521  * userspace app is possibly compatible.  This is extremely bogus since
2522  * our driver doesn't follow Adaptec's versioning system.  Cheat by just
2523  * returning what the card reported.
2524  */
2525 static int
2526 aac_rev_check(struct aac_softc *sc, caddr_t udata)
2527 {
2528 	struct aac_rev_check rev_check;
2529 	struct aac_rev_check_resp rev_check_resp;
2530 	int error = 0;
2531 
2532 	debug_called(2);
2533 
2534 	/*
2535 	 * Copyin the revision struct from userspace
2536 	 */
2537 	if ((error = copyin(udata, (caddr_t)&rev_check,
2538 			sizeof(struct aac_rev_check))) != 0) {
2539 		return error;
2540 	}
2541 
2542 	debug(2, "Userland revision= %d\n",
2543 	      rev_check.callingRevision.buildNumber);
2544 
2545 	/*
2546 	 * Doctor up the response struct.
2547 	 */
2548 	rev_check_resp.possiblyCompatible = 1;
2549 	rev_check_resp.adapterSWRevision.external.ul =
2550 	    sc->aac_revision.external.ul;
2551 	rev_check_resp.adapterSWRevision.buildNumber =
2552 	    sc->aac_revision.buildNumber;
2553 
2554 	return(copyout((caddr_t)&rev_check_resp, udata,
2555 			sizeof(struct aac_rev_check_resp)));
2556 }
2557 
2558 /*
2559  * Pass the caller the next AIF in their queue
2560  */
2561 static int
2562 aac_getnext_aif(struct aac_softc *sc, caddr_t arg)
2563 {
2564 	struct get_adapter_fib_ioctl agf;
2565 	int error, s;
2566 
2567 	debug_called(2);
2568 
2569 	if ((error = copyin(arg, &agf, sizeof(agf))) == 0) {
2570 
2571 		/*
2572 		 * Check the magic number that we gave the caller.
2573 		 */
2574 		if (agf.AdapterFibContext != (int)sc->aifthread) {
2575 			error = EFAULT;
2576 		} else {
2577 
2578 			s = splbio();
2579 			error = aac_return_aif(sc, agf.AifFib);
2580 
2581 			if ((error == EAGAIN) && (agf.Wait)) {
2582 				sc->aac_state |= AAC_STATE_AIF_SLEEPER;
2583 				while (error == EAGAIN) {
2584 					error = tsleep(sc->aac_aifq, PRIBIO |
2585 						       PCATCH, "aacaif", 0);
2586 					if (error == 0)
2587 						error = aac_return_aif(sc,
2588 						    agf.AifFib);
2589 				}
2590 				sc->aac_state &= ~AAC_STATE_AIF_SLEEPER;
2591 			}
2592 		splx(s);
2593 		}
2594 	}
2595 	return(error);
2596 }
2597 
2598 /*
2599  * Hand the next AIF off the top of the queue out to userspace.
2600  */
2601 static int
2602 aac_return_aif(struct aac_softc *sc, caddr_t uptr)
2603 {
2604 	int error;
2605 
2606 	debug_called(2);
2607 
2608 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2609 	if (sc->aac_aifq_tail == sc->aac_aifq_head) {
2610 		error = EAGAIN;
2611 	} else {
2612 		error = copyout(&sc->aac_aifq[sc->aac_aifq_tail], uptr,
2613 				sizeof(struct aac_aif_command));
2614 		if (error)
2615 			printf("aac_return_aif: copyout returned %d\n", error);
2616 		if (!error)
2617 			sc->aac_aifq_tail = (sc->aac_aifq_tail + 1) %
2618 					    AAC_AIFQ_LENGTH;
2619 	}
2620 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2621 	return(error);
2622 }
2623 
2624 /*
2625  * Give the userland some information about the container.  The AAC arch
2626  * expects the driver to be a SCSI passthrough type driver, so it expects
2627  * the containers to have b:t:l numbers.  Fake it.
2628  */
2629 static int
2630 aac_query_disk(struct aac_softc *sc, caddr_t uptr)
2631 {
2632 	struct aac_query_disk query_disk;
2633 	struct aac_container *co;
2634 	struct aac_disk	*disk;
2635 	int error, id;
2636 
2637 	debug_called(2);
2638 
2639 	disk = NULL;
2640 
2641 	error = copyin(uptr, (caddr_t)&query_disk,
2642 		       sizeof(struct aac_query_disk));
2643 	if (error)
2644 		return (error);
2645 
2646 	id = query_disk.ContainerNumber;
2647 	if (id == -1)
2648 		return (EINVAL);
2649 
2650 	AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
2651 	TAILQ_FOREACH(co, &sc->aac_container_tqh, co_link) {
2652 		if (co->co_mntobj.ObjectId == id)
2653 			break;
2654 		}
2655 
2656 	if (co == NULL) {
2657 			query_disk.Valid = 0;
2658 			query_disk.Locked = 0;
2659 			query_disk.Deleted = 1;		/* XXX is this right? */
2660 	} else {
2661 		disk = device_get_softc(co->co_disk);
2662 		query_disk.Valid = 1;
2663 		query_disk.Locked =
2664 		    (disk->ad_flags & AAC_DISK_OPEN) ? 1 : 0;
2665 		query_disk.Deleted = 0;
2666 		query_disk.Bus = device_get_unit(sc->aac_dev);
2667 		query_disk.Target = disk->unit;
2668 		query_disk.Lun = 0;
2669 		query_disk.UnMapped = 0;
2670 		bcopy(disk->ad_dev_t->si_name,
2671 		      &query_disk.diskDeviceName[0], 10);
2672 	}
2673 	AAC_LOCK_RELEASE(&sc->aac_container_lock);
2674 
2675 	error = copyout((caddr_t)&query_disk, uptr,
2676 			sizeof(struct aac_query_disk));
2677 
2678 	return (error);
2679 }
2680 
2681 static void
2682 aac_get_bus_info(struct aac_softc *sc)
2683 {
2684 	struct aac_fib *fib;
2685 	struct aac_ctcfg *c_cmd;
2686 	struct aac_ctcfg_resp *c_resp;
2687 	struct aac_vmioctl *vmi;
2688 	struct aac_vmi_businf_resp *vmi_resp;
2689 	struct aac_getbusinf businfo;
2690 	struct aac_cam_inf *caminf;
2691 	device_t child;
2692 	int i, found, error;
2693 
2694 	aac_alloc_sync_fib(sc, &fib, 0);
2695 	c_cmd = (struct aac_ctcfg *)&fib->data[0];
2696 	bzero(c_cmd, sizeof(struct aac_ctcfg));
2697 
2698 	c_cmd->Command = VM_ContainerConfig;
2699 	c_cmd->cmd = CT_GET_SCSI_METHOD;
2700 	c_cmd->param = 0;
2701 
2702 	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2703 	    sizeof(struct aac_ctcfg));
2704 	if (error) {
2705 		device_printf(sc->aac_dev, "Error %d sending "
2706 		    "VM_ContainerConfig command\n", error);
2707 		aac_release_sync_fib(sc);
2708 		return;
2709 	}
2710 
2711 	c_resp = (struct aac_ctcfg_resp *)&fib->data[0];
2712 	if (c_resp->Status != ST_OK) {
2713 		device_printf(sc->aac_dev, "VM_ContainerConfig returned 0x%x\n",
2714 		    c_resp->Status);
2715 		aac_release_sync_fib(sc);
2716 		return;
2717 	}
2718 
2719 	sc->scsi_method_id = c_resp->param;
2720 
2721 	vmi = (struct aac_vmioctl *)&fib->data[0];
2722 	bzero(vmi, sizeof(struct aac_vmioctl));
2723 
2724 	vmi->Command = VM_Ioctl;
2725 	vmi->ObjType = FT_DRIVE;
2726 	vmi->MethId = sc->scsi_method_id;
2727 	vmi->ObjId = 0;
2728 	vmi->IoctlCmd = GetBusInfo;
2729 
2730 	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2731 	    sizeof(struct aac_vmioctl));
2732 	if (error) {
2733 		device_printf(sc->aac_dev, "Error %d sending VMIoctl command\n",
2734 		    error);
2735 		aac_release_sync_fib(sc);
2736 		return;
2737 	}
2738 
2739 	vmi_resp = (struct aac_vmi_businf_resp *)&fib->data[0];
2740 	if (vmi_resp->Status != ST_OK) {
2741 		device_printf(sc->aac_dev, "VM_Ioctl returned %d\n",
2742 		    vmi_resp->Status);
2743 		aac_release_sync_fib(sc);
2744 		return;
2745 	}
2746 
2747 	bcopy(&vmi_resp->BusInf, &businfo, sizeof(struct aac_getbusinf));
2748 	aac_release_sync_fib(sc);
2749 
2750 	found = 0;
2751 	for (i = 0; i < businfo.BusCount; i++) {
2752 		if (businfo.BusValid[i] != AAC_BUS_VALID)
2753 			continue;
2754 
2755 		MALLOC(caminf, struct aac_cam_inf *,
2756 		    sizeof(struct aac_cam_inf), M_AACBUF, M_NOWAIT | M_ZERO);
2757 		if (caminf == NULL)
2758 			continue;
2759 
2760 		child = device_add_child(sc->aac_dev, "aacp", -1);
2761 		if (child == NULL) {
2762 			device_printf(sc->aac_dev, "device_add_child failed\n");
2763 			continue;
2764 		}
2765 
2766 		caminf->TargetsPerBus = businfo.TargetsPerBus;
2767 		caminf->BusNumber = i;
2768 		caminf->InitiatorBusId = businfo.InitiatorBusId[i];
2769 		caminf->aac_sc = sc;
2770 
2771 		device_set_ivars(child, caminf);
2772 		device_set_desc(child, "SCSI Passthrough Bus");
2773 
2774 		found = 1;
2775 	}
2776 
2777 	if (found)
2778 		bus_generic_attach(sc->aac_dev);
2779 
2780 	return;
2781 }
2782