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