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