СОДЕРЖАНИЕ
Обзор
WDM существует на промежуточном уровне драйверов режима ядра Windows 2000 и был введен для повышения функциональности и упрощения написания драйверов для Windows. Хотя WDM в основном разрабатывался для обеспечения двоичной совместимости с исходными кодами между Windows 98 и Windows 2000, это не всегда может быть желательным, и поэтому для любой операционной системы можно разработать специальные драйверы.
Драйверы режима ядра устройства
Хотя WDM определяет три типа драйверов устройств, не все стеки драйверов для данного устройства содержат все типы драйверов устройств. Три типа драйверов устройств WDM:
Функциональный драйвер : это основной драйвер для устройства, который обеспечивает рабочий интерфейс для устройства, обрабатывая операции чтения и записи. Функциональные драйверы пишутся производителями устройств, и для их взаимодействия с оборудованием они зависят от конкретного драйвера шины, присутствующего в операционной системе Windows.
Драйвер фильтра : этот драйвер не является обязательным и может изменять поведение устройства, например запросы ввода и вывода. Эти драйверы могут быть реализованы как драйверы фильтров нижнего и верхнего уровня.
Стек объектно-ориентированных драйверов
Функциональные драйверы и драйверы шины часто реализуются как пары драйвер / минидрайвер, которые на практике представляют собой либо класс / мини-класс, либо пару порт / минипорт.
Драйверы шины для устройств, подключенных к шине, реализованы как драйверы классов и не зависят от оборудования. Они будут поддерживать работу определенного типа устройства. Операционные системы Windows включают ряд драйверов классов, например драйвер kbdclass.sys для клавиатур. С другой стороны, драйверы миникласса поставляются производителем устройства и поддерживают только операции, специфичные для конкретного устройства, для конкретного устройства данного класса.
Драйверы портов поддерживают общие операции ввода / вывода (I / O) для интерфейса периферийного оборудования. Основная функциональность драйверов портов определяется операционной системой, а операционные системы Windows интегрируют различные драйверы портов. Например, драйвер порта i8042prt.sys для микроконтроллера 8042 подключает клавиатуры PS / 2 к периферийной шине материнской платы. Драйверы минипорта, как и драйверы мини-класса, поставляются производителями оборудования и поддерживают только определенные операции периферийного оборудования, подключенного к порту на материнской плате.
Драйверы устройств для разных операционных систем Windows
Драйверы устройств разработаны для определенных версий операционной системы Windows, и драйверы устройств для предыдущей версии Windows могут работать некорректно или вообще не работать с другими версиями. Поскольку многие драйверы устройств работают в режиме ядра, установка драйверов для предыдущей версии операционной системы может дестабилизировать операционную систему Windows. Поэтому для миграции компьютера на более новую версию операционной системы Windows требуется, чтобы были установлены новые драйверы устройств для всех компонентов оборудования. Поиск последних версий драйверов устройств и их установка для Windows 10 усложнили процесс миграции.
Диспетчер устройств
Диспетчер устройств является апплет панели управления в операционных системах Microsoft Windows. Это позволяет пользователям просматривать и управлять оборудованием, подключенным к компьютеру. Он позволяет пользователям просматривать и изменять свойства аппаратного устройства, а также является основным инструментом для управления драйверами устройств.
Критика
Также был ряд опасений по поводу качества документации и образцов, предоставленных Microsoft.
Из-за этих проблем Microsoft выпустила новый набор фреймворков поверх WDM под названием Windows Driver Frameworks (WDF; ранее Windows Driver Foundation), который включает в себя инфраструктуру драйвера режима ядра (KMDF) и платформу драйвера режима пользователя (UMDF). ). Windows Vista поддерживает как чистый WDM, так и более новый WDF. KMDF также доступен для загрузки для Windows XP и даже Windows 2000, а UMDF доступен для Windows XP и выше.
Writing WDM Drivers
This section discusses the Microsoft Windows Driver Model (WDM) architecture. This architecture started in Windows 2000 as an enhancement to previous Windows NT device drivers.
NoteВ В Drivers for versions of Windows NT-based operating systems before Windows 2000 are not supported, and you should update these drivers. The WDM architecture does not support drivers for non-Windows NT-based operating systems (such as Windows 98), and you should rewrite such drivers.
This section is divided into three parts:
Windows Driver Model describes the Windows Driver Model (WDM), including types of WDM drivers, device configuration, and WDM versioning.
Device Objects and Device Stacks describes device objects and device stacks. The section includes information about physical device objects (PDOs), functional device objects (FDOs), and filter device objects (filter DOs). Drivers are often built from a set of device objects that work together. This set of device objects is called a stack. Stacks can help you understand the flow of information to and from a driver and how different parts of the driver communicate internally.
Kernel-Mode Driver Components describes which routines you must implement to have a functional driver and which routines are optional.
A device driver is a set of software code that must integrate into the operating system. To complete this integration, you must write a set of handler routines in your driver that process calls from the operating system. These routines can be simple function calls, but many of them implement the processing of I/O request packets (IRPs), which facilitate communication between drivers and the operating system.
NoteВ В WDM drivers can also use the Windows Driver Frameworks (WDF) library to make some parts of a device driver easier to write. Specifically, kernel-mode drivers can use the Kernel-Mode Driver Framework (KMDF), which is part of WDF. For more information about KMDF for kernel-mode drivers, see Kernel-Mode Driver Framework Overview. Note that KMDF does not replace WDM. You must still understand many parts of WDM to write a KMDF driver.
Модель драйверов Windows (WDM)
В Windows 2000 была добавлена поддержка технологии Plug and Play, настроек электропитания и расширение модели драйверов Windows NT, названной моделью драйверов Windows (WDM). Windows 2000 и более поздние версии могут запускать драйверы, унаследованные у Windows NT 4, но, поскольку они не поддерживают технологию Plug and Play настройки электропитания, системы, запускающие эти драйверы, будут вынуждены ограничивать возможности в этих двух областях.
С точки зрения WDM, существуют драйверы трех типов:
Функциональный драйвер по определению является драйвером, который знает о конкретном устройстве практически все, и обычно он является единственным драйвером, обращающимся к специфическим регистрам устройства.
В среде окружения WDM все аспекты устройства контролируются не одним драйвером: драйвер шины занимается отправкой диспетчеру PnP отчетов об устройствах, подключенных к его шине, а функциональный драйвер управляет самим устройством.
В большинстве случаев драйверы фильтра, находящиеся на нижнем уровне, изменяют поведение устройства. Например, если устройство сообщает своему драйверу шины, что ему нужно 4 порта ввода-вывода, в то время как ему фактически нужно 16 портов ввода-вывода, функциональный драйвер фильтра для данного конкретного устройства может перехватить перечень аппаратных ресурсов, о котором драйвер шины сообщает диспетчеру PnP, и исправить количество портов ввода-вывода.
Драйверы фильтра, находящиеся на верхнем уровне, обычно предоставляют устройству какие-нибудь дополнительные свойства. Например, драйвер фильтра такого устройства, как клавиатура, находящийся на верхнем уровне, может навязывать дополнительные проверки безопасности.
Некоторые технологии Microsoft для программистов
Некоторые технологии, программные интерфейсы, протоколы и спецификации произведённые в недрах Microsoft.
Это не всё, конечно, даже из этой программистской категории. А есть ещё различные аббревиатуры и названия просто для разных частей Windows и т. п., но то не так интересно.
OLE — технология связывания и внедрения объектов в другие документы и объекты.
OLE Automation — механизм межпроцесорного вхаимодействия, основанный на COM; для использования в скриптовых языках.
aka Automation
ActiveX — ребрэндинг OLE
COM (Component Object Model) — обеспечивает межпроцессорное взаимодействие между объектами написанными на разных языках
COM+ — улучшена поддержка потоков, etc
DCOM — позволяет COM-компонентам взаимодействовать друг с другом по сети
VBX (Visual Basic Extension) — стали ненужны благодаря…
OCX (OLE custom controls) — элементы интерфейса на основе OLE
Ещё пятьсот → CDO (Collaboration Data Objects) — доступ к Global Address List и другим объектам на сервере, в дополнение к содержимому письменных ящиков и папок.
aka OLE Messaging
aka Active Messaging
IWA (Integrated Windows Authentication)
aka NT Authentication
aka NTLM Authentication
aka Domain authentication
aka Windows Integrated Authentication
aka Windows NT Challenge/Response authentication
aka Windows Authentication
NTLM (NT LAN Manager) — протокол сетевой аутентификации
SSPI (Security Support Provider Interface) — API используемый Windows’ами для выполнения разных секурных операций, таких как аутентификация.
Windows Sockets API
LSP (Layered Service Provider, англ. многоуровневый поставщик услуг) — технология Windows sockets версии 2.0, позволяющая пользователю подключать собственные DLL-библиотеки для обработки вызовов Winsock API.
SPI (Service Provider Interface)
AD (Active Directory)
aka NTDS (NT Directory Service)
FSMO (Flexible single master operation) — какая-то фича Active Directory
ADAM (Active Directory Application Mode) — простая имплементация AD
aka AD LDS (Lightweight Directory Services)
Мультимедиа
GDI — работаем с графикой
GDI+ — продолжение
WIC (Windows Imaging Component) — API для работы с изоюражениями.
WCS (Windows Color System) — подсистема и API в Vista для работы с цветом
CITE (Color Infrastructure and Translation Engine)
MF (Media Foundation) — замена для DirectShow, Windows Media SDK, DirectX Media Objects (DMOs) и всех других мультимедийных APIs таких как Audio Compression Manager (ACM) и Video for Windows (VfW).
ASF (Advanced Systems Format) — потоковый аудио- и видео-формат
aka Advanced Streaming Format
aka Active Streaming Format
Active Scripting
ActiveX Scripting
WSH (Windows Script Host) — автоматизация жития в Windows
WDM (Windows Driver Model) — API для написания драйверов
VxD (virtual xxx driver) — предшественник
WDF (Windows Driver Foundation) — API для создания драйверов начиная с Windows 2000
KMDF (Kernel-Mode Driver Framework) — API для создания драйверов в режиме ядра
UMDF (User-Mode Driver Framework) — создаём драйверы для Vista+
WDDM (Windows Display Driver Model) — архитектура для драйверов видеокарт начиная с Vista
aka WVDDM
DLL (Dynamic Link Library)
DDI
MSRPC (Microsoft Remote Procedure Call)
Windows DNA (Windows Distributed interNet Applications Architecture) — общее название для набора технологий, таких как ActiveX, Dynamic HTML (DHTML) и COM. Уже не используется.
MFC — ОО-прослойка над WINAPI
aka AFX (Application Framework Extensions)
WTL (Windows Template Library) — альтернатива MFC из недр Microsoft’а же!
ATL (Active Template Library) — упрощает создание COM-объектов; в некотором роде — более легковесная альтернатива MFC.
MSXML (Microsoft XML Core Services) — создаём родные XML-based Windows-приложения с VBScript, etc
WMI (Windows Management Instrumentation)
WIA (Windows Image Acquisition) — API для работы с периферией
WPD (Windows Portable Devices)
WPF (Windows Presentation Foundation)
aka Avalon
XAML (Extensible Application Markup Language) — язык для описания структуры в WPF
WF (Windows Workflow Foundation) — технология для определения, выполнения и управления рабочими процессами.
WinFX —?
MAPI (Messaging API)
RAPI (Remote Application Programming Interface)
SAPI (Speech Application Programming Interface)
TAPI (Telephony Application Programming Interface)
Базы данных
OLE DB — набор интерфейсов, основанных на COM, которые позволяют приложениям обращаться к данным, хранимым в разных источниках информации или хранилищах данных с помощью унифицированного доступа.
ADO (ActiveX Data Objects) — преемник RDO и DAO — интерфейс программирования приложений для доступа к данным, разработанный компанией Microsoft (MS Access, MS SQL Server) и основанный на технологии компонентов ActiveX. ADO позволяет представлять данные из разнообразных источников (реляционных баз данных, текстовых файлов и т. д.) в объектно-ориентированном виде.
ADO.NET — evolutionary improvement over traditional ADO for creating distributed, data-sharing applications.
RDO (Remote Data Objects) — технология доступа к базам данных
DAO (Data Access Objects) — технология доступа к данным
aka VT Objects
SQLXML — allowed Microsoft’s relational database to be viewed by XPath and allowed data to viewable as an XML file.
MDAC (Microsoft Data Access Components) — совокупность технологий компании Microsoft организованных в систему, которая позволяет программистам получить унифицированный и достаточно полный способ разработки приложений для доступа фактически к любым видам данных.
ADOMD (ADO Multi-Dimensional) is to be used with multidimensional data providers such as Microsoft OLAP Provider, also known as Microsoft Analysis Services Provider.
ADOX (ADO Extensions for DDL and Security) enable the creation and modification of definitions of a database, table, index, or stored procedure.
SQLOLEDB (Microsoft OLE DB Provider for SQL Server) supports access to Microsoft SQL Server.
SQLODBC (Microsoft SQL Server ODBC Driver) enables access to Microsoft SQL Server.
MSDASQL (The Microsoft OLE DB Provider for ODBC) is a technology that allows applications that are built on OLEDB and ADO (which uses OLEDB internally) to access data sources through an ODBC driver.
MSDADS (Microsoft OLE DB Provider for Data Shaping) — you can create hierarchical relationships between keys, fields, or rowsets in an application.
JRO (Jet Replication Objects) — used within ADO with Jet (*.mdb) databases to create and compress Jet Databases (.mdb’s) and perform Jet Replication Management.
RDS (Remote Data Services) — technology used in conjunction with ActiveX Data Objects (ADO) that allowed the retrieval of a set of data from a database server, which the client then altered in some way and then sent back to the server for further processing.
aka ADC (Advanced Data Connector)
ESE (Extensible Storage Engine) — реализация ISAM (Индексно-Последовательный Метода Доступа, способ хранения данных для быстрого доступа к ним, by IBM)
aka JET Blue
JET Red
JET (Joint Engine Technology)
aka Microsoft JET Engine
Microsoft Jet Database Engine — database engine on which several Microsoft products were built.
MSDE (Microsoft SQL Server Desktop Engine) — система управления реляционными БД. Урезанная версия Microsoft SQL Server 7.0.
aka Microsoft Data Engine
aka Microsoft Desktop Engine
WDM Audio Terminology
This section describes the differences in terminology between the Microsoft Windows Driver Model (WDM) audio driver architecture and the generic Windows layered driver architecture. The generic driver architecture is exemplified by SCSI port/miniport drivers (see Storage Driver Architecture).
The terms defined by the generic and WDM audio driver architectures are similar, but they do have some important differences, as described below.
Miniport Driver (Generic)
The miniport driver (generic) is the hardware-specific driver for an adapter that resides on a system bus (for example, PCI or ISA). This driver has a single entry point, DriverEntry, and registers a table of functions with a port driver. This table of functions serves as the miniport driver’s upper-edge interface.
The miniport driver sits below the port driver in the driver stack. That is, all calls to the miniport driver are made from the port driver and all calls out of the miniport driver are to the port driver’s lower-edge interface.
The following figure illustrates the meaning of the terms stack, upper-edge interface, and lower-edge interface as they are used in this context. The block representing the port driver is stacked on top of the block representing the miniport driver. Hence, the miniport driver sits below the port driver in the «stack».
The port and miniport drivers communicate through the software interfaces that they expose to each other. In the preceding figure, these interfaces are associated with the lower-edge of the block representing the port driver and the upper-edge of the block representing the miniport driver. This representation is the source of the terms «lower-edge interface» and «upper-edge interface».
Port Driver (Generic)
The port driver (generic) surrounds a miniport driver.
Implements WDM streaming filters.
Provides a common interface to the rest of the operating system.
Handles I/O requests from the system and recasts these requests as calls into the miniport driver’s function table.
Provides the miniport driver with a library of support functions (the port driver’s lower-edge interface).
The port driver hides many of the details of the operating system from the miniport driver, and the miniport driver hides the specifics of the underlying hardware from the port driver. The implementation of the port driver might undergo changes for different operating system releases, but the port driver’s interface to the miniport driver remains more-or-less unchanged, enabling the miniport driver to be largely platform-independent.
Minidriver (Generic)
The minidriver (generic) represents a hardware component on a bus. The minidriver uses the bus driver to communicate to the physical device over the bus, and it binds together the bus driver and one or more class drivers.
Class drivers help the minidriver present the physical device to clients as a type of logical device. In WDM environments, a minidriver typically receives requests in IRP form from class drivers, and sends requests in IRP form to a bus driver.
A minidriver might also have to communicate with several class drivers. An example of a minidriver that binds to multiple class drivers is a minidriver for a CD-ROM drive on an IEEE 1394 bus. It might bind to a file-system driver so that the drive can be accessed from the file system. However, it also binds to a Redbook system driver so that audio can be streamed from CDs.
Bus Driver (Generic)
The bus driver (generic) gives minidrivers access to a physical bus. The Microsoft Windows hardware abstraction layer (HAL) is sometimes referred to as the system bus driver because it provides access to the system bus. For more information, see Bus Drivers.
Class Driver (Generic)
The class driver (generic) implements behavior that is common across a class of similar devices.
Eliminates duplication of functionality in hardware-specific drivers.
Is not bus-specific.
Is not aware of resource issues (for example, DMA and interrupts).
Miniport Driver (WDM Audio)
The miniport driver (WDM audio) implements a function-specific interface for a function on an audio adapter card that resides on a system bus. A miniport driver is a component of an adapter driver. It is not recognized as a driver by the operating system. In this regard, an audio miniport driver differs from a generic miniport driver.
Unlike generic miniport drivers, audio miniport drivers do not implement DriverEntry, are not registered, and do not rely entirely on their respective port drivers for support. Multiple audio miniport drivers that address multiple functions can be linked into a single adapter driver (and associated with a single device object).
Adapter Driver (WDM Audio)
The audio adapter driver consists of a set of miniport drivers and additional code that addresses initialization issues. For example, an adapter driver implements a DriverEntry entry point.
Port Driver (WDM Audio)
The port driver (WDM audio) implements a KS filter on behalf of a miniport driver and operates in the context of a port class driver. The port driver exposes the miniport driver’s function-specific code as a KS filter to the system and is responsible for implementing adapter-independent functionality.
Unlike the generic port driver, the audio port driver shares the device object and is, therefore, instantiated differently. An audio port driver is also more closely resembles a generic class driver than it does a generic port driver in that it implements behavior that is expected of a class of devices (it is not bus-independent).
Port Class Driver (WDM Audio)
The port class driver (WDM audio) serves as a container for a collection of port drivers, each of which provides support for a different type of audio hardware function. The following figure shows the relationships between the audio port class and adapter drivers.
An adapter driver manages an adapter card that might contain several different hardware functions. As shown in the preceding figure, the adapter driver contains a miniport driver to manage each type of hardware function. Similarly, the port class driver is designed to provide support to adapter cards with multiple hardware functions. The port class driver provides a port driver for each of the well defined function types that it supports. The adapter driver binds its miniport driver for a particular function to the corresponding port driver for that function type. The port driver for each function handles communication with the WDM audio clients that use the function. The miniport driver contains all of the hardware-specific code for managing that function.
The port class driver (WDM audio) primarily functions as a container for multiple subdevices that are associated with a single device object. Bus drivers create a single physical device object (PDO) for each Plug and Play (PnP) node they enumerate.
In the case of an audio adapter, a single PnP node frequently contains multiple audio functions. To expose the various functions associated with a node as distinct devices typically requires writing a bus driver for the adapter. The bus driver enumerates the hardware functions and creates corresponding PDOs. In this scenario, one or more function-specific drivers need to bind to the PDOs and negotiate with the bus driver for access to shared resources on the adapter.
The port class driver uses the kernel streaming driver’s ability to expose various aspects of a single device object in order that the operating system recognizes the device as a set of distinct subdevices.
A reference string is appended to the device name to specify the desired subdevice. The kernel streaming driver dispatches creation IRPs based on this reference string. After a file object is created, the kernel streaming driver provides dispatching of IRPs that are targeted at the file object that represents the subdevice. In addition, the port class driver implements a COM-based model for packaging subdevices.
An adapter driver instantiates a port driver and a miniport driver and binds them together by passing a pointer to the miniport driver as a parameter to the port driver’s initialization function (see the code example in Subdevice Creation). The resulting port/miniport driver stack constitutes a KS filter that represents one of the subdevice types that the port class driver supports.
The port class driver’s PcRegisterSubdevice function registers the subdevice, which is perceived as a device by the rest of the system. The port driver receives creation IRPs targeted at the device object, but for only those IRPs that are specified by the reference string under which the subdevice is registered. The port driver also receives the IRPs targeted at the file objects that are associated with the subdevice. The port driver is responsible for the subdevice’s behavior as a KS filter and for communicating appropriately with the miniport driver.
For more information about designing drivers for multifunction audio cards, see Multifunction Audio Devices.

