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