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