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