P. 1
WinCE6.0 Developer Guide

WinCE6.0 Developer Guide

|Views: 4,112|Likes:

More info:

Published by: gunasekaran.subramani3879 on Sep 10, 2009
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

05/11/2014

pdf

text

original

WinCE 6.

0 MOC Introduction
Victor Lin Field Application Engineer SYNNEX INTERNATIONAL CORP. (02)25063320-2231 victorlin@synnex.com.tw

SYNNEX

Overview
Toolkit. OS Architecture. Memory Architecture. Driver Development. Application Development.

SYNNEX

Toolkit
SYNNEX

Runtime Image of the CE 6.0 Operating System

Application Layer OS Layer

Windows CE Application

Custom Application Application Services Kernel

Internet Client Services

OEM Layer (BSP)

OEM Adaptation Layer (OAL) Process Specific Definition Files

Drivers

NK.BIN
SYNNEX

Visual Studio 2005 Platform Builder
Solution Platforms
Connectivity Status

Connectivity Device Name

Project Tree

Code Editor

Debug tool status indicators

Output Selection

Tabbed Output Windows

SYNNEX

Visual Studio 2005 Platform Builder

CE OS Design – Major Menu Options Project – Creation or management of projects Build – Build options for the OS Design Debug – Access to Debug Options Target – configuration and specifics of the target device. Tools – Includes the CE Device Emulator Manager

SYNNEX

Building the Run-time Image
Build Build TrainingOSDesign

SYNNEX

Building the Run-time Image
Builds can take an extended amount of time to complete Zero errors on a build is the goal

SYNNEX

CE 6.0 Build Steps
Pre-Sysgen Build 0 1 2 3 4

Build Demo Tool (blddemo.bat)

Sysgen Post-Sysgen Build Build Release Dir Make Run-Time Image

Build process consists of 5 major phases Initial step should not normally be used Build Demo tool (Blddemo.bat) Interface to unified build system
SYNNEX

Build Phases
1 System Generation - SYSGEN

1 2 2 3 3

Filters and combines modules and components based on OS Design settings Post-Sysgen Build – BUILD Builds Source Code for the BSP and subprojects Build Release Directory - BUILDREL Copies files into the Flat Release Directory
4 Make Run-time Image – MAKEIMG

4

Generates the OS Run-Time Image from the files in the Release Directory

SYNNEX

System Generation Phase

Pre-Sysgen Build

0 1 2 3 4

Build Demo Tool (blddemo.bat)

Sysgen Post-Sysgen Build Build Release Dir Make Run-Time Image

Sysgen Generates system configuration based on chosen Catalog items in OS design
SYNNEX

System Generation Phase

Complete header and source code files

Systemspecific header files

Complete system libraries

SYSGEN

Linked libraries

Module definitions (.def)

Specific .def files

SYNNEX

System Generation Phase
%__PROJROOT%\CESYSGEN

MAKEFILE

yyy_lib.lib

zzzz.lib

aaa.Exe aaa.Dll

SYNNEX

System Generation Phase
Filtering Uses @CESYSGEN comment tags to filter files based on component settings Run from inside %__PROJROOT%\CESYSGEN\MAKEFILE
// @CESYSGEN IF [!]<Component> [[OR | || | AND | &&] [!]Component] // @CESYSGEN ELSE // @CESYSGEN ELSE IF [!]<Component> [[OR | || | AND | &&] [!]Component] // @CESYSGEN ELSEIF [!]<Component> [[OR | || | AND | &&] [!]Component] // @CESYSGEN ENDIF

SYNNEX

System Generation Phase
Filtering

Input files from %_COMMONPUBROOT% Sdk\Inc\*.* Oak\Inc\*.* Ddk\Inc\*.* Oak\Files\Common\*.*

Output directory in %_PROJECTROOT% Cesysgen\Sdk\Inc Cesysgen\Oak\Inc Cesysgen\Ddk\Inc Cesysgen\Oak\Files
SYNNEX

Post-Sysgen Build Phase
0 1 2 3 4

Pre-Sysgen Build

Build Demo Tool (blddemo.bat)

Sysgen Post-Sysgen Build Build Release Dir Make Run-Time Image

Post-Sysgen Build Phase Compile source code in BSP and user subprojects

SYNNEX

Post-Sysgen Build Phase
Compile platform source code Uses Build.exe tool Compiles and links source code in $(_WINCEROOT)\PLATFORM\COMMON Compiles and links source code in BSP
Bootloader, drivers, OAL etc

Compiles and links source code in subprojects Uses filtered OS components
Libraries, header files

SYNNEX

Build Release Directory Phase
Pre-Sysgen Build 0 1 2 3 4

Build Demo Tool (blddemo.bat)

Sysgen Post-Sysgen Build Build Release Dir Make Run-Time Image

Build Release Directory Phase (BUILDREL) Copy output files to staging directory in preparation for making OS run-time image
SYNNEX

Build Release Directory Phase
Copy files to release directory Copies OS binaries and configuration files from the OS design directory to the release directory Copies project binaries and configuration files from the OS design directory to the release directory Copies BSP binaries and configuration files from the BSP directory to the release directory

SYNNEX

Build Release Directory Phase
Binaries automatically copied to release directory when built if WINCEREL environment variable is set No need to run entire buildrel phase for a single changed binary Must run buildrel at least once Hard link vs. xcopy Copy performed using hard link by default
Major performance enhancement

Do not edit files directly in release directory
Some editors will cause original source file to change Unexpected file corruption

Force xcopy with BUILDREL_USE_COPY environment variable if necessary
SYNNEX

Make Run-Time Image Phase
0 1 2 3 4

Pre-Sysgen Build

Build Demo Tool (blddemo.bat)

Sysgen Post-Sysgen Build Build Release Dir Make Run-Time Image

Make Run-Time Image Phase (MAKEIMG) Create operating system image
SYNNEX

Make Run-Time Image Phase
Merges release folder files to create the Windows CE image Based on a set of configuration files Process Merge configuration files: All .BIB files into CE.BIB All .reg files into REGINIT.INI All .dat files into INITOBJ.DAT All .db files into INITDB.INI Compress reginit.ini in a binary registry file (DEFAULT.FDF) Replace resources in .exe and .dll for language adaptation From ce.BIB, combine binaries and files into a Windows CE image (NK.BIN)

SYNNEX

Build Phases
Change code in BSP Change Device Memory Layout Add New Item from Catalog Change code in subproject

Sysgen Post-Sysgen Build Build Release Dir Make Run-time Image

No Yes Maybe Yes

No Maybe Yes Yes

Yes Yes Yes Yes

No Yes Maybe Yes

Not all build steps must be performed on every change These are guidelines only Efficient use of build steps comes only with experience
SYNNEX

Build Types
debug build - a run-time image that usually includes debug information release (retail) build - a run-time image that does not include debug messages that are used during the development process. ship – the final product that will be shipped to customers that contains no debug code. Also some errors are suppressed that are displayed during the development process.

SYNNEX

The Build Tool Of The Build System
SYNNEX

Build.exe – The Build Tool

Build.exe

DIRs

Nmake.exe Sources

\MyProj DIRS \Proj1 Sources Makefile

Build.Exe parses DIRS and SOURCES to determine what to build, then calls NMake NMake.exe uses the data in Sources (via a makefile) to determine how to build
SYNNEX

DIRS Files
DIRS Contains a list of “project subdirectories” Text file that lists subdirectories containing other DIRS or SOURCES files BUILD.EXE will read the contents of DIRS files to determine what subdirectories to enter Supports * wildcard DIRS=\ Display \ Mouse \ Keyboard \

SYNNEX

SOURCES
SOURCES is the text file that is included into makefile.def to provide target specific information to the build

MAKEFILE

Local Project Folder

MAKEFILE.DEF %_MAKEENVROOT%

SOURCES

SYNNEX

SOURCES
SOURCES List of source code files for the project TARGETNAME Name of output target (without extension) TARGETTYPE PROGRAM – (.EXE) Application DYNLINK – (.DLL) Dynamic Link Library LIBRARY – (.LIB) Static library

SYNNEX

SOURCES
TARGETLIBS List of libraries to include in the target
Not used when TARGETTYPE=LIBRARY Typically used for import libs from DLLs

SOURCELIBS List of source libraries to include in target RELEASETYPE Indicates where build output file should be placed
LOCAL, OAK, PLATFORM

SYNNEX

SOURCES
POSTLINK_PASS_CMD Specifies a command to run after link completes
Usually a BAT file, often useful for copying raw data files to %_FLATRELEASEDIR% as there is no custom BUILDREL support for PBPXML projects

PRELINK_PASS_CMD Specifies a command to run BEFORE linking the final output

SYNNEX

SOURCES
Visual Studio 2005 contains SOURCES editor Right click on subproject and select Properties Most SOURCES functionality exposed

SYNNEX

MAKEFILE.DEF
Default MAKE rules for most aspects of the build Provides standard rules for various types of targets Includes project SOURCES file Reduces amount of MAKEFILE “code” needed for each project Located in %_MAKEENVROOT% %_WINCEROOT%\public\common\OAK\misc

SYNNEX

SOURCES.CMN
Common SOURCES file settings applied to all SOURCES projects in a sub folder (listed in a DIRS file) Placed at root of DIRS tree Build.exe will walk back up directories until no parent DIRS is found and look for SOURCES.CMN in the folder with the top level DIRS file Commonly used in BSPs and PUBLIC folders _COMMONPUBROOT __PROJROOT _ISVINCPATH _OEMINCPATH
SYNNEX

Mapping the IDE to the Command Line
Build Menu Build Solution
blddemo –q

Rebuild Solution
blddemo clean –q

Build <OS Design project name>
blddemo -q

Rebuild <OS Design project name>
blddemo clean -q

Copy Files to Release Directory
buildrel

Make Run-Time Image
makeimg
SYNNEX

Mapping the IDE to the Command Line
Build | Advanced Build Commands Menu Sysgen
blddemo –q

Clean Sysgen
blddemo clean –q

Build and Sysgen
blddemo

Not Recommended Not Recommended

Rebuild and Clean Sysgen
blddemo clean cleanplat -c

Build Current BSP and Subprojects
blddemo –qbsp

Rebuild Current BSP and Subprojects
Blddemo –qbsp -c

SYNNEX

Mapping the IDE to the Command Line
Targeted Build – BSP Build
set wincerel=1&&build

Rebuild
set wincerel=1&&build -c

Sysgen
SysgenPlatform %_TARGETPLATROOT% preproc&&SysgenPlatform %_TARGETPLATROOT% postproc

Build and Sysgen
blddemo –qbsp

Rebuild and Sysgen
blddemo –qbsp -c
SYNNEX

Mapping the IDE to the Command Line
Targeted Build – Subproject Applies to all sources subprojects
Includes sources subprojects in BSP

Build
Set wincerel=1&&build

Rebuild
Set wincerel=1&&build -c

SYNNEX

Mapping the IDE to the Command Line
Build | Global Build Settings Applies to builds initiated from the IDE menu Modifies build behavior
Copy Files to Release Directory after Build Make Run-Time Image After Build

Build | Targeted Build Settings Applies to targeted builds initiated from the Solution Explorer Modifies build behavior
Make Run-Time Image After Building

SYNNEX

Downloading the Run-time Image
Configuration – Connectivity Options

SYNNEX

Downloading the Run-time Image
Configuration – Connectivity Options

SYNNEX

Downloading the Run-time Image
Download – Attach Device

SYNNEX

Downloading the Run-time Image
Note that during the download, the directory for the specific runtime image NK.BIN file is shown

SYNNEX

Downloading the Run-time Image
The downloaded NK.BIN file will be loaded by the Target Device and the CE desktop will appear.

SYNNEX

Testing and Debugging the Run-time Image

After deploying the Run-time image, CE 6.0 offers a wide choice of testing and debug tools. Debug windows in Visual Studio Remote Tools Program launch options

SYNNEX

Debug Windows
Debug Windows – CE 6.0 uses the standard Visual Studio debug windows and offers the full compliment of debug functionality

SYNNEX

Program Launch Options
Command Line RUN from the Target Device’s Start Button. Target Control Window s explorer Target | Run Programs

SYNNEX

Remote Tools
Remote Zoom Tool Remote File Viewer Remote System Information Tool Remote Spy Tool Remote Performance Monitor Remote Kernel Tracker

SYNNEX

CE 6.0 Directory Structure
SYNNEX

Environment Variables in the Build
%_WINCEROOT% - Root of the Windows CE build install Typically C:\WINCE600 %_PUBLICROOT% - %_WINCEROOT%\PUBLIC %_PLATROOT% - %_WINCEROOT%\PLATFORM Many others Use ‘set’ in a command prompt build window to see a list of the environment variables currently set.

SYNNEX

CE Development System Directory Structure

Main CE 6.0 Directories C:\WINCE600\OSDesigns C:\WINCE600\OTHERS C:\WINCE600\PLATFORM C:\WINCE600\PUBLIC C:\WINCE600\SDK C:\WINCE600\PRIVATE

SYNNEX

Directory Structure
OSDesigns Directory Located at the path %_WINCEROOT%\OSDesigns Contains OS Design projects and subprojects

SYNNEX

\WINCE600\PLATFORM
The PLATFORM Directory Is located at the path %_WINCEROOT%\PLATFORM Is different for different hardware platforms Contains Hardware Platform-specific Board Support Platform (BSP) files Contains subdirectories that each represent a Windows CE–specific platform adaptation
SYNNEX

\WINCE600\PUBLIC
The PUBLIC Directory Contains a set of components and configurations that are hardware platform independent. Is located at the path %_WINCEROOT%\PUBLIC

SYNNEX

\WINCE600\PRIVATE
Private Directory Option at installation
Agree to separate Shared Source license Includes full Kernel source code among others

Can ship modified versions of the private code with your product Premium (“Almost everything”) Source available
GWES components Filesys components Others

SYNNEX

\WINCE600\PRIVATE
The Private Directory located at %_WINCEROOT%\Private Contains Premium Shared Source if available

SYNNEX

\WINCE600\SDK
The SDK Directory is located at the path %_WINCEROOT%\SDK Contains tools to support Platform Builder
Processor compilers Development tools Miscellaneous utilities

SYNNEX

\WINCE600\Others
The Others Directory is located at the path %_WINCEROOT%\OTHERS and contains subdirectories: ATL8 DOTNETV2 EDB SQLCE20 VISUALSTUDIO

SYNNEX

CE Development System Directory Structure
Visual Studio Directories Visual Studio PB Plug-in Dir:
C:\Program Files\Microsoft Platform Builder\6.00

Visual Studio SmartDevice Dir:
C:\Program Files\Microsoft Visual Studio 8\SmartDevices

Common Shared Files:
C:\Program Files\Common Files\Microsoft Shared

SYNNEX

CE Development System Directory Structure
Project Default Directories Visual Studio 2005 Default OS Projects Dir C:\WINCE600\OSDesigns Visual Studio 2005 Code Top Level Projects Dir C:\Documents and Settings\LoginName\ My Documents\Visual Studio 2005\Projects

SYNNEX

Board Support Package
SYNNEX

BSP Overview
Acronym Review OEM - Original Equipment Manufacturer OAL - OEM Adaptation Layer BSP - Board Support Package KITL – Kernel Independent Transport Layer

SYNNEX

BSP Overview
What does a BSP contain? Bootloader - Initializes hardware and launches the operating system OAL – Hardware specific routines supporting OS kernel for interrupt handling, memory mapping etc Drivers for custom hardware devices not already supported by Platform Builder Configuration files Requires circuit level design information

SYNNEX

BSP Overview
PLATFORM Directory Contains all BSPs Microsoft sample reference platforms Third party platforms Your BSP Common Directory Source code for libraries of routines available for use by BSPs Contains implementations for many BSP requirements No platform specific dependencies
SYNNEX

Platform Common Code Of Board Support Package

SYNNEX

Platform Common Code
Architecture Implemented in \WINCE600\PLATFORM\COMMON Organized by CPU dependency and function Exposed to BSP as libraries Referenced with _PLATCOMMONLIB in sources file _PLATCOMMONLIB = (_PLATFORMROOT)\common\lib BSP links to individual libraries as needed

SYNNEX

Platform Common Code
Organization Common Code \WINCE600\PLATFORM\COMMON\SRC\COMMON No CPU dependencies CPU independent modules, e.g.
• bootloader framework • kitl • PCI • interrupt framework • timer framework

SYNNEX

Platform Common Code
Organization CPU Architecture Specific \WINCE600\PLATFORM\COMMON\SRC\<arch>
ARM, MIPS, SHX, X86

May be further divided into sub architecture and common code Contains routines that are common to all CPUs in a particular architecture/family CPU architecture dependent modules, e.g.
• cache routines • abort handlers • memory map support • architecture specific interrupt support

SYNNEX

Platform Common Code
Organization System On Chip (SOC) Specific
\WINCE600\PLATFORM\COMMON\SRC\SOC\<soc_vendor_version>
E.g. PXA27X_MS_V1

Contains routines that support specific peripherals and CPU resources in a particular SOC Most CPU specific Common code is located in this area Supposed to be hardware implementation independent

SYNNEX

Platform Common Code
Documentation Header Files \WINCE600\PLATFORM\COMMON\INC\
#include <oal.h>

Platform Builder Documentation
Bringing Up a Hardware Platform Developing a Board Support Package Developing an OEM Adaptation Layer Production-Quality OAL

Source code Always the best documentation
SYNNEX

Platform Common Code
Using the Common code Leverage an existing BSP that uses the Common code Some Common code implementations dictate architecture of other BSP components Easier to implement with working example Implement BSP specific callbacks BSP has interdependencies with Common code Reference individual Common libraries in sources file
TARGETLIBS=$(TARGETLIBS) \ (_PLATCOMMONLIB)\$(_CPUINDPATH)\oal_cache_pxa27x_ms_v1.lib \

SYNNEX

BSP Components Of Board Support Package

SYNNEX

BSP Directory Structure
CATALOG - Contains the catalog file that exposes the BSP to the Platform Builder IDE CESYSGEN – Contains configuration files used during SYSGEN phase FILES – Contains platform configuration files including registry and BIB files SRC - Contains source code for BSP

SYNNEX

Bootloader
The Bootloader is the first software component that runs on a target hardware device Purpose Initialize hardware Perform any device specific action that needs to occur prior to booting the operating system Load the operating system image into memory Jump to the operating system entry point Typically implemented as a separate component Will have its own .bib file
SYNNEX

Bootloader
Each bootloader is unique WindowsCE does not impose any restrictions or requirements on loader code except to call OS entry point with MMU off and hardware properly initialized OEMs have unique needs for custom bootloader functionality Support custom user interface for low level device management Diagnostics Load operating system from various resources BLCOMMON library provides one possible implementation framework Do not assume that a bootloader will be implemented following any particular standard

SYNNEX

Bootloader
Bootloader Framework (BLCOMMON) Components located in Base framework simple Initialize hardware Call BootloaderMain() Implement required callbacks Use other Common libraries as needed Supports integration with Platform Builder tools Download images across debug connection Extensible
SYNNEX

WINCE600\PLATFORM\COMMON\SRC\COMMON\BOOT

Bootloader
Startup Main BootloaderMain OEMDebugInit OEMPlatformInit OEMPreDownload DownloadImage OEMWriteFlash OEMLaunch BLCommon Basic Flow
SYNNEX

OAL
The OAL (OEM Abstration Layer) is the platform specific interface between the kernel and the device hardware Purpose Handles interrupts, timers, power management, etc. Implements the operating system entry point Essentially is the kernel “process” containing kernel mode DLLs

SYNNEX

OAL
Architecture OAL is a separate component -No longer statically linked as part of OS kernel OAL must implement set of required functions OAL and Kernel each expose interface as export table - Can only call exported functions

SYNNEX

OAL
OAL Directory Structure SRC\OAL\OALLIB
Contains BSP specific OAL functions Builds as library that will eventually link with others to create OAL

SRC\OAL\OALEXE
Contains sources file with build instructions for OAL.EXE Links OAL.LIB along other Microsoft supplied libraries to create OAL.EXE OAL.EXE is renamed to NK.EXE during build process

SYNNEX

OAL – Required Function Interface
Implement using Common libraries Common libraries provide implementation for many required OAL functions Libraries may require callback functions implemented in BSP to handle BSP specific functionality Libraries may require custom data structures to be implemented in BSP OAL architecture based on Common libraries called Production Quality OAL (PQOAL) Implement directly No requirement to use Common code Can selectively choose functionality from Common code
May be a good choice for BSPs derived from a non PQOAL source
SYNNEX

OAL – Common Functions
OEMInitDebugSerial First call to OEM code by kernel Opportunity to initialize serial debug communications OEMInit Second call to OEM code by kernel Very early in boot sequence
No system calls allowed Single threaded No blocking Exception handlers not available

Initialize all necessary hardware interfaces, OS timer etc Register ISRs (except ARM) Initialize Kitl
SYNNEX

OAL – Common Functions
OEMInterruptEnable Enables specified interrupt based on interrupt identifier Called by InterruptInitialize and InterruptMask OEMInterruptDisable Disables specified interrupt based on interrupt identifier Called by InterruptDisable and InterruptMask OEMInterruptDone Unmasks specified interrupt based on interrupt identifier Called by InterruptDone OEMInterruptHandler (ARM only) Interrupt handler function (ISR) Returns interrupt identifier corresponding to interrupt source
SYNNEX

OAL – Common Functions
OEMIdle Called when no threads are scheduled to run Opportunity to place CPU in low power state OEMPowerOff Called in response to SetSystemPowerState()
POWER_STATE_OFF POWER_STATE_SUSPEND POWER_STATE_CRITICAL

Place CPU in lowest power “suspend” state

SYNNEX

OAL – Common Functions
OEMIoControl Called in response to KernelIoControl Generic IOCTL interface for the kernel Some standard IOCTLs must be implemented Can be extended by the OEM Implements interrupt identifier management

SYNNEX

OAL – Common IOCTLs
IOCTL_HAL_INIT_RTC Resets the realtime clock IOCTL_HAL_GET_DEVICE_INFO Supports SystemParametersInfo function IOCTL_HAL_REQUEST_IRQ Returns IRQ based on device location IOCTL_HAL_REQUEST_SYSINTR Returns interrupt identifier based on IRQ IOCTL_HAL_REBOOT Warm boots the target device
SYNNEX

OAL – Common Functions
OEMSetRealTime/OEMGetRealTime Called by the kernel to get/set the real time clock Called in response to Get/SetSystemTime OEMSetAlarmTime Set the Real Time Clock alarm

SYNNEX

Drivers
Most CPUs have peripherals or expansion bus interface that can support peripherals A particular hardware platform may require drivers for a subset of available peripherals Microsoft provides driver support for many peripherals
Some drivers fully implemented outside of the BSP Some drivers require BSP support for platform specific implementations

Drivers not fully implemented by Microsoft must be provided in BSP
SRC\DRIVERS

SYNNEX

Drivers
Drivers are found in several places PUBLIC tree
\PUBLIC\COMMON\OAK\DRIVERS Provided by Microsoft Bus agnostic drivers External peripherals (not on CPU silicon) MDDs for various common driver types e.g. Wave, Touch, Serial

SYNNEX

Drivers
Drivers are found in several places (con’t) Platform Common Contains support for peripherals that exist on CPU silicon Some SOC drivers may be fully implemented in Common code Other drivers may require some BSP support for platform specific functionality BSP Custom devices that don’t have driver support from Microsoft Drivers obtained from third parties Cloned (copied) versions of Microsoft provided drivers Hardware specific (PDD) implementations
SYNNEX

Miscellaneous Files Of Board Support Package

SYNNEX

Catalog File
Catalog Items View

SYNNEX

Platform Batch File
deviceemulator.bat
<snip> REM ----------------------------------------------REM Select which KITL transport to use. REM REM ----------------------------------------------set BSP_KITL_ETHERNET= set BSP_KITL_DMA=1 set IMGNOSIR=1 set IMG_RESERVERAMFMD=1 set IMGSDKCERTS=1 set IMGHEADSET=1 <snip>

SYNNEX

Configuration Files
Binary Image Builder (*.bib) Specify files to be included in the run-time image Specify memory configuration and use Registry (*.reg) Specify the initial registry File System (*.dat) Specify the initial directory structure Database (*.db) Specify initial database contents

SYNNEX

Configuration Files: .BIB Files
MEMORY section Partitions the memory into two types
RAMIMAGE RAM Contains OS image (‘ROM’), supports XIP Program and Data memory

Name Start address Size(bytes) Type Name Start address Size(bytes) Type --------------------------------------------------------------------------------------------NK 8C800000 00800000 RAMIMAGE NK 8C800000 00800000 RAMIMAGE RAM 8C050000 007B0000 RAM RAM 8C050000 007B0000 RAM CONFIG section Contains settings that control certain kernel features Contains settings that control characteristics of the build output file

SYNNEX

The Configuration Files: .BIB Files
MODULES section Lists modules to include in the run-time image Components in this section will be configured to XIP Only executable modules can be listed here FILES section Other modules to be included in the run-time image Can include both executable modules and data files Will be managed by the object store file system ;Name Path Memory Type ;Name Path Memory Type --------------------------------------------------------------------------------------------------------Tahoma.ttf $(_FLATRELEASEDIR)\Tahoma.ttf NK SHU Tahoma.ttf $(_FLATRELEASEDIR)\Tahoma.ttf NK SHU
SYNNEX

FILES – Config.bib
MEMORY Section RAMIMAGE Type Specifies memory range OS will execute from Virtual Addresses
Corresponds to mapping in OEMAddressTable (ARM, X86) or fixed static mapping (other processors)

Could be RAM or ROM Virtual memory range must be physically contiguous Must be aligned on 64KB boundary Size must be 64KB granularity Must be large enough to contain the entire operating system image

SYNNEX

FILES – Config.bib
MEMORY Section RAM Type Specifies memory range available for program and storage (working RAM) Virtual Addresses
Corresponds to mapping in OEMAddressTable (ARM, X86) or fixed static mapping (other processors)

Must be RAM Virtual memory range must be physically contiguous Must be aligned on 64KB boundary Size must be 64KB granularity
SYNNEX

FILES – Config.bib
MEMORY Section RESERVED Type Ignored by build tools Document use of other memory regions
Bootloader DMA buffers Framebuffer Etc

SYNNEX

FILES – Config.bib
CONFIG Section AUTOSIZE Allows boundary between RAM/RAMIMAGE sections to be dynamically determined Makes efficient use of RAM resources Only works with images running entirely from RAM

SYNNEX

FILES – Platform.bib
Lists BSP components to be included in the image Modules Section
Components in this section will XIP if not compressed Can only include executable components, no data files Components can’t be accessed as files because header information is stripped away

FILES Section
Components in this section are included with full headers Can be manipulated as files Executable code will be paged into memory for execution

Flags specify component characteristics E.g. USER/KERNEL, Hidden, System etc All components end up in \WINDOWS directory
SYNNEX

Configuration Files: .REG Files
Define default registry settings COMMON.REG, IE.REG, WCEAPPS.REG, WCESHELL.REG: define registry settings for Windows CE modules PLATFORM.REG: platform-dependent registry settings, such as device driver entries PROJECT.REG: defines registry settings relative to your project
[HKEY_LOCAL_MACHINE\init] [HKEY_LOCAL_MACHINE\init] “Launch10”=“shell.exe” “Launch10”=“shell.exe” “Launch20”=“device.dll” “Launch20”=“device.dll”
SYNNEX

BIB REG Editor VS2005

SYNNEX

The Configuration Files: .DAT Files
Define directory structures All files are located in \Windows (ROM) Filesystem parses information provided by .dat files to create and populate additional RAM directory structure Results in multiple copies of files Example:
Root:-Directory(“Program Files”) Root:-Directory(“Program Files”) Directory(“\Program Files”):-Directory(“My Projects”) Directory(“\Program Files”):-Directory(“My Projects”) Root:-Directory(“My Documents”) Root:-Directory(“My Documents”) Directory(“\My Documents”):-File(“MyFile.doc”,“\ Directory(“\My Documents”):-File(“MyFile.doc”,“\ Windows\Myfile.doc”) Windows\Myfile.doc”)

SYNNEX

The Configuration Files: .DB Files
Define databases in the object store Various OS components create databases for their own use Platform.db adds BSP specific database entries Project.db adds OS design specific database entries Merged into initdb.ini and included in the image

SYNNEX

Creating a New BSP Of Board Support Package

SYNNEX

Creating a New BSP
Always start with a reference BSP Don’t attempt to create a BSP entirely from scratch Find a reference BSP that most closely matches your target hardware platform CPU vendor Microsoft reference BSPs Third party systems integrator

SYNNEX

Creating a New BSP
Clone the source BSP This preserves the original BSP Original reference remains intact Changes made by source vendor do not overwrite your changes Never modify code you did not clone! Use the Clone Tool provided in Platform Builder Tools->Platform Builder for CE 6.0->Clone BSP

SYNNEX

Creating a New BSP
Port the BSP Update areas of the BSP that differ from your target hardware Requires a thorough understanding of your hardware implementation Must analyze the entire BSP code base
Memory map System initialization Interrupts GPIO configuration Peripheral implementation

Difficulty varies depending on how close the reference BSP matches target hardware and quality of original BSP Not a trivial task
SYNNEX

Creating a New BSP
Update BSP Features Implement the unique requirements your device requires Bootloader features Custom drivers Support new OS features Build/Test/Ship!

SYNNEX

The SDK Of Customizing the OS Design
SYNNEX

SDK
Platform Builder
CE 6.0 OS Design OEM Adaptation Layer (OAL) Run-time Libraries

Custom SDK
Platform Manager Run-time Files SDK Documentation OS Design Extensions

Headers and Libraries

Microsoft Embedded Development Software Visual Studio 2005
SYNNEX

SDK Development Steps
Build OS Design – create a run-time image Configure the SDK – use the SDK Wizard to configure basic settings Build the SDK - created SDK is a Microsoft Windows Installer (MSI) package Install the SDK on Visual Studio 2005

SYNNEX

Configuring the SDK Options - General
Configurable SDK properties

SYNNEX

Configuring the SDK Options - Install
Configurable MSI install properties

SYNNEX

Configuring the SDK Options – CPU Families
Configuring CPU family supported by SDK

SYNNEX

Configuring the SDK – Adding User-defined Files
Add additional folders from the SDK’s Properties Pages

SYNNEX

Building an SDK
From the Build menu, choose Build All SDKs.

SYNNEX

Installing the SDK
Installing the SDK on other development machines (with VS 2005 SP1)

SYNNEX

Operating System Internals
SYNNEX

CE 6.0 Architecture – User Processes
ServicesD.EXE Windows CE Application Shell Service 1 Service n Udevice.EXE User Mode Driver 1 Udevice.EXE User Mode Driver n

Win32 CE APIs – COREDLL / WINSOCK / COMMCTRL / COMMDLG

Shell – Standard or custom interface for the device ServicesD.EXE has the ability to host n number of Services UDevice.EXE has the ability to host n number of user mode drivers

SYNNEX

CE 6.0 Architecture – Kernel
Win32 CE APIs – COREDLL / WINSOCK / COMMCTRL / COMMDLG KERNEL.DLL OAL DEVMGR.DLL Drivers FILESYS.DLL GWES.DLL FSDMGR.DLL KCOREDLL.DLL Networking DLLs

FILESYS.DLL – Init sequence, Object Store, notifications etc FSDMGR.DLL – File system support GWES.DLL – Graphics, Windowing, and Events Subsystem Networking DLLs – NDIS based networking services DEVMGR.DLL provides device driver services KITL.DLL (Optional)
SYNNEX

CE 6.0 Architecture – Kernel
Win32 CE APIs – COREDLL / WINSOCK / COMMCTRL / COMMDLG KERNEL.DLL OAL DEVMRG.DLL Drivers FILESYS.DLL GWES.DLL FSDMGR.DLL KCOREDLL.DLL Networking DLLs

The Kernel contains base OS services API calls from modules loaded in the Kernel use K.COREDLL.DLL to get to other kernel services. K.COREDLL.DLL- kernel equivalent to COREDLL.DLL

SYNNEX

CE 6.0 Architecture - Hardware
Win32 CE APIs – COREDLL / WINSOCK / COMMCTRL / COMMDLG KERNEL.DLL OAL RAM ROM
IRQ

DEVMGR.DLL Drivers

FILESYS.DLL GWES.DLL FSDMGR.DLL KCOREDLL.DLL SDIO Touch Display Keyboard OEM

Networking DLLs

CPU Control USB

PAN WAN LAN MAN

Hardware connects to the operating system through standard interfaces: device drivers. There is great flexibility in the types of hardware that CE 6.0 supports
SYNNEX

CE 6.0 Architecture
ServicesD.EXE Windows CE Application Shell Service 1 Service n Udevice.EXE User Mode Driver 1 Udevice.EXE User Mode Driver n

Win32 CE APIs – COREDLL / WINSOCK / COMMCTRL / COMMDLG KERNEL.DLL OAL DEVMGR.DLL Drivers FILESYS.DLL GWES.DLL FSDMGR.DLL KCOREDLL.DLL Networking DLLs

OAL Component

SYNNEX

CE 6.0 Architecture
ServicesD.EXE Windows CE Application Shell Service 1 Service n Udevice.EXE User Mode Driver 1 Udevice.EXE User Mode Driver n

Win32 CE APIs – COREDLL / WINSOCK / COMMCTRL / COMMDLG KERNEL.DLL OAL DEVMGR.DLL Drivers FILESYS.DLL GWES.DLL FSDMGR.DLL KCOREDLL.DLL Networking DLLs

Microsoft

OEM

ISV

SYNNEX

Applications, Processes & Threads
Application A logical group of executable code Process A process is a single instance of an application Static context within which one or more threads execute Up to 32,000 processes loaded simultaneously Thread Basic unit of execution managed by the scheduler Each process has at least one thread called the primary thread Number of threads limited by maximum number of handles in a process

SYNNEX

Operating System Internals Memory Architecture
SYNNEX

Memory Architecture Overview
Memory Overview Virtual Memory Model Program Memory Heaps and Stacks Processes, Threads and Memory Memory System Tools

SYNNEX

Memory Overview
Memory Types Random Access Memory (RAM) Read Only Memory (ROM) What Uses Memory? Bootloader Operating System Applications Object Store - File system, Registry, Databases Shared heap Memory Mapped Files
SYNNEX

Memory Overview Operating System Image Requires Space
The operating system image itself is located in RAM or ROM at runtime Often copied to RAM in totality from a storage location (hard drive, flash memory) by the bootloader RAM occupied by the OS image is not available for application use Could be in located in ROM and not copied to RAM

SYNNEX

Memory Overview
eXecute In Place (XIP) Allows execution of programs from directly from their location in the OS image in memory Loader does not need to copy into RAM and fixup addresses Preserves limited RAM resources especially when XIP from ROM

SYNNEX

Memory Overview
User Settable Program vs. Storage Memory Program Memory is available for application use Storage Memory is used just for system object store which contains the file system, the system database and the registry.

SYNNEX

Virtual Memory Architecture
Virtual Memory Single 32-bit (4 Gigabyte) flat virtual memory address space Permits efficient use of physical memory with protection Virtual Addressing Memory Management Unit (MMU) “owns” physical memory Virtual addresses translated to physical addresses by MMU A valid virtual address must map to a physical address Static or Dynamically mapped virtual addressing All CE components use virtual, not physical addresses Physical Addressing Used by CPU before MMU is activated during power-up and by bus mastering components such as DMA controllers.
SYNNEX

Virtual Address Mapping – Static Mapping Example
Physical Memory Virtual Memory
Kernel Space
C000 0000

FFFF FFFF

Uncached Cached

32 MB Flash 64 MB RAM 32 MB Flash
82000000 04000000

512 MB
A000 0000

512 MB

32 MB Flash

64 MB RAM

8000 0000

64 MB Flash
00000000

2 GB User

Address Translation

User Space

0000 0000

SYNNEX

Virtual Memory Map

2 GB kernel space

Kernel Filesystem GWES Drivers

Memory mapped files

Process code

..
32 K processes
SYNNEX

..

2 GB VM per process

..

User DLLs

..

Kernel Memory Space

CPU Specific VM Kernel VM (if supported by CPU) 256 MB

Kernel Space 2 Gigabytes Fixed mapping independent of user space

Kernel VM 256 MB Object Store (128 MB) Kernel XIP DLLs (128 MB) Static Mapped Uncached 512 MB Static Mapped Cached 512 MB

SYNNEX

User Memory Space

Shared System Heap 255 MB RAM Backed Mapfiles 256 MB

User Space 2 Gigabytes Each process has its own mapping

Shared User DLLs 512 MB

Process Space 1 GB process

SYNNEX

Program Memory
RAM available for use by OS/Drivers/Applications Data RAM, does not include code pages Major Types of Program Memory Heap The primary area of memory used by the application Stack Storage area for variables referenced in a program

SYNNEX

Program Memory - Heap
Heap Characteristics
Dynamic memory allocation Processor-independent (hides memory paging) Automatically allocates memory and commits pages on demand

SYNNEX

Program Memory - Heap
Types of Heap Memory
Local Heap (Default) Reserves virtual memory at process load time Commits physical pages on demand Private Heap Reserves initial fixed size or expandable (disjointed) heap space Serialization for mutual exclusion of multiple threads Shared Heap Writable to kernel and read only to user processes Visible to all user processes Remote Heap Shared between user processes
SYNNEX

Program Memory - Stack
Creation Default stack allocated for each thread at creation All threads of a process have same stack size by default Default thread stack size override with /STACK linker switch Individual threads can be created dynamically with unique stack size Note: CE 6.0 compiler automatically inserts code to detect buffer overruns on the stack with the /GS switch

SYNNEX

Program Memory - Processes and Threads

Process Heap Primary Thread Stack Additional Thread Stack

Each Process has at least one heap Each Thread has a stack

Additional Thread Stack
SYNNEX

Operating System Internals Threads and Scheduling

SYNNEX

Threads
Scheduler provides efficient context switching among threads Each process has one or more threads Each thread has its own context (stack, priority, etc) Predictable sequence of thread execution based on priority

SYNNEX

Processes and Threads

Priority-based Scheduling Preemptive scheduling within 256 priority levels Round-robin scheduling of threads on same priority Priority 0 (or highest priority) threads run to completion

SYNNEX

Scheduler – Quantum Time Slicing
Thread 1 P=0 Thread 2 P=252 Thread 3 P=252 Thread 2 Thread 3 Thread 1 Thread 1 Thread 2 Thread 3

t1

t2

t3

t4

t5

t6

t7

Same priority threads run in round-robin fashion Switch threads when blocked Switch threads after quantum has elapsed Programmable quantum from 1 to N ms, default 100 ms
SYNNEX

Thread Priority Map
Priority 0 - 96 97-152 Component Typically reserved for real-time drivers Used by the default Windows Embedded CE–based device drivers Typically reserved for non-real-time drivers Mapped to other non-real-time priorities

153-247 248-255

SYNNEX

Priority Inversion

OS Priority OS Priority Restoration Inversion

High Priority

Thread 1 Thread 3
Preempt

Thread 1

Medium Priority

Thread 2
Preempt

Thread 2

Low Priority

Thread 3

Thread 3

Resource Owner:

Thread 3

Thread 1

SYNNEX

Thread APIs
Thread Creation CreateThread Thread Priority CeGetThreadPriority
Get current priority level of a thread

Creates a new thread at normal priority

CeSetThreadPriority
Set priority level of a thread

SetThreadPriority
Legacy function

GetThreadPriority
Legacy function
SYNNEX

Thread Blocking APIs
Thread Blocking APIs Sleep (n) – minimum number of milliseconds to suspend execution Sleep(0) – relinquish remainder of quantum to other threads with the same priority SleepTillTick – suspend execution until next system tick WaitForSingleObject – block until specified kernel object is signaled WaitForMultipleObjects – block until one of a set of specified kernel objects is signaled
SYNNEX

Operating System Internals Interrupt Model
SYNNEX

Interrupt Model
Interrupt Service Thread (IST)

KERNEL.DLL Exception Handler Interrupt ID 3

Event

4

Interrupt

1

Device

2 Interrupt Service Routine (ISR)

Interrupt Processing 1. Device raises registered hardware interrupt 2. Kernel gets exception, calls associated Interrupt Service Routine (ISR) 3. Interrupt Service Routine (ISR) quickly deals with pending interrupt 4. Interrupt Service Thread (IST) in driver is signaled to process interrupt
SYNNEX

Interrupt Service Routine (ISR)
Registered to an IRQ Called to handle the hardware interrupt Acknowledges hardware and determines Interrupt ID Returns Interrupt ID (SYSINTR) to kernel Static (built into NK.EXE) or Installable (chained in) via Kernel call Must be written to run quickly with no outside dependencies

SYNNEX

Interrupt Service Thread (IST)
Thread registered to handle an interrupt Performs majority of interrupt handling task Created by a device driver Standard thread that waits for interrupt events Scheduled like any other thread in the system Performs device-specific servicing for Interrupt ID Signals completion of interrupt processing to hardware

SYNNEX

ISRs And ISTs Work Together
ISRs and ISTs work as pairs ISR identifies and masks interrupt quickly IST handles the bulk of the work Synchronized by using an Event Object IST creates an Event Object mapped to SYSINTR ID IST blocks on event with WaitForSingleObject ISR returns SYSINTR to kernel Kernel sets Event, unblocking IST If the IST is the highest priority runnable thread, it will be scheduled to run immediately
SYNNEX

Installable ISRs
Allows a driver to install an ISR at run time Typically used for shared interrupts There must already be an ISR registered for that IRQ supporting shared interrupts ISR implemented in a DLL Loaded into kernel by LoadIntChainHandler OAL ISR MUST call NKCallIntChain for all shared IRQs

SYNNEX

Shared Interrupts Using Chaining

ISR 1 Shared Interrupt Line

ISR 2

ISR 3

Bar Code Scanner

Power Switch

WiFi Receive

Some platforms designed to have several devices use same interrupt line One interrupt that is shared by all Multiple ISRs chained to handle shared interrupts Each ISR, in turn, determines if it owns the interrupt
SYNNEX

Operating System Components Power Management
SYNNEX

Concepts – Role of the Power Manager
What is the Power Manager? OS component responsible for meeting the power needs of the system efficiently Application Interface
Applications communicate their power needs Applications can choose to receive notification of power related events

Device Interface
Individual devices request their desired power state based on need PM determines actual device power states Devices must operate in state set by Power Manager
SYNNEX

Concepts – Role of the Power Manager

Notification Message Queue

Application Application APIs Power Manager APIs Driver APIs

Power Manager (pm.dll)

Drivers

SYNNEX

Concepts – Device Power States
Device Power States Power level of a given device
Device in this context means individual hardware peripheral

Fixed number of predefined states
D0 D1 D2 D3 D4 Full on Low on Standby Sleep Off Full functionality Full functionality, reduced performance Partial power, auto wakeup on request Partial power, can wake up No power

Devices may implement a subset of states Device determines how a particular state is implemented
SYNNEX

Concepts – System Power States
System Power States Named power states for entire system
Defined by the OEM Act as global setting for device power states

Set maximum device power states Default implementation provided by Microsoft
On UserIdle SystemIdle Suspend User actively using device User passively using the device User not using the device Device powered down

SYNNEX

Concepts - System Power States
System power states map to device power states in the registry Default mapping for all devices Default implementation On UserIdle SystemIdle Suspend

D0 D1 D2 D3

Individual devices can have exceptions to default Example: Suspend state maps to D4 for NDIS devices OEM can easily modify device power state to system power state mapping using the default Power Manager implementation

SYNNEX

Concepts – Activity Timers
Activity Timers Named timers implemented by Power Manager
Configurable in registry Any number of timers can be implemented General purpose mechanism that can be used by any component

Implemented with named events Used by default Power Manager implementation
PM implements two timers for its own use Used to determine user and system activity Some OS components reset timers to indicate activity GWES, Networking
SYNNEX

Power Manager Implementation
Power Manager implementation provided by Microsoft WINCE600\PUBLIC\COMMON\OAK\DRIVERS\PM MDD/PDD model PDD defines the supported system power states PDD contains logic that determines when/how to transition between system power states OEMs can modify PDD to meet unique device requirements
Different system power state needs

SYNNEX

Power Manager Implementation
Power Manager determines when to change system power states Decision logic implemented in PDD Default implementation based on activity timers
UserActivity timer SystemActivity timer

Timer settings exposed to user with control panel applet

SYNNEX

Device Power Management
Power Manager support optional in driver PM only controls drivers that are Power Manager aware Drivers not required to support Power Manager Devices must advertise that they support the Power Manager interface for PM control
Iclass registry entry with Power Manager GUID AdvertiseInterface with Power Manager GUID

SYNNEX

Device Power Management
Device Power State Changes Drivers may not change power state unless instructed to by Power Manager Drivers should manage power within a power state on their own Drivers can request that the Power Manager change their state
Power Manager may change to requested state, another state, or no change at all Drivers must not assume that their request will be honored

SYNNEX

Device Power Management
Drivers communicate power needs with DevicePowerNotify Power Manager sets device state with DeviceIoControl Drivers must expose stream interface

Power Manager PM.DLL PM APIs DevicePowerNotify Device Driver DeviceIoControl

SYNNEX

Device Power Management
Device State Code Sample
case IOCTL_POWER_SET: // update device registers ... deviceDx = *(PCEDEVICE_POWER_STATE) pOutBuf; fBoostRequested = FALSE; fReductionRequested = FALSE; break;

SYNNEX

Applications and Power Management
Applications can request notification of Power events RequestPowerNotifications/StopPowerNotifications Notifications generated by Power Manager
Uses point to point message queues

Applications register for desired event type
System power state transitions Change between AC/DC power sources Resume occurred Battery power status field has changed

Notification only, no opportunity to modify, delay or block event
SYNNEX

Applications and Power Management
Applications can request a system power state change SetSystemPowerState will instruct the Power Manager to change power states
Specify by name Specify by “hint” (bitmask)

System power states are OEM defined, so applications may not know state names
Power manager chooses most appropriate state based on hint Hint bitmasks defined by Microsoft for standard state types

Power Manager may restrict applications from entering certain system power states
SYNNEX

Applications and Power Management
Applications can set power requirement for a device Application calls SetPowerRequirement to request a specific device maintain a minimum power state Allows device to be at a higher power state than system power state would otherwise allow Application should call ReleasePowerRequirement as soon as possible to allow normal power management to continue

SYNNEX

Application Power Management APIs
GetSystemPowerState Retrieve the current system power state SetSystemPowerState Request a particular system power state SetPowerRequirement Request specific device to maintain minimum power level ReleasePowerRequirement Release device requirement RequestPowerNotifications Request notification when certain types of power related events occur StopPowerNotifications No longer have a need to receive power notifications
SYNNEX

Idle Power Management
Kernel knows when no threads are running Calls OEMIdle to put the CPU in lower power states
Must be supported by CPU

Transparent to rest of system and user Independent of Power Manager Small change here = big change in Standby time
Majority of time spent is in OEMIdle

SYNNEX

Suspend/Resume
Suspend Lowest possible power state Device is off from user perspective, but maintains volatile memory Must be supported by cpu Resume “Instant on” Returns to state that existed prior to entering suspend Transparent to applications
SYNNEX

Suspend/Resume
Power Manager implements suspend/resume sequence Initiated in response to SetSystemPowerState Drivers participate in suspend/resume process
Includes drivers that are not managed by Power Manager

Applications can initiate suspend sequence if permitted by Power Manager implementation Applications have no opportunity to block or otherwise participate in the suspend sequence

SYNNEX

Suspend/Resume
Suspend Path PM disables all PM-aware non-block drivers PM calls IOCTL_HAL_PRESUSPEND PM notifies file systems PM disables all PM-aware block drivers System goes “single threaded” Kernel calls all legacy xxx_PowerDown functions Kernel calls OEMPowerOff

SYNNEX

Suspend/Resume
Resume Path CPU wakes up and continues executing OEMPowerOff returns Kernel calls all legacy xxx_PowerUp routines System goes multi-threaded PM enables PM-aware block drivers PM enables file systems PM enables remaining PM-aware drivers

SYNNEX

Operating System Components Internationalization
SYNNEX

Internationalization

Platform localization options Localization vs. Internationalization Changing the language of your operating system

SYNNEX

Internationalization
Locale Support Arabic English (U.S.) English (Worldwide) French German Hebrew Indic Japanese Korean Simplified Chinese Traditional Chinese Thai
SYNNEX

Internationalization
Adding locales Selecting codepages

SYNNEX

Multilingual User Interface

German DLL English DLL

French DLL Spanish DLL

CE OS

Allows users to change the language of the user interface (UI) Single core binary that includes the system default language One resource dynamic–link library (DLL) for each additional target language
SYNNEX

Internationalization Components National Language Support (NLS) Multilingual User Interface (MUI) Unicode Script Processor for Complex Scripts Input Method Manager (IMM) Handwriting Recognizer Engine (HWX) Keyboards and Fonts for Many Languages Additional language specific components

SYNNEX

Device Driver Concepts
SYNNEX

What is a Device Driver?

Application Driver CE 6.0

Device A device driver is software that abstracts the functionality of a physical or virtual device
SYNNEX

Device Driver Categories
Drivers are classified in a number of different ways Native vs Stream
Who loads the driver

User vs Kernel
Where the driver is loaded

Monolithic vs Layered (MDD/PDD)
How the driver is architected

Built In vs Dynamic/Installable
When the driver is loaded

Driver Family
WAV/Miniport/Touch/Display/Serial etc
SYNNEX

Monolithic vs Layered
MDD/PDD or Layered Drivers Model Device Driver + Platform Device Driver = Driver Sample implementations provided by Microsoft MDD implements functionality common to all similar devices MDD implements defined architecture for specific drivers MDD can often be used unmodified MDD calls PDD functions for hardware specific functionality PDD must be customized to match target hardware Interface to PDD is sometimes called DDSI Provides for code reuse, ease of implementation Can be less efficient due to layering
SYNNEX

Monolithic vs. Layered
Monolithic Drivers Does not leverage high level shared library of interface routines Written to implement requirements as efficiently as possible Can have increased or otherwise unique feature set (not dependent on MDD implementation) Less code reuse, more complex development Can be more efficient due to streamlined functions

SYNNEX

Monolithic vs. Layered
Hybrid Drivers MDDs are not immutable. Clone and modify as necessary Modified MDDs are often used to implement missing feature requirements Maintains ease of development benefits by starting with existing high level driver implementation

SYNNEX

Native vs. Stream
Native Fixed set of native device classes defined by CE •Keyboard •Display •Touch Drivers loaded directly by GWES, not managed by device Each has its own model

SYNNEX

Native Device Driver Model
Graphics, Windowing, and Events System (GWES) Device Driver Interface (DDI) Device Driver Interface (DDI) MDD Monolithic Native Driver PDD Device
SYNNEX

Native vs. Stream
Stream Drivers Loaded and managed by Device Manager Support any type of physical or virtual device Device Manager imposes minimum interface requirements (driver entry points and behavior) Stream model applies to most drivers Exposed to applications through filesystem APIs Can be loaded at boot or dynamically

SYNNEX

Stream Interface Device Driver Model
Device Manager
Stream Interface Stream Interface Stream Interface (DDI)
NDIS Wrapper

MDD Monolithic Stream Interface Driver PDD

NDIS Miniport
NDIS Wrapper

NDIS

Device
SYNNEX

Stream Driver Architecture
SYNNEX

Device File Names
Drivers can be accessed as special file system device Three different namespaces provide different features Share common 3 letter prefix Legacy
Example: “COM1:”

Device
Example: “\$device\COM1”

Bus
Example: “\$bus\PCMCIA_0_0_0”

Named interface not required
SYNNEX

Device File Names
Legacy Namespace Original naming convention Used by most legacy drivers Consists of Prefix followed by Index (0-9) Limited to 10 instances of a particular prefix (COM0 COM9) Prefix included in driver entry points Unless special registry flag is set

SYNNEX

Device File Names
Device Similar to Legacy namespace Consists of Prefix followed by number Provides support for more than 10 devices “\$device\COM27”

SYNNEX

Device File Names
Bus Typically used with client drivers loaded by a bus driver Provides mechanism to differentiate between IO and bus control operations Provides mechanism for more sophisticated driver loading/unloading/power management features

SYNNEX

Stream Driver Architecture
Application
CreateFile

File System Stream Interface Driver (Loaded at Boot up)

OAL

Window CE Kernel

Device Manager
Interrupt Events

Software Hardware

Hardware Platform

Built-in Device SYNNEX

Implementing Generic Stream Drivers
How do you implement a Stream Driver? Select a device file name prefix Implement the required entry points Create the *.DEF file Create the registry values necessary to load your driver

SYNNEX

Stream Entry Points: Init, Deinit
XXX_Init Called when Device Manager loads the driver Initialize necessary resources Perform memory mapping Initialize IST XXX_Deinit Called when Device Manager unloads the driver Frees allocated resources, stops the IST

SYNNEX

Stream Entry Points: Open, Close

XXX_Open Called in response to CreateFile on device name Provides handle for use by other IO functions Allocate resources for open context and prepare for operation XXX_Close Called in response to CloseHandle Clean up open context

SYNNEX

Stream Entry Points: Read, Write and Seek
XXX_Read Called in response to ReadFile XXX_Write Called in response to WriteFile XXX_Seek Called in response to SetFilePointer

SYNNEX

Stream Entry Points: IOControl
XXX_IOControl Called in response to DeviceIoControl Provides mechanism supporting custom driver operations Workhorse of most drivers I/O control code identifies the operation I/O control code is device-specific

SYNNEX

Stream Entry Points: PowerUp, PowerDown

XXX_PowerDown Callback notifying device that OS is suspending Allows driver to perform any desired operations necessary to go into low power mode XXX_PowerUp Callback notifying device that OS is resuming Allows driver to perform any desired operations necessary to exit low power mode

SYNNEX

Stream Entry Points: PreClose, PreDeinit

XXX_PreClose Called prior to XXX_Close when application calls CloseHandle Provides opportunity for driver to wake sleeping threads Eliminates potential race condition with multiple threads XXX_PreDeinit Called prior to XXX_Deinit when driver unloads Provides opportunity for driver to mark handle as invalid Eliminates potential race condition with multiple threads

SYNNEX

Stream Driver Interfaces – Entry Points
Function xxx_Init xxx_DeInit xxx_Open xxx_Close xxx_IOControl xxx_Read xxx_Write xxx_Seek xxx_PowerOn xxx_PowerOff Called When The driver is initialized (loaded) The driver is de-initialized (unloaded) Application calls CreateFile Application calls CloseHandle Application calls DeviceIoControl Application calls ReadFile Application calls WriteFile Application calls SetFilePointer OS resumes from suspend state OS enters suspend state
SYNNEX

User Mode Driver Framework
SYNNEX

User and Kernel Mode Drivers
User Memory Space
ServicesD.EXE Windows CE Application Shell Service 1 Service n Udevice.EXE User Mode Driver 1 Udevice.EXE User Mode Driver n

Marshalling Kernel Memory Space

Win32 CE APIs – COREDLL / WINSOCK / COMMCTRL / COMMDLG

KERNEL.DLL OAL

DEVMRG.DLL Drivers

FILESYS.DLL GWES.DLL FSDMGR.DLL K.COREDLL.DLL

Networking DLLs

SYNNEX

User vs. Kernel Mode Drivers – Kernel Mode
Default driver model Run in kernel memory space Link to kernel version of coredll, k.coredll.dll Automatic, no need to change build rules Highest performance Fast access to kernel APIs Direct access to user buffers Must be robust Driver crash could corrupt kernel
SYNNEX

User vs. Kernel Mode Drivers – User Mode
Also managed by Device manager Hosted by udevice.exe Close compatibility with kernel mode drivers UM Drivers lose Kernel privileges No access to kernel structures or memory Cannot call certain kernel only APIs Restricted access to other kernel APIs Increases system stability Examples Expansion buses like USB and SDIO
SYNNEX

User Mode Driver Framework
Improved stability User-Mode Drivers are isolated from other drivers Kernel is isolated from user-mode drivers Increased security Kernel protected from compromised drivers Lower privileges restrain a compromised driver Recoverability System can recover after a driver crash Driver can be restarted without rebooting
SYNNEX

Loading a User Mode Driver
User Mode Driver Host Process User Application ActivateDeviceEx HANDLE 10 Returned XXX_Init forwarded to UM Driver Host 6 5 10 2 9 3 XXX_Init(…) 8

User Mode Driver udevice.exe CreateProcess(,,Volume Name) 4 7 9 Device Context

User Mode Kernel Mode

1

Device Manager 1

Reflector Service

HANDLE Returned Parent Bus Driver
SYNNEX

Registry For User Mode Driver

User Mode Driver Host process is launched and managed by registry settings Example of the registry keys for Group ID 3
[HKEY_LOCAL_MACHINE\Drivers\ProcGroup_0003] "ProcName"="udevice.exe" "ProcVolPrefix"="$udevice"

[HKEY_LOCAL_MACHINE\Drivers\BuiltIn\Ethman] "Prefix"="ETM" "Dll"="ethman.dll" "Index"=dword:1 ; WZCSVC must be started before ethman "Order"=dword:2A
; Flags==12 is DEVFLAGS_LOADLIBRARY and DEVFLAGS_LOAD_AS_USERPROC

"Flags"=dword:12 "UserProcGroup"=dword:3 ; // default to group 3 SYNNEX

BIB File Issues

Driver in MODULES section of BIB file must be fixed up properly to run in either User or Kernel mode Use K flag to fix up to kernel space Remove K flag to fix up to user space Use Q flag to fix up both places Driver in FILES section can be loaded into user or kernel space

SYNNEX

Device Driver Concepts Interrupts
SYNNEX

Interrupt Terminology
ISR – Interrupt Service Routine Runs in OAL Identifies interrupt source and returns Interrupt ID to kernel Minimal processing – identify and mask interrupt IST – Interrupt Service Thread Runs in device driver Signaled by kernel when ISR returns corresponding Interrupt ID Performs bulk of processing necessary to handle interrupt
SYNNEX

Interrupt Terminology
IRQ Hardware identifier indicating interrupt source Interpretation specific to BSP Could map to multiple SYSINTRs (shared interrupts) SYSINTR Software identifier indicating interrupt source Mapped to a single IRQ by the OAL Associated with Event object by InterruptInitialize Returned by ISR to kernel
SYNNEX

Setup Interrupt
SYSINTR value needed to associate with interrupt Might be hard coded into driver (non portable) Use DDKReg_GetIsrInfo to retrieve from registry
Use SYSINTR value directly if it exists Use Irq with IOCTL_HAL_REQUEST_SYSINTR to retrieve SYSINTR from OAL

Create Event object Normal event object Will be signaled by the kernel when ISR returns SYSINTR Associate event with SYSINTR (InterruptInitialize) Configures kernel with SYSINTR<->Event mapping

SYNNEX

Interrupt Service Thread
Create IST thread using CreateThread IST is just a secondary thread in the host process Adjust thread priority using CeSetThreadPriority Retrieve thread priority from registry if available IST loop Block on event using WaitForSingleObject Process interrupt when event is signaled Call InterruptDone to unmask interrupt

SYNNEX

Installable ISRs
Allows a driver to install an ISR at run time Supports driver installation after image creation OAL agnostic to device(s) using IRQ OAL must support interrupt chaining on that IRQ NKCallIntChain Typically used for shared interrupts Supports custom functionality in ISR Example: High speed serial port driver

SYNNEX

Installable ISRs
ISR implemented in a DLL All code must be contained in the DLL and cannot have dependent DLLs Cannot link implicitly to other DLLs
NOMIPS16CODE=1

Must disable C run time library
NOLIBC=1

SYNNEX

Installable ISRs - APIs
LoadIntChainHandler Loads DLL into kernel Registers for particular IRQ Indicates handler function within DLL FreeIntChainHandler Unload interrupt handler KernelLibIoControl IST interface to ISR

SYNNEX

Generic Installable ISR (GIISR)
Suitable for many devices Provided by Microsoft Reads register to determine interrupt status Configurable Register/Port address Register/Port size Memory vs. IO Mask

SYNNEX

Loading Stream Drivers
SYNNEX

Driver Loading
Driver loading controlled by registry keys When the driver loads How the driver loads Parameters passed to the driver Drivers loaded with call to ActivateDeviceEx Takes handle to registry key as parameter Different loading requirements supported Can be loaded automatically at boot (Built In) Can be loaded dynamically (Plug and Play)
SYNNEX

Driver Registry Settings
Dll [Required] Specifies the name of the driver DLL Prefix [Optional] Specifies the file name for the device driver Order [Optional] Specifies order to load driver Index [Optional] Specifies the device index (x in COMx:) IClass [Optional] Specifies GUID(s) for device class(es) for use by PnP notification system Flags [Optional] Specifies load flags for the driver

SYNNEX

Driver Registry Settings – Flags Parameter

Flag

Value

Description

DEVFLAGS_UNLOAD

0x00000001

Driver unloads after a call to the XXX_Init entry point Driver is not loaded Driver entry points do not have an XXX Prefix prepended Driver is loaded during system phase one. Bus Driver loads the driver only when it has exclusive access to the IRQ. Loads a driver into user mode SYNNEX

DEVFLAGS_NOLOAD DEVFLAGS_NAKEDENTRIES DEVFLAGS_BOOTPHASE_1 DEVFLAGS_IRQ_EXCLUSIVE

0x00000004 0x00000008 0x00001000 0x00000100

DEVFLAGS_LOAD_AS_USERPROC 0x00000010

Driver Registry Settings – Bus Information
InterfaceType Specifies the Interface (Bus) type used for a device
See INTERFACE_TYPE enumeration in CEDDK.H for a complete list of interface types defined by Microsoft. (You can define new ones if you need to)

BusNumber Bus Instance number
Uniquely identifies the specific bus in case there is more than one of the specified type in the system

SYNNEX

Driver Registry Settings – Memory and I/O Windows
Memory and I/O Window information may be populated by a Plug and Play Bus Driver or configured by the system OEM IoBase Specifies the bus relative base of an I/O mapped window used by the device.
Multiple windows specified using a binary array of 32bit values, one for each window needed

IoLen Specifies the length of each I/O window needed by the device MemBase Specifies the bus relative base of a memory mapped window used by the device.
Multiple windows specified using a binary array of 32bit values, one for each window needed

MemLen Specifies the length of each memory mapped window needed by the device
SYNNEX

Driver Registry Settings – Interrupts
IRQ Specifies the physical IRQ used by the device SYSINTR Specifies a Logical interrupt Identifier
Typically allocated by a bus driver for shared IRQs, the Device driver reads this value and if present uses the one provided by the bus driver. Otherwise the driver should use the IRQ to request a new logical ID.

IsrDll Specifies a DLL to containing an installable interrupt handler IsrHandler Specifies the ISR handler in the ISR DLL

SYNNEX

Bus Drivers
What is a Bus Driver? Load drivers for the devices on their respective buses Provides Device Manager with enough information to create bus-relative names and enable device handles Provides bus level services for the bus Examples are: USB PCI (PCIBus.dll) PCMCIA (Pcmcia.dll) Bus Enumerator (BusEnum.dll)
SYNNEX

Bus Enumerator
Bus Driver used by Device Manager Starts top level driver loading process “Bus” consists of registry subkeys Loads drivers listed in subkeys Loads other bus drivers and unmanaged drivers Can be re-entered

SYNNEX

Device Manager – Loading Drivers at Boot
Reads registry HKEY_LOCAL_MACHINE\Drivers for “RootKey” value Usually: "RootKey"="Drivers\\BuiltIn" Calls ActivateDeviceEx on the registry path specified in “RootKey” Example:
[HKEY_LOCAL_MACHINE\Drivers\BuiltIn] "Dll"="BusEnum.dll" "BusName"="BuiltIn" "Flags"=dword:8

Bus Enumerator (BusEnum) driver loads drivers below it
SYNNEX

Sample Registry
Example:
[HKEY_LOCAL_MACHINE\Drivers\BuiltIn\AmdNorFMD] [HKEY_LOCAL_MACHINE\Drivers\BuiltIn\AmdNorFMD] "Dll"="amdnord.dll" "Dll"="amdnord.dll" "Prefix"=“DSK" "Prefix"=“DSK" "Flags"=dword:00010000 "Flags"=dword:00010000 "Order"=dword:2 "Order"=dword:2 [HKEY_LOCAL_MACHINE\Drivers\BuiltIn\Backlight] [HKEY_LOCAL_MACHINE\Drivers\BuiltIn\Backlight] "Dll"=“backlight.dlll" "Dll"=“backlight.dlll" "Prefix"=“BKL“ "Prefix"=“BKL“ "Order"=dword:1 "Order"=dword:1

SYNNEX

Application Development
SYNNEX

Application Development Options
Languages C, C++, C#, VB and Assembler Frameworks WIN32 MFC, ATL, WTL, STL .NET Compact Framework

SYNNEX

.NET Managed Applications
Supported by the Compact Framework Languages all compile to Intermediate Language format to run on Common Language Runtime (CLR) C# application development Visual Basic .NET application development

SYNNEX

Native Applications
Must be rebuilt for each new CPU or Platform Developer manages system resources WIN32 runs without extra support files Can access all operating system services and APIs Must be rebuilt to run on desktop systems Supports COM, ActiveX programming

SYNNEX

Managed Applications
Built once for all devices Runtime engine manages system resources Requires runtime support files (.NET CF) Applications access the services exposed by the Compact Framework May Run directly on desktop without rebuilding

SYNNEX

~Thank You~
WinCE MOC Training Partner
Bsquare TechWare 巨匠
WinCE information and training data download http://www.synnex.com.tw/oem_cover.htm

SYNNEX

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->