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