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