Style(9) cleanup to src/sys/vfs, stage 20/21: umapfs.
[dragonfly.git] / sys / dev / raid / twe / twe_freebsd.c
1 /*-
2  * Copyright (c) 2000 Michael Smith
3  * Copyright (c) 2000 BSDi
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/dev/twe/twe_freebsd.c,v 1.2.2.5 2002/03/07 09:57:02 msmith Exp $
28  * $DragonFly: src/sys/dev/raid/twe/twe_freebsd.c,v 1.9 2004/05/13 23:49:19 dillon Exp $
29  */
30
31 /*
32  * FreeBSD-specific code.
33  */
34
35 #include <sys/param.h>
36 #include <sys/cons.h>
37 #include <machine/bus.h>
38 #include <machine/clock.h>
39 #include <machine/md_var.h>
40 #include <vm/vm.h>
41 #include <vm/pmap.h>
42 #include "twe_compat.h"
43 #include "twereg.h"
44 #include "tweio.h"
45 #include "twevar.h"
46 #include "twe_tables.h"
47
48 #include <sys/devicestat.h>
49
50 static devclass_t       twe_devclass;
51
52 #ifdef TWE_DEBUG
53 static u_int32_t        twed_bio_in;
54 #define TWED_BIO_IN     twed_bio_in++
55 static u_int32_t        twed_bio_out;
56 #define TWED_BIO_OUT    twed_bio_out++
57 #else
58 #define TWED_BIO_IN
59 #define TWED_BIO_OUT
60 #endif
61
62 /********************************************************************************
63  ********************************************************************************
64                                                          Control device interface
65  ********************************************************************************
66  ********************************************************************************/
67
68 static  d_open_t                twe_open;
69 static  d_close_t               twe_close;
70 static  d_ioctl_t               twe_ioctl_wrapper;
71
72 #define TWE_CDEV_MAJOR  146
73
74 static struct cdevsw twe_cdevsw = {
75     /* name */  "twe",
76     /* cmaj */  TWE_CDEV_MAJOR,
77     /* flags */ 0,
78     /* port */  NULL,
79     /* clone */ NULL,
80
81     twe_open,
82     twe_close,
83     noread,
84     nowrite,
85     twe_ioctl_wrapper,
86     nopoll,
87     nommap,
88     nostrategy,
89     nodump,
90     nopsize,
91 };
92
93 /********************************************************************************
94  * Accept an open operation on the control device.
95  */
96 static int
97 twe_open(dev_t dev, int flags, int fmt, d_thread_t *td)
98 {
99     int                 unit = minor(dev);
100     struct twe_softc    *sc = devclass_get_softc(twe_devclass, unit);
101
102     sc->twe_state |= TWE_STATE_OPEN;
103     return(0);
104 }
105
106 /********************************************************************************
107  * Accept the last close on the control device.
108  */
109 static int
110 twe_close(dev_t dev, int flags, int fmt, d_thread_t *td)
111 {
112     int                 unit = minor(dev);
113     struct twe_softc    *sc = devclass_get_softc(twe_devclass, unit);
114
115     sc->twe_state &= ~TWE_STATE_OPEN;
116     return (0);
117 }
118
119 /********************************************************************************
120  * Handle controller-specific control operations.
121  */
122 static int
123 twe_ioctl_wrapper(dev_t dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *td)
124 {
125     struct twe_softc            *sc = (struct twe_softc *)dev->si_drv1;
126     
127     return(twe_ioctl(sc, cmd, addr));
128 }
129
130 /********************************************************************************
131  ********************************************************************************
132                                                              PCI device interface
133  ********************************************************************************
134  ********************************************************************************/
135
136 static int      twe_probe(device_t dev);
137 static int      twe_attach(device_t dev);
138 static void     twe_free(struct twe_softc *sc);
139 static int      twe_detach(device_t dev);
140 static void     twe_shutdown(device_t dev);
141 static int      twe_suspend(device_t dev);
142 static int      twe_resume(device_t dev);
143 static void     twe_pci_intr(void *arg);
144 static void     twe_intrhook(void *arg);
145
146 static device_method_t twe_methods[] = {
147     /* Device interface */
148     DEVMETHOD(device_probe,     twe_probe),
149     DEVMETHOD(device_attach,    twe_attach),
150     DEVMETHOD(device_detach,    twe_detach),
151     DEVMETHOD(device_shutdown,  twe_shutdown),
152     DEVMETHOD(device_suspend,   twe_suspend),
153     DEVMETHOD(device_resume,    twe_resume),
154
155     DEVMETHOD(bus_print_child,  bus_generic_print_child),
156     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
157     { 0, 0 }
158 };
159
160 static driver_t twe_pci_driver = {
161         "twe",
162         twe_methods,
163         sizeof(struct twe_softc)
164 };
165
166 #ifdef TWE_OVERRIDE
167 DRIVER_MODULE(Xtwe, pci, twe_pci_driver, twe_devclass, 0, 0);
168 #else
169 DRIVER_MODULE(twe, pci, twe_pci_driver, twe_devclass, 0, 0);
170 #endif
171
172 /********************************************************************************
173  * Match a 3ware Escalade ATA RAID controller.
174  */
175 static int
176 twe_probe(device_t dev)
177 {
178
179     debug_called(4);
180
181     if ((pci_get_vendor(dev) == TWE_VENDOR_ID) &&
182         ((pci_get_device(dev) == TWE_DEVICE_ID) || 
183          (pci_get_device(dev) == TWE_DEVICE_ID_ASIC))) {
184         device_set_desc(dev, TWE_DEVICE_NAME);
185 #ifdef TWE_OVERRIDE
186         return(0);
187 #else
188         return(-10);
189 #endif
190     }
191     return(ENXIO);
192 }
193
194 /********************************************************************************
195  * Allocate resources, initialise the controller.
196  */
197 static int
198 twe_attach(device_t dev)
199 {
200     struct twe_softc    *sc;
201     int                 rid, error;
202     u_int32_t           command;
203
204     debug_called(4);
205
206     /*
207      * Initialise the softc structure.
208      */
209     sc = device_get_softc(dev);
210     sc->twe_dev = dev;
211
212     sysctl_ctx_init(&sc->sysctl_ctx);
213     sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
214         SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
215         device_get_nameunit(dev), CTLFLAG_RD, 0, "");
216     if (sc->sysctl_tree == NULL) {
217         twe_printf(sc, "cannot add sysctl tree node\n");
218         return (ENXIO);
219     }
220     SYSCTL_ADD_STRING(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
221         OID_AUTO, "driver_version", CTLFLAG_RD, "$Revision$", 0,
222         "TWE driver version");
223
224     /*
225      * Make sure we are going to be able to talk to this board.
226      */
227     command = pci_read_config(dev, PCIR_COMMAND, 2);
228     if ((command & PCIM_CMD_PORTEN) == 0) {
229         twe_printf(sc, "register window not available\n");
230         return(ENXIO);
231     }
232     /*
233      * Force the busmaster enable bit on, in case the BIOS forgot.
234      */
235     command |= PCIM_CMD_BUSMASTEREN;
236     pci_write_config(dev, PCIR_COMMAND, command, 2);
237
238     /*
239      * Allocate the PCI register window.
240      */
241     rid = TWE_IO_CONFIG_REG;
242     if ((sc->twe_io = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid, 0, ~0, 1, RF_ACTIVE)) == NULL) {
243         twe_printf(sc, "can't allocate register window\n");
244         twe_free(sc);
245         return(ENXIO);
246     }
247     sc->twe_btag = rman_get_bustag(sc->twe_io);
248     sc->twe_bhandle = rman_get_bushandle(sc->twe_io);
249
250     /*
251      * Allocate the parent bus DMA tag appropriate for PCI.
252      */
253     if (bus_dma_tag_create(NULL,                                /* parent */
254                            1, 0,                                /* alignment, boundary */
255                            BUS_SPACE_MAXADDR_32BIT,             /* lowaddr */
256                            BUS_SPACE_MAXADDR,                   /* highaddr */
257                            NULL, NULL,                          /* filter, filterarg */
258                            MAXBSIZE, TWE_MAX_SGL_LENGTH,        /* maxsize, nsegments */
259                            BUS_SPACE_MAXSIZE_32BIT,             /* maxsegsize */
260                            BUS_DMA_ALLOCNOW,                    /* flags */
261                            &sc->twe_parent_dmat)) {
262         twe_printf(sc, "can't allocate parent DMA tag\n");
263         twe_free(sc);
264         return(ENOMEM);
265     }
266
267     /* 
268      * Allocate and connect our interrupt.
269      */
270     rid = 0;
271     if ((sc->twe_irq = bus_alloc_resource(sc->twe_dev, SYS_RES_IRQ, &rid, 0, ~0, 1, RF_SHAREABLE | RF_ACTIVE)) == NULL) {
272         twe_printf(sc, "can't allocate interrupt\n");
273         twe_free(sc);
274         return(ENXIO);
275     }
276     if (bus_setup_intr(sc->twe_dev, sc->twe_irq, INTR_TYPE_BIO | INTR_ENTROPY,  twe_pci_intr, sc, &sc->twe_intr)) {
277         twe_printf(sc, "can't set up interrupt\n");
278         twe_free(sc);
279         return(ENXIO);
280     }
281
282     /*
283      * Create DMA tag for mapping objects into controller-addressable space.
284      */
285     if (bus_dma_tag_create(sc->twe_parent_dmat,         /* parent */
286                            1, 0,                        /* alignment, boundary */
287                            BUS_SPACE_MAXADDR,           /* lowaddr */
288                            BUS_SPACE_MAXADDR,           /* highaddr */
289                            NULL, NULL,                  /* filter, filterarg */
290                            MAXBSIZE, TWE_MAX_SGL_LENGTH,/* maxsize, nsegments */
291                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
292                            0,                           /* flags */
293                            &sc->twe_buffer_dmat)) {
294         twe_printf(sc, "can't allocate data buffer DMA tag\n");
295         twe_free(sc);
296         return(ENOMEM);
297     }
298
299     /*
300      * Initialise the controller and driver core.
301      */
302     if ((error = twe_setup(sc)))
303         return(error);
304
305     /*
306      * Print some information about the controller and configuration.
307      */
308     twe_describe_controller(sc);
309
310     /*
311      * Create the control device.
312      */
313     sc->twe_dev_t = make_dev(&twe_cdevsw, device_get_unit(sc->twe_dev), UID_ROOT, GID_OPERATOR,
314                              S_IRUSR | S_IWUSR, "twe%d", device_get_unit(sc->twe_dev));
315     sc->twe_dev_t->si_drv1 = sc;
316     /*
317      * Schedule ourselves to bring the controller up once interrupts are available.
318      * This isn't strictly necessary, since we disable interrupts while probing the
319      * controller, but it is more in keeping with common practice for other disk 
320      * devices.
321      */
322     sc->twe_ich.ich_func = twe_intrhook;
323     sc->twe_ich.ich_arg = sc;
324     if (config_intrhook_establish(&sc->twe_ich) != 0) {
325         twe_printf(sc, "can't establish configuration hook\n");
326         twe_free(sc);
327         return(ENXIO);
328     }
329
330     return(0);
331 }
332
333 /********************************************************************************
334  * Free all of the resources associated with (sc).
335  *
336  * Should not be called if the controller is active.
337  */
338 static void
339 twe_free(struct twe_softc *sc)
340 {
341     struct twe_request  *tr;
342
343     debug_called(4);
344
345     /* throw away any command buffers */
346     while ((tr = twe_dequeue_free(sc)) != NULL)
347         twe_free_request(tr);
348
349     /* destroy the data-transfer DMA tag */
350     if (sc->twe_buffer_dmat)
351         bus_dma_tag_destroy(sc->twe_buffer_dmat);
352
353     /* disconnect the interrupt handler */
354     if (sc->twe_intr)
355         bus_teardown_intr(sc->twe_dev, sc->twe_irq, sc->twe_intr);
356     if (sc->twe_irq != NULL)
357         bus_release_resource(sc->twe_dev, SYS_RES_IRQ, 0, sc->twe_irq);
358
359     /* destroy the parent DMA tag */
360     if (sc->twe_parent_dmat)
361         bus_dma_tag_destroy(sc->twe_parent_dmat);
362
363     /* release the register window mapping */
364     if (sc->twe_io != NULL)
365         bus_release_resource(sc->twe_dev, SYS_RES_IOPORT, TWE_IO_CONFIG_REG, sc->twe_io);
366
367     /* destroy control device */
368     if (sc->twe_dev_t != (dev_t)NULL)
369         destroy_dev(sc->twe_dev_t);
370
371     sysctl_ctx_free(&sc->sysctl_ctx);
372 }
373
374 /********************************************************************************
375  * Disconnect from the controller completely, in preparation for unload.
376  */
377 static int
378 twe_detach(device_t dev)
379 {
380     struct twe_softc    *sc = device_get_softc(dev);
381     int                 s, error;
382
383     debug_called(4);
384
385     error = EBUSY;
386     s = splbio();
387     if (sc->twe_state & TWE_STATE_OPEN)
388         goto out;
389
390     /*  
391      * Shut the controller down.
392      */
393     twe_shutdown(dev);
394
395     twe_free(sc);
396
397     error = 0;
398  out:
399     splx(s);
400     return(error);
401 }
402
403 /********************************************************************************
404  * Bring the controller down to a dormant state and detach all child devices.
405  *
406  * Note that we can assume that the bioq on the controller is empty, as we won't
407  * allow shutdown if any device is open.
408  */
409 static void
410 twe_shutdown(device_t dev)
411 {
412     struct twe_softc    *sc = device_get_softc(dev);
413     int                 i, s;
414
415     debug_called(4);
416
417     s = splbio();
418
419     /* 
420      * Delete all our child devices.
421      */
422     for (i = 0; i < TWE_MAX_UNITS; i++) {
423         twe_detach_drive(sc, i);
424     }
425
426     /*
427      * Bring the controller down.
428      */
429     twe_deinit(sc);
430
431     splx(s);
432 }
433
434 /********************************************************************************
435  * Bring the controller to a quiescent state, ready for system suspend.
436  */
437 static int
438 twe_suspend(device_t dev)
439 {
440     struct twe_softc    *sc = device_get_softc(dev);
441     int                 s;
442
443     debug_called(4);
444
445     s = splbio();
446     sc->twe_state |= TWE_STATE_SUSPEND;
447     
448     twe_disable_interrupts(sc);
449     splx(s);
450
451     return(0);
452 }
453
454 /********************************************************************************
455  * Bring the controller back to a state ready for operation.
456  */
457 static int
458 twe_resume(device_t dev)
459 {
460     struct twe_softc    *sc = device_get_softc(dev);
461
462     debug_called(4);
463
464     sc->twe_state &= ~TWE_STATE_SUSPEND;
465     twe_enable_interrupts(sc);
466
467     return(0);
468 }
469
470 /*******************************************************************************
471  * Take an interrupt, or be poked by other code to look for interrupt-worthy
472  * status.
473  */
474 static void
475 twe_pci_intr(void *arg)
476 {
477     twe_intr((struct twe_softc *)arg);
478 }
479
480 /********************************************************************************
481  * Delayed-startup hook
482  */
483 static void
484 twe_intrhook(void *arg)
485 {
486     struct twe_softc            *sc = (struct twe_softc *)arg;
487
488     /* pull ourselves off the intrhook chain */
489     config_intrhook_disestablish(&sc->twe_ich);
490
491     /* call core startup routine */
492     twe_init(sc);
493 }
494
495 /********************************************************************************
496  * Given a detected drive, attach it to the bio interface.
497  *
498  * This is called from twe_add_unit.
499  */
500 void
501 twe_attach_drive(struct twe_softc *sc, struct twe_drive *dr)
502 {
503     char        buf[80];
504     int         error;
505
506     dr->td_disk =  device_add_child(sc->twe_dev, NULL, -1);
507     if (dr->td_disk == NULL) {
508         twe_printf(sc, "device_add_child failed\n");
509         return;
510     }
511     device_set_ivars(dr->td_disk, dr);
512
513     /* 
514      * XXX It would make sense to test the online/initialising bits, but they seem to be
515      * always set...
516      */
517     sprintf(buf, "Unit %d, %s, %s",
518             dr->td_unit,
519             twe_describe_code(twe_table_unittype, dr->td_type),
520             twe_describe_code(twe_table_unitstate, dr->td_state & TWE_PARAM_UNITSTATUS_MASK));
521     device_set_desc_copy(dr->td_disk, buf);
522
523     if ((error = bus_generic_attach(sc->twe_dev)) != 0)
524         twe_printf(sc, "bus_generic_attach returned %d\n", error);
525 }
526
527 /********************************************************************************
528  * Detach the specified unit if it exsists
529  *
530  * This is called from twe_del_unit.
531  */
532 void
533 twe_detach_drive(struct twe_softc *sc, int unit)
534 {
535
536     if (sc->twe_drive[unit].td_disk != 0) {
537         if (device_delete_child(sc->twe_dev, sc->twe_drive[unit].td_disk) != 0)
538             twe_printf(sc, "failed to delete unit %d\n", unit);
539         sc->twe_drive[unit].td_disk = 0;
540     }
541 }
542
543 /********************************************************************************
544  * Clear a PCI parity error.
545  */
546 void
547 twe_clear_pci_parity_error(struct twe_softc *sc)
548 {
549     TWE_CONTROL(sc, TWE_CONTROL_CLEAR_PARITY_ERROR);
550     pci_write_config(sc->twe_dev, PCIR_STATUS, TWE_PCI_CLEAR_PARITY_ERROR, 2);
551 }
552
553 /********************************************************************************
554  * Clear a PCI abort.
555  */
556 void
557 twe_clear_pci_abort(struct twe_softc *sc)
558 {
559     TWE_CONTROL(sc, TWE_CONTROL_CLEAR_PCI_ABORT);
560     pci_write_config(sc->twe_dev, PCIR_STATUS, TWE_PCI_CLEAR_PCI_ABORT, 2);
561 }
562
563 /********************************************************************************
564  ********************************************************************************
565                                                                       Disk device
566  ********************************************************************************
567  ********************************************************************************/
568
569 /*
570  * Disk device softc
571  */
572 struct twed_softc 
573 {
574     device_t            twed_dev;
575     dev_t               twed_dev_t;
576     struct twe_softc    *twed_controller;       /* parent device softc */
577     struct twe_drive    *twed_drive;            /* drive data in parent softc */
578     struct disk         twed_disk;              /* generic disk handle */
579     struct devstat      twed_stats;             /* accounting */
580     struct disklabel    twed_label;             /* synthetic label */
581     int                 twed_flags;
582 #define TWED_OPEN       (1<<0)                  /* drive is open (can't shut down) */
583 };
584
585 /*
586  * Disk device bus interface
587  */
588 static int twed_probe(device_t dev);
589 static int twed_attach(device_t dev);
590 static int twed_detach(device_t dev);
591
592 static device_method_t twed_methods[] = {
593     DEVMETHOD(device_probe,     twed_probe),
594     DEVMETHOD(device_attach,    twed_attach),
595     DEVMETHOD(device_detach,    twed_detach),
596     { 0, 0 }
597 };
598
599 static driver_t twed_driver = {
600     "twed",
601     twed_methods,
602     sizeof(struct twed_softc)
603 };
604
605 static devclass_t       twed_devclass;
606 #ifdef TWE_OVERRIDE
607 DRIVER_MODULE(Xtwed, Xtwe, twed_driver, twed_devclass, 0, 0);
608 #else
609 DRIVER_MODULE(twed, twe, twed_driver, twed_devclass, 0, 0);
610 #endif
611
612 /*
613  * Disk device control interface.
614  */
615 static  d_open_t        twed_open;
616 static  d_close_t       twed_close;
617 static  d_strategy_t    twed_strategy;
618 static  d_dump_t        twed_dump;
619
620 #define TWED_CDEV_MAJOR 147
621
622 static struct cdevsw twed_cdevsw = {
623     "twed",
624     TWED_CDEV_MAJOR,
625     D_DISK,
626     /* port */  NULL,
627     /* clone */ NULL,
628     twed_open,
629     twed_close,
630     physread,
631     physwrite,
632     noioctl,
633     nopoll,
634     nommap,
635     twed_strategy,
636     twed_dump,
637     nopsize,
638 };
639
640
641 /********************************************************************************
642  * Handle open from generic layer.
643  *
644  * Note that this is typically only called by the diskslice code, and not
645  * for opens on subdevices (eg. slices, partitions).
646  */
647 static int
648 twed_open(dev_t dev, int flags, int fmt, d_thread_t *td)
649 {
650     struct twed_softc   *sc = (struct twed_softc *)dev->si_drv1;
651     struct disklabel    *label;
652
653     debug_called(4);
654         
655     if (sc == NULL)
656         return (ENXIO);
657
658     /* check that the controller is up and running */
659     if (sc->twed_controller->twe_state & TWE_STATE_SHUTDOWN)
660         return(ENXIO);
661
662     /* build synthetic label */
663     label = &sc->twed_disk.d_label;
664     bzero(label, sizeof(*label));
665     label->d_type = DTYPE_ESDI;
666     label->d_secsize    = TWE_BLOCK_SIZE;
667     label->d_nsectors   = sc->twed_drive->td_sectors;
668     label->d_ntracks    = sc->twed_drive->td_heads;
669     label->d_ncylinders = sc->twed_drive->td_cylinders;
670     label->d_secpercyl  = sc->twed_drive->td_sectors * sc->twed_drive->td_heads;
671     label->d_secperunit = sc->twed_drive->td_size;
672
673     sc->twed_flags |= TWED_OPEN;
674     return (0);
675 }
676
677 /********************************************************************************
678  * Handle last close of the disk device.
679  */
680 static int
681 twed_close(dev_t dev, int flags, int fmt, d_thread_t *td)
682 {
683     struct twed_softc   *sc = (struct twed_softc *)dev->si_drv1;
684
685     debug_called(4);
686         
687     if (sc == NULL)
688         return (ENXIO);
689
690     sc->twed_flags &= ~TWED_OPEN;
691     return (0);
692 }
693
694 /********************************************************************************
695  * Handle an I/O request.
696  */
697 static void
698 twed_strategy(twe_bio *bp)
699 {
700     struct twed_softc   *sc = (struct twed_softc *)TWE_BIO_SOFTC(bp);
701
702     debug_called(4);
703
704     TWED_BIO_IN;
705
706     /* bogus disk? */
707     if (sc == NULL) {
708         TWE_BIO_SET_ERROR(bp, EINVAL);
709         printf("twe: bio for invalid disk!\n");
710         TWE_BIO_DONE(bp);
711         TWED_BIO_OUT;
712         return;
713     }
714
715     /* perform accounting */
716     TWE_BIO_STATS_START(bp);
717
718     /* queue the bio on the controller */
719     twe_enqueue_bio(sc->twed_controller, bp);
720
721     /* poke the controller to start I/O */
722     twe_startio(sc->twed_controller);
723     return;
724 }
725
726 /********************************************************************************
727  * System crashdump support
728  */
729 int
730 twed_dump(dev_t dev)
731 {
732     struct twed_softc   *twed_sc = (struct twed_softc *)dev->si_drv1;
733     struct twe_softc    *twe_sc  = (struct twe_softc *)twed_sc->twed_controller;
734     u_int               count, blkno, secsize;
735     vm_paddr_t          addr = 0;
736     long                blkcnt;
737     int                 dumppages = MAXDUMPPGS;
738     int                 error;
739     int                 i;
740
741     if ((error = disk_dumpcheck(dev, &count, &blkno, &secsize)))
742         return(error);
743
744     if (!twed_sc || !twe_sc)
745         return(ENXIO);
746
747     blkcnt = howmany(PAGE_SIZE, secsize);
748
749     while (count > 0) {
750         caddr_t va = NULL;
751
752         if ((count / blkcnt) < dumppages)
753             dumppages = count / blkcnt;
754
755         for (i = 0; i < dumppages; ++i) {
756             vm_paddr_t a = addr + (i * PAGE_SIZE);
757             if (is_physical_memory(a))
758                 va = pmap_kenter_temporary(trunc_page(a), i);
759             else
760                 va = pmap_kenter_temporary(trunc_page(0), i);
761         }
762
763         if ((error = twe_dump_blocks(twe_sc, twed_sc->twed_drive->td_unit, blkno, va, 
764                                      (PAGE_SIZE * dumppages) / TWE_BLOCK_SIZE)) != 0)
765             return(error);
766
767
768         if (dumpstatus(addr, (off_t)count * DEV_BSIZE) < 0)
769             return(EINTR);
770
771         blkno += blkcnt * dumppages;
772         count -= blkcnt * dumppages;
773         addr += PAGE_SIZE * dumppages;
774     }
775     return(0);
776 }
777
778 /********************************************************************************
779  * Handle completion of an I/O request.
780  */
781 void
782 twed_intr(twe_bio *bp)
783 {
784     debug_called(4);
785
786     /* if no error, transfer completed */
787     if (!TWE_BIO_HAS_ERROR(bp))
788         TWE_BIO_RESID(bp) = 0;
789
790     TWE_BIO_STATS_END(bp);
791     TWE_BIO_DONE(bp);
792     TWED_BIO_OUT;
793 }
794
795 /********************************************************************************
796  * Default probe stub.
797  */
798 static int
799 twed_probe(device_t dev)
800 {
801     return (0);
802 }
803
804 /********************************************************************************
805  * Attach a unit to the controller.
806  */
807 static int
808 twed_attach(device_t dev)
809 {
810     struct twed_softc   *sc;
811     device_t            parent;
812     dev_t               dsk;
813     
814     debug_called(4);
815
816     /* initialise our softc */
817     sc = device_get_softc(dev);
818     parent = device_get_parent(dev);
819     sc->twed_controller = (struct twe_softc *)device_get_softc(parent);
820     sc->twed_drive = device_get_ivars(dev);
821     sc->twed_dev = dev;
822
823     /* report the drive */
824     twed_printf(sc, "%uMB (%u sectors)\n",
825                 sc->twed_drive->td_size / ((1024 * 1024) / TWE_BLOCK_SIZE),
826                 sc->twed_drive->td_size);
827     
828     devstat_add_entry(&sc->twed_stats, "twed", device_get_unit(dev), TWE_BLOCK_SIZE,
829                       DEVSTAT_NO_ORDERED_TAGS,
830                       DEVSTAT_TYPE_STORARRAY | DEVSTAT_TYPE_IF_OTHER, 
831                       DEVSTAT_PRIORITY_ARRAY);
832
833     /* attach a generic disk device to ourselves */
834     dsk = disk_create(device_get_unit(dev), &sc->twed_disk, 0, &twed_cdevsw);
835     dsk->si_drv1 = sc;
836     dsk->si_drv2 = &sc->twed_drive->td_unit;
837     sc->twed_dev_t = dsk;
838
839     /* set the maximum I/O size to the theoretical maximum allowed by the S/G list size */
840     dsk->si_iosize_max = (TWE_MAX_SGL_LENGTH - 1) * PAGE_SIZE;
841
842     return (0);
843 }
844
845 /********************************************************************************
846  * Disconnect ourselves from the system.
847  */
848 static int
849 twed_detach(device_t dev)
850 {
851     struct twed_softc *sc = (struct twed_softc *)device_get_softc(dev);
852
853     debug_called(4);
854
855     if (sc->twed_flags & TWED_OPEN)
856         return(EBUSY);
857
858     devstat_remove_entry(&sc->twed_stats);
859     disk_destroy(&sc->twed_disk);
860
861     return(0);
862 }
863
864 /********************************************************************************
865  ********************************************************************************
866                                                                              Misc
867  ********************************************************************************
868  ********************************************************************************/
869
870 static void     twe_setup_data_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
871 static void     twe_setup_request_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
872
873 /********************************************************************************
874  * Malloc space for a command buffer.
875  */
876 MALLOC_DEFINE(TWE_MALLOC_CLASS, "twe commands", "twe commands");
877
878 struct twe_request *
879 twe_allocate_request(struct twe_softc *sc)
880 {
881     struct twe_request  *tr;
882     int aligned_size;
883
884     /*
885      * TWE requires requests to be 512-byte aligned.  Depend on malloc()
886      * guarenteeing alignment for power-of-2 requests.  Note that the old
887      * (FreeBSD-4.x) malloc code aligned all requests, but the new slab
888      * allocator only guarentees same-size alignment for power-of-2 requests.
889      */
890     aligned_size = (sizeof(struct twe_request) + TWE_ALIGNMASK) &
891                     ~TWE_ALIGNMASK;
892     if ((tr = malloc(aligned_size, TWE_MALLOC_CLASS, M_NOWAIT)) == NULL)
893         return(NULL);
894     bzero(tr, sizeof(*tr));
895     tr->tr_sc = sc;
896     if (bus_dmamap_create(sc->twe_buffer_dmat, 0, &tr->tr_cmdmap)) {
897         twe_free_request(tr);
898         return(NULL);
899     }
900     if (bus_dmamap_create(sc->twe_buffer_dmat, 0, &tr->tr_dmamap)) {
901         bus_dmamap_destroy(sc->twe_buffer_dmat, tr->tr_cmdmap);
902         twe_free_request(tr);
903         return(NULL);
904     }    
905     return(tr);
906 }
907
908 /********************************************************************************
909  * Permanently discard a command buffer.
910  */
911 void
912 twe_free_request(struct twe_request *tr) 
913 {
914     struct twe_softc    *sc = tr->tr_sc;
915     
916     debug_called(4);
917
918     bus_dmamap_destroy(sc->twe_buffer_dmat, tr->tr_cmdmap);
919     bus_dmamap_destroy(sc->twe_buffer_dmat, tr->tr_dmamap);
920     free(tr, TWE_MALLOC_CLASS);
921 }
922
923 /********************************************************************************
924  * Map/unmap (tr)'s command and data in the controller's addressable space.
925  *
926  * These routines ensure that the data which the controller is going to try to
927  * access is actually visible to the controller, in a machine-independant 
928  * fashion.  Due to a hardware limitation, I/O buffers must be 512-byte aligned
929  * and we take care of that here as well.
930  */
931 static void
932 twe_fillin_sgl(TWE_SG_Entry *sgl, bus_dma_segment_t *segs, int nsegments, int max_sgl)
933 {
934     int i;
935
936     for (i = 0; i < nsegments; i++) {
937         sgl[i].address = segs[i].ds_addr;
938         sgl[i].length = segs[i].ds_len;
939     }
940     for (; i < max_sgl; i++) {                          /* XXX necessary? */
941         sgl[i].address = 0;
942         sgl[i].length = 0;
943     }
944 }
945                 
946 static void
947 twe_setup_data_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
948 {
949     struct twe_request  *tr = (struct twe_request *)arg;
950     TWE_Command         *cmd = &tr->tr_command;
951
952     debug_called(4);
953
954     /* save base of first segment in command (applicable if there only one segment) */
955     tr->tr_dataphys = segs[0].ds_addr;
956
957     /* correct command size for s/g list size */
958     tr->tr_command.generic.size += 2 * nsegments;
959
960     /*
961      * Due to the fact that parameter and I/O commands have the scatter/gather list in
962      * different places, we need to determine which sort of command this actually is
963      * before we can populate it correctly.
964      */
965     switch(cmd->generic.opcode) {
966     case TWE_OP_GET_PARAM:
967     case TWE_OP_SET_PARAM:
968         cmd->generic.sgl_offset = 2;
969         twe_fillin_sgl(&cmd->param.sgl[0], segs, nsegments, TWE_MAX_SGL_LENGTH);
970         break;
971     case TWE_OP_READ:
972     case TWE_OP_WRITE:
973         cmd->generic.sgl_offset = 3;
974         twe_fillin_sgl(&cmd->io.sgl[0], segs, nsegments, TWE_MAX_SGL_LENGTH);
975         break;
976     case TWE_OP_ATA_PASSTHROUGH:
977         cmd->generic.sgl_offset = 5;
978         twe_fillin_sgl(&cmd->ata.sgl[0], segs, nsegments, TWE_MAX_ATA_SGL_LENGTH);
979         break;
980     default:
981         /*
982          * Fall back to what the linux driver does.
983          * Do this because the API may send an opcode
984          * the driver knows nothing about and this will
985          * at least stop PCIABRT's from hosing us.
986          */
987         switch (cmd->generic.sgl_offset) {
988         case 2:
989             twe_fillin_sgl(&cmd->param.sgl[0], segs, nsegments, TWE_MAX_SGL_LENGTH);
990             break;
991         case 3:
992             twe_fillin_sgl(&cmd->io.sgl[0], segs, nsegments, TWE_MAX_SGL_LENGTH);
993             break;
994         case 5:
995             twe_fillin_sgl(&cmd->ata.sgl[0], segs, nsegments, TWE_MAX_ATA_SGL_LENGTH);
996             break;
997         }
998     }
999 }
1000
1001 static void
1002 twe_setup_request_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
1003 {
1004     struct twe_request  *tr = (struct twe_request *)arg;
1005
1006     debug_called(4);
1007
1008     /* command can't cross a page boundary */
1009     tr->tr_cmdphys = segs[0].ds_addr;
1010 }
1011
1012 void
1013 twe_map_request(struct twe_request *tr)
1014 {
1015     struct twe_softc    *sc = tr->tr_sc;
1016
1017     debug_called(4);
1018
1019
1020     /*
1021      * Map the command into bus space.
1022      */
1023     bus_dmamap_load(sc->twe_buffer_dmat, tr->tr_cmdmap, &tr->tr_command, sizeof(tr->tr_command), 
1024                     twe_setup_request_dmamap, tr, 0);
1025     bus_dmamap_sync(sc->twe_buffer_dmat, tr->tr_cmdmap, BUS_DMASYNC_PREWRITE);
1026
1027     /*
1028      * If the command involves data, map that too.
1029      */
1030     if (tr->tr_data != NULL) {
1031
1032         /* 
1033          * Data must be 512-byte aligned; allocate a fixup buffer if it's not.
1034          */
1035         if (((vm_offset_t)tr->tr_data % TWE_ALIGNMENT) != 0) {
1036             int aligned_size;
1037
1038             aligned_size = (tr->tr_length + TWE_ALIGNMASK) & ~TWE_ALIGNMASK;
1039             tr->tr_realdata = tr->tr_data;                              /* save pointer to 'real' data */
1040             tr->tr_flags |= TWE_CMD_ALIGNBUF;
1041             tr->tr_data = malloc(aligned_size, TWE_MALLOC_CLASS, M_NOWAIT);     /* XXX check result here */
1042         }
1043         
1044         /*
1045          * Map the data buffer into bus space and build the s/g list.
1046          */
1047         bus_dmamap_load(sc->twe_buffer_dmat, tr->tr_dmamap, tr->tr_data, tr->tr_length, 
1048                         twe_setup_data_dmamap, tr, 0);
1049         if (tr->tr_flags & TWE_CMD_DATAIN)
1050             bus_dmamap_sync(sc->twe_buffer_dmat, tr->tr_dmamap, BUS_DMASYNC_PREREAD);
1051         if (tr->tr_flags & TWE_CMD_DATAOUT) {
1052             /* if we're using an alignment buffer, and we're writing data, copy the real data out */
1053             if (tr->tr_flags & TWE_CMD_ALIGNBUF)
1054                 bcopy(tr->tr_realdata, tr->tr_data, tr->tr_length);
1055             bus_dmamap_sync(sc->twe_buffer_dmat, tr->tr_dmamap, BUS_DMASYNC_PREWRITE);
1056         }
1057     }
1058 }
1059
1060 void
1061 twe_unmap_request(struct twe_request *tr)
1062 {
1063     struct twe_softc    *sc = tr->tr_sc;
1064
1065     debug_called(4);
1066
1067     /*
1068      * Unmap the command from bus space.
1069      */
1070     bus_dmamap_sync(sc->twe_buffer_dmat, tr->tr_cmdmap, BUS_DMASYNC_POSTWRITE);
1071     bus_dmamap_unload(sc->twe_buffer_dmat, tr->tr_cmdmap); 
1072
1073     /*
1074      * If the command involved data, unmap that too.
1075      */
1076     if (tr->tr_data != NULL) {
1077         
1078         if (tr->tr_flags & TWE_CMD_DATAIN) {
1079             bus_dmamap_sync(sc->twe_buffer_dmat, tr->tr_dmamap, BUS_DMASYNC_POSTREAD);
1080             /* if we're using an alignment buffer, and we're reading data, copy the real data in */
1081             if (tr->tr_flags & TWE_CMD_ALIGNBUF)
1082                 bcopy(tr->tr_data, tr->tr_realdata, tr->tr_length);
1083         }
1084         if (tr->tr_flags & TWE_CMD_DATAOUT)
1085             bus_dmamap_sync(sc->twe_buffer_dmat, tr->tr_dmamap, BUS_DMASYNC_POSTWRITE);
1086
1087         bus_dmamap_unload(sc->twe_buffer_dmat, tr->tr_dmamap); 
1088     }
1089
1090     /* free alignment buffer if it was used */
1091     if (tr->tr_flags & TWE_CMD_ALIGNBUF) {
1092         free(tr->tr_data, TWE_MALLOC_CLASS);
1093         tr->tr_data = tr->tr_realdata;          /* restore 'real' data pointer */
1094     }
1095 }
1096
1097 #ifdef TWE_DEBUG
1098 /********************************************************************************
1099  * Print current controller status, call from DDB.
1100  */
1101 void
1102 twe_report(void)
1103 {
1104     struct twe_softc    *sc;
1105     int                 i, s;
1106
1107     s = splbio();
1108     for (i = 0; (sc = devclass_get_softc(twe_devclass, i)) != NULL; i++)
1109         twe_print_controller(sc);
1110     printf("twed: total bio count in %u  out %u\n", twed_bio_in, twed_bio_out);
1111     splx(s);
1112 }
1113 #endif