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