Annotation of wikisrc/tutorials/bus_space_tutorial.mdwn, revision 1.5

1.2       mspo        1: [[!toc ]]
1.1       mspo        2: 
1.3       mspo        3: ## Introduction
1.1       mspo        4: 
                      5: ### Why was this tutorial created?
                      6: 
                      7: -   Introductory-level documentation is scarce
                      8: -   Writing device drivers is often considered black magic
                      9: -   Reading the man pages won’t give you the big picture
                     10: -   BSD systems are always in need of new drivers
                     11: -   Device drivers are fun
                     12: 
                     13: ### What won’t be covered here?
                     14: 
                     15: We don’t have much time, so several ~~advanced~~ topics were omitted:
                     16: 
                     17: -   Interrupt handling
                     18: -   Direct Memory Access and the bus\_dma framework
                     19: -   Power management
                     20: -   Driver detachment
                     21: -   Drivers as kernel modules
                     22: -   Examples for buses other than PCI
                     23: -   Pretty much everything else...
                     24: 
                     25: However, once you finish this tutorial, you should be able to pursue
                     26: this knowledge yourself.
                     27: 
                     28: ### What is a driver anyway?
                     29: 
                     30: -   The interface between user space and hardware, implemented as a part
                     31:     of the kernel
                     32: -   The NetBSD drivers are written mostly in C
                     33: -   Sometimes they have machine dependent assembler parts, but this is a
                     34:     rare case
                     35: 
                     36: ### What do you need to write a driver?
                     37: 
                     38: -   C programming skills
                     39: -   Hardware documentation (or the ability to reverse engineer the
                     40:     hardware)
                     41: -   A reference driver implementation will help but is not essential
                     42: -   A NetBSD installation and kernel source, or a cross-build
                     43:     environment (the latter is usually preferred for development of
                     44:     drivers)
                     45: -   A lot of time, coffee and patience
                     46: 
                     47: ### Why is writing the device drivers considered difficult?
                     48: 
                     49: -   It’s not as difficult as you may expect, in fact during this
                     50:     tutorial we’ll prove that it’s quite easy
                     51: -   You need to think on a very low level
                     52:     -   Good understanding of computer architecture is a must
                     53: -   Often documentation is the main problem – writing the driver is not
                     54:     possible if you don’t understand how the device works
                     55:     -   No access to documentation (uncooperative hardware vendors,
                     56:         vendors out of business)
                     57:     -   Documentation is incomplete or plain wrong
                     58:     -   Reverse engineering can solve these problems but it’s a very
                     59:         time consuming process
                     60: 
1.4       mspo       61: ## The NetBSD driver model
1.1       mspo       62: 
                     63: ### The NetBSD kernel basics
                     64: 
                     65: -   NetBSD has a classic monolithic UNIX-like kernel - all drivers are
                     66:     running in the same address space
                     67: -   Thanks to the above, communication between drivers and other kernel
                     68:     layers is simple
                     69: -   However, it also means that one badly written driver can affect the
                     70:     whole kernel
                     71: -   Numerous in-kernel frameworks standardise the way drivers are
                     72:     written (bus\_space, autoconf, etc.)
                     73: 
                     74: ### The NetBSD source directory structure
                     75: 
                     76: -   We’ll only cover parts interesting for a device driver programmer
                     77: -   src/sys/
                     78:     - kernel source directory
                     79: -   src/sys/dev/
                     80:     - machine-independent device drivers
                     81: -   src/sys/arch/
                     82:     - port-specific or architecture-specific parts (such as the
                     83:     low-level system initialisation procedures or machine-dependent
                     84:     drivers)
                     85: -   src/sys/arch/\$PORTNAME/conf/
                     86:     - kernel configuration files for a given port
                     87: 
                     88: ### Kernel autoconfiguration framework - autoconf(9)
                     89: 
                     90: -   Autoconfiguration is the process of matching hardware devices with
                     91:     an appropriate device driver
                     92: -   The kernel message buffer (dmesg) contains information about
                     93:     autoconfiguration of devices
                     94: -   driver0 at bus0: Foo hardware
                     95:     -   Instance 0 of the driver has attached to instance 0 of the
                     96:         particular bus
                     97:     -   Such messages often carry additional bus-specific information
                     98:         about the exact location of the device (like the device and
                     99:         function number on the PCI bus)
                    100: -   driver0: some message
                    101:     -   Additional information about the driver state or device
                    102:         configuration
                    103: 
                    104: ### Autoconfiguration as seen in the dmesg
                    105: 
                    106:     NetBSD 6.99.12 (GENERIC) #7: Fri Oct  5 18:43:21 CEST 2012
                    107:             rkujawa@saiko.local:/Users/rkujawa/netbsd-eurobsdcon2012/src/sys/arch/cobalt/compile/obj/GENERIC
                    108:     Cobalt Qube 2
                    109:     total memory = 32768 KB
                    110:     avail memory = 27380 KB
                    111:     mainbus0 (root)
                    112:     com0 at mainbus0 addr 0x1c800000 level 3: ns16550a, working fifo
                    113:     com0: console
                    114:     cpu0 at mainbus0: QED RM5200 CPU (0x28a0) Rev. 10.0 with built-in FPU Rev. 1.0
                    115:     cpu0: 48 TLB entries, 256MB max page size
                    116:     cpu0: 32KB/32B 2-way set-associative L1 instruction cache
                    117:     cpu0: 32KB/32B 2-way set-associative write-back L1 data cache
                    118:     mcclock0 at mainbus0 addr 0x10000070: mc146818 compatible time-of-day clock
                    119:     panel0 at mainbus0 addr 0x1f000000
                    120:     gt0 at mainbus0 addr 0x14000000
                    121:     pci0 at gt0
                    122:     pchb0 at pci0 dev 0 function 0: Galileo GT-64011 System Controller, rev 1
                    123:     pcib0 at pci0 dev 9 function 0
                    124:     pcib0: VIA Technologies VT82C586 PCI-ISA Bridge, rev 57
                    125:     viaide0 at pci0 dev 9 function 1
                    126:     viaide0: VIA Technologies VT82C586 (Apollo VP) ATA33 controller
                    127:     viaide0: primary channel interrupting at irq 14
                    128:     atabus0 at viaide0 channel 0
                    129:     viaide0: secondary channel interrupting at irq 15
                    130:     atabus1 at viaide0 channel 1
                    131:     wd0 at atabus0 drive 0
                    132:     wd0: <netbsd-cobalt.img>
                    133:     wd0: 750 MB, 1524 cyl, 16 head, 63 sec, 512 bytes/sect x 1536192 sectors
                    134: 
                    135: ### Autoconfiguration as seen in the dmesg
                    136: 
                    137: ![image](img_cobaltdevices.png)
                    138: 
                    139: ### The bus\_space(9) framework
                    140: 
                    141: -   “The goal of the bus\_space functions is to allow a single driver
                    142:     source file to manipulate a set of devices on different system
                    143:     architectures, and to allow a single driver object file to
                    144:     manipulate a set of devices on multiple bus types on a single
                    145:     architecture.”
                    146: -   Provides a set of functions implementing common operations on the
                    147:     bus like mapping, reading, writing, copying, etc.
                    148: -   The bus\_space(9) is implemented at the machine-dependent level
                    149:     (typically it’s a part of architecture-specific code), but all
                    150:     implementations present the same interface[^1]
                    151: 
                    152: ### Machine independent drivers
                    153: 
                    154: -   If possible drivers should work on any hardware platform
                    155: -   High quality, machine-independent (MI) drivers are an important
                    156:     factor that adds to NetBSD portability
                    157: -   Some drivers are completely MI, some have MD or bus dependent
                    158:     attachments and some are completely MD
                    159:     -   A driver for a typical PCI card will be completely MI
                    160:     -   A driver for the components of a SoC will usually be completely
                    161:         MD
                    162: -   The bus\_space abstraction helps to achieve portability,
                    163:     transparently handling endianness issues and hiding bus
                    164:     implementation details from the device driver
                    165: -   Even if we have MI drivers, writing the drivers is always
                    166:     significant part of effort needed to port NetBSD to new hardware
                    167: 
1.4       mspo      168: ## Example driver from scratch
1.1       mspo      169: 
                    170: ### Development environment
                    171: 
                    172: -   Out of scope of this course, but very well documented
                    173: -   Cross compiling is an easy task with the build.sh script
                    174: -   Described in [Part V of the NetBSD
                    175:     Guide](http://www.netbsd.org/docs/guide/en/part-compile.html)
                    176: -   Check out the NetBSD sources
                    177: -   \$ build.sh -m cobalt tools
                    178:     will build compiler, assembler, linker, etc. for cobalt port
                    179: -   \$ build.sh -m cobalt kernel=GENERIC
                    180:     will build the GENERIC kernel for cobalt
                    181: -   Call build.sh with a -u parameter to update (won’t rebuilding
                    182:     everything)
                    183: -   build.sh
                    184:     is calling nbconfig and nbmake tools, no magic involved
                    185: 
                    186: ### Quick introduction to GXemul
                    187: 
                    188: -   A framework for full-system computer architecture emulation,
                    189:     excellent for educational purposes
                    190: -   Capable of emulating several real machines supported by NetBSD
                    191: -   We’ll emulate a [Cobalt](http://en.wikipedia.org/wiki/Cobalt_Qube),
                    192:     MIPS-based micro server with PCI bus
                    193: -   I’ve modified GXemul and implemented an emulation of an additional
                    194:     PCI device
                    195: -   It will be used to show (almost) a real-life example of the driver
                    196:     development process
                    197: 
                    198: ### Our hardware - functional description
                    199: 
                    200: -   Business applications often use arithmetic operations like addition
                    201: -   Fake Cards Inc. responded to market needs and created a new product,
                    202:     Advanced Addition Accelerator
                    203: -   Pointy Haired Bosses will certainly buy it to accelerate their
                    204:     business applications, so let’s create a driver for NetBSD!
                    205: 
                    206: ### Our hardware - technical details
                    207: 
                    208: -   Overview
                    209:     -   Implemented as a PCI device
                    210:     -   Arithmetic unit capable of addition of two numbers
                    211:     -   Four[^2] registers in the PCI memory space
                    212: -   PCI configuration space
                    213:     -   Identified by the PCI vendor ID 0xfabc and product ID 0x0001
                    214:     -   Base Address Register 0x10 used to configure the engine address
                    215:     -   4 x 32-bit registers = 16 bytes
                    216:     -   Other configuration registers irrelevant
                    217: 
                    218: ### Our hardware - technical details (memory mapped register set)
                    219: 
                    220: -   Advanced Addition Acceleration registers
                    221: 
1.4       mspo      222: <table>
                    223: <tr><th>Register Name</th><th>Offset</th><th>Description</th></tr>
                    224: <tr><td>COMMAND</td><td>0x4</td><td>Register used to issue commands to the engine</td></tr>
                    225: <tr><td>DATA</td><td>0x8</td><td>Register used to load data to internal engine registers</td></tr>
                    226: <tr><td>RESULT</td><td>0xC</td><td>Register used to store the result of arithmetic operation</td></tr>
                    227: </table>
1.1       mspo      228: 
                    229: -   COMMAND register
                    230: 
1.4       mspo      231: <table>
                    232: <tr><th>Bit</th><th>R/W</th><th>Description</th></tr>
                    233: <tr><td>0</td><td>W</td><td>Execute ADD operation on values loaded into internal register A and B</td></tr>
                    234: <tr><td>1</td><td>R/W</td><td>Select internal register A for access through DATA register</td></tr>
                    235: <tr><td>2</td><td>R/W</td><td>Select internal register B for access through DATA register</td></tr>
                    236: </table>
1.1       mspo      237: 
                    238: -   Selecting internal register A and B at the same time will lead to
                    239:     undefined behaviour
                    240: 
                    241: ### Our hardware - technical details (memory mapped register set)
                    242: 
                    243: -   DATA register
                    244: 
1.4       mspo      245: <table>
                    246: <tr><th>Bit</th><th>R/W</th><th>Description</th></tr>
                    247: <tr><td>0:31</td><td>R/W</td><td>Read/write the value in internal engine register</td></tr>
                    248: </table>
1.1       mspo      249: 
                    250: -   RESULT register
                    251: 
1.4       mspo      252: <table>
                    253: <tr><th>Bit</th><th>R/W</th><th>Description</th></tr>
                    254: <tr><td>0:31</td><td>R</td><td>Holds the result of last ADD operation</td></tr>
                    255: </table>
1.1       mspo      256: 
                    257: ### Our hardware - technical details (operation algorithm)
                    258: 
                    259: -   Select the internal register A for access (write 0x2 into COMMAND
                    260:     register)
                    261: -   Write the first number into DATA register
                    262: -   Select the internal register B for access (write 0x4 into COMMAND
                    263:     register)
                    264: -   Write the second number into DATA register
                    265: -   Issue the ADD operation (write 0x1 into COMMAND register)
                    266: -   Read the result from RESULT register
                    267: 
                    268: ### Adding a new driver to the NetBSD kernel
                    269: 
                    270: -   We’ll discuss the steps needed to add a new MI PCI device driver to
                    271:     the NetBSD kernel
                    272:     -   Add the vendor and device ID to the database of PCI IDs
                    273:     -   Create a set of the driver source files in
                    274:         src/sys/dev/\$BUSNAME/
                    275:     -   Add the new driver to src/sys/dev/\$BUSNAME/\$BUSNAME.files file
                    276:     -   Add the new driver to DEVNAMES[^3] file
                    277: 
                    278: ### Modifying the PCI device database
                    279: 
                    280:     unmatched vendor 0xfabc product 0x0001 (Co-processor 
                    281:     processor, revision 0x01) at pci0 dev 12 function 0 
                    282:     not configured
                    283: 
                    284: -   The kernel does not know anything about this vendor and device
                    285: -   Add it to the PCI device database - src/sys/dev/pci/pcidevs
                    286: -   vendor VENDORNAME 0xVENDORID Long Vendor Name
                    287: -   product VENDORNAME PRODUCTNAME 0xPRODUCTID Long Product Name
                    288: -   To regenerate pcidevs\*.h run awk -f devlist2h.awk pcidevs or
                    289:     Makefile.pcidevs if you’re on NetBSD
                    290: 
                    291: ### Modifying the PCI device database - example
                    292: 
                    293:     --- pcidevs 29 Sep 2012 10:26:14 -0000  1.1139
                    294:     +++ pcidevs 5 Oct 2012 08:52:59 -0000
                    295:     @@ -669,6 +669,7 @@
                    296:      vendor CHRYSALIS   0xcafe  Chrysalis-ITS
                    297:      vendor MIDDLE_DIGITAL  0xdeaf  Middle Digital
                    298:      vendor ARC     0xedd8  ARC Logic
                    299:     +vendor FAKECARDS   0xfabc  Fake Cards
                    300:      vendor INVALID     0xffff  INVALID VENDOR ID
                    301:      
                    302:      /*
                    303:     @@ -2120,6 +2121,9 @@
                    304:      /* Eumitcom products */
                    305:      product EUMITCOM WL11000P  0x1100  WL11000P PCI WaveLAN/IEEE 802.11
                    306:      
                    307:     +/* FakeCards products */
                    308:     +product FAKECARDS AAA      0x0001  Advanced Addition Accelerator
                    309:     +
                    310:      /* O2 Micro */
                    311:      product O2MICRO 00F7       0x00f7  Integrated OHCI IEEE 1394 Host Controller
                    312:      product O2MICRO OZ6729     0x6729  OZ6729 PCI-PCMCIA Bridge
                    313: 
                    314: ### Modifying the PCI device database - example
                    315: 
                    316:     Fake Cards Advanced Addition Accelerator (Co-processor 
                    317:     processor, revision 0x01) at pci0 dev 12 function 0 
                    318:     not configured
                    319: 
                    320: -   Now the kernel knows the vendor and product ID
                    321: -   But there’s still no driver for this device
                    322: 
                    323: ### Adding the new PCI driver
                    324: 
                    325: -   Choose a name - short, easy to remember, avoid numbers
1.5     ! mspo      326:     -   faa looks like a good name, but you can choose any name you like
1.1       mspo      327: -   Create a set of new files in src/sys/dev/pci
                    328:     -   faa.c
                    329:         - main driver code
                    330:     -   faareg.h
                    331:         - register definitions[^4]
                    332:     -   faavar.h
                    333:         - driver structures and functions used in other parts of the
                    334:         kernel[^5]
                    335: -   Modify driver definitions
                    336:     -   src/sys/dev/pci/files.pci
                    337:     -   src/sys/dev/DEVNAMES
                    338: -   Configure the kernel to use the newly added driver -
                    339:     src/sys/arch/\$PORTNAME/conf/GENERIC
                    340: 
                    341: ### Adding the new PCI driver - main driver
                    342: 
                    343: -   Kernel includes are at the beginning, followed by machine-specific
                    344:     and bus-specific includes
                    345: -   Should also include faareg.h and faavar.h files
                    346: -   A minimal driver needs just two functions
                    347:     -   faa\_match
                    348:         (or faa\_probe for some buses)
                    349:     -   faa\_attach
                    350: -   The CFATTACH\_DECL\_NEW macro plugs the above functions into
                    351:     autoconf(9) mechanism
                    352: 
                    353: ### Adding the new PCI driver - main driver
                    354: 
                    355: -   static int faa\_match(device\_t parent, cfdata\_t match, void
                    356:     \*aux);
                    357:     -   Check if the driver should attach to a given device (for example
                    358:         in case of PCI bus, it will be used to check vendor and product
                    359:         ID)
                    360:     -   parent
                    361:         - pointer to parent’s driver device structure
                    362:     -   match
                    363:         - pointer to autoconf(9) details structure
                    364:     -   aux
                    365:         - despite the name the most important argument, usually contains
                    366:         bus-specific structure describing device details
                    367: 
                    368: -   static void faa\_attach(device\_t parent, device\_t self, void
                    369:     \*aux);
                    370:     -   Attach the driver to a given device
                    371:     -   parent
                    372:         - same as with match function
                    373:     -   self
                    374:         - pointer to driver’s device structure
                    375:     -   aux
                    376:         - same as with match function
                    377: -   See definitions of these functions in the
                    378:     [driver(9)](http://netbsd.gw.com/cgi-bin/man-cgi?driver+9+NetBSD-current)
                    379:     man page.
                    380: 
                    381: ### Adding the new PCI driver - main driver cont’d
                    382: 
                    383: -   CFATTACH\_DECL\_NEW(faa, sizeof(struct faa\_softc), faa\_match,
                    384:     faa\_attach, NULL, NULL);
                    385:     -   driver name
                    386:     -   size of softc structure containing state of driver’s instance
                    387:     -   match/probe function
                    388:     -   attach function
                    389:     -   detach function
                    390:     -   activate function
                    391: -   The “\_NEW” name is unfortunate
                    392: -   Pass NULL for unimplemented functions
                    393: -   We won’t cover detach and activate now, as they are not needed for a
                    394:     simple driver
                    395: 
                    396: ### Adding the new PCI driver - main driver example
                    397: 
                    398: -   src/sys/dev/pci/faa.c
                    399: 
                    400: <!-- -->
                    401: 
                    402:     #include <sys/cdefs.h>
1.5     ! mspo      403:     __KERNEL_RCSID(0, "$NetBSD: bus_space_tutorial.mdwn,v 1.4 2013/06/23 14:34:32 mspo Exp $");
1.1       mspo      404:     #include <sys/param.h>
                    405:     #include <sys/device.h>
                    406:     #include <dev/pci/pcivar.h>
                    407:     #include <dev/pci/pcidevs.h>
                    408:     #include <dev/pci/faareg.h>
                    409:     #include <dev/pci/faavar.h>
                    410: 
                    411:     static int      faa_match(device_t, cfdata_t, void *);
                    412:     static void     faa_attach(device_t, device_t, void *);
                    413: 
                    414:     CFATTACH_DECL_NEW(faa, sizeof(struct faa_softc),
                    415:         faa_match, faa_attach, NULL, NULL);
                    416: 
                    417:     static int
                    418:     faa_match(device_t parent, cfdata_t match, void *aux)
                    419:     {
                    420:             return 0;
                    421:     }
                    422: 
                    423:     static void
                    424:     faa_attach(device_t parent, device_t self, void *aux)
                    425:     { 
                    426:     }
                    427: 
                    428: ### Adding the new PCI driver - auxiliary includes
                    429: 
                    430: -   src/sys/dev/pci/faareg.h
                    431: 
                    432: <!-- -->
                    433: 
                    434:     #ifndef FAAREG_H
                    435:     #define FAAREG_H
                    436:     /* 
                    437:      * Registers are defined using preprocessor:
                    438:      * #define FAA_REGNAME  0x0
                    439:      * We'll add them later, let's leave it empty for now.
                    440:      */
                    441:     #endif /* FAAREG_H */
                    442: 
                    443: -   src/sys/dev/pci/faavar.h
                    444: 
                    445: <!-- -->
                    446: 
                    447:     #ifndef FAAVAR_H
                    448:     #define FAAVAR_H
                    449: 
                    450:     /* sc_dev is an absolute minimum, we'll add more later */
                    451:     struct faa_softc {
                    452:             device_t sc_dev;
                    453:     };
                    454:     #endif /* FAAVAR_H */
                    455: 
                    456: ### Adding the new PCI driver - registering the driver (courtesy)
                    457: 
                    458: -   src/sys/dev/DEVNAMES
                    459: 
                    460: <!-- -->
                    461: 
                    462:     --- DEVNAMES    1 Sep 2012 11:19:58 -0000   1.279
                    463:     +++ DEVNAMES    6 Oct 2012 19:59:06 -0000
                    464:     @@ -436,6 +436,7 @@
                    465:      ex         MI
                    466:      exphy          MI
                    467:      ezload         MI      Attribute
                    468:     +faa            MI
                    469:      fb         luna68k
                    470:      fb         news68k
                    471:      fb         newsmips
                    472: 
                    473: ### Adding the new PCI driver - registering the driver
                    474: 
                    475: -   See config(5)
                    476: -   src/sys/dev/pci/files.pci
                    477: 
                    478: <!-- -->
                    479: 
                    480:     --- pci/files.pci   2 Aug 2012 00:17:44 -0000   1.360
                    481:     +++ pci/files.pci   6 Oct 2012 19:59:10 -0000
                    482:     @@ -1122,3 +1122,9 @@
                    483:      device tdvfb: wsemuldisplaydev, rasops8, vcons, videomode
                    484:      attach tdvfb at pci
                    485:      file   dev/pci/tdvfb.c     tdvfb   
                    486:     +
                    487:     +# FakeCards Advanced Addition Accelerator
                    488:     +device faa
                    489:     +attach faa at pci
                    490:     +file   dev/pci/faa.c       faa 
                    491:     +
                    492: 
                    493: ### Adding the new PCI driver to the kernel configuration
                    494: 
                    495: -   src/sys/arch/cobalt/conf/GENERIC
                    496: 
                    497: <!-- -->
                    498: 
                    499:     --- GENERIC 10 Mar 2012 21:51:50 -0000  1.134
                    500:     +++ GENERIC 6 Oct 2012 20:12:37 -0000
                    501:     @@ -302,6 +302,9 @@
                    502:      #fms*      at pci? dev ? function ?    # Forte Media FM801
                    503:      #sv*       at pci? dev ? function ?    # S3 SonicVibes
                    504:      
                    505:     +# Fake Cards Advanced Addition Accelerator
                    506:     +faa*       at pci? dev ? function ?
                    507:     +
                    508:      # Audio support
                    509:      #audio*        at audiobus?
                    510: 
                    511: -   The above definition means that an instance of faa may be attached
                    512:     to any PCI bus, any device, any function
                    513: -   The exact position of the rule in the configuration file is not
                    514:     important in this case
                    515: -   See
                    516:     [config(5)](http://netbsd.gw.com/cgi-bin/man-cgi?config+5+NetBSD-current)
                    517:     for a description of the device definition language
                    518: 
                    519: ### Adding the new PCI driver - example
                    520: 
                    521: -   The driver should compile now
                    522: -   The driver’s match function will check if the driver is able to work
                    523:     with a given device
                    524: -   Since it is not implemented, the kernel will not attach the driver
                    525: 
                    526: ### Matching the PCI device
                    527: 
                    528: -   Modify the faa\_match function to match the specified PCI device
                    529: -   Use PCI\_VENDOR and PCI\_PRODUCT macros to obtain the IDs
                    530: 
                    531: <!-- -->
                    532: 
                    533:     static int
                    534:     faa_match(device_t parent, cfdata_t match, void *aux)
                    535:     {
                    536:             const struct pci_attach_args *pa = (const struct pci_attach_args *)aux;
                    537: 
                    538:             if ((PCI_VENDOR(pa->pa_id) == PCI_VENDOR_FAKECARDS) 
                    539:                 && (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_FAKECARDS_AAA))
                    540:                     return 1;
                    541: 
                    542:             return 0;
                    543:     }
                    544: 
                    545: ### Attaching to the PCI device
                    546: 
                    547:     faa0 at pci0 dev 12 function 0
                    548: 
                    549: -   The driver has successfully matched and attached to the PCI device
                    550:     but still is not doing anything useful
                    551: -   Let’s fill the attach function and actually program the hardware
                    552: 
                    553: ### Variable types used with bus\_space
                    554: 
                    555: -   bus\_space\_tag\_t
                    556: 
                    557:     – type used to describe a particular bus, usually passed to the
                    558:     driver from MI bus structures
                    559: 
                    560: -   bus\_space\_handle\_t
                    561: 
                    562:     – used to describe a mapped range of bus space, usually created with
                    563:     the bus\_space\_map() function
                    564: 
                    565: -   bus\_addr\_t
                    566: 
                    567:     – address on the bus
                    568: 
                    569: -   bus\_size\_t
                    570: 
                    571:     – an amount of space on the bus
                    572: 
                    573: -   Contents of these types are MD, so avoid modifying from within the
                    574:     driver[^6]
                    575: 
                    576: ### Why do we need to “map” the resources?
                    577: 
                    578: -   “The bus space must be mapped before it can be used, and should be
                    579:     unmapped when it is no longer needed”
                    580: -   It’s a machine-dependent process but it’s also conveniently hidden
                    581:     from the programmer by the bus\_space framework
                    582: 
                    583: ### Mapping the hardware resources
                    584: 
                    585: -   The generic bus\_space(9) way to map space
                    586: 
                    587: <!-- -->
                    588: 
                    589:     bus_space_map(bus_space_tag_t space, bus_addr_t address, 
                    590:     bus_size_t size, int flags, bus_space_handle_t  *handlep);
                    591: 
                    592: -   bus\_space\_map
                    593: 
                    594:     creates a mapping from the physical address to a kernel virtual
                    595:     address
                    596: 
                    597: -   space
                    598: 
                    599:     – represents the bus on which the mapping will be created
                    600: 
                    601: -   address
                    602: 
                    603:     – typically represents the physical address for which a mapping will
                    604:     be created
                    605: 
                    606: -   size
                    607: 
                    608:     – describes the amount of bus space to be mapped
                    609: 
                    610: -   handlep
                    611: 
                    612:     – pointer to mapped space (filled after successful mapping)
                    613: 
                    614: -   Separate space and address
                    615: 
                    616: ### Mapping the hardware resources
                    617: 
                    618: -   The PCI-specific way to map space
                    619: 
                    620: <!-- -->
                    621: 
                    622:     pci_mapreg_map(const struct pci_attach_args *pa, int reg, pcireg_t type, 
                    623:     int busflags, bus_space_tag_t *tagp, bus_space_handle_t *handlep, 
                    624:     bus_addr_t *basep, bus_size_t *sizep);
                    625: 
                    626: -   pci\_mapreg\_map
                    627: 
                    628:     creates mapping from physical address present in specified BAR
                    629:     register to kernel virtual address
                    630: 
                    631: -   pa
                    632: 
                    633:     – struct describing PCI attachment details (passed through aux)
                    634: 
                    635: -   reg
                    636: 
                    637:     – BAR register number
                    638: 
                    639: -   type
                    640: 
                    641:     – Select mapping type (I/O, memory)
                    642: 
                    643: -   busflags
                    644: 
                    645:     – Passed to bus\_space\_map flags argument
                    646: 
                    647: -   tagp
                    648: 
                    649:     – pointer to bus\_space\_tag
                    650: 
                    651: -   handlep
                    652: 
                    653:     – pointer to a mapped space
                    654: 
                    655: -   basep
                    656: 
                    657:     – address of a mapped space
                    658: 
                    659: -   sizep
                    660: 
                    661:     – size of mapped space (equivalent to BAR size)
                    662: 
                    663: -   The last four parameters are filled after successful mapping
                    664: 
                    665: ### Mapping the registers using BAR - adding auxiliary includes
                    666: 
                    667: -   src/sys/dev/pci/faareg.h
                    668: 
                    669: <!-- -->
                    670: 
                    671:     #define FAA_MMREG_BAR   0x10
                    672: 
                    673: -   src/sys/dev/pci/faavar.h
                    674: 
                    675: <!-- -->
                    676: 
                    677:     struct faa_softc {
                    678:             device_t sc_dev;
                    679: 
                    680:             bus_space_tag_t sc_regt;
                    681:             bus_space_handle_t sc_regh;
                    682:             bus_addr_t sc_reg_pa;
                    683: 
                    684:     };
                    685: 
                    686: ### Mapping the registers using BAR - main driver code
                    687: 
                    688: -   src/sys/dev/pci/faa.c
                    689: 
                    690: <!-- -->
                    691: 
                    692:     static void
                    693:     faa_attach(device_t parent, device_t self, void *aux)
                    694:     {
                    695:             struct faa_softc *sc = device_private(self);
                    696:             const struct pci_attach_args *pa = aux;
                    697: 
                    698:             sc->sc_dev = self;
                    699: 
                    700:             pci_aprint_devinfo(pa, NULL);
                    701: 
                    702:             if (pci_mapreg_map(pa, FAA_MMREG_BAR, PCI_MAPREG_TYPE_MEM, 0, 
                    703:                 &sc->sc_regt, &sc->sc_regh, &sc->sc_reg_pa, 0) != 0 ) {
                    704:                 aprint_error_dev(sc->sc_dev, "can't map the BAR\n");
                    705:                 return;
                    706:             }
                    707: 
                    708:             aprint_normal_dev(sc->sc_dev, "regs at 0x%08x\n", (uint32_t) sc->sc_reg_pa);
                    709:     }
                    710: 
                    711: ### Accessing the hardware registers
                    712: 
                    713: -   The bus\_space\_read\_ and bus\_space\_write\_ functions are basic
                    714:     methods of reading and writing the hardware registers
                    715: 
                    716: -   uintX\_t bus\_space\_read\_X(bus\_space\_tag\_t space,
                    717:     bus\_space\_handle\_t handle, bus\_size\_t offset);
                    718: 
                    719: -   void bus\_space\_write\_X(bus\_space\_tag\_t space,
                    720:     bus\_space\_handle\_t handle, bus\_size\_t offset, uintX\_t value);
                    721: 
                    722:     -   space
                    723: 
                    724:         - tag describing the bus
                    725: 
                    726:     -   handle
                    727: 
                    728:         - describes the exact location on the bus where read/write
                    729:         should occur, this handle is obtained by bus\_space\_map
                    730: 
                    731:     -   offset
                    732: 
                    733:         - offset from handle location
                    734: 
                    735:     -   The read function returns the data read from the specified
                    736:         location, while write has an argument value which should be
                    737:         filled with data to be written
                    738: 
                    739: ### Variants of bus\_space\_read and bus\_space\_write
                    740: 
                    741:     Data       Read function         Write function
                    742:   -------- --------------------- ----------------------
                    743:    8-bit    bus\_space\_read\_1   bus\_space\_write\_1
                    744:    16-bit   bus\_space\_read\_2   bus\_space\_write\_2
                    745:    32-bit   bus\_space\_read\_4   bus\_space\_write\_4
                    746:    64-bit   bus\_space\_read\_8   bus\_space\_write\_8
                    747: 
                    748: -   There are many more variants of read and write functions and they
                    749:     are useful in certain situations, see the
                    750:     [bus\_space(9)](http://netbsd.gw.com/cgi-bin/man-cgi?bus_space++NetBSD-current)
                    751:     man page
                    752: 
                    753: ### Accessing the hardware registers - example
                    754: 
                    755: -   Create a function that will write a value into the DATA register of
                    756:     our device, then read it back and check if the value is the same as
                    757:     written
                    758: 
                    759: -   Define the DATA register in the driver
                    760: 
                    761: -   src/sys/dev/pci/faareg.h
                    762: 
                    763: <!-- -->
                    764: 
                    765:     #define FAA_DATA                0x8
                    766:     #define FAA_COMMAND             0x4
                    767:     #define FAA_COMMAND_STORE_A         __BIT(1)
                    768: 
                    769: -   Define the new function in main driver code
                    770: 
                    771: -   static bool faa\_check(struct faa\_softc \*sc);
                    772: 
                    773: ### Accessing the hardware registers - example
                    774: 
                    775: -   src/sys/dev/pci/faa.c
                    776: 
                    777: <!-- -->
                    778: 
                    779:     static void
                    780:     faa_attach(device_t parent, device_t self, void *aux)
                    781:     {
                    782:        /* ... */
                    783:        if (!faa_check(sc)) {
                    784:             aprint_error_dev(sc->sc_dev, "hardware not responding\n");
                    785:             return;
                    786:        }
                    787:     }
                    788: 
                    789:     static bool
                    790:     faa_check(struct faa_softc *sc)
                    791:     {
                    792:             uint32_t testval = 0xff11ee22; 
                    793:             bus_space_write_4(sc->sc_regt, sc->sc_regh, FAA_COMMAND, FAA_COMMAND_STORE_A);
                    794:             bus_space_write_4(sc->sc_regt, sc->sc_regh, FAA_DATA, testval);
                    795:             if (bus_space_read_4(sc->sc_regt, sc->sc_regh, FAA_DATA) == testval)
                    796:                     return true;
                    797: 
                    798:             return false;
                    799:     }
                    800: 
                    801: ### Accessing the hardware registers - running the example
                    802: 
                    803: -   Update the kernel binary and run it again
                    804: 
                    805: -   Check the GXemul log
                    806: 
                    807: <!-- -->
                    808: 
                    809:     [ faa: COMMAND register (0x4) WRITE value 0x2 ]
                    810:     [ faa: DATA register (0x8) WRITE value 0xff11ee22 ]
                    811:     [ faa: DATA register (0x8) READ value 0xff11ee22 ]
                    812: 
                    813: -   GXemul will conveniently display all accesses to our device
                    814: 
                    815: -   The faa driver still does attach without error, which means that the
                    816:     check function is working properly
                    817: 
                    818: <!-- -->
                    819: 
                    820:     faa0 at pci0 dev 12 function 0: Fake Cards Advanced Addition Accelerator (rev. 0x01)
                    821:     faa0: registers at 0x10110000
                    822: 
                    823: ### Implementing addition using the hardware
                    824: 
                    825: -   The basic principle of device operation should be laid out in the
                    826:     data sheet
                    827: 
                    828: -   We need to implement an algorithm based on this description
                    829: 
                    830: -   Writing such an algorithm is often not needed, since the NetBSD
                    831:     kernel already has frameworks for common device types (such as
                    832:     atabus/wd for IDE and SATA hard disk controllers, wsdisplay/wscons
                    833:     for frame buffers, etc.)
                    834: 
                    835: ### Implementing addition using the hardware
                    836: 
                    837: -   Define all registers
                    838: 
                    839: -   src/sys/dev/pci/faareg.h
                    840: 
                    841: <!-- -->
                    842: 
                    843:     #define FAA_STATUS              0x0
                    844:     #define FAA_COMMAND             0x4
                    845:     #define FAA_COMMAND_ADD             __BIT(0)        
                    846:     #define FAA_COMMAND_STORE_A         __BIT(1)
                    847:     #define FAA_COMMAND_STORE_B         __BIT(2)
                    848:     #define FAA_DATA                0x8
                    849:     #define FAA_RESULT              0xC
                    850: 
                    851: ### Implementing addition using the hardware
                    852: 
                    853: -   Add a new function to the main driver code
                    854: 
                    855: -   src/sys/dev/pci/faa.c
                    856: 
                    857: <!-- -->
                    858: 
                    859:     static void
                    860:     faa_attach(device_t parent, device_t self, void *aux)
                    861:     {
                    862:             /* ... */
                    863:             aprint_normal_dev(sc->sc_dev, "just checking: 1 + 2 = %d\n", faa_add(sc, 1, 2));
                    864:     }
                    865: 
                    866:     static uint32_t
                    867:     faa_add(struct faa_softc *sc, uint32_t a, uint32_t b)
                    868:     {
                    869:             bus_space_write_4(sc->sc_regt, sc->sc_regh, FAA_COMMAND, FAA_COMMAND_STORE_A);
                    870:             bus_space_write_4(sc->sc_regt, sc->sc_regh, FAA_DATA, a);
                    871:             bus_space_write_4(sc->sc_regt, sc->sc_regh, FAA_COMMAND, FAA_COMMAND_STORE_B);
                    872:             bus_space_write_4(sc->sc_regt, sc->sc_regh, FAA_DATA, b);
                    873:             bus_space_write_4(sc->sc_regt, sc->sc_regh, FAA_COMMAND, FAA_COMMAND_ADD);
                    874:             return bus_space_read_4(sc->sc_regt, sc->sc_regh, FAA_RESULT);
                    875:     }
                    876: 
                    877: ### Implementing addition using the hardware - running the example
                    878: 
                    879: -   Update the kernel binary and run it again
                    880: 
                    881: -   Check GXemul log
                    882: 
                    883: <!-- -->
                    884: 
                    885:     [ faa: COMMAND register (0x4) WRITE value 0x2 ]
                    886:     [ faa: DATA register (0x8) WRITE value 0x1 ]
                    887:     [ faa: COMMAND register (0x4) WRITE value 0x4 ]
                    888:     [ faa: DATA register (0x8) WRITE value 0x2 ]
                    889:     [ faa: COMMAND register (0x4) WRITE value 0x1 ]
                    890:     [ faa: RESULT register (0xC) READ value 0x3 ]
                    891: 
                    892: -   Looks like it worked!
                    893: 
                    894: <!-- -->
                    895: 
                    896:     faa0 at pci0 dev 12 function 0: Fake Cards Advanced Addition Accelerator (rev. 0x01)
                    897:     faa0: registers at 0x10110000
                    898:     faa0: just checking: 1 + 2 = 3
                    899: 
1.3       mspo      900: ## Interacting with userspace
1.1       mspo      901: 
                    902: ### The kernel-user space interface
                    903: 
                    904: -   Now that the core functionality of the kernel driver is working, it
                    905:     should be exposed to user space
                    906: -   The interface between kernel driver and userspace can be designed in
                    907:     many different ways
                    908: -   The classic UNIX way of interfacing between the kernel and user
                    909:     space is a device file
                    910: -   Even when using device files there is no single interfacing method
                    911:     that fits all use cases
                    912: -   It’s up to the programmer to define the communication protocol
                    913: 
                    914: ### Device files
                    915: 
                    916: -   crw-r—– 1 root wheel 101, 1 Aug 12 21:53 /dev/file
                    917: -   The kernel identifies which driver should service the request to
                    918:     this file by using major and minor numbers (101 and 1 in the example
                    919:     above)
                    920: -   The major number identifies the driver
                    921: -   The minor number usually identifies the driver instance, although
                    922:     the driver is free to use it in any other way
                    923: -   In NetBSD device files are created statically
                    924:     -   By the MAKEDEV script during installation or boot
                    925:     -   Manually by using the mknod utility
                    926: 
                    927: ### Operations on device files
                    928: 
                    929: -   [open(2)](http://netbsd.gw.com/cgi-bin/man-cgi?read++NetBSD-current)
                    930:     and
                    931:     [close(2)](http://netbsd.gw.com/cgi-bin/man-cgi?read++NetBSD-current)
                    932: -   [read(2)](http://netbsd.gw.com/cgi-bin/man-cgi?read++NetBSD-current)
                    933:     and
                    934:     [write(2)](http://netbsd.gw.com/cgi-bin/man-cgi?write++NetBSD-current)
                    935: -   [ioctl(2)](http://netbsd.gw.com/cgi-bin/man-cgi?write++NetBSD-current)
                    936: -   [poll(2)](http://netbsd.gw.com/cgi-bin/man-cgi?poll++NetBSD-current)
                    937: -   [mmap(2)](http://netbsd.gw.com/cgi-bin/man-cgi?write++NetBSD-current)
                    938: -   and more…
                    939: -   Any mix of the above system calls might be used to interface between
                    940:     the kernel and user space
                    941: -   We’ll implement an ioctl(2)-based communication mechanism
                    942: 
                    943: ### Adding cdevsw
                    944: 
                    945: -   cdevsw
                    946: 
                    947:     is used to decide which operation on the character device file calls
                    948:     which driver function
                    949: 
                    950: -   Not all calls have to be implemented, although some device layers
                    951:     define a set of calls that a driver must implement
                    952: 
                    953: -   For example disk drivers must implement open, close, read, write and
                    954:     ioctl
                    955: 
                    956: -   src/sys/dev/pci/faa.c
                    957: 
                    958: <!-- -->
                    959: 
                    960:     dev_type_open(faaopen);
                    961:     dev_type_close(faaclose);
                    962:     dev_type_ioctl(faaioctl);
                    963: 
                    964:     const struct cdevsw faa_cdevsw = {
                    965:             faaopen, faaclose, noread, nowrite, faaioctl,
                    966:             nostop, notty, nopoll, nommap, nokqfilter, D_OTHER
                    967:     };
                    968: 
                    969: ### Prototyping the cdevsw operations
                    970: 
                    971: -   The dev\_type\* macros are used to prototype the functions passed to
                    972:     cdevsw
                    973: -   Pass no followed by a function name to the appropriate cdevsw field
                    974:     if it is not implemented
                    975: -   There’s also bdevsw for block devices, but we won’t use it in this
                    976:     example
                    977: -   The last member of the cdevsw structure defines the device flags,
                    978:     originally it was used to define the device type (still used for
                    979:     disks, tape drives and ttys, for other devices pass D\_OTHER)
                    980: 
                    981: ### Implemeting the cdevsw operations - open / close
                    982: 
                    983: -   src/sys/dev/pci/faa.c
                    984: 
                    985: <!-- -->
                    986: 
                    987:     int
                    988:     faaopen(dev_t dev, int flags, int mode, struct lwp *l)
                    989:     {
                    990:             struct faa_softc *sc;
                    991:             sc = device_lookup_private(&faa_cd, minor(dev));
                    992: 
                    993:             if (sc == NULL)
                    994:                     return ENXIO;
                    995:             if (sc->sc_flags & FAA_OPEN)
                    996:                     return EBUSY;
                    997: 
                    998:             sc->sc_flags |= FAA_OPEN;
                    999:             return 0;
                   1000:     }
                   1001:     int
                   1002:     faaclose(dev_t dev, int flag, int mode, struct lwp *l)
                   1003:     {
                   1004:             struct faa_softc *sc;
                   1005:             sc = device_lookup_private(&faa_cd, minor(dev));
                   1006: 
                   1007:             if (sc->sc_flags & FAA_OPEN)
                   1008:                     sc->sc_flags =~ FAA_OPEN;
                   1009: 
                   1010:             return 0;
                   1011:     }
                   1012: 
                   1013: ### Defining the ioctls
                   1014: 
                   1015: -   ioctl(2)
                   1016: 
                   1017:     can be used to call kernel-level functions and exchange data between
                   1018:     the kernel and user space
                   1019: 
                   1020: -   The classic way of passing data is by using structures, their
                   1021:     definitions are shared between the kernel and user space code
                   1022: -   The driver might support more than one ioctl, the \_IO\* macros are
                   1023:     used to define the operation and associated structure used to
                   1024:     exchange data
                   1025: 
                   1026:     -   \_IO
                   1027: 
                   1028:         - just a kernel function call, no data exchange
                   1029: 
                   1030:     -   \_IOR
                   1031: 
                   1032:         - kernel function call and data pass from kernel to user space
                   1033: 
                   1034:     -   \_IOW
                   1035: 
                   1036:         - kernel function call and data pass from user space to kernel
                   1037: 
                   1038:     -   \_IOWR
                   1039: 
                   1040:         - kernel function call and data exchange in both directions
                   1041: 
                   1042:     -   \#define DRIVERIO\_IOCTLNAME \_IOXXX(group, ioctl\_number, data
                   1043:         structure)
                   1044: 
1.3       mspo     1045: ## Using ioctls
1.1       mspo     1046: 
                   1047: ### Defining the ioctls
                   1048: 
                   1049: -   src/sys/dev/pci/faaio.h
                   1050: 
                   1051: <!-- -->
                   1052: 
                   1053:     #include <sys/ioccom.h>
                   1054:                          
                   1055:     #define FAAIO_ADD   _IOWR(0, 1, struct faaio_add)
                   1056: 
                   1057:     struct faaio_add {
                   1058:         uint32_t a;
                   1059:         uint32_t b;
                   1060:         uint32_t *result;
                   1061:     };
                   1062: 
                   1063: -   In the above example the ioctl group is not defined (0), but a
                   1064:     single letter identifier could appear as first argument to \_IOWR
                   1065: 
                   1066: ### Implemeting the cdevsw operations - ioctl
                   1067: 
                   1068: -   src/sys/dev/pci/faa.c
                   1069: 
                   1070: <!-- -->
                   1071: 
                   1072:     int
                   1073:     faaioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
                   1074:     {
                   1075:             struct faa_softc *sc = device_lookup_private(&faa_cd, minor(dev));
                   1076:             int err;
                   1077: 
                   1078:             switch (cmd) {
                   1079:             case FAAIO_ADD:
                   1080:                     err = faaioctl_add(sc, (struct faaio_add *) data);
                   1081:                     break;
                   1082:             default:
                   1083:                     err = EINVAL;
                   1084:                     break;
                   1085:             }
                   1086:             return(err);
                   1087:     }
                   1088:     static int
                   1089:     faaioctl_add(struct faa_softc *sc, struct faaio_add *data)
                   1090:     {
                   1091:             uint32_t result; int err;
                   1092: 
                   1093:             aprint_normal_dev(sc->sc_dev, "got ioctl with a %d, b %d\n",
                   1094:                 data->a, data->b);
                   1095: 
                   1096:             result = faa_add(sc, data->a, data->b);
                   1097:             err = copyout(&result, data->result, sizeof(uint32_t));
                   1098:             return err;
                   1099:     }
                   1100: 
                   1101: ### Using copyout to pass data to userspace
                   1102: 
                   1103: -   The copy(9) functions are used to copy kernel space data from/to
                   1104:     user space
                   1105: -   copyout(kernel\_address, user space\_address, size);
                   1106: -   Actually on Cobalt we could just do data-\>result = faa\_add();
                   1107:     instead of calling the copyout function, but that is a bad idea
                   1108: -   Some architectures (such as sparc64) have totally separate kernel
                   1109:     and user address spaces $ \implies $ user space addresses are
                   1110:     meaningless in the kernel
                   1111: 
                   1112: ### Defining device major number
                   1113: 
                   1114: -   Device major numbers for hardware drivers are usually defined in a
                   1115:     per-port manner[^7]
                   1116: -   src/sys/arch/\$PORTNAME/conf/majors.\$PORTNAME
                   1117: -   src/sys/arch/cobalt/conf/majors.cobalt
                   1118: -   The following defines a new character device file called /dev/faa\*
                   1119:     with major number 101, but only if the faa driver is included in the
                   1120:     kernel (last argument)
                   1121: -   device-major faa char 101 faa
                   1122: 
                   1123: ### Creating the device node
                   1124: 
                   1125: -   The mknod utility can be used to create the device file manually
                   1126: -   The driver name can be specified instead of the major number - it
                   1127:     will be automatically resolved into the correct major number
                   1128: -   mknod name [b | c] [major | driver] minor
                   1129: -   mknod /dev/faa0 c faa 0
                   1130: -   Created successfully
                   1131: -   crw-r–r– 1 root wheel 101, 0 Oct 8 2012 /dev/faa0
                   1132: 
                   1133: ### An example user space program
                   1134: 
                   1135: -   The example program will open the device file and call ioctl(2) on
                   1136:     it
                   1137: -   As simple as possible, just to show how communication is done
                   1138: -   Using ioctls from the user space
                   1139:     -   Open the device file with O\_RDWR
                   1140:     -   Call ioctl(2) with the operation number and structure as
                   1141:         parameters
                   1142: 
                   1143: ### An example user space program - source
                   1144: 
                   1145:     void add(int, uint32_t, uint32_t);
                   1146: 
                   1147:     static const char* faa_device = "/dev/faa0";
                   1148: 
                   1149:     int
                   1150:     main(int argc, char *argv[])
                   1151:     {
                   1152:             int devfd;
                   1153: 
                   1154:             if (argc != 3) {
                   1155:                     printf("usage: %s a b\n", argv[0]);
                   1156:                     return 1;
                   1157:             }
                   1158:             if ( (devfd = open(faa_device, O_RDWR)) == -1) {
                   1159:                     perror("can't open device file");
                   1160:                     return 1;
                   1161:             }
                   1162: 
                   1163:             add(devfd, atoi(argv[1]), atoi(argv[2]));
                   1164: 
                   1165:             close(devfd);
                   1166:             return 0;
                   1167:     }
                   1168: 
                   1169: ### An example user space program - source
                   1170: 
                   1171:     void
                   1172:     add(int devfd, uint32_t a, uint32_t b)
                   1173:     {
                   1174:             struct faaio_add faaio;
                   1175:             uint32_t result = 0;
                   1176: 
                   1177:             faaio.result = &result;
                   1178:             faaio.a = a;
                   1179:             faaio.b = b;
                   1180: 
                   1181:             if (ioctl(devfd, FAAIO_ADD, &faaio) == -1) {
                   1182:                     perror("ioctl failed");
                   1183:             }
                   1184:             printf("%d\n", result);
                   1185:     }
                   1186: 
                   1187: ### An example user space program - running it
                   1188: 
                   1189:     # make
                   1190:     cc -o aaa_add aaa_add.c
                   1191:     # ./aaa_add 3 7
                   1192:     faa0: got ioctl with a 3, b 7
                   1193:     10
                   1194: 
                   1195: -   The program is successfully accessing the faa driver through the
                   1196:     ioctl
                   1197: -   The faa0:... line is a kernel message, normally only seen on the
                   1198:     console terminal
                   1199: 
1.3       mspo     1200: ## A few tips
1.1       mspo     1201: 
                   1202: ### Avoiding common pitfalls
                   1203: 
                   1204: -   Always free resources allocated in the match or probe functions
                   1205: -   Always use bus\_space methods, don’t access the hardware using a
                   1206:     pointer dereference
                   1207: -   If possible test on more than one hardware architecture, some bugs
                   1208:     may surface
                   1209: -   Don’t reinvent the wheel, try to use existing kernel frameworks as
                   1210:     much as possible
                   1211: -   Use copy(9) (or uiomove(9) or store(9)/fetch(9)) to move data
                   1212:     between the kernel and user space
                   1213: 
                   1214: ### Basic driver debugging
                   1215: 
                   1216: -   Use aprint\_debug to print debug-level messages on console and log
                   1217:     them (enabled by passing AB\_DEBUG from the boot loader)
                   1218: -   Use the built-in DDB debugger
                   1219:     -   Enabled by the kernel option DDB
                   1220:     -   A kernel panic will start DDB if the DDB\_ONPANIC=1 kernel
                   1221:         option is specified or the ddb.onpanic sysctl is set to 1.
                   1222:     -   Run \# sysctl -w kern.panic\_now=1 to trigger a panic manually
                   1223:         (DIAGNOSTIC option)
                   1224: -   Remote debugging is possible on some ports
                   1225:     -   With KGDB through the serial port
                   1226:     -   With IPKDB through the network
                   1227: 
1.3       mspo     1228: ## Summary
1.1       mspo     1229: 
                   1230: ### Further reading
                   1231: 
                   1232: -   Documentation, articles:
                   1233:     -   [A Machine-Independent DMA Framework for NetBSD, Jason R.
                   1234:         Thorpe](http://www.netbsd.org/docs/kernel/bus_dma.pdf)
                   1235:     -   [Writing Drivers for NetBSD, Jochen
                   1236:         Kunz](ftp://ftp.netbsd.org/pub/NetBSD/misc/ddwg/NetBSD-driver_writing-1.0.1e.pdf)
                   1237:     -   [NetBSD Documentation: Writing a pseudo
                   1238:         device](http://www.netbsd.org/docs/kernel/pseudo/)
                   1239:     -   [autoconf(9)](http://netbsd.gw.com/cgi-bin/man-cgi?autoconf+9+NetBSD-current),
                   1240:         [bus\_space(9)](http://netbsd.gw.com/cgi-bin/man-cgi?bus_space+9+NetBSD-current)
                   1241:         [bus\_dma(9)](http://netbsd.gw.com/cgi-bin/man-cgi?bus_dma+9+NetBSD-current)
                   1242:         [driver(9)](http://netbsd.gw.com/cgi-bin/man-cgi?driver+9+NetBSD-current),
                   1243:         [pci(9)](http://netbsd.gw.com/cgi-bin/man-cgi?pci+9+NetBSD-current)
                   1244:         man pages, etc.
                   1245: 
                   1246: -   Example source code of drivers:
                   1247:     -   tdvfb
                   1248: 
1.4       mspo     1249:         voodoofb are fairly good frame buffer driver examples with
1.1       mspo     1250:         documentation publicly available.
                   1251: 
                   1252:     -   etsec
                   1253: 
                   1254:         is a nice example of a more complicated network interface driver
                   1255: 
                   1256: ### Get the source code
                   1257: 
                   1258: -   Download the source code and materials for this tutorial
                   1259: -   <https://github.com/rkujawa/busspace-tutorial>
                   1260: -   <https://github.com/rkujawa/gxemul-tutorial>
                   1261: 
                   1262: ### The End…
                   1263: 
1.5     ! mspo     1264: [^1]: At least they should, some functions are missing on less popular ports
1.1       mspo     1265: 
1.5     ! mspo     1266: [^2]: Only three of these registers are of any importance for us at this moment
1.1       mspo     1267: 
                   1268: [^3]: Required if you are NetBSD developer, optional otherwise.
                   1269: 
1.5     ! mspo     1270: [^4]: Might not exist if the driver is only a simple passthrough from a specific bus to another MI driver.
1.1       mspo     1271: 
                   1272: [^5]: Omitted if not needed.
                   1273: 
                   1274: [^6]: although you’ll often have to use bus\_size\_t
                   1275: 
1.5     ! mspo     1276: [^7]: It’s also possible to define a major in a machine-independent way in src/sys/conf/majors

CVSweb for NetBSD wikisrc <wikimaster@NetBSD.org> software: FreeBSD-CVSweb