Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @...

53
Windows CE Windows CE Driver Architecture Driver Architecture Jay Loney Jay Loney Program Manager Program Manager Windows CE Drivers Windows CE Drivers JayLoney @ Microsoft.com JayLoney @ Microsoft.com

Transcript of Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @...

Page 1: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

Windows CEWindows CEDriver ArchitectureDriver ArchitectureJay LoneyJay LoneyProgram ManagerProgram ManagerWindows CE DriversWindows CE DriversJayLoney @ Microsoft.comJayLoney @ Microsoft.com

Page 2: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

22

AgendaAgenda

Driver ArchitectureDriver Architecture Device, Regenum, Loading Model,Device, Regenum, Loading Model,

Power managementPower management Windows CE versus WDMWindows CE versus WDM

Memory and CEDDK Memory and CEDDK Basic Interrupt ArchitectureBasic Interrupt Architecture Windows CE .NET’s Installable ISRs (IISR)Windows CE .NET’s Installable ISRs (IISR) Bus DriversBus Drivers

Page 3: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

33

Windows CE ArchitectureWindows CE Architecture

OEM HardwareOEM HardwareOEM HardwareOEM Hardware

Embedded ShellEmbedded ShellEmbedded ShellEmbedded Shell

ApplicationsApplicationsApplicationsApplications

WIN32 APIsWIN32 APIsCOREDLL, WINSOCK, OLE, COMMCTRL, COMMDLG, WININET, TAPICOREDLL, WINSOCK, OLE, COMMCTRL, COMMDLG, WININET, TAPI

WIN32 APIsWIN32 APIsCOREDLL, WINSOCK, OLE, COMMCTRL, COMMDLG, WININET, TAPICOREDLL, WINSOCK, OLE, COMMCTRL, COMMDLG, WININET, TAPI

Windows CE Shell ServicesWindows CE Shell ServicesWindows CE Shell ServicesWindows CE Shell Services

Remote Remote ConnectivityConnectivityRemote Remote ConnectivityConnectivity

KernelKernelLibraryLibraryKernelKernelLibraryLibrary

IrDAIrDAIrDAIrDAGWESGWESGWESGWES Device Device ManagerManagerDevice Device

ManagerManagerFileFile

ManagerManagerFileFile

ManagerManagerTCP/IPTCP/IPTCP/IPTCP/IP

OALOALBootloaderBootloader

OALOALBootloaderBootloader DriversDriversDriversDrivers Device Device

driversdriversDevice Device driversdrivers File driversFile driversFile driversFile drivers

MicrosoftMicrosoftMicrosoftMicrosoft OEMOEMOEMOEM ISVISVISVISV

NetworkNetworkdriversdrivers

NetworkNetworkdriversdrivers

Page 4: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

44

What Is A Driver InWhat Is A Driver InWindows CEWindows CE Simply a DLL with a well defined set of entry pointsSimply a DLL with a well defined set of entry points Hosted by a Device Manager process spaceHosted by a Device Manager process space

(sometimes GWES)(sometimes GWES) Interface to apps via CreateFile (Streams – optional)Interface to apps via CreateFile (Streams – optional) Typically handle interrupts via dedicated thread (IST)Typically handle interrupts via dedicated thread (IST) Synchronization between apps and ISTs via Synchronization between apps and ISTs via

criticalsections and mutexescriticalsections and mutexes Driver can have multiple simultaneous threads activeDriver can have multiple simultaneous threads active

Page 5: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

55

Driver ArchitectureDriver Architecture

PCI Bus

PCMCIAHost

USB Host(OHCI/UHCI)

1394(OHCI)

HID

Printer

MassStorage

rNDIS

ATADiskSBP/2

AV/C

MouseBattery

Touch

NotificationLED

Display

AudioNetwork

Device GWES I/ORM

SerCard

NE2000

Page 6: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

66

Types Of DriversTypes Of Drivers

Page 7: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

77

Native Versus Stream Native Versus Stream Loading MechanismLoading Mechanism Generally Native device drivers are Generally Native device drivers are

loaded in the GWES process space byloaded in the GWES process space byregistry keysregistry keys

Bus drivers loaded by Device.exeBus drivers loaded by Device.exeusing registryusing registry

Installable, Stream, and Hybrid drivers in Installable, Stream, and Hybrid drivers in Device.exe by either bus driver orDevice.exe by either bus driver orRegistry EnumeratorRegistry Enumerator

Page 8: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

88

Device ManagerDevice Manager

User-level process that runs continouslyUser-level process that runs continously Separate application that interacts with the Separate application that interacts with the

kernel, the registry and stream interface kernel, the registry and stream interface driver DLLsdriver DLLs

Provides ActivateDevice and Provides ActivateDevice and DeactivateDevice APIsDeactivateDevice APIs

Page 9: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

99

Device ManagerDevice Manager

Contains the IO Resource ManagerContains the IO Resource Manager Loads the registry enumerator Loads the registry enumerator

(RegEnum.dll) which in turn loads the (RegEnum.dll) which in turn loads the drivers based on the registrydrivers based on the registry

Provides power notification callbacksProvides power notification callbacks Tracks all loaded devices and issues device Tracks all loaded devices and issues device

interface notifications for insertioninterface notifications for insertionand removaland removal

Page 10: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1010

Device Manager Device Manager

Device Driver Loading ProcessDevice Driver Loading Process

DEVICE.EXEKernelKernel

I/O Resource Manager(part of Device.exe)

REGENUM.DLL

PCIBUS.DLL

loadsloads

loadsloads

loadsloads

DEVICE.EXEDEVICE.EXE

I/O Resource ManagerI/O Resource Manager(part of Device.exe)(part of Device.exe) REGENUM.DLLREGENUM.DLL

PCIBUS.DLLPCIBUS.DLL

Page 11: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1111

Registry EnumeratorRegistry Enumerator

Registry Enumerator is RegEnum.dllRegistry Enumerator is RegEnum.dll Device.exe loads the Registry Enumerator from Device.exe loads the Registry Enumerator from

HKEY_LOCAL_MACHINE\Drivers\RootKeyHKEY_LOCAL_MACHINE\Drivers\RootKey Registry Enumerator scans the registry for more drivers Registry Enumerator scans the registry for more drivers

to loadto load Registry Enumerator is re-entrant and supports Registry Enumerator is re-entrant and supports

hierarchical usagehierarchical usage When it gets unloaded, it also unloads anything itWhen it gets unloaded, it also unloads anything it

directly loadeddirectly loaded Registry Enumerator examines the first level of keys just Registry Enumerator examines the first level of keys just

below the key passed to it, according to Orderbelow the key passed to it, according to Order Registry Enumerator invokes ActivateDeviceEx on each Registry Enumerator invokes ActivateDeviceEx on each

subkey it findssubkey it finds

Page 12: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1212

Driver Registry KeysDriver Registry Keys

Registry Enumerator examines the SubKeys as Registry Enumerator examines the SubKeys as defined belowdefined below Order – Smallest value gets loaded firstOrder – Smallest value gets loaded first dll – Which DLL to loaddll – Which DLL to load Prefix – Three letter stream interface name, used only Prefix – Three letter stream interface name, used only

with drivers that expose a stream interfacewith drivers that expose a stream interface Index – Identifier when multiple instances are present, Index – Identifier when multiple instances are present,

between 0 and 9, inclusivelybetween 0 and 9, inclusively Flags – Modifies the default behavior of the enumeratorFlags – Modifies the default behavior of the enumerator

Page 13: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1313

ActivateDeviceExActivateDeviceEx

Exposed by Device.exeExposed by Device.exe Bus Drivers call ActivateDeviceEx when they load Bus Drivers call ActivateDeviceEx when they load

device drivers device drivers ActivateDeviceEx also locks the stream interface ActivateDeviceEx also locks the stream interface

driver into working RAMdriver into working RAM This prevents code pages from being discardedThis prevents code pages from being discarded Registry Enumerator calls ActivateDeviceEx on Registry Enumerator calls ActivateDeviceEx on

each built-in each built-in subkey it findssubkey it finds

ActivateDeviceEx loads driver andActivateDeviceEx loads driver andupdates registryupdates registry

Page 14: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1414

Driver LoadingDriver Loading

Registry Enumerator is key to loading driversRegistry Enumerator is key to loading drivers Device Manager loads Registry EnumeratorDevice Manager loads Registry Enumerator Scans registry and loads drivers Scans registry and loads drivers public\common\oak\drivers\regenumpublic\common\oak\drivers\regenum

Driver loading processDriver loading process RegEnum scans registry, loads bus driversRegEnum scans registry, loads bus drivers Bus driver scans the bus and locates devicesBus driver scans the bus and locates devices Searches the registry for device informationSearches the registry for device information Finds a match and loads appropriate driverFinds a match and loads appropriate driver

Action for not finding a match differs with each busAction for not finding a match differs with each bus

Sends notification that interface is availableSends notification that interface is available

Page 15: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1515

Registry Key ExampleRegistry Key Example[HKEY_LOCAL_MACHINE\Drivers][HKEY_LOCAL_MACHINE\Drivers] "RootKey"="Drivers\\BuiltIn”"RootKey"="Drivers\\BuiltIn”

[HKEY_LOCAL_MACHINE\Drivers\BuiltIn][HKEY_LOCAL_MACHINE\Drivers\BuiltIn] "Dll"="RegEnum.dll“"Dll"="RegEnum.dll“

[HKEY_LOCAL_MACHINE\Drivers\CSP\Serial][HKEY_LOCAL_MACHINE\Drivers\CSP\Serial] "Dll"="Com16550.Dll""Dll"="Com16550.Dll" "Order"=dword:0"Order"=dword:0 "Irq"=dword:3"Irq"=dword:3 "MemBase"=dword:FFBFC000"MemBase"=dword:FFBFC000 "MemLen"=dword:8"MemLen"=dword:8 "SysIntr"=dword:13"SysIntr"=dword:13 "Prefix"="COM""Prefix"="COM" "DeviceArrayIndex"=dword:0"DeviceArrayIndex"=dword:0 "Priority"=dword:0"Priority"=dword:0

Page 16: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1616

Interface ClassesInterface Classes

Drivers are characterized by their interfaceDrivers are characterized by their interface Each IClass has a Each IClass has a GUIDGUID and a and a NameName GUIDGUID describes the generic device interface describes the generic device interface NameName identifies the instance of an interface identifies the instance of an interface

COM1:, DSK1: and so onCOM1:, DSK1: and so on

Exposing a driver’s interfaceExposing a driver’s interface IClass subkey in the registryIClass subkey in the registry Drivers publish interface – Drivers publish interface – AdvertiseInterfaceAdvertiseInterface

Apps query interface – Apps query interface – RequestDeviceNotificationsRequestDeviceNotifications Pre-defined GUIDs for existing interfacesPre-defined GUIDs for existing interfaces

A32942B7-920C-486b-B0E6-92A702A99B35 A32942B7-920C-486b-B0E6-92A702A99B35

Page 17: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1717

I/O Resource ManagerI/O Resource Manager

IORM is an intrinsic part of Device ManagerIORM is an intrinsic part of Device Manager Tracks available I/O resources (Tracks available I/O resources (IRQ and I/O IRQ and I/O

base addressbase address)) OEM pre-allocates resources for built-in devicesOEM pre-allocates resources for built-in devices Bus drivers request resources when loading a Bus drivers request resources when loading a

client driver on their busclient driver on their bus ResourceRequestResourceRequest ResourceReleaseResourceRelease ResourceCreateListResourceCreateList

IORM fails ResourceRequest when thereIORM fails ResourceRequest when thereis a conflictis a conflict

Page 18: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1818

Registry Helper RoutinesRegistry Helper Routines

Reads resource configuration from the registryReads resource configuration from the registry OpenDeviceKeyOpenDeviceKey DDKReg_GetIsrInfoDDKReg_GetIsrInfo DDKReg_GetWindowInfoDDKReg_GetWindowInfo DDKReg_GetPciInfoDDKReg_GetPciInfo APIs in COREDLLAPIs in COREDLL Prototyped in <Prototyped in <devload.hdevload.h> and <> and <ddkreg.hddkreg.h>>

Samples in public\common\oak\drivers Samples in public\common\oak\drivers wavedev\pdd\es1371\wavepdd.cpp -> GetRegistryConfigwavedev\pdd\es1371\wavepdd.cpp -> GetRegistryConfig

Page 19: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

1919

Contrast: Windows XP WDM Contrast: Windows XP WDM Loading ModelLoading Model Drivers are loaded in the kernel address space as a .sys fileDrivers are loaded in the kernel address space as a .sys file In Windows XP, everything is PNPIn Windows XP, everything is PNP

Boot time: BIOS tells you ACPI table which tells you which drivers to load,Boot time: BIOS tells you ACPI table which tells you which drivers to load,including bussesincluding busses

Windows CE walks through the registryWindows CE walks through the registry Run time: PNP manager is informed of added devices by the bus drivers. PNP manager Run time: PNP manager is informed of added devices by the bus drivers. PNP manager

asks bus driver who it is, PNP Man. loads the driver based on inf database. CE’s bus asks bus driver who it is, PNP Man. loads the driver based on inf database. CE’s bus drivers detect PNP devices, scan registry for driver and request driver loading from drivers detect PNP devices, scan registry for driver and request driver loading from Device ManagerDevice Manager

Driver entry is called DriverEntryDriver entry is called DriverEntry In CE it’s xxx_InitIn CE it’s xxx_Init

Then the other driver entry points are specified for read/write/IOCTL/powerThen the other driver entry points are specified for read/write/IOCTL/power In CE it’s the rest of the streams interfaceIn CE it’s the rest of the streams interface

Drivers are re-entrantDrivers are re-entrant PDO device objects (handle), provided by bus driver, to handle multiple instancesPDO device objects (handle), provided by bus driver, to handle multiple instances

Page 20: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2020

Power ManagementPower Management

Power ManagerPower Manager Flexible infrastructure for system-level and Flexible infrastructure for system-level and

peripheral-level power managementperipheral-level power management Lets devices intelligently manage theirLets devices intelligently manage their

own powerown power Acts as a mediator between the devices and Acts as a mediator between the devices and

system/applicationssystem/applications Enables OEMs to modify the code Enables OEMs to modify the code

surrounding calls to PowerOffSystem()surrounding calls to PowerOffSystem()

Page 21: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2121

Power ManagementPower Management

System-level power statesSystem-level power states

Device (peripheral) level power statesDevice (peripheral) level power states

OnOn System IdleSystem Idle

User IdleUser Idle SuspendSuspend

D0 Fully PoweredD0 Fully Powered D3 SleepD3 Sleep

D1 Low PerformanceD1 Low Performance D4 OffD4 Off

D2 StandbyD2 Standby

Page 22: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2222

Power Manager ArchitecturePower Manager Architecture

DriversDriversPower Power Manager Manager (pm.dll)(pm.dll)

PM PM APIsAPIs

ApplicationApplication

NotificationNotificationMessage QueueMessage Queue

DriverDriverAPIsAPIs

ApplicationApplicationAPIsAPIs

Page 23: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2323

Contrast: WDMContrast: WDMPower ManagementPower Management Similar structure, different implementationSimilar structure, different implementation Power manager lives in the Kernel (in Windows CE it’s in DeviceMan)Power manager lives in the Kernel (in Windows CE it’s in DeviceMan) S0-S5 system states (CE has OEMIdle and OEMPowerDown)S0-S5 system states (CE has OEMIdle and OEMPowerDown) WDM Power manager negotiates with all active drivers whether a WDM Power manager negotiates with all active drivers whether a

system state can be enteredsystem state can be entered WDM Power Manager walks the device tree, tells the drivers that the WDM Power Manager walks the device tree, tells the drivers that the

system is in a certain state. The driver then makes its own decision as system is in a certain state. The driver then makes its own decision as to what Device state (D-state) the device should be into what Device state (D-state) the device should be in (CE has D0-D5, but is extensible)(CE has D0-D5, but is extensible)

Driver can veto a System state because it is workingDriver can veto a System state because it is working Battery Critical off has the highest precedent and will override any Battery Critical off has the highest precedent and will override any

driver workingdriver working

Page 24: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2424

Physical MemoryPhysical Memory

64 MB64 MBRAMRAM

32 MB32 MBFlashFlash

Dbg Serial PortDbg Serial Port

2 2 G

BG

BU

serU

ser

512 MB

512 MB

Uncache

Uncache

dd

512 MB

512 MB

Cached

Cached

64 MB RAM64 MB RAM

32 MB Flash32 MB Flash

64 MB RAM64 MB RAM

32 MB Flash32 MB Flash

Physical MemoryPhysical MemoryKernel Virtual AddressKernel Virtual Address

ReservedReserved

0400000004000000

8200000082000000

8000000080000000

8000000080000000

A0000000A0000000

C0000000C0000000

00

Page 25: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2525

Not UsedNot Used

Slot 0Slot 0

Slot 32Slot 32

64 KB64 KB

32 MB32 MB

64 MB64 MB

2 GB2 GB

3 GB3 GB

4 GB4 GB

Memory mapped filesMemory mapped files

Above 2G-3GAbove 2G-3GMapped to physical Mapped to physical memorymemory

Virtual Virtual address address

spacespace

Slot 1Slot 1

Slot 32Slot 32

NULL pointers NULL pointers

Virtual Address SpaceVirtual Address Space

512M Cached512M Cached

512M Non-Cached512M Non-Cached

0x800000000x80000000

0xA00000000xA0000000

Accessable via Accessable via MmMapiIoSpaceMmMapiIoSpace

Page 26: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2626

Memory Management FunctionsMemory Management Functions

Device drivers are user-mode modules Device drivers are user-mode modules Necessary to map physical memory toNecessary to map physical memory to

virtual memoryvirtual memory

VirtualAlloc, VirtualFree: reserve, free VirtualAlloc, VirtualFree: reserve, free virtual memoryvirtual memory MEM_RESERVEMEM_RESERVE

VirtualCopy: Maps a physical memory VirtualCopy: Maps a physical memory range to a virtual memory rangerange to a virtual memory range PAGE_NOCACHEPAGE_NOCACHE PAGE_PHYSICALPAGE_PHYSICAL

Page 27: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2727

Driver Memory Access – Driver Memory Access – Mapped PointersMapped Pointers MapPtrToProcessMapPtrToProcess

Allows you to map a pointer from one Allows you to map a pointer from one address space to another address space to another

GetCurrentProcessGetCurrentProcess Retrieves a process identifier to be used with Retrieves a process identifier to be used with

the MapPtrToProcess function the MapPtrToProcess function

SetProcPermissionsSetProcPermissions Gives the current process access to other Gives the current process access to other

processes’ address spaces processes’ address spaces

Page 28: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2828

Driver Memory Access – Driver Memory Access – Mapped PointersMapped Pointers

App Calls DeviceIOControlApp Calls DeviceIOControlDM mapped into Slot 0DM mapped into Slot 0

App is mapped into Slot 0App is mapped into Slot 0

DM Calls xxx_IoControlDM Calls xxx_IoControlDM Sets permissions to App spaceDM Sets permissions to App space

APPAPP

DMDM

Slot 0Slot 0

APPAPPAPPAPPMapped pointerMapped pointer

Driver Calls MapPtrToProcessDriver Calls MapPtrToProcessDriver returns from xxx_IoControlDriver returns from xxx_IoControlDM Re-Sets permissions to App spaceDM Re-Sets permissions to App spaceApp is mapped into Slot 0App is mapped into Slot 0

APPAPPDMDMAPPAPPOriginal Original pointerpointer

DMDM

APPAPP

Page 29: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

2929

Contrast: WDM Basic Contrast: WDM Basic Memory ManagementMemory Management Windows XP drivers are in kernel address spaceWindows XP drivers are in kernel address space XP Drivers can access all kernel address spaceXP Drivers can access all kernel address space Can access the User space of the context from which Can access the User space of the context from which

they’re calledthey’re called In Windows CE, drivers have to map through virtual memory to In Windows CE, drivers have to map through virtual memory to

get to their physical port/memoryget to their physical port/memory Driver’s communicate in 2 waysDriver’s communicate in 2 ways

Buffered IOBuffered IO Direct IO (suggested only if packet is bigger then 1 page)Direct IO (suggested only if packet is bigger then 1 page)

MMMapIOSpace maps physical devices into kernel MMMapIOSpace maps physical devices into kernel address spaceaddress space Windows CE does this with OEMAddressTable in the OAL Windows CE does this with OEMAddressTable in the OAL

Page 30: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3030

CEDDKCEDDK

CE v2.1x and later supports a platform CE v2.1x and later supports a platform independent I/O schemeindependent I/O scheme

Left up to the OEM and driver writer to actually Left up to the OEM and driver writer to actually use themuse them

CEDDK.DLLCEDDK.DLL BUS ManagementBUS Management Memory ManagementMemory Management I/O ManagementI/O Management

CEDDK APIs taken from NTDDKCEDDK APIs taken from NTDDK Not documented until V2.12Not documented until V2.12 But most available in V2.00But most available in V2.00

Page 31: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3131

CEDDK AbstractionCEDDK Abstraction

Device drivers use Device drivers use CEDDKCEDDK

Properly written drivers Properly written drivers are binary compatible are binary compatible across platformsacross platforms Source code compatible Source code compatible

across CPUsacross CPUs

Device Device ManagerManager

Device DriverDevice Driver

CEDDK.DLLCEDDK.DLL

HardwareHardware

Page 32: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3232

CEDDK InternalsCEDDK Internals

CoverageCoverage Function ExamplesFunction ExamplesBus Bus

ManagementManagement

HalGetBusDataByOffset()HalGetBusDataByOffset()

HalGetBusData()HalGetBusData()

HalSetBusDataByOffset()HalSetBusDataByOffset()

HalSetBusData()HalSetBusData()

HalTranslateBusAddress()HalTranslateBusAddress()

HalTranslateSystemAddress()HalTranslateSystemAddress()

Memory Memory ManagementManagement

MmMapIOSpace – MmUnmapIOSpaceMmMapIOSpace – MmUnmapIOSpace

HalAllocateCommonBufferHalAllocateCommonBuffer

I/O AccessI/O Access XXXX => XXXX =>

UCHAR/USHORT/ULONGUCHAR/USHORT/ULONG

READ_REGISTER_XXXXREAD_REGISTER_XXXX

WRITE_REGISTER_XXXXWRITE_REGISTER_XXXX

READ_PORT_XXXXREAD_PORT_XXXX

WRITE_PORT_XXXXWRITE_PORT_XXXX

Page 33: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3333

Contrast: WDM Advanced Contrast: WDM Advanced Memory ManagementMemory Management The CEDDK-like functions aren’t used anymore in WDMThe CEDDK-like functions aren’t used anymore in WDM Bus drivers are now controlling the DMA for theirBus drivers are now controlling the DMA for their

own bussesown busses PNP Manager asks the bus driver what resources the driver needs PNP Manager asks the bus driver what resources the driver needs

and arbitrates the resources including DMA channel requestsand arbitrates the resources including DMA channel requests PNP Manager can arbitrate conflictsPNP Manager can arbitrate conflicts

(“resource rebalancing”)(“resource rebalancing”) Ex. Device1 can use irq 10 or 11 and gets 10, device2 comes later and Ex. Device1 can use irq 10 or 11 and gets 10, device2 comes later and

can only use 10, PNP Manager will shuffle device1 to 11 and restart himcan only use 10, PNP Manager will shuffle device1 to 11 and restart him In CE, always use shared interrupts to help avoid this problem. In the In CE, always use shared interrupts to help avoid this problem. In the

example above, you’re stuckexample above, you’re stuck

Page 34: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3434

Interrupt ArchitectureInterrupt Architecture

Interrupt is just a particular exceptionInterrupt is just a particular exception Caught by kernel codeCaught by kernel code Dealt with prior to resuming user codeDealt with prior to resuming user code But hardware is independent of OSBut hardware is independent of OS

CE uses two stage Interrupt Service modelCE uses two stage Interrupt Service model Lightweight code to quiet interruptLightweight code to quiet interrupt Scheduled code to service hardwareScheduled code to service hardware

OS provides API for enabling IRQ signals, OS provides API for enabling IRQ signals, prioritization, etc.prioritization, etc.

Hardware specific operations done in OAL and Hardware specific operations done in OAL and device driver codedevice driver code

Page 35: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3535

Kernel

Kernel

OA

LO

AL

User M

odeU

ser Mode

HW

HW

All All

CE 3.0 Interrupt HandlingCE 3.0 Interrupt Handling

NoneNone

Device DriverDevice DriverIST ProcessingIST Processing

SetSetEventEvent EOIEOI

Except.Except.HandlerHandler

ISRISR EnableEnable

AppApp

Higher Higher PriorityPriority

PSRPSRSYSINTR_SYSINTR_IDID

IRQ MaskedIRQ Masked All IRQAll IRQEnabledEnabled

WFSOWFSOWFSOWFSOon Eventon Event

Application ResumesApplication Resumes

Page 36: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3636

Notes On ISRs And ISTs Notes On ISRs And ISTs

ISTs are plain old user mode codeISTs are plain old user mode code Full CE .NET API and CRT library availableFull CE .NET API and CRT library available CE .NET scheduler controls IST execution CE .NET scheduler controls IST execution

based on thread prioritybased on thread priority Run-time binding to SYSINTRRun-time binding to SYSINTR

ISRs are called from Exception HandlerISRs are called from Exception Handler No OS services availableNo OS services available Stack space is limitedStack space is limited May be reentrant (OAL choice)May be reentrant (OAL choice) Assembly language on MIPS, SHxAssembly language on MIPS, SHx

Page 37: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3737

ISR ObservationsISR Observations

IRQ priorities CPU architecture dependentIRQ priorities CPU architecture dependent PIC hardware handles this on x86PIC hardware handles this on x86 OAL arrays IntrPriority, IntrMask on MIPS OAL arrays IntrPriority, IntrMask on MIPS

OAL could add real-time feature allowing IST OAL could add real-time feature allowing IST processing to preempt ISR serviceprocessing to preempt ISR service

Under CE 3.0, all ISR code part of OALUnder CE 3.0, all ISR code part of OAL Not particularly expandableNot particularly expandable IRQs bound to event IDs in OEMInitIRQs bound to event IDs in OEMInit No Support for PNP, IRQ sharing (PCI bus)No Support for PNP, IRQ sharing (PCI bus)

CE .NET addresses these limitations with CE .NET addresses these limitations with Installable ISR (IISR) chainInstallable ISR (IISR) chain

Page 38: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3838

CE .NET Installable ISRsCE .NET Installable ISRs

Preferable Extension to CE 3.0 ISR architecturePreferable Extension to CE 3.0 ISR architecture DLL code, bound at run timeDLL code, bound at run time Source code can be CPU independentSource code can be CPU independent

Typically coded in “C”Typically coded in “C” Some restrictions applySome restrictions apply

No calls to CRT, Windows API, or other DLLsNo calls to CRT, Windows API, or other DLLs

Run-to-completion ISR, or IST dispatchRun-to-completion ISR, or IST dispatch Support for hardware IRQ sharingSupport for hardware IRQ sharing

Distinct SYSINTR ID from same IRQDistinct SYSINTR ID from same IRQ

Page 39: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

3939

IISR

IIS

R

CE .NET Interrupt HandlingCE .NET Interrupt HandlingK

ernelK

ernelO

AL

OA

LD

riverD

riverH

WH

W

SetSetEventEvent

NoneNone

Except.Except.HandlerHandler

ISRISR

Higher Priority IRQs EnabledHigher Priority IRQs Enabled

PSRPSRSYSINTR_SYSINTR_IDID

IRQ MaskedIRQ Masked

SYSINTR_xxSYSINTR_xxSYSINTR_NOPSYSINTR_NOP

ISTIST

IISRIISR11

NKCallIntChain(IRQ)NKCallIntChain(IRQ)

IISRIISRnn

SYSINTR_CHAINSYSINTR_CHAIN

IISRIISR22

Page 40: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4040

IISR Control FlowIISR Control Flow

Driver registers IISR DLL with the Kernel with theDriver registers IISR DLL with the Kernel with thecall to LoadIntChainHandler()call to LoadIntChainHandler() Data passed to IISR via KernelLibIoControl()Data passed to IISR via KernelLibIoControl()

OAL ISR decodes IRQ from hardware, calls kernel OAL ISR decodes IRQ from hardware, calls kernel NkCallIntChain(dwIRQ) to query IISRsNkCallIntChain(dwIRQ) to query IISRs IISRs called in binding orderIISRs called in binding order

IISR return value indicates statusIISR return value indicates status SYSINTR_CHAIN indicates IRQ not recognizedSYSINTR_CHAIN indicates IRQ not recognized

OAL ISR translates IRQ to SYSINTR as beforeOAL ISR translates IRQ to SYSINTR as before SYSINTR_NOP indicates IISR run-to-completionSYSINTR_NOP indicates IISR run-to-completion

IISR must make IRQ go away!IISR must make IRQ go away! Other values indicate IISR owns interruptOther values indicate IISR owns interrupt

OAL ISR code must set PIC IRQ maskOAL ISR code must set PIC IRQ mask

OAL ISR handles PIC EOI, returns IDOAL ISR handles PIC EOI, returns ID

Page 41: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4141

Interrupt Service ThreadInterrupt Service Thread

Is user-mode thread of device drivers forIs user-mode thread of device drivers forbuilt-in devicesbuilt-in devices

Does the actual processing of the interrupt Does the actual processing of the interrupt Creates an event object associated with the Creates an event object associated with the

logical interrupt by calling CreateEvent functionlogical interrupt by calling CreateEvent function IST remains idle most of the time, awakened IST remains idle most of the time, awakened

when the kernel signals the event objectwhen the kernel signals the event object IST usually runs at above-normal priority, boost IST usually runs at above-normal priority, boost

priority with CeSetThreadPriority functionpriority with CeSetThreadPriority function

Page 42: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4242

Interrupt Service Thread Interrupt Service Thread

InterruptInitializeInterruptInitialize Call InterruptInitialize to link the Event with the Call InterruptInitialize to link the Event with the

Interrupt ID of the ISRInterrupt ID of the ISR

WaitForSingleObjectWaitForSingleObject Can be used to wait for an event to be signaledCan be used to wait for an event to be signaled This call is usually inside a loop so that when interrupt This call is usually inside a loop so that when interrupt

is processed, the IST gets back to this call waiting for is processed, the IST gets back to this call waiting for the next interrupt to be handledthe next interrupt to be handled

InterruptDoneInterruptDone After the interrupt data is processed, the IST must call After the interrupt data is processed, the IST must call

the the InterruptDoneInterruptDone function to instruct the kernel to function to instruct the kernel to enable the hardware interrupt related to this thread enable the hardware interrupt related to this thread

Page 43: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4343

Typical IST StartTypical IST Start

struct ISTData // Declare the Strucure to pass to the ISTstruct ISTData // Declare the Strucure to pass to the IST{{ HANDLE hThread; // IST HandleHANDLE hThread; // IST Handle DWORD sysIntr; // Logical IDDWORD sysIntr; // Logical ID HANDLE hEvent; // handle to the event to wait for interruptHANDLE hEvent; // handle to the event to wait for interrupt volatile BOOL abort; // flag to test to exit the ISTvolatile BOOL abort; // flag to test to exit the IST};};

ISTData g_KeypadISTData;ISTData g_KeypadISTData;// Create event to link to IST // Create event to link to IST g_KeypadISTData.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);g_KeypadISTData.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);// Translate IRQ to an logical ID (x86 CEPC)// Translate IRQ to an logical ID (x86 CEPC)g_KeypadISTData.sysIntr =Mapirq2Sysintr(5);g_KeypadISTData.sysIntr =Mapirq2Sysintr(5);// start the thread// start the threadg_KeypadISTData.hThread = CreateThread(NULL,0,&KeypadIST,g_KeypadISTData.hThread = CreateThread(NULL,0,&KeypadIST, &g_KeypadISTData, 0, NULL);&g_KeypadISTData, 0, NULL);

Page 44: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4444

Typical IST StartTypical IST Start

//Change the threads priority//Change the threads priorityCeSetThreadPriority(g_KeypadISTData.hThread,0);CeSetThreadPriority(g_KeypadISTData.hThread,0);

//disconnect any previous event from logical ID//disconnect any previous event from logical IDInterruptDisable(g_KeypadISTData.sysIntr);InterruptDisable(g_KeypadISTData.sysIntr);

// Connect Logical ID with Event// Connect Logical ID with EventInterruptInitialize(g_KeypadISTData.sysIntr, g_KeypadISTData.InterruptInitialize(g_KeypadISTData.sysIntr, g_KeypadISTData.hEvent,NULL,0);hEvent,NULL,0);

Set the IST Thread PrioritySet the IST Thread Priority Disconnect any previous events from the associated ISRDisconnect any previous events from the associated ISR Connect to the associated ISRConnect to the associated ISR

Page 45: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4545

Typical IST Start Typical IST Start

DWORD KeypadIST(void *dat)DWORD KeypadIST(void *dat){ { ISTData* pData= (ISTData*)dat;ISTData* pData= (ISTData*)dat; // loop until told to stop// loop until told to stop While(!pData->abort)While(!pData->abort) { // wait for the interrupt event... { // wait for the interrupt event... WaitForSingleObject(pData->hEvent, INFINITE)WaitForSingleObject(pData->hEvent, INFINITE) if(pData->abort)if(pData->abort) break;break; // Handle the interrupt...// Handle the interrupt... // Let OS know the interrupt processing is done// Let OS know the interrupt processing is done InterruptDone(pData->sysIntr); InterruptDone(pData->sysIntr); }} Return 0;Return 0;}}

Page 46: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4646

Typical IST StopTypical IST Stop

// set abort flag to true to let thread know// set abort flag to true to let thread know// that it should exit// that it should exitg_KeypadISTData.abort =TRUE;g_KeypadISTData.abort =TRUE;

//disconnect event from logical ID//disconnect event from logical ID//this internally sets g_KeypadISTData.sysIntr which in turn//this internally sets g_KeypadISTData.sysIntr which in turn//sets g_KeypadISTData.hEvent through the kernel//sets g_KeypadISTData.hEvent through the kernelInterruptDisable(g_KeypadISTData.sysIntr);InterruptDisable(g_KeypadISTData.sysIntr);

//wait for thread to exit//wait for thread to exitWaitForSingleObject(g_KeypadISTData.hEvent,INFINITE);WaitForSingleObject(g_KeypadISTData.hEvent,INFINITE);

CloseHandle(g_KeypadISTData.hEvent);CloseHandle(g_KeypadISTData.hEvent);CloseHandle(g_KeypadISTData.hThread);CloseHandle(g_KeypadISTData.hThread);

Set a flag that will cancel the IST loopSet a flag that will cancel the IST loop Call InterruptDisable to disconnect the triggering event fromCall InterruptDisable to disconnect the triggering event from

the logical IDthe logical ID Close the Thread Add Reference for the codeClose the Thread Add Reference for the code

Page 47: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4747

Contrast: WDM InterruptsContrast: WDM Interrupts Driver is assigned interrupt by the PNP managerDriver is assigned interrupt by the PNP manager Driver registers with kernel it’s ISRDriver registers with kernel it’s ISR When IRQ fires, IDT table links the IRQ to the ISRWhen IRQ fires, IDT table links the IRQ to the ISR ISR routines run in arbitrary thread context because all applications ISR routines run in arbitrary thread context because all applications

share the kernel spaceshare the kernel space ISR runs immediatelyISR runs immediately Priority by hardware first, then IRQL (levels) 0-31, 3-28 are Priority by hardware first, then IRQL (levels) 0-31, 3-28 are

hardware deviceshardware devices Queue Deferred Procedure Calls to do extended read/write work Queue Deferred Procedure Calls to do extended read/write work

when IRQL drops to 2, this queue is drained in FIFO orderwhen IRQL drops to 2, this queue is drained in FIFO order Threads (spell-checker) run when IRQL hits 0Threads (spell-checker) run when IRQL hits 0

DPCs are similar to CE ISTs, however CE ISTs are prioritizedDPCs are similar to CE ISTs, however CE ISTs are prioritized

Page 48: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4848

Bus Drivers OverviewBus Drivers Overview

PCMCIAPCMCIA I82365 (ISA)I82365 (ISA) TI-1250 (PCI)TI-1250 (PCI)

USB HostUSB Host Multiple Host ControllersMultiple Host Controllers

OHCI and UHCI (PCI)OHCI and UHCI (PCI)

Page 49: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

4949

PCMCIA HostPCMCIA Host

PCMCIA bus driver has three main threads PCMCIA bus driver has three main threads Status change thread (card insertion/removal) Status change thread (card insertion/removal) Interrupt thread (handles card functional interrupt requests) Interrupt thread (handles card functional interrupt requests) Callback thread (notifies card clients of events) Callback thread (notifies card clients of events)

Bus driver supports a subset of Card Serv. messages, Bus driver supports a subset of Card Serv. messages, delivered as callbacks from the callback threaddelivered as callbacks from the callback thread

Interrupts are delivered to client drivers as callbacksInterrupts are delivered to client drivers as callbacks Newly inserted cards are scanned for identifying PnP Newly inserted cards are scanned for identifying PnP

tuples and compared with entries in the registrytuples and compared with entries in the registry If no match is found, candidate drivers can run “detect” If no match is found, candidate drivers can run “detect”

routines to card-specific mechanisms to ID the cardroutines to card-specific mechanisms to ID the card May display a dialog box asking for the name of the DLLMay display a dialog box asking for the name of the DLL

Page 50: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

5050

USB HostUSB Host

USB Version 1.1 compliantUSB Version 1.1 compliant OHCI and UHCI fully supportedOHCI and UHCI fully supported Support for all transfer typesSupport for all transfer types

Isoch, bulk, interrupt, controlIsoch, bulk, interrupt, control

USBD supports multiplexing between multiple HCUSBD supports multiplexing between multiple HC Client drivers are typically loaded using LoadDriver and Client drivers are typically loaded using LoadDriver and

use USBD operations to communicate with the HCuse USBD operations to communicate with the HC Client drivers can optionally call ActivateDeviceEx() on Client drivers can optionally call ActivateDeviceEx() on

themselves to expose a stream interface to appsthemselves to expose a stream interface to apps Detects and identifies newly attached devices Detects and identifies newly attached devices Loads drivers as described in the registryLoads drivers as described in the registry

May display a dialog box asking for the name of the DLLMay display a dialog box asking for the name of the DLL

Page 51: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

USB Architecture

Client Drivers Peripheral

HCD

USBD

HCDInterface

HCInterface

PrinterMass

StorageHID Other

HardwareUSB Cable

USBDInterface

Host Controller

PDD

Function

USBlogicaldevice

USB busInterface

OHCI & UHCI

Page 52: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.

5252

Community ResourcesCommunity Resources

http://msdn.microsoft.com/embedded/http://msdn.microsoft.com/embedded/

Community SitesCommunity Sites http://www.microsoft.com/communities/default.mspxhttp://www.microsoft.com/communities/default.mspx

List of NewsgroupsList of Newsgroups http://communities2.microsoft.com/communities/newsgroups/en-uhttp://communities2.microsoft.com/communities/newsgroups/en-u

s/default.aspxs/default.aspx

Attend a free chat or webcastAttend a free chat or webcast http://www.microsoft.com/communities/chats/default.mspxhttp://www.microsoft.com/communities/chats/default.mspx http://www.microsoft.com/seminar/events/webcasts/default.mspxhttp://www.microsoft.com/seminar/events/webcasts/default.mspx

Locate a local user group(s)Locate a local user group(s) http://www.microsoft.com/communities/usergroups/default.mspxhttp://www.microsoft.com/communities/usergroups/default.mspx

Non-Microsoft Community SitesNon-Microsoft Community Sites http://www.microsoft.com/communities/related/default.mspxhttp://www.microsoft.com/communities/related/default.mspx

Page 53: Windows CE Driver Architecture Jay Loney Program Manager Windows CE Drivers JayLoney @ Microsoft.com.