twe.c revision 141492
1/*-
2 * Copyright (c) 2000 Michael Smith
3 * Copyright (c) 2003 Paul Saab
4 * Copyright (c) 2003 Vinod Kashyap
5 * Copyright (c) 2000 BSDi
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: head/sys/dev/twe/twe.c 141492 2005-02-08 03:43:02Z scottl $
30 */
31
32/*
33 * Driver for the 3ware Escalade family of IDE RAID controllers.
34 */
35
36#include <dev/twe/twe_compat.h>
37#include <dev/twe/twereg.h>
38#include <dev/twe/tweio.h>
39#include <dev/twe/twevar.h>
40#define TWE_DEFINE_TABLES
41#include <dev/twe/twe_tables.h>
42
43/*
44 * Command submission.
45 */
46static int	twe_get_param_1(struct twe_softc *sc, int table_id, int param_id, u_int8_t *result);
47static int	twe_get_param_2(struct twe_softc *sc, int table_id, int param_id, u_int16_t *result);
48static int	twe_get_param_4(struct twe_softc *sc, int table_id, int param_id, u_int32_t *result);
49static void	*twe_get_param(struct twe_softc *sc, int table_id, int parameter_id, size_t size,
50					       void (* func)(struct twe_request *tr));
51#ifdef TWE_SHUTDOWN_NOTIFICATION
52static int	twe_set_param_1(struct twe_softc *sc, int table_id, int param_id, u_int8_t value);
53#endif
54#if 0
55static int	twe_set_param_2(struct twe_softc *sc, int table_id, int param_id, u_int16_t value);
56static int	twe_set_param_4(struct twe_softc *sc, int table_id, int param_id, u_int32_t value);
57#endif
58static int	twe_set_param(struct twe_softc *sc, int table_id, int param_id, int param_size,
59					      void *data);
60static int	twe_init_connection(struct twe_softc *sc, int mode);
61static int	twe_wait_request(struct twe_request *tr);
62static int	twe_immediate_request(struct twe_request *tr, int usetmp);
63static void	twe_completeio(struct twe_request *tr);
64static void	twe_reset(struct twe_softc *sc);
65static int	twe_add_unit(struct twe_softc *sc, int unit);
66static int	twe_del_unit(struct twe_softc *sc, int unit);
67
68/*
69 * Command I/O to controller.
70 */
71static void	twe_done(struct twe_softc *sc);
72static void	twe_complete(struct twe_softc *sc);
73static int	twe_wait_status(struct twe_softc *sc, u_int32_t status, int timeout);
74static int	twe_drain_response_queue(struct twe_softc *sc);
75static int	twe_check_bits(struct twe_softc *sc, u_int32_t status_reg);
76static int	twe_soft_reset(struct twe_softc *sc);
77
78/*
79 * Interrupt handling.
80 */
81static void	twe_host_intr(struct twe_softc *sc);
82static void	twe_attention_intr(struct twe_softc *sc);
83static void	twe_command_intr(struct twe_softc *sc);
84
85/*
86 * Asynchronous event handling.
87 */
88static int	twe_fetch_aen(struct twe_softc *sc);
89static void	twe_handle_aen(struct twe_request *tr);
90static void	twe_enqueue_aen(struct twe_softc *sc, u_int16_t aen);
91static u_int16_t	twe_dequeue_aen(struct twe_softc *sc);
92static int	twe_drain_aen_queue(struct twe_softc *sc);
93static int	twe_find_aen(struct twe_softc *sc, u_int16_t aen);
94
95/*
96 * Command buffer management.
97 */
98static int	twe_get_request(struct twe_softc *sc, struct twe_request **tr);
99static void	twe_release_request(struct twe_request *tr);
100
101/*
102 * Debugging.
103 */
104static char 	*twe_format_aen(struct twe_softc *sc, u_int16_t aen);
105static int	twe_report_request(struct twe_request *tr);
106static void	twe_panic(struct twe_softc *sc, char *reason);
107
108/********************************************************************************
109 ********************************************************************************
110                                                                Public Interfaces
111 ********************************************************************************
112 ********************************************************************************/
113
114/********************************************************************************
115 * Initialise the controller, set up driver data structures.
116 */
117int
118twe_setup(struct twe_softc *sc)
119{
120    struct twe_request	*tr;
121    TWE_Command		*cmd;
122    u_int32_t		status_reg;
123    int			i;
124
125    debug_called(4);
126
127    /*
128     * Initialise request queues.
129     */
130    twe_initq_free(sc);
131    twe_initq_bio(sc);
132    twe_initq_ready(sc);
133    twe_initq_busy(sc);
134    twe_initq_complete(sc);
135    sc->twe_wait_aen = -1;
136
137    /*
138     * Allocate request structures up front.
139     */
140    for (i = 0; i < TWE_Q_LENGTH; i++) {
141	if ((tr = twe_allocate_request(sc, i)) == NULL)
142	    return(ENOMEM);
143	/*
144	 * Set global defaults that won't change.
145	 */
146	cmd = TWE_FIND_COMMAND(tr);
147	cmd->generic.host_id = sc->twe_host_id;		/* controller-assigned host ID */
148	cmd->generic.request_id = i;			/* our index number */
149	sc->twe_lookup[i] = tr;
150
151	/*
152	 * Put command onto the freelist.
153	 */
154	twe_release_request(tr);
155    }
156
157    /*
158     * Check status register for errors, clear them.
159     */
160    status_reg = TWE_STATUS(sc);
161    twe_check_bits(sc, status_reg);
162
163    /*
164     * Wait for the controller to come ready.
165     */
166    if (twe_wait_status(sc, TWE_STATUS_MICROCONTROLLER_READY, 60)) {
167	twe_printf(sc, "microcontroller not ready\n");
168	return(ENXIO);
169    }
170
171    /*
172     * Disable interrupts from the card.
173     */
174    twe_disable_interrupts(sc);
175
176    /*
177     * Soft reset the controller, look for the AEN acknowledging the reset,
178     * check for errors, drain the response queue.
179     */
180    for (i = 0; i < TWE_MAX_RESET_TRIES; i++) {
181
182	if (i > 0)
183	    twe_printf(sc, "reset %d failed, trying again\n", i);
184
185	if (!twe_soft_reset(sc))
186	    break;			/* reset process complete */
187    }
188    /* did we give up? */
189    if (i >= TWE_MAX_RESET_TRIES) {
190	twe_printf(sc, "can't initialise controller, giving up\n");
191	return(ENXIO);
192    }
193
194    return(0);
195}
196
197static int
198twe_add_unit(struct twe_softc *sc, int unit)
199{
200    struct twe_drive		*dr;
201    int				table, error = 0;
202    u_int16_t			dsize;
203    TWE_Param			*drives = NULL, *param = NULL;
204    TWE_Unit_Descriptor		*ud;
205
206    if (unit < 0 || unit > TWE_MAX_UNITS)
207	return (EINVAL);
208
209    /*
210     * The controller is in a safe state, so try to find drives attached to it.
211     */
212    if ((drives = twe_get_param(sc, TWE_PARAM_UNITSUMMARY, TWE_PARAM_UNITSUMMARY_Status,
213				TWE_MAX_UNITS, NULL)) == NULL) {
214	twe_printf(sc, "can't detect attached units\n");
215	return (EIO);
216    }
217
218    dr = &sc->twe_drive[unit];
219    /* check that the drive is online */
220    if (!(drives->data[unit] & TWE_PARAM_UNITSTATUS_Online)) {
221	error = ENXIO;
222	goto out;
223    }
224
225    table = TWE_PARAM_UNITINFO + unit;
226
227    if (twe_get_param_4(sc, table, TWE_PARAM_UNITINFO_Capacity, &dr->td_size)) {
228	twe_printf(sc, "error fetching capacity for unit %d\n", unit);
229	error = EIO;
230	goto out;
231    }
232    if (twe_get_param_1(sc, table, TWE_PARAM_UNITINFO_Status, &dr->td_state)) {
233	twe_printf(sc, "error fetching state for unit %d\n", unit);
234	error = EIO;
235	goto out;
236    }
237    if (twe_get_param_2(sc, table, TWE_PARAM_UNITINFO_DescriptorSize, &dsize)) {
238	twe_printf(sc, "error fetching descriptor size for unit %d\n", unit);
239	error = EIO;
240	goto out;
241    }
242    if ((param = twe_get_param(sc, table, TWE_PARAM_UNITINFO_Descriptor, dsize - 3, NULL)) == NULL) {
243	twe_printf(sc, "error fetching descriptor for unit %d\n", unit);
244	error = EIO;
245	goto out;
246    }
247    ud = (TWE_Unit_Descriptor *)param->data;
248    dr->td_type = ud->configuration;
249
250    /* build synthetic geometry as per controller internal rules */
251    if (dr->td_size > 0x200000) {
252	dr->td_heads = 255;
253	dr->td_sectors = 63;
254    } else {
255	dr->td_heads = 64;
256	dr->td_sectors = 32;
257    }
258    dr->td_cylinders = dr->td_size / (dr->td_heads * dr->td_sectors);
259    dr->td_twe_unit = unit;
260
261    error = twe_attach_drive(sc, dr);
262
263out:
264    if (param != NULL)
265	free(param, M_DEVBUF);
266    if (drives != NULL)
267	free(drives, M_DEVBUF);
268    return (error);
269}
270
271static int
272twe_del_unit(struct twe_softc *sc, int unit)
273{
274    int error;
275
276    if (unit < 0 || unit >= TWE_MAX_UNITS)
277	return (ENXIO);
278
279    if (sc->twe_drive[unit].td_disk == NULL)
280	return (ENXIO);
281
282    error = twe_detach_drive(sc, unit);
283    return (error);
284}
285
286/********************************************************************************
287 * Locate disk devices and attach children to them.
288 */
289void
290twe_init(struct twe_softc *sc)
291{
292    int 		i;
293
294    /*
295     * Scan for drives
296     */
297    for (i = 0; i < TWE_MAX_UNITS; i++)
298	twe_add_unit(sc, i);
299
300    /*
301     * Initialise connection with controller.
302     */
303    twe_init_connection(sc, TWE_INIT_MESSAGE_CREDITS);
304
305#ifdef TWE_SHUTDOWN_NOTIFICATION
306    /*
307     * Tell the controller we support shutdown notification.
308     */
309    twe_set_param_1(sc, TWE_PARAM_FEATURES, TWE_PARAM_FEATURES_DriverShutdown, 1);
310#endif
311
312    /*
313     * Mark controller up and ready to run.
314     */
315    sc->twe_state &= ~TWE_STATE_SHUTDOWN;
316
317    /*
318     * Finally enable interrupts.
319     */
320    twe_enable_interrupts(sc);
321}
322
323/********************************************************************************
324 * Stop the controller
325 */
326void
327twe_deinit(struct twe_softc *sc)
328{
329    /*
330     * Mark the controller as shutting down, and disable any further interrupts.
331     */
332    sc->twe_state |= TWE_STATE_SHUTDOWN;
333    twe_disable_interrupts(sc);
334
335#ifdef TWE_SHUTDOWN_NOTIFICATION
336    /*
337     * Disconnect from the controller
338     */
339    twe_init_connection(sc, TWE_SHUTDOWN_MESSAGE_CREDITS);
340#endif
341}
342
343/*******************************************************************************
344 * Take an interrupt, or be poked by other code to look for interrupt-worthy
345 * status.
346 */
347void
348twe_intr(struct twe_softc *sc)
349{
350    u_int32_t		status_reg;
351
352    debug_called(4);
353
354    /*
355     * Collect current interrupt status.
356     */
357    status_reg = TWE_STATUS(sc);
358    twe_check_bits(sc, status_reg);
359
360    /*
361     * Dispatch based on interrupt status
362     */
363    if (status_reg & TWE_STATUS_HOST_INTERRUPT)
364	twe_host_intr(sc);
365    if (status_reg & TWE_STATUS_ATTENTION_INTERRUPT)
366	twe_attention_intr(sc);
367    if (status_reg & TWE_STATUS_COMMAND_INTERRUPT)
368	twe_command_intr(sc);
369    if (status_reg & TWE_STATUS_RESPONSE_INTERRUPT)
370	twe_done(sc);
371};
372
373/********************************************************************************
374 * Pull as much work off the softc's work queue as possible and give it to the
375 * controller.
376 */
377void
378twe_startio(struct twe_softc *sc)
379{
380    struct twe_request	*tr;
381    TWE_Command		*cmd;
382    twe_bio		*bp;
383    int			error;
384
385    debug_called(4);
386
387    if (sc->twe_state & (TWE_STATE_CTLR_BUSY | TWE_STATE_FRZN))
388	return;
389
390    /* spin until something prevents us from doing any work */
391    for (;;) {
392
393	/* try to get a command that's already ready to go */
394	tr = twe_dequeue_ready(sc);
395
396	/* build a command from an outstanding bio */
397	if (tr == NULL) {
398
399	    /* get a command to handle the bio with */
400	    if (twe_get_request(sc, &tr))
401		break;
402
403	    /* see if there's work to be done */
404	    if ((bp = twe_dequeue_bio(sc)) == NULL) {
405		twe_release_request(tr);
406		break;
407	    }
408
409	    /* connect the bio to the command */
410	    tr->tr_complete = twe_completeio;
411	    tr->tr_private = bp;
412	    tr->tr_data = TWE_BIO_DATA(bp);
413	    tr->tr_length = TWE_BIO_LENGTH(bp);
414	    cmd = TWE_FIND_COMMAND(tr);
415	    if (TWE_BIO_IS_READ(bp)) {
416		tr->tr_flags |= TWE_CMD_DATAIN;
417		cmd->io.opcode = TWE_OP_READ;
418	    } else {
419		tr->tr_flags |= TWE_CMD_DATAOUT;
420		cmd->io.opcode = TWE_OP_WRITE;
421	    }
422
423	    /* build a suitable I/O command (assumes 512-byte rounded transfers) */
424	    cmd->io.size = 3;
425	    cmd->io.unit = TWE_BIO_UNIT(bp);
426	    cmd->io.block_count = (tr->tr_length + TWE_BLOCK_SIZE - 1) / TWE_BLOCK_SIZE;
427	    cmd->io.lba = TWE_BIO_LBA(bp);
428	}
429
430	/* did we find something to do? */
431	if (tr == NULL)
432	    break;
433
434	/* try to map and submit the command to controller */
435	error = twe_map_request(tr);
436
437	if (error != 0) {
438	    if (error == EBUSY)
439		break;
440	    tr->tr_status = TWE_CMD_ERROR;
441	    if (tr->tr_private != NULL) {
442		bp = (twe_bio *)(tr->tr_private);
443		TWE_BIO_SET_ERROR(bp, error);
444		tr->tr_private = NULL;
445		twed_intr(bp);
446	        twe_release_request(tr);
447	    } else if (tr->tr_flags & TWE_CMD_SLEEPER)
448		wakeup_one(tr); /* wakeup the sleeping owner */
449	}
450    }
451}
452
453/********************************************************************************
454 * Write blocks from memory to disk, for system crash dumps.
455 */
456int
457twe_dump_blocks(struct twe_softc *sc, int unit,	u_int32_t lba, void *data, int nblks)
458{
459    struct twe_request	*tr;
460    TWE_Command		*cmd;
461    int			error;
462
463    if (twe_get_request(sc, &tr))
464	return(ENOMEM);
465
466    tr->tr_data = data;
467    tr->tr_status = TWE_CMD_SETUP;
468    tr->tr_length = nblks * TWE_BLOCK_SIZE;
469    tr->tr_flags = TWE_CMD_DATAOUT;
470
471    cmd = TWE_FIND_COMMAND(tr);
472    cmd->io.opcode = TWE_OP_WRITE;
473    cmd->io.size = 3;
474    cmd->io.unit = unit;
475    cmd->io.block_count = nblks;
476    cmd->io.lba = lba;
477
478    error = twe_immediate_request(tr, 0);
479    if (error == 0)
480	if (twe_report_request(tr))
481	    error = EIO;
482    twe_release_request(tr);
483    return(error);
484}
485
486/********************************************************************************
487 * Handle controller-specific control operations.
488 */
489int
490twe_ioctl(struct twe_softc *sc, int ioctlcmd, void *addr)
491{
492    struct twe_usercommand	*tu = (struct twe_usercommand *)addr;
493    struct twe_paramcommand	*tp = (struct twe_paramcommand *)addr;
494    struct twe_drivecommand	*td = (struct twe_drivecommand *)addr;
495    union twe_statrequest	*ts = (union twe_statrequest *)addr;
496    TWE_Param			*param;
497    TWE_Command			*cmd;
498    void			*data;
499    u_int16_t			*aen_code = (u_int16_t *)addr;
500    struct twe_request		*tr;
501    u_int8_t			srid;
502    int				s, error;
503#ifdef __amd64__
504    struct twe_paramcommand32	*tp32 = (struct twe_paramcommand32 *)addr;
505    struct twe_usercommand32	*tu32 = (struct twe_usercommand32 *)addr;
506    struct twe_paramcommand	tp_swab;
507    struct twe_usercommand	tu_swab;
508#endif
509
510    error = 0;
511    switch(ioctlcmd) {
512
513#ifdef __amd64__
514    case TWEIO_COMMAND32:
515	tu_swab.tu_command = tu32->tu_command;
516	tu_swab.tu_data = (void *)(uintptr_t)tu32->tu_data;
517	tu_swab.tu_size = tu32->tu_size;
518	tu = &tu_swab;
519	/* FALLTHROUGH */
520#endif
521
522	/* handle a command from userspace */
523    case TWEIO_COMMAND:
524	/* get a request */
525	while (twe_get_request(sc, &tr))
526	    tsleep(sc, PPAUSE, "twioctl", hz);
527
528	/*
529	 * Save the command's request ID, copy the user-supplied command in,
530	 * restore the request ID.
531	 */
532	cmd = TWE_FIND_COMMAND(tr);
533	srid = cmd->generic.request_id;
534	bcopy(&tu->tu_command, cmd, sizeof(TWE_Command));
535	cmd->generic.request_id = srid;
536
537	/*
538	 * if there's a data buffer, allocate and copy it in.
539	 * Must be in multipled of 512 bytes.
540	 */
541	tr->tr_length = (tu->tu_size + 511) & ~511;
542	if (tr->tr_length > 0) {
543	    if ((tr->tr_data = malloc(tr->tr_length, M_DEVBUF, M_WAITOK)) == NULL) {
544		error = ENOMEM;
545		goto cmd_done;
546	    }
547	    if ((error = copyin(tu->tu_data, tr->tr_data, tu->tu_size)) != 0)
548		goto cmd_done;
549	    tr->tr_flags |= TWE_CMD_DATAIN | TWE_CMD_DATAOUT;
550	}
551
552	/* run the command */
553	error = twe_wait_request(tr);
554	if (error)
555	    goto cmd_done;
556
557	/* copy the command out again */
558	bcopy(cmd, &tu->tu_command, sizeof(TWE_Command));
559
560	/* if there was a data buffer, copy it out */
561	if (tr->tr_length > 0)
562	    error = copyout(tr->tr_data, tu->tu_data, tu->tu_size);
563
564    cmd_done:
565	/* free resources */
566	if (tr->tr_data != NULL)
567	    free(tr->tr_data, M_DEVBUF);
568	if (tr != NULL)
569	    twe_release_request(tr);
570
571	break;
572
573	/* fetch statistics counter */
574    case TWEIO_STATS:
575	switch (ts->ts_item) {
576#ifdef TWE_PERFORMANCE_MONITOR
577	case TWEQ_FREE:
578	case TWEQ_BIO:
579	case TWEQ_READY:
580	case TWEQ_BUSY:
581	case TWEQ_COMPLETE:
582	    bcopy(&sc->twe_qstat[ts->ts_item], &ts->ts_qstat, sizeof(struct twe_qstat));
583	    break;
584#endif
585	default:
586	    error = ENOENT;
587	    break;
588	}
589	break;
590
591	/* poll for an AEN */
592    case TWEIO_AEN_POLL:
593	*aen_code = twe_dequeue_aen(sc);
594	break;
595
596	/* wait for another AEN to show up */
597    case TWEIO_AEN_WAIT:
598	s = splbio();
599	while ((*aen_code = twe_dequeue_aen(sc)) == TWE_AEN_QUEUE_EMPTY) {
600	    error = tsleep(&sc->twe_aen_queue, PRIBIO | PCATCH, "tweaen", 0);
601	    if (error == EINTR)
602		break;
603	}
604	splx(s);
605	break;
606
607#ifdef __amd64__
608    case TWEIO_GET_PARAM32:
609	tp_swab.tp_table_id = tp32->tp_table_id;
610	tp_swab.tp_param_id = tp32->tp_param_id;
611	tp_swab.tp_data = (void *)(uintptr_t)tp32->tp_data;
612	tp_swab.tp_size = tp32->tp_size;
613	tp = &tp_swab;
614	/* FALLTHROUGH */
615#endif
616
617    case TWEIO_GET_PARAM:
618	if ((param = twe_get_param(sc, tp->tp_table_id, tp->tp_param_id, tp->tp_size, NULL)) == NULL) {
619	    twe_printf(sc, "TWEIO_GET_PARAM failed for 0x%x/0x%x/%d\n",
620		       tp->tp_table_id, tp->tp_param_id, tp->tp_size);
621	    error = EINVAL;
622	} else {
623	    if (param->parameter_size_bytes > tp->tp_size) {
624		twe_printf(sc, "TWEIO_GET_PARAM parameter too large (%d > %d)\n",
625			   param->parameter_size_bytes, tp->tp_size);
626		error = EFAULT;
627	    } else {
628		error = copyout(param->data, tp->tp_data, param->parameter_size_bytes);
629	    }
630	    free(param, M_DEVBUF);
631	}
632	break;
633
634#ifdef __amd64__
635    case TWEIO_SET_PARAM32:
636	tp_swab.tp_table_id = tp32->tp_table_id;
637	tp_swab.tp_param_id = tp32->tp_param_id;
638	tp_swab.tp_data = (void *)(uintptr_t)tp32->tp_data;
639	tp_swab.tp_size = tp32->tp_size;
640	tp = &tp_swab;
641	/* FALLTHROUGH */
642#endif
643
644    case TWEIO_SET_PARAM:
645	if ((data = malloc(tp->tp_size, M_DEVBUF, M_WAITOK)) == NULL) {
646	    error = ENOMEM;
647	} else {
648	    error = copyin(tp->tp_data, data, tp->tp_size);
649	    if (error == 0)
650		error = twe_set_param(sc, tp->tp_table_id, tp->tp_param_id, tp->tp_size, data);
651	    free(data, M_DEVBUF);
652	}
653	break;
654
655    case TWEIO_RESET:
656	twe_reset(sc);
657	break;
658
659    case TWEIO_ADD_UNIT:
660	error = twe_add_unit(sc, td->td_unit);
661	break;
662
663    case TWEIO_DEL_UNIT:
664	error = twe_del_unit(sc, td->td_unit);
665	break;
666
667	/* XXX implement ATA PASSTHROUGH */
668
669	/* nothing we understand */
670    default:
671	error = ENOTTY;
672    }
673
674    return(error);
675}
676
677/********************************************************************************
678 * Enable the useful interrupts from the controller.
679 */
680void
681twe_enable_interrupts(struct twe_softc *sc)
682{
683    sc->twe_state |= TWE_STATE_INTEN;
684    TWE_CONTROL(sc,
685	       TWE_CONTROL_CLEAR_ATTENTION_INTERRUPT |
686	       TWE_CONTROL_UNMASK_RESPONSE_INTERRUPT |
687	       TWE_CONTROL_ENABLE_INTERRUPTS);
688}
689
690/********************************************************************************
691 * Disable interrupts from the controller.
692 */
693void
694twe_disable_interrupts(struct twe_softc *sc)
695{
696    TWE_CONTROL(sc, TWE_CONTROL_DISABLE_INTERRUPTS);
697    sc->twe_state &= ~TWE_STATE_INTEN;
698}
699
700/********************************************************************************
701 ********************************************************************************
702                                                               Command Submission
703 ********************************************************************************
704 ********************************************************************************/
705
706/********************************************************************************
707 * Read integer parameter table entries.
708 */
709static int
710twe_get_param_1(struct twe_softc *sc, int table_id, int param_id, u_int8_t *result)
711{
712    TWE_Param	*param;
713
714    if ((param = twe_get_param(sc, table_id, param_id, 1, NULL)) == NULL)
715	return(ENOENT);
716    *result = *(u_int8_t *)param->data;
717    free(param, M_DEVBUF);
718    return(0);
719}
720
721static int
722twe_get_param_2(struct twe_softc *sc, int table_id, int param_id, u_int16_t *result)
723{
724    TWE_Param	*param;
725
726    if ((param = twe_get_param(sc, table_id, param_id, 2, NULL)) == NULL)
727	return(ENOENT);
728    *result = *(u_int16_t *)param->data;
729    free(param, M_DEVBUF);
730    return(0);
731}
732
733static int
734twe_get_param_4(struct twe_softc *sc, int table_id, int param_id, u_int32_t *result)
735{
736    TWE_Param	*param;
737
738    if ((param = twe_get_param(sc, table_id, param_id, 4, NULL)) == NULL)
739	return(ENOENT);
740    *result = *(u_int32_t *)param->data;
741    free(param, M_DEVBUF);
742    return(0);
743}
744
745/********************************************************************************
746 * Perform a TWE_OP_GET_PARAM command.  If a callback function is provided, it
747 * will be called with the command when it's completed.  If no callback is
748 * provided, we will wait for the command to complete and then return just the data.
749 * The caller is responsible for freeing the data when done with it.
750 */
751static void *
752twe_get_param(struct twe_softc *sc, int table_id, int param_id, size_t param_size,
753	      void (* func)(struct twe_request *tr))
754{
755    struct twe_request	*tr;
756    TWE_Command		*cmd;
757    TWE_Param		*param;
758    int			error;
759
760    debug_called(4);
761
762    tr = NULL;
763    param = NULL;
764
765    /* get a command */
766    if (twe_get_request(sc, &tr))
767	goto err;
768
769    /* get a buffer */
770    if ((param = (TWE_Param *)malloc(TWE_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL)
771	goto err;
772    tr->tr_data = param;
773    tr->tr_length = TWE_SECTOR_SIZE;
774    tr->tr_flags = TWE_CMD_DATAIN | TWE_CMD_DATAOUT;
775
776    /* build the command for the controller */
777    cmd = TWE_FIND_COMMAND(tr);
778    cmd->param.opcode = TWE_OP_GET_PARAM;
779    cmd->param.size = 2;
780    cmd->param.unit = 0;
781    cmd->param.param_count = 1;
782
783    /* fill in the outbound parameter data */
784    param->table_id = table_id;
785    param->parameter_id = param_id;
786    param->parameter_size_bytes = param_size;
787
788    /* submit the command and either wait or let the callback handle it */
789    if (func == NULL) {
790	/* XXX could use twe_wait_request here if interrupts were enabled? */
791	error = twe_immediate_request(tr, 1 /* usetmp */);
792	if (error == 0) {
793	    if (twe_report_request(tr))
794		goto err;
795	} else {
796	    goto err;
797	}
798	twe_release_request(tr);
799	return(param);
800    } else {
801	tr->tr_complete = func;
802	error = twe_map_request(tr);
803	if ((error == 0) || (error == EBUSY))
804	    return(func);
805    }
806
807    /* something failed */
808err:
809    debug(1, "failed");
810    if (tr != NULL)
811	twe_release_request(tr);
812    if (param != NULL)
813	free(param, M_DEVBUF);
814    return(NULL);
815}
816
817/********************************************************************************
818 * Set integer parameter table entries.
819 */
820#ifdef TWE_SHUTDOWN_NOTIFICATION
821static int
822twe_set_param_1(struct twe_softc *sc, int table_id, int param_id, u_int8_t value)
823{
824    return(twe_set_param(sc, table_id, param_id, sizeof(value), &value));
825}
826#endif
827
828#if 0
829static int
830twe_set_param_2(struct twe_softc *sc, int table_id, int param_id, u_int16_t value)
831{
832    return(twe_set_param(sc, table_id, param_id, sizeof(value), &value));
833}
834
835static int
836twe_set_param_4(struct twe_softc *sc, int table_id, int param_id, u_int32_t value)
837{
838    return(twe_set_param(sc, table_id, param_id, sizeof(value), &value));
839}
840#endif
841
842/********************************************************************************
843 * Perform a TWE_OP_SET_PARAM command, returns nonzero on error.
844 */
845static int
846twe_set_param(struct twe_softc *sc, int table_id, int param_id, int param_size, void *data)
847{
848    struct twe_request	*tr;
849    TWE_Command		*cmd;
850    TWE_Param		*param;
851    int			error;
852
853    debug_called(4);
854
855    tr = NULL;
856    param = NULL;
857    error = ENOMEM;
858
859    /* get a command */
860    if (twe_get_request(sc, &tr))
861	goto out;
862
863    /* get a buffer */
864    if ((param = (TWE_Param *)malloc(TWE_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL)
865	goto out;
866    tr->tr_data = param;
867    tr->tr_length = TWE_SECTOR_SIZE;
868    tr->tr_flags = TWE_CMD_DATAIN | TWE_CMD_DATAOUT;
869
870    /* build the command for the controller */
871    cmd = TWE_FIND_COMMAND(tr);
872    cmd->param.opcode = TWE_OP_SET_PARAM;
873    cmd->param.size = 2;
874    cmd->param.unit = 0;
875    cmd->param.param_count = 1;
876
877    /* fill in the outbound parameter data */
878    param->table_id = table_id;
879    param->parameter_id = param_id;
880    param->parameter_size_bytes = param_size;
881    bcopy(data, param->data, param_size);
882
883    /* XXX could use twe_wait_request here if interrupts were enabled? */
884    error = twe_immediate_request(tr, 1 /* usetmp */);
885    if (error == 0) {
886	if (twe_report_request(tr))
887	    error = EIO;
888    }
889
890out:
891    if (tr != NULL)
892	twe_release_request(tr);
893    if (param != NULL)
894	free(param, M_DEVBUF);
895    return(error);
896}
897
898/********************************************************************************
899 * Perform a TWE_OP_INIT_CONNECTION command, returns nonzero on error.
900 *
901 * Typically called with interrupts disabled.
902 */
903static int
904twe_init_connection(struct twe_softc *sc, int mode)
905{
906    struct twe_request	*tr;
907    TWE_Command		*cmd;
908    int			error;
909
910    debug_called(4);
911
912    /* get a command */
913    if (twe_get_request(sc, &tr))
914	return(0);
915
916    /* build the command */
917    cmd = TWE_FIND_COMMAND(tr);
918    cmd->initconnection.opcode = TWE_OP_INIT_CONNECTION;
919    cmd->initconnection.size = 3;
920    cmd->initconnection.host_id = 0;
921    cmd->initconnection.message_credits = mode;
922    cmd->initconnection.response_queue_pointer = 0;
923
924    /* submit the command */
925    error = twe_immediate_request(tr, 0 /* usetmp */);
926    twe_release_request(tr);
927
928    if (mode == TWE_INIT_MESSAGE_CREDITS)
929	sc->twe_host_id = cmd->initconnection.host_id;
930    return(error);
931}
932
933/********************************************************************************
934 * Start the command (tr) and sleep waiting for it to complete.
935 *
936 * Successfully completed commands are dequeued.
937 */
938static int
939twe_wait_request(struct twe_request *tr)
940{
941    int		s;
942
943    debug_called(4);
944
945    tr->tr_flags |= TWE_CMD_SLEEPER;
946    tr->tr_status = TWE_CMD_BUSY;
947    twe_enqueue_ready(tr);
948    twe_startio(tr->tr_sc);
949    s = splbio();
950    while (tr->tr_status == TWE_CMD_BUSY)
951	tsleep(tr, PRIBIO, "twewait", 0);
952    splx(s);
953
954    return(tr->tr_status != TWE_CMD_COMPLETE);
955}
956
957/********************************************************************************
958 * Start the command (tr) and busy-wait for it to complete.
959 * This should only be used when interrupts are actually disabled (although it
960 * will work if they are not).
961 */
962static int
963twe_immediate_request(struct twe_request *tr, int usetmp)
964{
965    struct twe_softc *sc;
966    int		error;
967    int		count = 0;
968
969    debug_called(4);
970
971    sc = tr->tr_sc;
972
973    if (usetmp && (tr->tr_data != NULL)) {
974	tr->tr_flags |= TWE_CMD_IMMEDIATE;
975	if (tr->tr_length > MAXBSIZE)
976	    return (EINVAL);
977	bcopy(tr->tr_data, sc->twe_immediate, tr->tr_length);
978    }
979    tr->tr_status = TWE_CMD_BUSY;
980    if ((error = twe_map_request(tr)) != 0)
981	if (error != EBUSY)
982	    return(error);
983
984    /* Wait up to 5 seconds for the command to complete */
985    while ((count++ < 5000) && (tr->tr_status == TWE_CMD_BUSY)){
986	DELAY(1000);
987	twe_done(sc);
988    }
989    if (usetmp && (tr->tr_data != NULL))
990	bcopy(sc->twe_immediate, tr->tr_data, tr->tr_length);
991
992    return(tr->tr_status != TWE_CMD_COMPLETE);
993}
994
995/********************************************************************************
996 * Handle completion of an I/O command.
997 */
998static void
999twe_completeio(struct twe_request *tr)
1000{
1001    TWE_Command		*cmd = TWE_FIND_COMMAND(tr);
1002    struct twe_softc	*sc = tr->tr_sc;
1003    twe_bio		*bp = (twe_bio *)tr->tr_private;
1004
1005    debug_called(4);
1006
1007    if (tr->tr_status == TWE_CMD_COMPLETE) {
1008
1009	if (cmd->generic.status)
1010	    if (twe_report_request(tr))
1011		TWE_BIO_SET_ERROR(bp, EIO);
1012
1013    } else {
1014	twe_panic(sc, "twe_completeio on incomplete command");
1015    }
1016    tr->tr_private = NULL;
1017    twed_intr(bp);
1018    twe_release_request(tr);
1019}
1020
1021/********************************************************************************
1022 * Reset the controller and pull all the active commands back onto the ready
1023 * queue.  Used to restart a controller that's exhibiting bad behaviour.
1024 */
1025static void
1026twe_reset(struct twe_softc *sc)
1027{
1028    struct twe_request	*tr;
1029    int			i, s;
1030
1031    /*
1032     * Sleep for a short period to allow AENs to be signalled.
1033     */
1034    tsleep(sc, PRIBIO, "twereset", hz);
1035
1036    /*
1037     * Disable interrupts from the controller, and mask any accidental entry
1038     * into our interrupt handler.
1039     */
1040    twe_printf(sc, "controller reset in progress...\n");
1041    twe_disable_interrupts(sc);
1042    s = splbio();
1043
1044    /*
1045     * Try to soft-reset the controller.
1046     */
1047    for (i = 0; i < TWE_MAX_RESET_TRIES; i++) {
1048
1049	if (i > 0)
1050	    twe_printf(sc, "reset %d failed, trying again\n", i);
1051
1052	if (!twe_soft_reset(sc))
1053	    break;			/* reset process complete */
1054    }
1055    /* did we give up? */
1056    if (i >= TWE_MAX_RESET_TRIES) {
1057	twe_printf(sc, "can't reset controller, giving up\n");
1058	goto out;
1059    }
1060
1061    /*
1062     * Move all of the commands that were busy back to the ready queue.
1063     */
1064    i = 0;
1065    while ((tr = twe_dequeue_busy(sc)) != NULL) {
1066	twe_enqueue_ready(tr);
1067	i++;
1068    }
1069
1070    /*
1071     * Kick the controller to start things going again, then re-enable interrupts.
1072     */
1073    twe_startio(sc);
1074    twe_enable_interrupts(sc);
1075    twe_printf(sc, "controller reset done, %d commands restarted\n", i);
1076
1077out:
1078    splx(s);
1079    twe_enable_interrupts(sc);
1080}
1081
1082/********************************************************************************
1083 ********************************************************************************
1084                                                        Command I/O to Controller
1085 ********************************************************************************
1086 ********************************************************************************/
1087
1088/********************************************************************************
1089 * Try to deliver (tr) to the controller.
1090 *
1091 * Can be called at any interrupt level, with or without interrupts enabled.
1092 */
1093int
1094twe_start(struct twe_request *tr)
1095{
1096    struct twe_softc	*sc = tr->tr_sc;
1097    TWE_Command		*cmd;
1098    int			i, s, done;
1099    u_int32_t		status_reg;
1100
1101    debug_called(4);
1102
1103    /* mark the command as currently being processed */
1104    tr->tr_status = TWE_CMD_BUSY;
1105    cmd = TWE_FIND_COMMAND(tr);
1106
1107    /*
1108     * Spin briefly waiting for the controller to come ready
1109     *
1110     * XXX it might be more efficient to return EBUSY immediately
1111     *     and let the command be rescheduled.
1112     */
1113    for (i = 100000, done = 0; (i > 0) && !done; i--) {
1114	s = splbio();
1115
1116	/* check to see if we can post a command */
1117	status_reg = TWE_STATUS(sc);
1118	twe_check_bits(sc, status_reg);
1119
1120	if (!(status_reg & TWE_STATUS_COMMAND_QUEUE_FULL)) {
1121	    twe_enqueue_busy(tr);
1122
1123	    TWE_COMMAND_QUEUE(sc, TWE_FIND_COMMANDPHYS(tr));
1124	    done = 1;
1125	    /* move command to work queue */
1126#ifdef TWE_DEBUG
1127	    if (tr->tr_complete != NULL) {
1128		debug(3, "queued request %d with callback %p", cmd->generic.request_id, tr->tr_complete);
1129	    } else if (tr->tr_flags & TWE_CMD_SLEEPER) {
1130		debug(3, "queued request %d with wait channel %p", cmd->generic.request_id, tr);
1131	    } else {
1132		debug(3, "queued request %d for polling caller", cmd->generic.request_id);
1133	    }
1134#endif
1135	}
1136	splx(s);	/* drop spl to allow completion interrupts */
1137    }
1138
1139    /* command is enqueued */
1140    if (done)
1141	return(0);
1142
1143    /*
1144     * We couldn't get the controller to take the command; try submitting it again later.
1145     * This should only happen if something is wrong with the controller, or if we have
1146     * overestimated the number of commands it can accept.  (Should we actually reject
1147     * the command at this point?)
1148     */
1149    return(EBUSY);
1150}
1151
1152/********************************************************************************
1153 * Poll the controller (sc) for completed commands.
1154 *
1155 * Can be called at any interrupt level, with or without interrupts enabled.
1156 */
1157static void
1158twe_done(struct twe_softc *sc)
1159{
1160    TWE_Response_Queue	rq;
1161    TWE_Command		*cmd;
1162    struct twe_request	*tr;
1163    int			s, found;
1164    u_int32_t		status_reg;
1165
1166    debug_called(5);
1167
1168    /* loop collecting completed commands */
1169    found = 0;
1170    s = splbio();
1171    for (;;) {
1172	status_reg = TWE_STATUS(sc);
1173	twe_check_bits(sc, status_reg);		/* XXX should this fail? */
1174
1175	if (!(status_reg & TWE_STATUS_RESPONSE_QUEUE_EMPTY)) {
1176	    found = 1;
1177	    rq = TWE_RESPONSE_QUEUE(sc);
1178	    tr = sc->twe_lookup[rq.u.response_id];	/* find command */
1179	    cmd = TWE_FIND_COMMAND(tr);
1180	    if (tr->tr_status != TWE_CMD_BUSY)
1181		twe_printf(sc, "completion event for nonbusy command\n");
1182	    tr->tr_status = TWE_CMD_COMPLETE;
1183	    debug(3, "completed request id %d with status %d",
1184		  cmd->generic.request_id, cmd->generic.status);
1185	    /* move to completed queue */
1186	    twe_remove_busy(tr);
1187	    twe_enqueue_complete(tr);
1188	    sc->twe_state &= ~TWE_STATE_CTLR_BUSY;
1189	} else {
1190	    break;					/* no response ready */
1191	}
1192    }
1193    splx(s);
1194
1195    /* if we've completed any commands, try posting some more */
1196    if (found)
1197	twe_startio(sc);
1198
1199    /* handle completion and timeouts */
1200    twe_complete(sc);		/* XXX use deferred completion? */
1201}
1202
1203/********************************************************************************
1204 * Perform post-completion processing for commands on (sc).
1205 *
1206 * This is split from twe_done as it can be safely deferred and run at a lower
1207 * priority level should facilities for such a thing become available.
1208 */
1209static void
1210twe_complete(struct twe_softc *sc)
1211{
1212    struct twe_request	*tr;
1213
1214    debug_called(5);
1215
1216    /*
1217     * Pull commands off the completed list, dispatch them appropriately
1218     */
1219    while ((tr = twe_dequeue_complete(sc)) != NULL) {
1220	/* unmap the command's data buffer */
1221	twe_unmap_request(tr);
1222
1223	/* dispatch to suit command originator */
1224	if (tr->tr_complete != NULL) {		/* completion callback */
1225	    debug(2, "call completion handler %p", tr->tr_complete);
1226	    tr->tr_complete(tr);
1227
1228	} else if (tr->tr_flags & TWE_CMD_SLEEPER) {	/* caller is asleep waiting */
1229	    debug(2, "wake up command owner on %p", tr);
1230	    wakeup_one(tr);
1231
1232	} else {					/* caller is polling command */
1233	    debug(2, "command left for owner");
1234	}
1235    }
1236}
1237
1238/********************************************************************************
1239 * Wait for (status) to be set in the controller status register for up to
1240 * (timeout) seconds.  Returns 0 if found, nonzero if we time out.
1241 *
1242 * Note: this busy-waits, rather than sleeping, since we may be called with
1243 * eg. clock interrupts masked.
1244 */
1245static int
1246twe_wait_status(struct twe_softc *sc, u_int32_t status, int timeout)
1247{
1248    time_t	expiry;
1249    u_int32_t	status_reg;
1250
1251    debug_called(4);
1252
1253    expiry = time_second + timeout;
1254
1255    do {
1256	status_reg = TWE_STATUS(sc);
1257	if (status_reg & status)	/* got the required bit(s)? */
1258	    return(0);
1259	DELAY(100000);
1260    } while (time_second <= expiry);
1261
1262    return(1);
1263}
1264
1265/********************************************************************************
1266 * Drain the response queue, which may contain responses to commands we know
1267 * nothing about.
1268 */
1269static int
1270twe_drain_response_queue(struct twe_softc *sc)
1271{
1272    TWE_Response_Queue	rq;
1273    u_int32_t		status_reg;
1274
1275    debug_called(4);
1276
1277    for (;;) {				/* XXX give up eventually? */
1278	status_reg = TWE_STATUS(sc);
1279	if (twe_check_bits(sc, status_reg))
1280	    return(1);
1281	if (status_reg & TWE_STATUS_RESPONSE_QUEUE_EMPTY)
1282	    return(0);
1283	rq = TWE_RESPONSE_QUEUE(sc);
1284    }
1285}
1286
1287/********************************************************************************
1288 * Soft-reset the controller
1289 */
1290static int
1291twe_soft_reset(struct twe_softc *sc)
1292{
1293    u_int32_t		status_reg;
1294
1295    debug_called(2);
1296
1297    TWE_SOFT_RESET(sc);
1298
1299    if (twe_wait_status(sc, TWE_STATUS_ATTENTION_INTERRUPT, 30)) {
1300	twe_printf(sc, "no attention interrupt\n");
1301	return(1);
1302    }
1303    TWE_CONTROL(sc, TWE_CONTROL_CLEAR_ATTENTION_INTERRUPT);
1304    if (twe_drain_aen_queue(sc)) {
1305	twe_printf(sc, "can't drain AEN queue\n");
1306	return(1);
1307    }
1308    if (twe_find_aen(sc, TWE_AEN_SOFT_RESET)) {
1309	twe_printf(sc, "reset not reported\n");
1310	return(1);
1311    }
1312    status_reg = TWE_STATUS(sc);
1313    if (TWE_STATUS_ERRORS(status_reg) || twe_check_bits(sc, status_reg)) {
1314	twe_printf(sc, "controller errors detected\n");
1315	return(1);
1316    }
1317    if (twe_drain_response_queue(sc)) {
1318	twe_printf(sc, "can't drain response queue\n");
1319	return(1);
1320    }
1321    return(0);
1322}
1323
1324/********************************************************************************
1325 ********************************************************************************
1326                                                               Interrupt Handling
1327 ********************************************************************************
1328 ********************************************************************************/
1329
1330/********************************************************************************
1331 * Host interrupt.
1332 *
1333 * XXX what does this mean?
1334 */
1335static void
1336twe_host_intr(struct twe_softc *sc)
1337{
1338    debug_called(4);
1339
1340    twe_printf(sc, "host interrupt\n");
1341    TWE_CONTROL(sc, TWE_CONTROL_CLEAR_HOST_INTERRUPT);
1342}
1343
1344/********************************************************************************
1345 * Attention interrupt.
1346 *
1347 * Signalled when the controller has one or more AENs for us.
1348 */
1349static void
1350twe_attention_intr(struct twe_softc *sc)
1351{
1352    debug_called(4);
1353
1354    /* instigate a poll for AENs */
1355    if (twe_fetch_aen(sc)) {
1356	twe_printf(sc, "error polling for signalled AEN\n");
1357    } else {
1358	TWE_CONTROL(sc, TWE_CONTROL_CLEAR_ATTENTION_INTERRUPT);
1359    }
1360}
1361
1362/********************************************************************************
1363 * Command interrupt.
1364 *
1365 * Signalled when the controller can handle more commands.
1366 */
1367static void
1368twe_command_intr(struct twe_softc *sc)
1369{
1370    debug_called(4);
1371
1372    /*
1373     * We don't use this, rather we try to submit commands when we receive
1374     * them, and when other commands have completed.  Mask it so we don't get
1375     * another one.
1376     */
1377    TWE_CONTROL(sc, TWE_CONTROL_MASK_COMMAND_INTERRUPT);
1378}
1379
1380/********************************************************************************
1381 ********************************************************************************
1382                                                      Asynchronous Event Handling
1383 ********************************************************************************
1384 ********************************************************************************/
1385
1386/********************************************************************************
1387 * Request an AEN from the controller.
1388 */
1389static int
1390twe_fetch_aen(struct twe_softc *sc)
1391{
1392
1393    debug_called(4);
1394
1395    if ((twe_get_param(sc, TWE_PARAM_AEN, TWE_PARAM_AEN_UnitCode, 2, twe_handle_aen)) == NULL)
1396	return(EIO);
1397    return(0);
1398}
1399
1400/********************************************************************************
1401 * Handle an AEN returned by the controller.
1402 */
1403static void
1404twe_handle_aen(struct twe_request *tr)
1405{
1406    struct twe_softc	*sc = tr->tr_sc;
1407    TWE_Param		*param;
1408    u_int16_t		aen;
1409
1410    debug_called(4);
1411
1412    /* XXX check for command success somehow? */
1413
1414    param = (TWE_Param *)tr->tr_data;
1415    aen = *(u_int16_t *)(param->data);
1416
1417    free(tr->tr_data, M_DEVBUF);
1418    twe_release_request(tr);
1419    twe_enqueue_aen(sc, aen);
1420
1421    /* XXX poll for more AENs? */
1422}
1423
1424/********************************************************************************
1425 * Pull AENs out of the controller and park them in the queue, in a context where
1426 * interrupts aren't active.  Return nonzero if we encounter any errors in the
1427 * process of obtaining all the available AENs.
1428 */
1429static int
1430twe_drain_aen_queue(struct twe_softc *sc)
1431{
1432    u_int16_t	aen;
1433
1434    for (;;) {
1435	if (twe_get_param_2(sc, TWE_PARAM_AEN, TWE_PARAM_AEN_UnitCode, &aen))
1436	    return(1);
1437	if (aen == TWE_AEN_QUEUE_EMPTY)
1438	    return(0);
1439	twe_enqueue_aen(sc, aen);
1440    }
1441}
1442
1443/********************************************************************************
1444 * Push an AEN that we've received onto the queue.
1445 *
1446 * Note that we have to lock this against reentrance, since it may be called
1447 * from both interrupt and non-interrupt context.
1448 *
1449 * If someone is waiting for the AEN we have, wake them up.
1450 */
1451static void
1452twe_enqueue_aen(struct twe_softc *sc, u_int16_t aen)
1453{
1454    char	*msg;
1455    int		s, next, nextnext;
1456
1457    debug_called(4);
1458
1459    if ((msg = twe_format_aen(sc, aen)) != NULL)
1460	twe_printf(sc, "AEN: <%s>\n", msg);
1461
1462    s = splbio();
1463    /* enqueue the AEN */
1464    next = ((sc->twe_aen_head + 1) % TWE_Q_LENGTH);
1465    nextnext = ((sc->twe_aen_head + 2) % TWE_Q_LENGTH);
1466
1467    /* check to see if this is the last free slot, and subvert the AEN if it is */
1468    if (nextnext == sc->twe_aen_tail)
1469	aen = TWE_AEN_QUEUE_FULL;
1470
1471    /* look to see if there's room for this AEN */
1472    if (next != sc->twe_aen_tail) {
1473	sc->twe_aen_queue[sc->twe_aen_head] = aen;
1474	sc->twe_aen_head = next;
1475    }
1476
1477    /* wake up anyone asleep on the queue */
1478    wakeup(&sc->twe_aen_queue);
1479
1480    /* anyone looking for this AEN? */
1481    if (sc->twe_wait_aen == aen) {
1482	sc->twe_wait_aen = -1;
1483	wakeup(&sc->twe_wait_aen);
1484    }
1485    splx(s);
1486}
1487
1488/********************************************************************************
1489 * Pop an AEN off the queue, or return -1 if there are none left.
1490 *
1491 * We are more or less interrupt-safe, so don't block interrupts.
1492 */
1493static u_int16_t
1494twe_dequeue_aen(struct twe_softc *sc)
1495{
1496    u_int16_t	result;
1497
1498    debug_called(4);
1499
1500    if (sc->twe_aen_tail == sc->twe_aen_head) {
1501	result = TWE_AEN_QUEUE_EMPTY;
1502    } else {
1503	result = sc->twe_aen_queue[sc->twe_aen_tail];
1504	sc->twe_aen_tail = ((sc->twe_aen_tail + 1) % TWE_Q_LENGTH);
1505    }
1506    return(result);
1507}
1508
1509/********************************************************************************
1510 * Check to see if the requested AEN is in the queue.
1511 *
1512 * XXX we could probably avoid masking interrupts here
1513 */
1514static int
1515twe_find_aen(struct twe_softc *sc, u_int16_t aen)
1516{
1517    int		i, s, missing;
1518
1519    missing = 1;
1520    s = splbio();
1521    for (i = sc->twe_aen_tail; (i != sc->twe_aen_head) && missing; i = (i + 1) % TWE_Q_LENGTH) {
1522	if (sc->twe_aen_queue[i] == aen)
1523	    missing = 0;
1524    }
1525    splx(s);
1526    return(missing);
1527}
1528
1529
1530#if 0	/* currently unused */
1531/********************************************************************************
1532 * Sleep waiting for at least (timeout) seconds until we see (aen) as
1533 * requested.  Returns nonzero on timeout or failure.
1534 *
1535 * XXX: this should not be used in cases where there may be more than one sleeper
1536 *      without a mechanism for registering multiple sleepers.
1537 */
1538static int
1539twe_wait_aen(struct twe_softc *sc, int aen, int timeout)
1540{
1541    time_t	expiry;
1542    int		found, s;
1543
1544    debug_called(4);
1545
1546    expiry = time_second + timeout;
1547    found = 0;
1548
1549    s = splbio();
1550    sc->twe_wait_aen = aen;
1551    do {
1552	twe_fetch_aen(sc);
1553	tsleep(&sc->twe_wait_aen, PZERO, "twewaen", hz);
1554	if (sc->twe_wait_aen == -1)
1555	    found = 1;
1556    } while ((time_second <= expiry) && !found);
1557    splx(s);
1558    return(!found);
1559}
1560#endif
1561
1562/********************************************************************************
1563 ********************************************************************************
1564                                                        Command Buffer Management
1565 ********************************************************************************
1566 ********************************************************************************/
1567
1568/********************************************************************************
1569 * Get a new command buffer.
1570 *
1571 * This will return NULL if all command buffers are in use.
1572 */
1573static int
1574twe_get_request(struct twe_softc *sc, struct twe_request **tr)
1575{
1576    TWE_Command		*cmd;
1577    debug_called(4);
1578
1579    /* try to reuse an old buffer */
1580    *tr = twe_dequeue_free(sc);
1581
1582    /* initialise some fields to their defaults */
1583    if (*tr != NULL) {
1584	cmd = TWE_FIND_COMMAND(*tr);
1585	(*tr)->tr_data = NULL;
1586	(*tr)->tr_private = NULL;
1587	(*tr)->tr_status = TWE_CMD_SETUP;		/* command is in setup phase */
1588	(*tr)->tr_flags = 0;
1589	(*tr)->tr_complete = NULL;
1590	cmd->generic.status = 0;			/* before submission to controller */
1591	cmd->generic.flags = 0;				/* not used */
1592    }
1593    return(*tr == NULL);
1594}
1595
1596/********************************************************************************
1597 * Release a command buffer for reuse.
1598 *
1599 */
1600static void
1601twe_release_request(struct twe_request *tr)
1602{
1603    debug_called(4);
1604
1605    if (tr->tr_private != NULL)
1606	twe_panic(tr->tr_sc, "tr_private != NULL");
1607    twe_enqueue_free(tr);
1608}
1609
1610/********************************************************************************
1611 ********************************************************************************
1612                                                                        Debugging
1613 ********************************************************************************
1614 ********************************************************************************/
1615
1616/********************************************************************************
1617 * Print some information about the controller
1618 */
1619void
1620twe_describe_controller(struct twe_softc *sc)
1621{
1622    TWE_Param		*p[6];
1623    u_int8_t		ports;
1624    u_int32_t		size;
1625    int			i;
1626
1627    debug_called(2);
1628
1629    /* get the port count */
1630    twe_get_param_1(sc, TWE_PARAM_CONTROLLER, TWE_PARAM_CONTROLLER_PortCount, &ports);
1631
1632    /* get version strings */
1633    p[0] = twe_get_param(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_FW,   16, NULL);
1634    p[1] = twe_get_param(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_BIOS, 16, NULL);
1635    if (p[0] && p[1])
1636	 twe_printf(sc, "%d ports, Firmware %.16s, BIOS %.16s\n", ports, p[0]->data, p[1]->data);
1637
1638    if (bootverbose) {
1639	p[2] = twe_get_param(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_Mon,  16, NULL);
1640	p[3] = twe_get_param(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_PCB,  8, NULL);
1641	p[4] = twe_get_param(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_ATA,  8, NULL);
1642	p[5] = twe_get_param(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_PCI,  8, NULL);
1643
1644	if (p[2] && p[3] && p[4] && p[5])
1645	    twe_printf(sc, "Monitor %.16s, PCB %.8s, Achip %.8s, Pchip %.8s\n", p[2]->data, p[3]->data,
1646		p[4]->data, p[5]->data);
1647	if (p[2])
1648	    free(p[2], M_DEVBUF);
1649	if (p[3])
1650	    free(p[3], M_DEVBUF);
1651	if (p[4])
1652	    free(p[4], M_DEVBUF);
1653	if (p[5])
1654	    free(p[5], M_DEVBUF);
1655    }
1656    if (p[0])
1657	free(p[0], M_DEVBUF);
1658    if (p[1])
1659	free(p[1], M_DEVBUF);
1660
1661    /* print attached drives */
1662    if (bootverbose) {
1663	p[0] = twe_get_param(sc, TWE_PARAM_DRIVESUMMARY, TWE_PARAM_DRIVESUMMARY_Status, 16, NULL);
1664	for (i = 0; i < ports; i++) {
1665	    if (p[0]->data[i] != TWE_PARAM_DRIVESTATUS_Present)
1666		continue;
1667	    twe_get_param_4(sc, TWE_PARAM_DRIVEINFO + i, TWE_PARAM_DRIVEINFO_Size, &size);
1668	    p[1] = twe_get_param(sc, TWE_PARAM_DRIVEINFO + i, TWE_PARAM_DRIVEINFO_Model, 40, NULL);
1669	    if (p[1] != NULL) {
1670		twe_printf(sc, "port %d: %.40s %dMB\n", i, p[1]->data, size / 2048);
1671		free(p[1], M_DEVBUF);
1672	    } else {
1673		twe_printf(sc, "port %d, drive status unavailable\n", i);
1674	    }
1675	}
1676	if (p[0])
1677	    free(p[0], M_DEVBUF);
1678    }
1679}
1680
1681/********************************************************************************
1682 * Look up a text description of a numeric code and return a pointer to same.
1683 */
1684char *
1685twe_describe_code(struct twe_code_lookup *table, u_int32_t code)
1686{
1687    int         i;
1688
1689    for (i = 0; table[i].string != NULL; i++)
1690	if (table[i].code == code)
1691	    return(table[i].string);
1692    return(table[i+1].string);
1693}
1694
1695/********************************************************************************
1696 * Complain if the status bits aren't what we're expecting.
1697 *
1698 * Rate-limit the complaints to at most one of each every five seconds, but
1699 * always return the correct status.
1700 */
1701static int
1702twe_check_bits(struct twe_softc *sc, u_int32_t status_reg)
1703{
1704    int			result;
1705    static time_t	lastwarn[2] = {0, 0};
1706
1707    /*
1708     * This can be a little problematic, as twe_panic may call twe_reset if
1709     * TWE_DEBUG is not set, which will call us again as part of the soft reset.
1710     */
1711    if ((status_reg & TWE_STATUS_PANIC_BITS) != 0) {
1712	twe_printf(sc, "FATAL STATUS BIT(S) %b\n", status_reg & TWE_STATUS_PANIC_BITS,
1713		   TWE_STATUS_BITS_DESCRIPTION);
1714	twe_panic(sc, "fatal status bits");
1715    }
1716
1717    result = 0;
1718    if ((status_reg & TWE_STATUS_EXPECTED_BITS) != TWE_STATUS_EXPECTED_BITS) {
1719	if (time_second > (lastwarn[0] + 5)) {
1720	    twe_printf(sc, "missing expected status bit(s) %b\n", ~status_reg & TWE_STATUS_EXPECTED_BITS,
1721		       TWE_STATUS_BITS_DESCRIPTION);
1722	    lastwarn[0] = time_second;
1723	}
1724	result = 1;
1725    }
1726
1727    if ((status_reg & TWE_STATUS_UNEXPECTED_BITS) != 0) {
1728	if (time_second > (lastwarn[1] + 5)) {
1729	    twe_printf(sc, "unexpected status bit(s) %b\n", status_reg & TWE_STATUS_UNEXPECTED_BITS,
1730		       TWE_STATUS_BITS_DESCRIPTION);
1731	    lastwarn[1] = time_second;
1732	}
1733	result = 1;
1734	if (status_reg & TWE_STATUS_PCI_PARITY_ERROR) {
1735	    twe_printf(sc, "PCI parity error: Reseat card, move card or buggy device present.");
1736	    twe_clear_pci_parity_error(sc);
1737	}
1738	if (status_reg & TWE_STATUS_PCI_ABORT) {
1739	    twe_printf(sc, "PCI abort, clearing.\n");
1740	    twe_clear_pci_abort(sc);
1741	}
1742    }
1743
1744    return(result);
1745}
1746
1747/********************************************************************************
1748 * Return a string describing (aen).
1749 *
1750 * The low 8 bits of the aen are the code, the high 8 bits give the unit number
1751 * where an AEN is specific to a unit.
1752 *
1753 * Note that we could expand this routine to handle eg. up/downgrading the status
1754 * of a drive if we had some idea of what the drive's initial status was.
1755 */
1756
1757static char *
1758twe_format_aen(struct twe_softc *sc, u_int16_t aen)
1759{
1760    static char	buf[80];
1761    device_t	child;
1762    char	*code, *msg;
1763
1764    code = twe_describe_code(twe_table_aen, TWE_AEN_CODE(aen));
1765    msg = code + 2;
1766
1767    switch (*code) {
1768    case 'q':
1769	if (!bootverbose)
1770	    return(NULL);
1771	/* FALLTHROUGH */
1772    case 'a':
1773	return(msg);
1774
1775    case 'c':
1776	if ((child = sc->twe_drive[TWE_AEN_UNIT(aen)].td_disk) != NULL) {
1777	    sprintf(buf, "twed%d: %s", device_get_unit(child), msg);
1778	} else {
1779	    sprintf(buf, "twe%d: %s for unknown unit %d", device_get_unit(sc->twe_dev),
1780		    msg, TWE_AEN_UNIT(aen));
1781	}
1782	return(buf);
1783
1784    case 'p':
1785	sprintf(buf, "twe%d: port %d: %s", device_get_unit(sc->twe_dev), TWE_AEN_UNIT(aen),
1786		msg);
1787	return(buf);
1788
1789
1790    case 'x':
1791    default:
1792	break;
1793    }
1794    sprintf(buf, "unknown AEN 0x%x", aen);
1795    return(buf);
1796}
1797
1798/********************************************************************************
1799 * Print a diagnostic if the status of the command warrants it, and return
1800 * either zero (command was ok) or nonzero (command failed).
1801 */
1802static int
1803twe_report_request(struct twe_request *tr)
1804{
1805    struct twe_softc	*sc = tr->tr_sc;
1806    TWE_Command		*cmd = TWE_FIND_COMMAND(tr);
1807    int			result = 0;
1808
1809    /*
1810     * Check the command status value and handle accordingly.
1811     */
1812    if (cmd->generic.status == TWE_STATUS_RESET) {
1813	/*
1814	 * The status code 0xff requests a controller reset.
1815	 */
1816	twe_printf(sc, "command returned with controller reset request\n");
1817	twe_reset(sc);
1818	result = 1;
1819    } else if (cmd->generic.status > TWE_STATUS_FATAL) {
1820	/*
1821	 * Fatal errors that don't require controller reset.
1822	 *
1823	 * We know a few special flags values.
1824	 */
1825	switch (cmd->generic.flags) {
1826	case 0x1b:
1827	    device_printf(sc->twe_drive[cmd->generic.unit].td_disk,
1828			  "drive timeout");
1829	    break;
1830	case 0x51:
1831	    device_printf(sc->twe_drive[cmd->generic.unit].td_disk,
1832			  "unrecoverable drive error");
1833	    break;
1834	default:
1835	    device_printf(sc->twe_drive[cmd->generic.unit].td_disk,
1836			  "controller error - %s (flags = 0x%x)\n",
1837			  twe_describe_code(twe_table_status, cmd->generic.status),
1838			  cmd->generic.flags);
1839	    result = 1;
1840	}
1841    } else if (cmd->generic.status > TWE_STATUS_WARNING) {
1842	/*
1843	 * Warning level status.
1844	 */
1845	device_printf(sc->twe_drive[cmd->generic.unit].td_disk,
1846		      "warning - %s (flags = 0x%x)\n",
1847		      twe_describe_code(twe_table_status, cmd->generic.status),
1848		      cmd->generic.flags);
1849    } else if (cmd->generic.status > 0x40) {
1850	/*
1851	 * Info level status.
1852	 */
1853	device_printf(sc->twe_drive[cmd->generic.unit].td_disk,
1854		      "attention - %s (flags = 0x%x)\n",
1855		      twe_describe_code(twe_table_status, cmd->generic.status),
1856		      cmd->generic.flags);
1857    }
1858
1859    return(result);
1860}
1861
1862/********************************************************************************
1863 * Print some controller state to aid in debugging error/panic conditions
1864 */
1865void
1866twe_print_controller(struct twe_softc *sc)
1867{
1868    u_int32_t		status_reg;
1869
1870    status_reg = TWE_STATUS(sc);
1871    twe_printf(sc, "status   %b\n", status_reg, TWE_STATUS_BITS_DESCRIPTION);
1872    twe_printf(sc, "          current  max    min\n");
1873    twe_printf(sc, "free      %04d     %04d   %04d\n",
1874	sc->twe_qstat[TWEQ_FREE].q_length, sc->twe_qstat[TWEQ_FREE].q_max, sc->twe_qstat[TWEQ_FREE].q_min);
1875
1876    twe_printf(sc, "ready     %04d     %04d   %04d\n",
1877	sc->twe_qstat[TWEQ_READY].q_length, sc->twe_qstat[TWEQ_READY].q_max, sc->twe_qstat[TWEQ_READY].q_min);
1878
1879    twe_printf(sc, "busy      %04d     %04d   %04d\n",
1880	sc->twe_qstat[TWEQ_BUSY].q_length, sc->twe_qstat[TWEQ_BUSY].q_max, sc->twe_qstat[TWEQ_BUSY].q_min);
1881
1882    twe_printf(sc, "complete  %04d     %04d   %04d\n",
1883	sc->twe_qstat[TWEQ_COMPLETE].q_length, sc->twe_qstat[TWEQ_COMPLETE].q_max, sc->twe_qstat[TWEQ_COMPLETE].q_min);
1884
1885    twe_printf(sc, "bioq      %04d     %04d   %04d\n",
1886	sc->twe_qstat[TWEQ_BIO].q_length, sc->twe_qstat[TWEQ_BIO].q_max, sc->twe_qstat[TWEQ_BIO].q_min);
1887
1888    twe_printf(sc, "AEN queue head %d  tail %d\n", sc->twe_aen_head, sc->twe_aen_tail);
1889}
1890
1891static void
1892twe_panic(struct twe_softc *sc, char *reason)
1893{
1894    twe_print_controller(sc);
1895#ifdef TWE_DEBUG
1896    panic(reason);
1897#else
1898    twe_reset(sc);
1899#endif
1900}
1901
1902#if 0
1903/********************************************************************************
1904 * Print a request/command in human-readable format.
1905 */
1906static void
1907twe_print_request(struct twe_request *tr)
1908{
1909    struct twe_softc	*sc = tr->tr_sc;
1910    TWE_Command	*cmd = TWE_FIND_COMMAND(tr);
1911    int		i;
1912
1913    twe_printf(sc, "CMD: request_id %d  opcode <%s>  size %d  unit %d  host_id %d\n",
1914	       cmd->generic.request_id, twe_describe_code(twe_table_opcode, cmd->generic.opcode), cmd->generic.size,
1915	       cmd->generic.unit, cmd->generic.host_id);
1916    twe_printf(sc, " status %d  flags 0x%x  count %d  sgl_offset %d\n",
1917	       cmd->generic.status, cmd->generic.flags, cmd->generic.count, cmd->generic.sgl_offset);
1918
1919    switch(cmd->generic.opcode) {	/* XXX add more opcodes? */
1920    case TWE_OP_READ:
1921    case TWE_OP_WRITE:
1922	twe_printf(sc, " lba %d\n", cmd->io.lba);
1923	for (i = 0; (i < TWE_MAX_SGL_LENGTH) && (cmd->io.sgl[i].length != 0); i++)
1924	    twe_printf(sc, "  %d: 0x%x/%d\n",
1925		       i, cmd->io.sgl[i].address, cmd->io.sgl[i].length);
1926	break;
1927
1928    case TWE_OP_GET_PARAM:
1929    case TWE_OP_SET_PARAM:
1930	for (i = 0; (i < TWE_MAX_SGL_LENGTH) && (cmd->param.sgl[i].length != 0); i++)
1931	    twe_printf(sc, "  %d: 0x%x/%d\n",
1932		       i, cmd->param.sgl[i].address, cmd->param.sgl[i].length);
1933	break;
1934
1935    case TWE_OP_INIT_CONNECTION:
1936	twe_printf(sc, " response queue pointer 0x%x\n",
1937		   cmd->initconnection.response_queue_pointer);
1938	break;
1939
1940    default:
1941	break;
1942    }
1943    twe_printf(sc, " tr_command %p/0x%x  tr_data %p/0x%x,%d\n",
1944	       tr, TWE_FIND_COMMANDPHYS(tr), tr->tr_data, tr->tr_dataphys, tr->tr_length);
1945    twe_printf(sc, " tr_status %d  tr_flags 0x%x  tr_complete %p  tr_private %p\n",
1946	       tr->tr_status, tr->tr_flags, tr->tr_complete, tr->tr_private);
1947}
1948
1949#endif
1950