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