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