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