Windows® Driver Model History And Architectural Overview Bob Rinne Director Windows Operating System Base Microsoft Corporation.

Slides:



Advertisements
Similar presentations
CT213 – Computing system Organization
Advertisements

WDM 드라이버의 기본 구조 What is WDM?
1/1/ / faculty of Electrical Engineering eindhoven university of technology Architectures of Digital Information Systems Part 1: Interrupts and DMA dr.ir.
Chorus and other Microkernels Presented by: Jonathan Tanner and Brian Doyle Articles By: Jon Udell Peter D. Varhol Dick Pountain.
EEE 435 Principles of Operating Systems Principles and Structure of I/O Software (Modern Operating Systems 5.2 & 5.3) 5/22/20151Dr Alain Beaulieu.
CMPT 300: Operating Systems I Dr. Mohamed Hefeeda
Contiki A Lightweight and Flexible Operating System for Tiny Networked Sensors Presented by: Jeremy Schiff.
Architectural Support for Operating Systems. Announcements Most office hours are finalized Assignments up every Wednesday, due next week CS 415 section.
Introduction to Operating Systems – Windows process and thread management In this lecture we will cover Threads and processes in Windows Thread priority.
Home: Phones OFF Please Unix Kernel Parminder Singh Kang Home:
OS Spring’03 Introduction Operating Systems Spring 2003.
Figure 1.1 Interaction between applications and the operating system.
1 Last Class: Introduction Operating system = interface between user & architecture Importance of OS OS history: Change is only constant User-level Applications.
OPERATING SYSTEMS Introduction
1 Process Description and Control Chapter 3 = Why process? = What is a process? = How to represent processes? = How to control processes?
1 I/O Management in Representative Operating Systems.
Operating System Organization
Operating Systems Concepts 1. A Computer Model An operating system has to deal with the fact that a computer is made up of a CPU, random access memory.
Chapter 13: I/O Systems I/O Hardware Application I/O Interface
I/O Tanenbaum, ch. 5 p. 329 – 427 Silberschatz, ch. 13 p
1 Input/Output. 2 Principles of I/O Hardware Some typical device, network, and data base rates.
Chapter 3.1:Operating Systems Concepts 1. A Computer Model An operating system has to deal with the fact that a computer is made up of a CPU, random access.
Introduction to Embedded Systems
Chapter 8 Windows Outline Programming Windows 2000 System structure Processes and threads in Windows 2000 Memory management The Windows 2000 file.
Protection and the Kernel: Mode, Space, and Context.
Segmentation & O/S Input/Output Chapter 4 & 5 Tuesday, April 3, 2007.
CSC 322 Operating Systems Concepts Lecture - 25: by Ahmed Mumtaz Mustehsan Special Thanks To: Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall,
Hardware Definitions –Port: Point of connection –Bus: Interface Daisy Chain (A=>B=>…=>X) Shared Direct Device Access –Controller: Device Electronics –Registers:
Three fundamental concepts in computer security: Reference Monitors: An access control concept that refers to an abstract machine that mediates all accesses.
1-1 Embedded Network Interface (ENI) API Concepts Shared RAM vs. FIFO modes ENI API’s.
Recall: Three I/O Methods Synchronous: Wait for I/O operation to complete. Asynchronous: Post I/O request and switch to other work. DMA (Direct Memory.
A Comparative Study of the Linux and Windows Device Driver Architectures with a focus on IEEE1394 (high speed serial bus) drivers Melekam Tsegaye
The Functions of Operating Systems Interrupts. Learning Objectives Explain how interrupts are used to obtain processor time. Explain how processing of.
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
Windows 2000 System Mechanisms Computing Department, Lancaster University, UK.
CE Operating Systems Lecture 11 Windows – Object manager and process management.
Operating Systems Lecture 7 OS Potpourri Adapted from Operating Systems Lecture Notes, Copyright 1997 Martin C. Rinard. Zhiqing Liu School of Software.
Hardware process When the computer is powered up, it begins to execute fetch-execute cycle for the program that is stored in memory at the boot strap entry.
Device Drivers CPU I/O Interface Device Driver DEVICECONTROL OPERATIONSDATA TRANSFER OPERATIONS Disk Seek to Sector, Track, Cyl. Seek Home Position.
NT Kernel CS Spring Overview Interrupts and Exceptions: Trap Handler Interrupt Request Levels and IRT DPC’s, and APC’s System Service Dispatching.
WHDC PowerPoint Template Notes & Handouts
Interrupt driven I/O. MIPS RISC Exception Mechanism The processor operates in The processor operates in user mode user mode kernel mode kernel mode Access.
CE Operating Systems Lecture 2 Low level hardware support for operating systems.
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
Introduction to Operating Systems and Concurrency.
System Components ● There are three main protected modules of the System  The Hardware Abstraction Layer ● A virtual machine to configure all devices.
CE Operating Systems Lecture 2 Low level hardware support for operating systems.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
1 Lecture 1: Computer System Structures We go over the aspects of computer architecture relevant to OS design  overview  input and output (I/O) organization.
Hardware process When the computer is powered up, it begins to execute fetch-execute cycle for the program that is stored in memory at the boot strap entry.
Interrupt driven I/O Computer Organization and Assembly Language: Module 12.
Interrupts and Exception Handling. Execution We are quite aware of the Fetch, Execute process of the control unit of the CPU –Fetch and instruction as.
CITA 171 Section 1 DOS/Windows Introduction. DOS Disk operating system (DOS) –Term most often associated with MS-DOS –Single-tasking operating system.
Embedded Real-Time Systems Processing interrupts Lecturer Department University.
Threads, SMP, and Microkernels Chapter 4. Processes and Threads Operating systems use processes for two purposes - Resource allocation and resource ownership.
Introduction to Operating Systems Concepts
Topics Covered What is Real Time Operating System (RTOS)
Chapter 3: Windows7 Part 2.
Introduction to writing device drivers for Windows
Chapter 3: Windows7 Part 2.
Operating Systems Chapter 5: Input/Output Management
Lecture Topics: 11/1 General Operating System Concepts Processes
CSE 451: Operating Systems Spring 2008 Module 15 I/O
Architectural Support for OS
CSE 451: Operating Systems Spring 2007 Module 15 I/O
CSE 451: Operating Systems Autumn 2003 Lecture 2 Architectural Support for Operating Systems Hank Levy 596 Allen Center 1.
CSE 451: Operating Systems Autumn 2001 Lecture 2 Architectural Support for Operating Systems Brian Bershad 310 Sieg Hall 1.
CSE 451: Operating Systems Winter 2003 Lecture 2 Architectural Support for Operating Systems Hank Levy 412 Sieg Hall 1.
Architectural Support for OS
Chapter 13: I/O Systems “The two main jobs of a computer are I/O and [CPU] processing. In many cases, the main job is I/O, and the [CPU] processing is.
Presentation transcript:

Windows® Driver Model History And Architectural Overview Bob Rinne Director Windows Operating System Base Microsoft Corporation

Purpose Of This Talk The WDM reality Discuss what is covered in WDM It has taken a long time Get an overview of its history and versions Get an overview of the architectures Basic information for navigating through WDM

Technical Outline Goals of WDM History of WDM Current state Overview of WDM

Goals Of WDM Common development environment for Windows NT® and Windows 9x family products Method of bringing Plug and Play and Power Management to Windows NT Binary compatibility between products Broad coverage of new technology busses

What Is WDM NDIS/SCSI System environment Bus support Pre-WDM, but satisfies goals System environment Bus support Device class support

History Of WDM Introduced after Windows 95 launch First available in Windows 98 Now available in Windows 2000 Is present on Windows ME with enhancements from Windows 98

History Of WDM Windows 98 versions Started from a device oriented Plug and Play operating system Added portable abstractions and I/O subsystem from Windows NT Provided definition for Plug and Play and power management mapping to Windows NT Work done as a mapper between WDM and Windows 95 core

Windows 98 And Me Applications System services Virtual Memory Manager System VM MS-DOS VM Applications MS-DOS VM MS-DOS VM System services Installable file system Windows NT I/O Manager Virtual Memory Manager FSD FSD Device drivers Windows 95 I/O subsystem Services Device drivers Drivers HAL

History Of WDM Windows NT version Started from non-Plug and Play, “driver”-oriented operating system Made WDM interfaces native Converted to Plug and Play/“device”- oriented operating system

Windows NT Daemons Services Environments Applications Other Other Spooler Replicator File server Logon Security Alerter Session manager Event logger Windows LPC LPC LPC LPC Windows NT System I/O manager Security monitor Executive Power Management Memory Management Process support File systems Object management/executive run time Device drivers Kernel Hardware abstraction layer Platform interface I/O devices DMA control Bus mapping Clocks/ timers Cache control Interrupt dispatch Privileged architecture

Current State WDM is real There now is a common development environment Binary compatibility is possible Unfortunately it is harder than we wanted Requires extensive testing on all versions of all operating systems

Current State Busses covered Still have NDIS and SCSI USB 1394 New ones coming

Current State Devices covered Input Cameras/Scanners Audio WinModem Storage (*) Many more New ones coming

Current State What’s not there Video Generic storage Super I/O chip

Overview Of WDM Breakdown the components Definition of functionality What do those first two characters in DDI calls mean? Definition of functionality

Components In WDM wdm.h ks.h Wmi Ke Ob Ex Io Mm Ps Rtl Po Pnp Hal (platform support) Zw (magic) ks.h Ks Wmi

Ke - Kernel Minimal set of items exported here in WDM Synchronization primitives Performance counters and timers Stall and Irq control

Ob - Object Manager Very minimal set Used only for object reference count maintenance

Ex - The System Executive Memory allocations Interlocked operations List operations Work items There is a better set in the IO manager (Io*)

Io - I/O Manager I/O Request Packet (IRP) Handling The routines that pass Irps Global locks Device Object Plumbing The routines that set device relationships Work items Registry access routines System state notifications DMA assistance Interrupt assistance

Mm - Memory Manager Virtual to Physical mapping Physical memory commit/locking Driver image memory locking Portable I/O space handling

Ps - Process Service System thread support Just creation and deletion

Rtl - Run-Time Library Bulk memory activity support Unicode support Conversion support Unicode to Ansi Integer to Unicode Etc.

Po - Power Manager Power state change support Power Irp handling Device idle detection support

PnP - Plug And Play Subsystem There are no Plug and Play decorated routine names Exists as part of the I/O manager Actually implemented as an entity in the system

Hal - Hardware Abstraction Layer Device manipulation I/O port access and usage Memory mapped device access and usage Platform abstraction Component owner of interrupts

Zw - Magic Kernel mode map to system APIs Registry access Open/Close keys Create/Delete keys Query values Minimal file access

Ks - Kernel Streaming Separate component on both platforms Definitions of interfaces located in ks.h Provides plumbing for streaming data device connections

WMI - Windows Management Infrastructure Similar to Plug and Play as a component of Io GUID support - wmidata.h Structure definitions - wmistr.h Support library definitions - wmilib.h

Conclusion Its taken awhile Some of it is simple; Some of it isn’t Develop driver first under Windows 2000 Test, test, test, on all releases of all supported operating systems

WDM Driver Implementation Guide Adrian J WDM Driver Implementation Guide Adrian J. Oney Software Engineer Windows Core OS Microsoft Corporation

Preview Writing an Windows NT 4.0 skeleton driver required mastery of many concepts Scheduling Synchronization DeviceObjects, DriverObjects I/O theory (IRP handling, queuing, asynchronous I/O) Security Debugging

Preview Writing a WDM driver requires mastery of all of those concepts plus: Plug and Play Power Management WMI (Windows® Management Interface) Windows 9x/Windows 2000 differences And don’t forget technology specific issues Device class specific: Audio, Modem, … Bus specific: USB, 1394, PCI, …

Scheduling Basics WDM presents two types of scheduling Thread-based scheduling Kernel support for semaphores, mutexes, event objects Windows 2000 adds new high-level support for reader/writer operations to WDM (For instance ExAcquireSharedStarveExclusive) Interrupt Level-based scheduling Code running at a higher IRQ Level (IRQL) immediately preempts code running at a lower IRQL Code runs on same thread, no switching! The lowest three IRQL’s are scheduling constructs, unrelated to hardware: PASSIVE_LEVEL, APC_LEVEL, DISPATCH_LEVEL Multiple processors can each run at a different IRQL!

Callbacks PASSIVE_LEVEL (IRQL 0) APC_LEVEL (IRQL 1) “Work Item” Queue-able from DISPATCH_LEVEL or lower Two types, Ex-WorkItems and Io-WorkItems APC_LEVEL (IRQL 1) Asynchronous Procedure Call aka “APC” Thread specific No WDM function to queue these I/O Manager queues them to get back into correct process during I/O DISPATCH_LEVEL (IRQL 2) Deferred Procedure Call aka “DPC” Queue-able anytime and anywhere, including ISRs

Scheduling Basics PASSIVE_LEVEL (IRQL 0) APC_LEVEL (IRQL 1) Drivers typically run at this level Drivers can touch pageable memory Drivers can do file I/O Blocking causes a processor to switch threads APC_LEVEL (IRQL 1) When switching into a new thread, the processor will run any pending APC’s at APC_LEVEL Blocking lets other threads run at PASSIVE_LEVEL Restriction: Drivers cannot use file functions DISPATCH_LEVEL (IRQL 2) A processor never switches threads when running driver code at DISPATCH_LEVEL Restrictions: A driver cannot touch pagable memory, or use file functions

IRQs And IRQLs On 8259 PIC CLOCK IDE ISR queues DPC Thread Switches 31 Hardware Interrupt 0 Hardware Interrupt 1 … Hardware Interrupt 14 Hardware Interrupt 15 2 – DISPATCH_LEVEL 1 – APC_LEVEL 0 – PASSIVE_LEVEL IDE ISR queues DPC IRQL  Thread Switches DPC executes

IO-APIC Example From an 8-Way server machine down the hall, other machines will be different! Device IRQ IRQL USB Controller 0xB4 0xA SCSI Controller 0xA3 9 Network Adapter 0xA4 9 SCSI Controller 0x93 8 Network Adapter 0x94 8 SCSI Controller 0x83 7 IDE Controller 0x72 6 SCSI Controller 0x73 6 Floppy Controller 0x62 5 Video Controller 0x63 5 Com Port 0x51 4 Network Adapter 0x53 4

Synchronization PASSIVE_LEVEL (IRQL 0) APC_LEVEL (IRQL 1) Semaphores Events Resources (a kind of Mutex) APC_LEVEL (IRQL 1) Fast Mutexes (automatically raises IRQL to APC_LEVEL) Semaphores, Events, Resources (note: none raise IRQL) DISPATCH_LEVEL (IRQL 2) Spinlocks No reentrant primitives (i.e., mutexes) Hardware levels (IRQL > 2) KeSynchronizeExecution

Security Attack A user mode application may choose to “freeze” a thread. User mode does this by queuing an APC to the appropriate thread. Security is compromised if your driver gets frozen holding a sync object Use synchronization objects that raise to APC_LEVEL or above, or Move such operations into a system thread, or Use KeEnterCriticalRegion and KeLeaveCriticalRegion

Drivers And Devices Every driver has a DriverObject associated with it DriverObject(s) represent driver-specific information Dispatch table Each driver creates one or more DeviceObject(s) via IoCreateDevice(…) DeviceObject(s) contain per-device information DeviceExtension Name Flags (e.g., DO_POWER_PAGABLE) A WDM driver is typically unloaded when all it’s DeviceObject(s) have been deleted

Drivers And Devices DRIVER_OBJECT Scanner.sys DRIVER_OBJECT Toaster.sys DEVICE_OBJECT (Scanner #3) DEVICE_OBJECT (Toaster #1) DEVICE_OBJECT (Scanner #2) DEVICE_OBJECT (Scanner #1)

Device Stacks Doing an operation often requires multiple drivers DeviceObjects are arranged into chains called Device Stack DEVICE_OBJECT DRIVER_OBJECT Scanner.sys DEVICE_OBJECT (Scanner #2) DEVICE_OBJECT DEVICE_OBJECT (Scanner #1) DEVICE_OBJECT DEVICE_OBJECT

I/O Request Packets The OS communicates with drivers by sending I/O Request Packets (IRPs) to a device stack IRPs are WDM’s solution to asynchronous I/O IRP DEVICE_OBJECT DEVICE_OBJECT (Scanner #2) DEVICE_OBJECT DEVICE_OBJECT

Asynchronous I/O Goal: Let applications queue one or more requests without blocking Example: Decompressing GIF frames from a CD Two dedicated application threads is not an optimal solution Thread switches are expensive Policy needs to be in the driver stack Only it knows whether a given request should be handled synchronously or asynchronously

Synchronous OS design App Driver A Driver B Driver C Thread Stack Param for A Return address to App … Param for B Return address to A Param for C Return address to B Thread Stack App User Mode Kernel Mode Driver A Driver B Driver C Instruction Pointer Stack Pointer

(Contains Status and Stack Pointer) I/O Request Packets Param for A Return address to App … Param for B Return address to A Param for C Return address to B Thread Stack IRP Header (Contains Status and Stack Pointer) Param A Callback for Initator Param B Callback for A Param C Callback for B

I/O Request Packets Thread Stack Concept IRP Stack Concept Stack Frame Stack Pointer Subroutine call Return from subroutine Return Address/Callback Return Value IO_STACK_LOCATION IoGetCurrentIrpStackLocation (and IoGetNextIrpStackLocation) IoCallDriver IoCompleteRequest Completion routine (IoSetCompletionRoutine) Irp->IoStatus.Status/Information

(Contains Status and Stack Pointer) I/O Request Packets Each IRP must be targeted at a specific device stack IRPs typically have just enough stack locations to traverse the device stack You must allocate a new IRP if you need to forward the request to another stack Device A IRP Header (Contains Status and Stack Pointer) Param A Callback for Initiator Param B Callback for A Param C Callback for B 3 Device B 2 Device C 1

I/O Request Packets IRP Header Thread UserIoStatus UserEvent Stack Pointer IoStatus CancelRoutine Major Code Minor Code Param Completion Routine Completion Context IRP_MJ_ IRP_MN_ … func(…) PVOID IRP_MJ_CREATE IRP_MJ_CLOSE IRP_MJ_READ IRP_MJ_WRITE IRP_MJ_DEVICE_CONTROL IRP_MJ_PNP IRP_MJ_POWER DRIVER_OBJECT Dispatch Table DEVICE_OBJECT

Callers completion routine I/O Request Packets What do I return from my dispatch routine? Return same value completion routine would see, else return STATUS_PENDING Caller on thread stack Callers completion routine status = IoCallDriver(...); status = Irp->IoStatus.Status;

I/O Request Packets Correct value returned from dispatch handler: Irp->IoStatus.Status = STATUS_UNSUCCESSFUL; IoCompleteRequest( Irp, IO_NO_INCREMENT ); return STATUS_UNSUCCESSFUL; Irp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation( Irp ); return IoCallDriver( deviceBeneathMe, Irp ); Incorrect value returned from dispatch handler: Irp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation( Irp ); IoCallDriver( deviceBeneathMe, Irp ); return STATUS_SUCCESS; // Be extra careful when changing status in completion routines!

The Two Types Of I/O Buffered I/O Direct I/O Driver writes into Irp->AssociatedIrp.SystemBuffer OS queues an APC in the requesting process context where it performs a copy Direct I/O Doesn’t require a copy Memory pages are locked during the duration of the operation Pages are described by the IRPs Memory Descriptor List (Irp->MdlAddress) Driver use DMA functions or get a kernel address via MmGetSystemAddressForMdlSafe(Irp->MdlAddress)

WDM Device Stacks A WDM driver stack can contain several different kinds of device objects: Functional Device Object ( “FDO” ) Physical Device Object (“PDO”) Filters The stack and the OS data associated with it is called a “DevNode” Upper Class Filters Upper Device Filters FDO Functional Device Object Lower Class Filters Lower Device Filters PDO Physical Device Object Device Node (“DevNode”)

FDO Functional Device Object PDO Physical Device Object WDM Device Stacks I/O IRPs are typically handled by the FDO Create, Close, Read, Write, etc. Drivers must fail any such IRP explicitly if it’s not handled PnP and Power IRPs traverse the entire stack except if there is an error Drivers do not modify these IRPs if they do not implement the request WMI IRPs are targeted at specific device objects in the stack Drivers do not modify WMI IRPs if they do not implement WMI IRP Upper Class Filters Upper Device Filters FDO Functional Device Object Lower Class Filters Lower Device Filters PDO Physical Device Object DevNode

FDO Functional Device Object PDO Physical Device Object WDM Device Stacks A PDO is created by the bus driver This is done in response to an OS enumeration request Only the PDO has a name! More on this later FDO’s and Filters are created in AddDevice routines Drivers do not find their hardware, rather their hardware finds them Plug and Play passes the PDO to AddDevice Drivers attach new device objects to the stack via IoAttachDeviceToDeviceStack Upper Class Filters Upper Device Filters FDO Functional Device Object Lower Class Filters Lower Device Filters PDO Physical Device Object DevNode

PNP Manager Registry Search INF Files 4 [Version] Signature = Provider Search INF Files PNP Manager 3 IRP Information IRP_MN_QUERY_ID 2 IRP_MN_QUERY_DEVICE_RELATIONS IRP Information 5 Call Class Installers and Co-Installers USB Floppy DevNode Upper Filters FDO USBFLOP.SYS Registry Lower Filters 6 Load drivers PDO USBHUB.SYS FDO USBHUB.SYS 1 IoInvalidateDeviceRelations PDO USB Hub DevNode

Plug And Play The Plug and Play Manager queries the stack to get a list of all possible resource solutions: The PDO responds to IRP_MN_QUERY_RESOURCE_REQUIREMENTS The FDO can adjust these requirements by responding to IRP_MN_FILTER_RESOURCE_REQUIREMENTS The Plug and Play Manager sends the best resource settings in IRP_MN_START_DEVICE The card is configured to use the “Raw’ resource set The driver communicates with the card via the “Translated” resource set

Plug And Play FDO’s must respond to the following Plug and Play events: “Remove” events occur when a device is removed or disabled IRP_MN_REMOVE_DEVICE IRP_MN_SURPRISE_REMOVAL IRP_MN_QUERY_REMOVE_DEVICE IRP_MN_CANCEL_REMOVE_DEVICE “Stop” events occur when a device is to be paused for resource rebalancing IRP_MN_QUERY_STOP_DEVICE IRP_MN_STOP_DEVICE IRP_MN_CANCEL_STOP_DEVICE Other Plug and Play events FDO’s typically respond to: IRP_MN_START_DEVICE (We hope) IRP_MN_QUERY_CAPABILITIES

Plug And Play PDO’s must respond to even more messages: “Who” are you, “What” are you? IRP_MN_QUERY_ID IRP_MN_QUERY_DEVICE_TEXT “Where are you, and where can you go today?” IRP_MN_QUERY_RESOURCES IRP_MN_QUERY_RESOURCE_REQUIREMENTS Settings, capabilities, and location: IRP_MN_QUERY_CAPABILITIES IRP_MN_QUERY_BUS_INFORMATION Misc. IRP_MN_QUERY_DEVICE_RELATIONS (TargetRelations)

“Finding” Plug And Play Devices Applications often need a list of devices to manipulate or display to the user Printers, Scanners, etc Using “well known names” (i.e., LptX) doesn’t work well in a Plug and Play environment Applications often need a list of devices that share a given property, and properties can be hierarchical (E.g., all storage devices, just CDROMs, just Zip drives, etc.) WDM drivers expose one or more “Interfaces”, identified via GUID Note: Only started devices can expose interfaces

Interfaces Drivers register support for a given Interface by calling IoRegisterDeviceInterface Drivers dynamically enable and disable an interface via IoSetDeviceInterfaceState IoSetDeviceInterfaceState creates a symbolic link so that user mode applications can communicate with the device More on this later Applications enumerate devices by passing an interface GUID to various SetupApi functions

FDO Functional Device Object PDO Physical Device Object Kernel mode security User mode can attempt to open a device with Read, Write, and Execute privileges By default, all users get full access to a WDM device stack Security checks are done at Create/Open time Access to a device can be restricted via INF Search DDK for “INF AddReg”, or stay tuned… Upper Class Filters Upper Device Filters FDO Functional Device Object Lower Class Filters Lower Device Filters PDO Physical Device Object

Kernel Mode Security Allow All System (Example: System only access) [MyDevice.NTx86] CopyFiles = ... [MyDevice.NTx86.Services] AddService = ... [MyDevice.NTx86.HW] AddReg = MyDevice.Security [MyDevice.Security] HKR,,DeviceCharacteristics,0x10001,0x100 HKR,,Security,,”security-descriptor-string” "D:P( ;; ;;; ) (...)" "D:P(A;;GA;;;SY)" A: Allow D: Deny GA: All GR: Read GW: Write SY: System LA: Local Administrator PU: Power user WD: World Allow All System (Example: System only access)

FDO Functional Device Object PDO Physical Device Object Security Attacks Security constraints are applied to named device objects In a WDM stack, only the PDO should be named If another device is named, it might compromise system security A device doesn’t have to expose a symbolic link to be opened! Be sure to pass in FILE_DEVICE_SECURE_OPEN when creating PDO’s Upper Class Filters Upper Device Filters FDO Functional Device Object Lower Class Filters Lower Device Filters PDO Physical Device Object

IOCTL Security Method Function Access Device Number 31 15 13 2 Drivers encode the security requirements of Device IOCTLs in the 32bit code itself The Access mask can specify one of four different privilege levels: Openable Opened with read access Opened with write access Opened with both read and write access The IO Manager prevents applications from forming IOCTL codes their privileges don’t allow

Security Attacks Method Function Access Device Number 31 15 13 2 Drivers should always check the full 32bit Ioctl code! Masking out the Access bits lets lower privileged Ioctl’s succeed Do not use the IoGetFunctionCodeFromCtlCode macro Drivers should always check the buffer size of incoming Ioctl’s Malicious applications can attempt to crash the system via malformed requests Do not implement IOCTLs that allow an application to read or write any piece of virtual or physical memory Don’t ship with debugging IOCTLs enabled Don’t pass back “pointers” as handles

Power Management To implement power management, a driver needs code to: Save and restore the state of its hardware Disable and enable the device Queue incoming requests Convert System states to Device states A driver must not touch it’s hardware while it’s device is off Memory and I/O typically return 0xFFFFFFFF when off, fooling badly written ISR’s

System States S0: Working S1: Standby S2: Standby S3: Standby Machine is fully powered and responsive S1: Standby Processor and bus clocks are off, recovery time typically two seconds S2: Standby Greater power conservation, recovery time more than two seconds S3: Standby Typically only memory remains powered S4: Hibernation Machine is off, memory is written to persistent storage S5: Off

Device States D0 D1 D2 D3: Off Hardware is fully powered Less power consumption than D0 Transition to fully powered happens quickly Driver cannot access device until powered up D2 Less power consumption than D1 Longer power-up time than D1 D3: Off Device is completely off (inaccessable)

Converting S IRPs To D IRPs The WDM Power Manager sends S IRPs: IRP_MN_QUERY_POWER IRP_MN_SET_POWER Each device stack has a “Power Policy Owner” who converts S IRPs to D IRPs The Power Policy Owner is typically the FDO The mapping comes from the S  D array stored in the IRP_MN_QUERY_CAPABILITIES structure Each entry calls out the lightest possible D state for a given S state Mappings can be rounded down (deeper) The Power Policy Owner then uses PoRequestPowerIrp to request the appropriate D IRP The conversion code is complicated, but most drivers can use the boilerplate code in the WDM DDK

System State S0 – Working Modem HDD CDROM Net Card D3 D3 D3 D3 D2 D2 D2 D2 D1 D1 D1 D1 D0 D0 D0 C0 D0 PCI Bus S0  D0 PCI.SYS ACPI.SYS PCIIDE.SYS SCSI Card S0  D0 SCSIPORT.SYS IDE Controller S0  D0 Net Card S0  D0 NDIS.SYS ACPI.SYS ACPI.SYS ACPI.SYS PCI.SYS PCI.SYS PCI.SYS IDE Channel S0  D0 ATAPI.SYS CDROM S0  D0 CDROM.SYS PCIIDE.SYS SCSIPORT.SYS HDD S0  D0 DISK.SYS S0  D0 ATAPI.SYS

System State S1 – Standby Modem HDD CDROM Net Card D3 D3 D3 D3 D2 D2 D2 D2 D1 D1 D1 D1 D0 D0 D0 C0 D0 PCI Bus S1  D1 PCI.SYS ACPI.SYS PCIIDE.SYS SCSI Card S1  D3 SCSIPORT.SYS IDE Controller S1  D1 Net Card S1  D3 NDIS.SYS ACPI.SYS ACPI.SYS ACPI.SYS PCI.SYS PCI.SYS PCI.SYS IDE Channel S1  D1 ATAPI.SYS CDROM S1  D3 CDROM.SYS PCIIDE.SYS SCSIPORT.SYS HDD S1  D1 DISK.SYS S1  D? ATAPI.SYS

System State S3 – Standby Modem HDD CDROM Net Card D3 D3 D3 D3 D2 D2 D2 D2 D1 D1 D1 D1 D0 D0 D0 C0 D0 PCI Bus S3  D3 PCI.SYS ACPI.SYS PCIIDE.SYS SCSI Card S3  D3 SCSIPORT.SYS IDE Controller S3  D3 Net Card S3  D3 NDIS.SYS ACPI.SYS ACPI.SYS ACPI.SYS PCI.SYS PCI.SYS PCI.SYS IDE Channel S3  D3 ATAPI.SYS CDROM S3  D3 CDROM.SYS PCIIDE.SYS SCSIPORT.SYS HDD S3  D3 DISK.SYS S3  D? ATAPI.SYS

System State S4 – Hibernate Modem HDD CDROM Net Card D3 D3 D3 D3 D2 D2 D2 D2 D1 D1 D1 D1 D0 D0 D0 C0 D0 PCI Bus S4  D3 PCI.SYS ACPI.SYS PCIIDE.SYS SCSI Card S4  D3 SCSIPORT.SYS IDE Controller S4  D3 Net Card S4  D3 NDIS.SYS ACPI.SYS ACPI.SYS ACPI.SYS PCI.SYS PCI.SYS PCI.SYS IDE Channel S4  D3 ATAPI.SYS CDROM S4  D3 CDROM.SYS PCIIDE.SYS SCSIPORT.SYS HDD S4  D3 DISK.SYS S4  D3 ATAPI.SYS

System State S5 – Off S5  D3 PCI Bus S5  D3 SCSI Card Net Card Modem HDD CDROM Net Card D3 D3 D3 D3 D2 D2 D2 D2 D1 D1 D1 D1 D0 D0 D0 C0 D0 PCI Bus S5  D3 PCI.SYS ACPI.SYS PCIIDE.SYS SCSI Card S5  D3 SCSIPORT.SYS IDE Controller S5  D3 Net Card S5  D3 NDIS.SYS ACPI.SYS ACPI.SYS ACPI.SYS PCI.SYS PCI.SYS PCI.SYS IDE Channel S5  D3 ATAPI.SYS CDROM S5  D3 CDROM.SYS PCIIDE.SYS SCSIPORT.SYS HDD S5  D3 DISK.SYS S5  D3 ATAPI.SYS

Converting S IRPs To D IRPs ( Simplified from Toaster Sample in the WDM DDK ) NTSTATUS ToasterDispatchPower( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { PIO_STACK_LOCATION stackLocation; // // Not shown: Are we deleted? If so, fail IRP. // Not shown: Are we started? If not, pass on IRP untouched. // stackLocation = IoGetCurrentIrpStackLocation( Irp ); switch(stackLocation->MinorFunction) { case IRP_MN_QUERY_POWER: return ToasterQueryPowerState( DeviceObject, Irp ); case IRP_MN_SET_POWER: return ToasterSetPowerState( DeviceObject, Irp ); default: // Not shown: default logic }

Converting S IRPs To D IRPs NTSTATUS ToasterQueryPowerState( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp ) { PIO_STACK_LOCATION stackLocation; if (stackLocation->Parameters.Power.Type == SystemPowerState) { return HandleSystemPowerIrp( DeviceObject, Irp ); } return HandleDeviceQueryPower( DeviceObject, Irp ); } S  D routine

Converting S IRPs To D IRPs NTSTATUS ToasterSetPowerState( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp ) { PIO_STACK_LOCATION stackLocation; if (stackLocation->Parameters.Power.Type == SystemPowerState) { return HandleSystemPowerIrp( DeviceObject, Irp ); } return HandleDeviceSetPower( DeviceObject, Irp ); } S  D routine

Converting S IRPs To D IRPs NTSTATUS HandleSystemPowerIrp( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp ) { // // Forward IRP *asynchronously*, catch it on way up IoMarkIrpPending( Irp ); IoCopyCurrentIrpStackLocationToNext( Irp ); IoSetCompletionRoutine( Irp, (PIO_COMPLETION_ROUTINE) OnFinishSystemPowerUp, NULL, TRUE, TRUE, TRUE); PoCallDriver( fdoData->NextLowerDriver, Irp ); return STATUS_PENDING; } S-IRP PPO

Converting S IRPs To D IRPs NTSTATUS OnFinishSystemPowerUp( IN PDEVICE_OBJECT Fdo, IN PIRP Irp, IN PVOID NotUsed ) { NTSTATUS status = Irp->IoStatus.Status; if (!NT_SUCCESS(status)) { PoStartNextPowerIrp(Irp); return STATUS_SUCCESS; } QueueCorrespondingDeviceIrp( Irp, Fdo ); return STATUS_MORE_PROCESSING_REQUIRED; PPO S-IRP

Converting S IRPs To D IRPs VOID QueueCorrespondingDeviceIrp( IN PIRP SIrp, IN PDEVICE_OBJECT DeviceObject ) { POWER_STATE dState; PFDO_DATA fdoData = (PFDO_DATA) DeviceObject->DeviceExtension; PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(SIrp); SYSTEM_POWER_STATE sState = stack->Power.State.SystemState; if ((sState == PowerSystemWorking) || (fdoData->ArmedForWake)) { dState.DeviceState = fdoData->DeviceCaps.DeviceState[sState]; } else { dState.DeviceState = PowerDeviceD3; } status = PoRequestPowerIrp( fdoData->UnderlyingPDO, stack->MinorFunction, dState, OnPowerRequestComplete, SIrp, NULL); // Not shown: Handle case where PoRequestPowerIrp fails D-IRP PPO S-IRP

Converting S IRPs To D IRPs VOID OnPowerRequestComplete( IN PDEVICE_OBJECT DeviceObject, IN UCHAR MinorFunction, IN POWER_STATE State, IN PVOID PowerContext, IN PIO_STATUS_BLOCK IoStatus ) { PIRP sIrp = (PIRP) PowerContext; // // Copy status from D IRP to S IRP sIrp->IoStatus.Status = IoStatus->Status; PoStartNextPowerIrp( sIrp ); IoCompleteRequest( sIrp, IO_NO_INCREMENT ); } D-IRP PPO S-IRP

Converting S IRPs To D IRPs VOID OnPowerRequestComplete( IN PDEVICE_OBJECT DeviceObject, IN UCHAR MinorFunction, IN POWER_STATE State, IN PVOID PowerContext, IN PIO_STATUS_BLOCK IoStatus ) { PIRP sIrp = (PIRP) PowerContext; // // Copy status from D IRP to S IRP sIrp->IoStatus.Status = IoStatus->Status; PoStartNextPowerIrp( sIrp ); IoCompleteRequest( sIrp, IO_NO_INCREMENT ); } S-IRP PPO

Power Management Gotcha’s Drivers cannot block a thread and wait for a power IRP to complete on Windows 2000 S  D state mapping for non-power manageable PCI devices may contain invalid D states on Windows 2000 Drivers cannot safely complete power IRPs at DISPATCH_LEVEL on Windows 9x Drivers cannot safely do “idle time” power management on Windows 9x PCI supports two types of D3 which WDM doesn’t distinguish

WDM And Hardware – DSP Bad design: Correct design: OS loads DSP driver against “DSP device” Driver uploads software into volatile DSP RAM “DSP device” disappears from bus New device appears in it’s place Problem: What happens when the device is turned off? Correct design: OS loads DSP bus driver against “DSP device” DSP bus driver uploads DSP software into volatile DSP RAM Bus driver exposes new functionality by creating a child device Bus driver reprograms DSP when appropriate