DOC

Sample Drivers for the Kernel-Mode Driver Framework

By Clara Stevens,2014-03-29 00:25
6 views 0
Plx9x5x, Sample function driver for devices based on the PLx PCI9056RDK-Lite Adapter, The driver determines whether to use the I/O-mapped BAR or the

Sample Drivers for the

    Kernel-Mode Driver Framework May 10, 2006

    Abstract

    This paper provides information about sample drivers for the kernel-mode driver framework (KMDF), which is a component of the Windows Driver Foundation (WDF) for the Microsoft? Windows? family of operating systems. The paper is for driver writers who are familiar with KMDF and are preparing to use KMDF to write their first kernel-mode driver. It steps through several sample kernel-mode drivers, explaining the structure of a WDF driver and demonstrating how each sample implements common driver features.

    This information applies for the following operating systems:

     Microsoft Windows Vista?

     Microsoft Windows Server? 2003

     Microsoft Windows XP

     Microsoft Windows 2000

    The information and sample code in this paper apply to the first release of the Windows Driver Foundation.

    The current version of this paper is maintained on the Web at http://www.microsoft.com/whdc/driver/wdf/KMDF-samp.mspx.

    References and resources discussed here are listed at the end of this paper. Contents

    Introduction ............................................................................................................................. 4

    WDF Sample Drivers .............................................................................................................. 4

    Differences between KMDF and WDM Samples ................................................................ 7

    Macros Used in KMDF Samples ........................................................................................ 9

    KMDF Driver Structure and Concepts ..................................................................................... 9

    Object Creation ................................................................................................................ 10

    Object Context Area ......................................................................................................... 11

    I/O Queues ....................................................................................................................... 11

    I/O Requests .................................................................................................................... 12

    A Minimal KMDF Driver: The Simple Toaster ....................................................................... 13

    Creating a WDF Driver Object: DriverEntry ...................................................................... 13

    Creating the Device Object, Device Interface, and I/O Queue: EvtDriverDeviceAdd ....... 15

    Device Object and Device Context Area ..................................................................... 17

    Device Interface .......................................................................................................... 18

    Default I/O Queue ....................................................................................................... 18

    Handling I/O Requests: EvtIoRead, EvtIoWrite, EvtIoDeviceControl ............................... 19

    Sample Software-Only Driver ................................................................................................ 21

    File Create and Close Requests ...................................................................................... 21

    Additional Device Object Attributes .................................................................................. 22

    Synchronization Scope ................................................................................................ 22

    Execution Level ........................................................................................................... 23

    EvtCleanupCallback Function ..................................................................................... 23

    Setting Additional Device Object Attributes ................................................................. 24

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 2

    Plug and Play and Power Management Support .............................................................. 24 Registering Callbacks .................................................................................................. 25 Managing Power Policy ............................................................................................... 28 Callbacks for Power Up and Power Down ................................................................... 29 Callbacks for Wake Signal Support ............................................................................. 30 WMI Support .................................................................................................................... 31 Initializing WMI Support ............................................................................................... 31 WMI Instance Event Callbacks .................................................................................... 35 Firing WMI Events ....................................................................................................... 38 Sample Hardware Driver ....................................................................................................... 41 Supporting Device Interrupts ............................................................................................ 42 Creating an Interrupt Object ........................................................................................ 42 Enabling and Disabling Interrupts ................................................................................ 43 Post-Interrupt Enable and Pre-Interrupt Disable Processing ....................................... 44 Handling Interrupts ...................................................................................................... 45 Deferred Processing for Interrupts .............................................................................. 47 Mapping Resources ......................................................................................................... 48 Using Multiple I/O Queues and Performing I/O ................................................................ 52 Creating and Configuring the Queues ......................................................................... 54 Handling Requests from a Parallel Queue .................................................................. 57 Performing Buffered I/O ............................................................................................... 59 Forwarding Requests to a Queue ................................................................................ 60 Retrieving Requests from a Manual Queue ................................................................. 61 Reading and Writing the Registry ..................................................................................... 64 Watchdog Timer: Self-Managed I/O ................................................................................. 67 Self-Managed I/O during Device Startup and Restart.................................................. 67 Self-Managed I/O during Device Power-Down and Removal ...................................... 68 Implementing a Watchdog Timer ................................................................................. 68 Resources ............................................................................................................................. 73

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 3

Disclaimer

    This is a preliminary document and may be changed substantially prior to final commercial release of the software described herein. The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication. This White Paper is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, email address, logo, person, place or event is intended or should be inferred. ? 2006 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Server, and Windows Vista are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 4

Introduction

    The Windows Driver Foundation (WDF) is Microsoft’s next-generation driver model

    for the Microsoft? Windows? family of operating systems. WDF supports both kernel-mode and user-mode drivers through separate but functionally similar driver frameworks.

    The kernel-mode driver framework (KMDF) is designed to encourage incremental driver development. You can use the framework to quickly create a skeletal driver that will load and run, and then you can add support for more complex functionality and hardware-specific features.

    This paper provides a practical introduction to using the kernel-mode framework to write WDF drivers. Its primary focus is a detailed examination of sample code from three drivers: the Simple Toaster, the Featured Toaster, and PCIDRV. By studying the software-only Toaster drivers, you can see how to approach driver development in WDF. The PCIDRV sample shows how to implement common driver features in a driver that supports physical hardware.

    To get the most out of this paper, you should:

    ; Understand the fundamentals of kernel-mode operation, including interrupt

    request level (IRQL) and locks.

    ; Understand the basic design goals of WDF, as described in “Architecture of the

    Windows Driver Foundation,” listed in the Resources section.

    ; Be familiar with the KMDF object model and I/O model, as described in

    Architecture of the Kernel-Mode Driver Framework,” also listed in the

    Resources section.

    ; Install the latest WDF release for reference.

    Note

    The sample code in this paper is for illustrative and instructive purposes, although some details have been removed to conserve space. Microsoft has made every effort to keep the samples up to date. However, if you use the samples as a basis for your own driver, you should always use the versions available with the most recent WDF release.

WDF Sample Drivers

    The WDF release includes several sample kernel-mode drivers. You can use these sample drivers as a basis for your own drivers and refer to them for examples of specific implementation techniques. The KMDF sample drivers are installed in the Src\Kmdf subdirectory of the WDF installation directory.

    This section lists the samples in three ways: by name, by device function, and by the features that they demonstrate. Table 1 lists the samples by name. Table 1. KMDF Samples by Name

    Name Description

    1394 Virtual (1394vdev.sys) and physical (1394diag.sys) diagnostic

    drivers for IEEE 1394 devices that interface with the upper edge of

    the 1394 stack.

    AMCC5933 Sample driver for devices based on or similar to the AMCC5933

    chip for PCI or ISA.

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 5

Name Description

    Echo Demonstration driver that does not control any hardware. It uses a

    serial I/O queue to serialize read and write requests that are

    targeted at the device and shows how to handle request

    cancellation.

    FakeModem Driver for controllerless modem (soft modem).

    Firefly Filter driver for a human interface device (HID).

    Kbfiltr Filter driver for a keyboard. It exposes a raw physical device object

    (PDO) for communication with user-mode application.

    NdisEdge Driver that exposes an NDIS miniport interface at its upper edge

    and interacts with other drivers such as USB, IEEE 1394, and

    serial at its lower edge.

    NdisProt Driver that exposes a WDF interface at its upper edge and an

    NDIS interface at its lower edge.

    Nonpnp Legacy, NT 4.0-style driver that does not support Plug and Play or

    interact with hardware. It handles four different device I/O control

    (IOCTL) requests and shows how to handle METHOD_NEITHER

    I/O. It provides kernel-level services to a user application, which

    dynamically loads and unloads it.

    OsrUsbFx2 Driver for OSR USB-FX2 Learning Kit. It shows how to perform

    bulk and isochronous data transfers to a generic USB device and

    how to write a bus driver.

    Pcidrv Function driver for Intel 82557/82558-based PCI Ethernet Adapter

    (10/100) and Intel compatibles.

    Plx9x5x Sample function driver for devices based on the PLx PCI9056RDK-

    Lite Adapter, a PCI/DMA device.

    Ramdisk RAM disk driver that shows how to create a virtual disk in memory.

    Serial WDF version of the in-box serial driver.

    Toaster Function, filter, and bus drivers for a hypothetical toaster device. If none of the sample drivers supports your specific device type, you might be able

    to find a sample that supports a device that has similar characteristics or is used in

    a similar way. Table 2 lists the device characteristics and usage models that the

    KMDF samples support.

    Table 2. KMDF Samples by Device Usage Model Device usage model Device or driver type KMDF sample

    Hardware that supports only port-Parallel port, legacy joystick AMCC5933 ISA

    mapped I/O. port, and ISA devices sample (S5933DK1)

    Driver that handles I/O operations

    serially and reads or writes one port

    at a time.

    Driver that polls read operation at

    regular intervals from either a

    deferred procedure call (DPC) or a

    dedicated kernel thread.

    Hardware that supports port-mapped Serial port, parallel port, IDE Serial

    I/O and interrupts to notify the driver controller, and PS/2

    about input data and other controller

    asynchronous events.

    Same as previous, but also supports Typical PCI and EISA PLX9x5x

    memory-mapped I/O. devices for data acquisition

    that use direct memory

    access (DMA)

    Same as previous, but also supports Network adapters and PCIDRV

    bus master DMA channels to read similar PCI drivers

    and write.

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 6

    Device usage model Device or driver type KMDF sample Hardware that has more than one Multifunction PCI devices Toaster bus driver function or emulates more than one that do not confirm to the device. PCI specification, multiport Driver that supports a virtual bus. serial cards, and multiport

    network cards

    Filter driver that modifies I/O Keyboard and mouse filters, Toaster filter driver requests and provides an interface storage class filter drivers, for applications to directly control the and serial devices

    filter.

    Filter driver that modifies the

    hardware resources.

    Driver that interacts with an NDIS protocol drivers, NdisEdge and unrelated device stack to perform Asyncmac, transport driver NdisProt I/O. interface (TDI) client drivers,

    and Ftdisk or volsnap

    Driver that supports a USB client. Any USB device Osrusbfx2 Software-only drivers or drivers that No device or legacy devices Nonpnp are not part of any Plug and Play

    stack.

    Legacy NT 4.0-style drivers that do

    not support Plug and Play.

    Driver that must run in the context of Video capture devices, Nonpnp the user application so that it can audio cards, and high-speed handle METHOD_NEITHER IOCTLs data-acquisition devices

    or map memory into user address space.

    Driver that registers in-process

    context callback to handle

    METHOD_NEITHER I/O requests.

     You can also refer to the samples to find out how to use specific KMDF features.

    Table 3 lists the samples that support each fundamental feature.

    Table 3. KMDF Feature Support in Samples

    KMDF feature Sample

    Buffered I/O Ndisprot

    Child device enumeration OsrUsbFx2

    Toaster bus

    Collection PCIDRV

    Toaster bus

    Direct I/O Ramdisk

    DMA AMCC5933

    PCIDRV

    PLX9x5x

    DPC PCIDRV

    PLX9x5x

    Event tracing AMCC5933

    NonPnP

    OsrUsbFx2

    PCIDRV

    Functional device object (FDO) interface All samples

    File object NonPnP

    Filter driver Firefly

    Kbfiltr

    I/O request cancellation Echo

    I/O requests and I/O queues All samples

    (serial/parallel/manual)

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 7

    KMDF feature Sample I/O target objects 1394

    Firefly

    NdisEdge

    OsrUsbFx2 Idle detection PCIDRV

    Serial In-process callback to handle events in caller’s NonPnP thread context

    Interrupt handling PCIDRV

    PLX9x5x

    Serial Memory pool All samples METHOD_NEITHER I/O NonPnp Non-Plug and Play, NT 4.0-style device objects Ndisprot (also called control device objects)

    Physical Device object (PDO) interface Kbfiltr

    OsrUsbFx2/EnumSwitches

    Toaster bus Plug and Play device interfaces AMCC5933

    PCIDRV

    PlX9x5x

    Toaster function Plug and Play hardware resources PCIDRV

    PLX9x5x

    AMCC5933 Plug and Play query interfaces Toaster bus Power policy owner PCIDRV Preprocessing callbacks for Serial IRP_MJ_FLUSH_BUFFERS,

    IRP_MJ_QUERY_INFORMATION, and IRP_MJ_SET_INFORMATION

    Raw PDO Kbfiltr

    OsrUsbFx2 Registry Fakemodem

    PCIDRV

    Ramdisk

    Serial

    Toaster bus Self-managed I/O Echo

    PCIDRV Symbolic links to device names Fakemodem

    Ramdisk Synchronization scope Echo Timer objects Echo USB device support OsrUsbFx2 Wake signal support OsrUsbFx2

    PCIDRV

    Serial Windows management instrumentation (WMI) Firefly

    PCIDRV

    Serial

    Toaster function Work items AMCC5933

    PCIDRV

Differences between KMDF and WDM Samples

    The KMDF samples are based on the similarly named Windows Driver Model

    (WDM) samples that are provided in the Windows Driver Kit (WDK). With a few

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 8

    exceptions, the corresponding drivers support similar features. If you are experienced with WDM, you might find useful a comparison of the KMDF and WDM samples.

    The primary difference between the samples is that the KMDF samples are much shorter and less complex. The reason is that KMDF implements most of the details of WDM, so that you can avoid writing many lines of code that perform common tasks and implement common features required in all drivers. Instead, you define callbacks for the conditions and events that your driver must handle. For example, KMDF drivers, like WDM drivers, support Plug and Play and power management for their devices. WDM drivers typically include thousands of lines of code to ensure that they handle every possible state and minor I/O request packet (IRP) code; drivers often require code to handle IRPs that they don’t even support.

    A KMDF driver, however, includes code to handle only those features and requests that its device supports. All other Plug and Play and power requests are handled by WDF in a default manner. These defaults make possible the incremental development of KMDF drivers. You can implement a skeletal set of features, test the implementation, and then incrementally add code to support additional features or perform more complicated tasks.

    In a practical sense, the most significant difference between KMDF and WDM drivers is the number and complexity of the required functions. For a graphic example of this difference, compare the simplest form of the WDM Toaster sample (src/general/toaster/func/incomplete1in the WDK installation directory) with the simplest KMDF Toaster sample (src/kmdf/toaster/func/simple in the WDF installation directory).

    Both drivers support basic Plug and Play, power, and WMI requests. The KMDF sample also includes stub functions to handle read, write, and IOCTL requests. However, the KMDF sample contains many fewer lines of code than the WDM sample. The following table compares the functions in these two drivers. Table 4. Comparison of KMDF Simple Toaster and

     WDM Incomplete1 Toaster Samples

    WDM function Equivalent KMDF Comments

    function

    DriverEntry DriverEntry Function has same prototype.

    KMDF driver creates WDF

    driver object.

    ToasterAddDevice ToasterEvtDeviceAdd KMDF driver creates a default

    queue for I/O requests.

    ToasterUnload None KMDF driver uses defaults.

    ToasterDispatchPnP None KMDF driver uses defaults.

    ToasterSendIrpSynchronously None WDM driver passes IRPs

    down the stack to be

    completed synchronously.

    KMDF driver uses defaults.

    ToasterDispatchPnPComplete None KMDF driver uses defaults.

    ToasterDispatchPower None KMDF driver uses defaults.

    ToasterSystemControl None WDM function passes WMI

    IRPs to the next lower driver.

    KMDF driver uses defaults.

    None ToasterEvtIoRead WDM function handles and

    completes read requests.

    KMDF function is a stub.

    None ToasterEvtIoWrite WDM function handles and

    completes write requests.

    KMDF function is a stub.

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 9

WDM function Equivalent KMDF Comments

    function

    None ToasterEvtIoDeviceControl WDM function handles and

    completes device I/O control

    requests. KMDF function is a

    stub.

    Macros Used in KMDF Samples

    Many of the KMDF samples use two macros that might be unfamiliar:

    PAGED_CODE and UNREFERENCED_PARAMETER.

    The PAGED_CODE macro causes the driver to assert if the function is called at IRQL DISPATCH_LEVEL or higher. This macro is defined in ntddk.h and takes no arguments. It works only in a checked build.

    The UNREFERENCED_PARAMETER is defined in the standard WDK header file ntdef.h, which is included by ntddk.h. It disables compiler warnings about unreferenced parameters. It can be used in any kernel-mode driver. KMDF Driver Structure and Concepts

    KMDF drivers are object-oriented, event-driven drivers that link dynamically with the kernel-mode driver framework at run time. This section provides a brief overview of KMDF concepts. For further details, see the white paper titled Architecture of the

    Kernel-Mode Driver Framework,” which is listed in the Resources section.

    The KMDF object model defines object types to represent common driver constructs. Each object exports methods (functions) and properties (data) that drivers can access and is associated with object-specific events, which drivers can support by providing event callbacks. The objects themselves are opaque to the driver. KMDF and the driver instantiate the objects that are required to service the device. The driver provides callbacks for the events for which the KMDF defaults do not suit its device and calls methods on the object to get and set properties and perform any additional actions. Thus, a KMDF driver consists of a DriverEntry

    function, callback routines for events that affect the driver or its devices, and whatever utility functions the driver requires.

    All KMDF drivers create a WDFDRIVER object to represent the driver and a WDFDEVICE object to represent each device that the driver supports. Most drivers also create one or more WDFQUEUE objects to represent the driver’s I/O queues. KMDF places I/O requests into the queues until the driver is ready to handle them. Drivers can create additional objects as their device hardware and driver features require. KMDF objects are organized hierarchically, with the WDFDRIVER object as the root. The object hierarchy defines the object’s lifetime—each object is deleted

    when its parent is deleted.

    All KMDF objects are created in the same way, by using KMDF-defined initialization functions and an object creation method. Any KMDF object can have one or more driver-defined object context areas, in which the driver can store data that is specific to that particular instance of the object.

    The following sections provide more information on object creation and context areas and on I/O queues and requests, which are fundamental to KMDF drivers. May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

    错误?使用“开始”选项卡将 Title 应用于要在此处显示的文字。 - 10

Object Creation

    To create a KMDF object, a driver follows these steps:

    1. Initialize the configuration structure for the object, if one exists. 2. Initialize the attributes structure for the object, if necessary. 3. Call the creation method to create the object.

     The object configuration structure and the object attributes structure supply basic information about the object and how the driver uses it. All object types have the same attributes structure, but the configuration structure for each type of object is different and some objects do not have one.

    The configuration structure holds pointers to object-specific information, such as the driver’s event callback functions for the object. The driver fills in this structure and then passes it to the framework when it calls the object creation method. The framework uses the information from the configuration structure to initialize the object. For example, the WDFDRIVER object contains a pointer to the driver’s

    EvtDriverDeviceAdd callback function, which KMDF invokes when a Plug and Play add-device event occurs.

    KMDF defines functions named WDF_Object_CONFIG_INIT to initialize the

    configuration structures, where Object represents the name of the object type. Not

    all object types have configuration structures or the corresponding initialization functions.

    The object attributes structure (WDF_OBJECT_ATTRIBUTES) specifies attributes that are common to all objects:

    ; Callbacks to handle object cleanup and destruction.

    ; The interrupt request level (IRQL) at which the object’s callback functions are

    invoked and its locks are held.

    ; An object context area.

    ; Information about the context area, such as its size and type.

    KMDF defines the following for use in initializing object attributes: ; WDF_OBJECT_ATTRIBUTES_INIT

    ; WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE

    ; WDF_OBJECT_ATTRIBUTES_SET_CONTEXT_TYPE

    The WDF_OBJECT_ATTRIBUTES_INIT function sets values for synchronization and execution level, which determine which of the driver’s callbacks KMDF invokes concurrently and the highest IRQL at which they can be called. The two context-type initialization macros set information about the object’s context area, which is

    described in the next section.

    Although attributes can apply to any type of object, the defaults are typically acceptable for objects for which the driver does not define a context area. To accept the defaults, a driver specifies WDF_NO_OBJECT_ATTRIBUTES, which WDF defines as NULL.

    After initializing the object’s configuration structure and attributes, the driver creates an instance of the object by calling the creation method for the object type with a pointer to the attributes structure and any other object-type-specific parameters. Creation methods are all named WdfObjectCreate, where Object indicates the type

    May 10, 2006 ? 2006 Microsoft Corporation. All rights reserved.

Report this document

For any questions or suggestions please email
cust-service@docsford.com