module 3: kernel features -...

51
Contents Overview 1 Definition of Real Time 2 Windows CE Kernel Features 4 Handling Processes, Threads, and Fibers 6 Protecting Applications 17 Synchronization Objects 23 Memory Model 28 Module 3: Kernel Features Module 3: Kernel Features

Upload: others

Post on 26-Jul-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Contents

Overview 1

Definition of Real Time 2

Windows CE Kernel Features 4

Handling Processes, Threads, and Fibers 6

Protecting Applications 17

Synchronization Objects 23

Memory Model 28

Structured Exception Handling 33

Optimizing a Windows CE Device 37

Lab 3: Kernel Tracking Thread Priorities 45

Review 46

Module 3: Kernel Features

Module 3: Kernel Features

Page 2: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, places or events is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2001 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Visual Studio are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Page 3: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features iii

Instructor Notes This module provides students with an understanding of the kernel features that are supported by Microsoft Windows CE .NET. Students will be able to optimize the Real-time systems by using various optimizing tools and techniques.

After completing this module, students will be able to:

Describe the real time operating system. State the Windows CE kernel features. Describe the process, thread, and fiber handling in Windows CE .NET. Protect threads from unauthorized priority or quantum modification. Explain synchronization objects in Windows CE .NET. Describe the memory model in Windows CE .NET. Perform structured exception handling. Measure and fine-tune time-critical operations.

Materials and Preparation This section provides the materials and preparation tasks that you need to teach this module.

Required Materials To teach this module, you need the following materials:

Microsoft PowerPoint® file 2535A_03.ppt Module 3, “Kernel Features”

Preparation Tasks To prepare for this module:

Read all the materials for this module. Read the instructor notes and margin notes for the module. Practice and complete all the labs pertaining to this module. Read the Platform Builder documentation on “Building a Windows CE

Platform.”

Presentation: 75 Minutes Lab: 40 Minutes

Page 4: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

iv Module 3: Kernel Features

Module Strategy Use the following strategy to present this module:

Definition of Real Time Discuss the various terms that are used with real-time systems.

Windows CE Kernel Features Briefly describe the kernel features of Windows CE .NET. Describe the basic features of processes, threads, and synchronization.

Handling Processes, Threads, and Fibers Explain how scheduling is improved in Windows CE .NET by providing features such as more thread priorities and better synchronization support.

Protecting Applications Explain how to secure an application and a platform by using OEMCertifyModule to protect thread quantum and priority, and the registry.

Synchronization Objects Discuss the purpose of synchronization using critical sections, mutexes, and semaphores.

Memory Model Discuss how to attach to virtual memory in Windows CE.NET.

Structured Exception Handling Discuss the exception handling techniques used in Windows CE .NET. Explain the try-except pair and different structured exception handling expressions, such as filter and exception API.

Optimizing a Windows CE Device Discuss how the code for Windows CE .NET real-time performance can be optimized. Explain the measurement tools and the measurement Application Programming Interface (APIs) that can be used for optimization.

Page 5: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 1

Overview

Definition of Real Time

Windows CE Kernel Features

Handling Processes, Threads, and Fibers

Protecting Applications

Synchronization Objects

Memory Model

Structured Exception Handling

Optimizing a Windows CE Device

This module covers the relevant kernel features that are used in building a CE Platform. Windows CE .NET is a real time operating system. This module covers what that means in actual timing terms. In this module, you will learn about how the kernel handles and schedules processes and threads. When utilizing resources on a device, you often have multiple access or dual-port issues requiring synchronization. You will learn about the physical to virtual mapping used by the Windows CE kernel in memory mapping. Another kernel feature is the ability to protect your individual applications and your device as a whole from malicious applications by utilizing the certification security system. The module provides the security measures used by Windows CE .NET to protect your application. Finally, the module provides some optimization tips for speeding up your system’s performance.

After completing this module, you will be able to:

Describe the real time operating system. State the Windows CE kernel features. Describe the process, thread, and fiber handling in Windows CE .NET. Protect threads from unauthorized priority or quantum modification. Explain synchronization objects in Windows CE .NET. Describe the memory model in Windows CE .NET. Perform structured exception handling. Measure and fine-tune time-critical operations.

Topic Objective To provide an overview of the module topics and objectives.

Lead-in In this module, you will learn about basic kernel features utilized by CE developers.

Page 6: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

2 Module 3: Kernel Features

Definition of Real Time Real Time

A system in which specific data collection or device control must be handled within specified time parameters.

Hard Real Time

Catastrophic results for failure to meet time constraints.

Soft Real Time

Non-catastrophic results for failing to meet time constraints

Latency

Is delay in response

Different people use different definitions to explain the term Real-time based on their solutions. Arriving at the correct solution involves performing calculation within a defined time constraint. Quite often, this time constraint is an issue because of the need to coordinate applications with external devices. Some external devices are used for data collection. For example, the need to collect a specific number of samples from a photo-eye per unit time to gauge how many units have passed it. Other external devices involve direct control by the real-time system.

Characteristics of Real-Time Performance Windows CE .NET provides the following characteristics for its real-time performance:

Guaranteed upper bounds on high-priority thread scheduling. It is provided only for the highest-priority thread among all the scheduled threads.

Guaranteed upper bounds on delay in scheduling high-priority interrupt service routines (ISRs). The kernel has a few places where preemption is turned off for a short, bounded time.

Fine control over the scheduler and how it schedules threads.

The Real-time features of Windows CE.NET provide certain characteristics that help to meet the needs of developers who have specific time constraints for their systems.

Latency Latency is delay in response. For example, the interval between the time when a sound buffer plays and the time when the speakers actually reproduce the sound. In general, embedded engineers use this term in relation to the measure of time between hardware interrupt pulsing and when the operating system responds to the request.

Topic Objective To define some terms used in this module.

Lead-in The term real time is pervasive in the industry. Here we define what we mean by real time.

Page 7: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 3

For information on Benchmarking, see article “Assessing Microsoft Windows CE 3.0 Real-Time Capabilities” on the Microsoft MSDN site. This article also compares several CPUs with real data.

Note Delivery Tip Open this white paper for the students and show them the information on benchmarking.

Page 8: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

4 Module 3: Kernel Features

Windows CE Kernel Features Multiple processes

Can support maximum of 32 separate processesMultiple threads

Supports 256 thread prioritiesFibers

Unit of execution that must be manually scheduled by the application

Synchronization objectsCritical SectionsMutexes

Memory modelPaged, No backing store

Windows CE kernel features include:

Multiple processes Windows CE .NET is a multi-process operating system, and can support a maximum of 32 separate processes. Each process has its own private address space, which is 32 MB in size. This is in contrast to the 2 GB address space of a Windows 2000 process.

Multiple threads Threads are the unit of scheduling. Only limit is available system memory. Threads reside within a process. Threads have a priority. Prior to Windows CE 3.0, there were eight thread priorities. Windows CE .NET has 256 priorities.

Fibers A fiber is a unit of execution that must be manually scheduled by the application.

Synchronization objects Key issue in a multi-threaded environment is to coordinate the activity of threads, and that is the job of the synchronization objects. A critical section variable can be defined and used to pass a token to synchronize objects. A mutex is an event object that signals when it is not owned by another process.

Memory model On the memory front, Windows CE .NET supports paged virtual memory. This can cause delays. The easiest way to avoid these delays is to force time-critical code to be non-paged. This can most easily be accomplished by putting such code in a dynamic link library (DLL), then loading the DLL into memory with a call to LoadDriver. Both, LoadDriver and LoadLibrary load DLLs into memory; the difference is that a DLL loaded by LoadDriver cannot be paged out of memory.

Topic Objective To describe Windows CE kernel features.

Lead-in Windows CE kernel features include…

zhoulz
Highlight
zhoulz
Highlight
zhoulz
Highlight
Page 9: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 5

Unlike other operating systems that support paged virtual memory, Windows CE .NET does not support a backing store. Unlike desktop versions of Windows, Windows CE .NET does not have a page file to backup the virtual.

Page 10: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

6 Module 3: Kernel Features

Handling Processes, Threads, and Fibers

Process Management

Thread Priority

Priority Inversion Handling

Thread Quantum Control

Thread APIs

Fibers

Windows CE .NET provides enhanced real time support for scheduling by enhancing built in features. In the latest releases of Windows CE, the following enhancements are provided:

Increased timer resolution More thread priorities for greater separation Unique thread quantum for each thread

Topic Objective To describe how Windows CE .NET handles threads, processes, and fibers.

Lead-in Windows CE .NET is a multi-process, multi-threaded operating system.

Page 11: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 7

Process Management

The maximum number of simultaneous processes are limited 32 processes because:

It is the number of bits in a DWORD

It is a reasonable limit for most embedded devices, as using multi-thread is recommended over multi-processes

Windows CE .NET uses the same loading and unloading mechanism as Windows NT

Support for console applications

Call CreateProcess() to start a process

Windows CE .NET limits the number of processes that can run simultaneously to 32, mainly because that is the number of bits in a DWORD. The virtual memory system and handle-management logic in the kernel use 32-bit bitmasks as access keys. For example, every handle has a bitmask that indicates which of the applications are allowed to access it. This is a fast and efficient way of handling resource protection. Moreover, 32 simultaneous processes is a reasonable limit for most embedded devices because you are strongly advised to use multiple threads instead of multiple processes.

When Windows CE starts, you do not have 32 processes available for your own use because the system loads several executable files such as the kernel (NK.EXE), GWES.EXE, FILESYS.EXE, and SHELL.EXE (if you have a shell) files. Therefore, you can count on 28 available processes for your own purposes.

Comparing Windows NT and Windows CE .NET The process file format is the same as for Windows NT. Windows CE .NET uses the same loading and unloading mechanism as Windows NT.

Console applications have been supported from Windows CE version 2.12 onwards. A console application is an application that does not create a window, but only produces output that is similar to a text-based application.

Windows CE .NET does not support the equivalent of a Windows NT service, although you can create a process without any windows. By setting the appropriate registry key, you can cause such a process to start running at system boot time.

Here is an example of calling CreateProcess to start a program running:

Topic Objective To define what a Process is for Windows CE .NET.

Lead-in Processes define the basic executable program of Windows CE.

zhoulz
Highlight
Page 12: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

8 Module 3: Kernel Features

bProcess = CreateProcess (achRun, // Exe file name. NULL, // Command line. NULL, // Process Security. NULL, // Thread Security. FALSE, // Inherit Handles? 0, // Flags. NULL, // Environment block. NULL, // Current drive & directory. #ifdef UNDER_CE NULL, // Start info must be NULL in WinCE. #else &si, // Start info non-NULL on desktop. #endif &pi); // Returned: Process info.

Page 13: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 9

Thread Priority

Thread A is in the highest priority

If at any point while thread A is running, thread B or C wake up

If A is blocked, and both B and C are awake

If thread A wakes up at any point during execution of any thread below its priority level

The illustration on the slide shows thread handling in Windows CE. The explanation of the illustration is as follows:

1. Thread A is in the highest priority. It runs until it blocks or puts itself to sleep.

2. If at any point while thread A is running, thread B or C wake up, they do not run until A is done.

3. If A is blocked, and both B and C are awake, B and C get scheduled in a round robin fashion inside their own priority level. Each runs for its quantum (configurable in Windows CE .NET) and then passes control to the other until they are done.

4. If thread A wakes up at any point during execution of any thread below its priority level, then that thread will be preempted. The lower thread’s state will be saved off and A will be serviced immediately. When A is finished, the original lower priority thread will be restored and continue to run.

Windows CE supports priority inversion, which refers to a situation in which the use of a mutex, critical section, or semaphore resource by a lower-priority thread delays the execution of a higher-priority thread, when both are contending for the same resources. To correct this situation and free the higher-priority thread, Windows CE allows the lower-priority thread to inherit the more critical thread's priority and run at the higher priority until it releases its use of the resource. Because an unbounded amount of time is needed to relinquish the inverted thread and it is out of the control of the kernel, the OEM loses control of the scheduling process. To guarantee real-time performance, OEMs should ensure that a priority inversion condition does not occur.

Topic Objective To graphically explain pre-emptive, priority based scheduling.

Lead-in In the illustration shown in the slide, let us take the scenario where we have three threads running on our platform.

zhoulz
Highlight
zhoulz
Highlight
Page 14: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

10 Module 3: Kernel Features

Thread Priority (continued)

Windows CE 2.x

Supported eight priorities – 0 to 7

Use the SetThreadPriority(hThread, nPriority) function to set the priorities

Windows CE 3.0 and higher

Supports 256 Priorities – 0 (real-time) to 255

Uses CeSetThreadPriority(hThread, nPriority) function to set priorties

With previous versions of Windows CE, you used to set a version by specifying a symbolic constant like THREAD_PRIORITY_TIME_CRITICAL (highest priority) and THREAD_PRIORITY_IDLE (lowest priority). If you look in the include file, winbase.h, you find the following values:

#define THREAD_PRIORITY_TIME_CRITICAL 0 #define THREAD_PRIORITY_IDLE 7

Windows CE.NET does not have 256 symbolic constants. Instead, you use integer values 0 to 255 to specify priorities, where 0 signifies the highest priority and 255 signifies the lowest priority.

The eight priorities – 0 to 8 – in Windows CE 2.x get mapped to the lowest eight priorities – 248 to 255 – in Windows CE 3.0 or higher version. For example, you can run a program written for Windows CE 2.x on Windows CE 3.0 or higher version. Such a program sets its priorities by calling SetThreadPriority(). For example:

SetThreadPriority(hThread, 0); // 0 is the highest priority

If you call the equivalent Windows CE .NET function with the same parameters, the output will remain the same. For example,

CeSetThreadPriority(hThread, 248); // 0 is the highest priority In other words, to access the highest thread priorities in Windows CE 3.0 or higher version, you must call the new thread priority function: CeSetThreadPriority.

The default thread priority is 251. Each of the two following lines of code set the thread priority to 251 when running on Windows CE 3.0:

Topic Objective To define thread priorities in Windows CE .NET.

Lead-in Windows CE .NET uses thread priorities to schedule its tasks.

Delivery Tip Some drivers have default priorities set in the registry

Page 15: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 11

SetThreadPriority (hThread, THREAD_PRIORITY_NORMAL); CeSetThreadPriority (hThread, 251);

Page 16: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

12 Module 3: Kernel Features

Priority Inversion Handling

Time

Priority

A

BAcquires

Mutex

Blocks on Mutex

Acquires Mutex

Frees Mutex

Mutex

C

Windows CE supports priority inversion, which refers to a situation in which the use of a mutex, critical section, or semaphore resource by a lower-priority thread delays the execution of a higher-priority thread, when both are contending for the same resources. To correct this situation and free the higher-priority thread, Windows CE allows the lower-priority thread to inherit the more critical thread's priority and run at the higher priority until it releases its use of the resource. Because an unbounded amount of time is needed to relinquish the inverted thread and it is out of the control of the kernel, the OEM loses control of the scheduling process. To guarantee real-time performance, OEMs should ensure that a priority inversion condition does not occur.

Topic Objective To introduce the concept of priority inversion for threads.

Lead-in When using synchronization objects, there is an inherent issue with thread priority levels.

Page 17: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 13

Thread Quantum Control

Quantum defines the duration of time sliceDefault Quantum Value

Windows CE .NET uses a default value of 100msDuring call to OEMInit(), OEM can override this valueOverride by setting dwDefaultThreadQuantum

Applications Can Override for individual threads:DWORD CeGetThreadQuantum();BOOL CeSetThreadQuantum(HANDLE hThread, DWORD dwTime)

The thread quantum is the duration of the scheduler's time slice.

Each Windows CE .NET system has a default quantum, which is set in the OEM Adaption Layer (OAL) in the call to OemInit by setting the dwDefaultThreadQuantum global variable.

In addition, individual threads can query and set the time slice by calling the CeSetThreadQuantum function. This function is defined as follows:

WINBASEAPI BOOL WINAPI CeSetThreadQuantum(HANDLE hThread, DWORD dwTime); The first parameter, hThread, is either a thread handle returned by the call to CreateThread, or – for the currently executing thread – the value returned by GetCurrentThread.

The second parameter, dwTime, is the duration in milliseconds.

Incidentally, there has been an important change to the Windows CE scheduler. In Windows CE 2.0, threads with the highest priority – that is, threads with a priority of THREAD_PRIORITY_TIME_CRITICAL – always run to completion. This is no longer true on Windows CE.NET.

Under Windows CE 3.0, any thread to become a run-to-completion thread by setting the thread quantum to zero. Such threads can still be interrupted by higher priority threads, but will never be interrupted to allow other threads at the same priority to run.

Topic Objective To describe the thread quantum control.

Lead-in The thread quantum is the duration of the scheduler's time slice.

zhoulz
Highlight
Page 18: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

14 Module 3: Kernel Features

Thread APIs

Call CreateThread function to create a thread

lpsa points to a SECURITY_ATTRIBUTES structure, for the thread security dwStack is the stack size. If ZERO, the process default is used lpfn is the thread entry point lpParam is the parameter to be passed to the thread entry point function dwCreate is a flag field lpThreadID points to a DWORD location for the return value, the thread ID

HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpsa, DWORD dwStack,LPTHREAD_START_ROUTINE lpfn, LPVOID lpParam, DWORD dwCreate,LPDWORD lpThreadID)

HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpsa, DWORD dwStack,LPTHREAD_START_ROUTINE lpfn, LPVOID lpParam, DWORD dwCreate,LPDWORD lpThreadID)

You can create a thread by calling CreateThread. The CreateThread function has the most features and requires the most parameters:

HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpsa, DWORD dwStack, LPTHREAD_START_ROUTINE lpfn, LPVOID lpParam, DWORD dwCreate, LPDWORD lpThreadID)

lpsa lpsa points to a SECURITY_ATTRIBUTES structure, for the thread security.

dwStack dwStack is the stack size. If ZERO, the process default is used.

lpfn lpfn is the thread entry point. Declare as follows: DWORD WINAPI ThreadMain (LPVOID lpParam) {...}

lpParam lpParam is the parameter to be passed to the thread entry point function.

dwCreate dwCreate is a flag field. The only defined value is CREATE_SUSPENDED, which creates the thread in a suspended state.

lpThreadID lpThreadID points to a DWORD location for the return value, the thread ID.

Topic Objective To introduce the functions used with threads.

Lead-in Here are the functions you will use from your drivers and applications to implement threads on your system.

Page 19: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 15

Fibers Run in the context of the threads that schedule them

Each thread can schedule multiple fibersDoes not have the same state information as that is associated with a thread

Are not preemptively scheduled You schedule a fiber by switching to it. Call SwitchToFiber

ConvertThreadToFiberMust be called before scheduling the first fiber to create an area that stores fiber state information

CreateFiberIs used to create a new fiber from an existing fiber

DeleteFiberCleans up the data associated with a fiber

Fibers run in the context of the threads that schedule them. Each thread can schedule multiple fibers. In general, fibers do not provide advantages over a well-designed multithreaded application. However, using fibers can make it easier to port applications that were designed to schedule their own threads.

From a system standpoint, a fiber assumes the identity of the thread that created it. For example, if a fiber accesses thread local storage (TLS), it is accessing the thread local storage of the thread that created it. In addition, if a fiber calls the ExitThread function, the thread that created it exits. However, a fiber does not have all the same state information associated with it as that associated with a thread. The only state information maintained for a fiber is its stack, a subset of its registers, and the fiber data provided during fiber creation. The saved registers are the set of registers typically preserved across a function call.

Fibers are not preemptively scheduled. You schedule a fiber by switching to it from another fiber. The system still schedules threads to run. When a thread running fibers is preempted, its currently running fiber is preempted. The fiber runs when its thread runs.

Before scheduling the first fiber, call the ConvertThreadToFiber function to create an area in which to save fiber state information. The calling thread is now the currently executing fiber. The stored state information for this fiber includes the fiber data passed as an argument to ConvertThreadToFiber.

The CreateFiber function is used to create a new fiber from an existing fiber; the call requires the stack size, the starting address, and the fiber data. The starting address is typically a user-supplied function, called the fiber function that takes one parameter (the fiber data) and does not return a value. If your fiber function returns, the thread running the fiber exits. To execute any fiber created with CreateFiber, call the SwitchToFiber function. You can call SwitchToFiber with the address of a fiber created by a different thread. To do this, you must have the address returned to the other thread when it called CreateFiber and you must use proper synchronization.

Topic Objective To introduce a new v4.0 concept called Fibers.

Lead-in Fibers are used by applications developers when they wish to manually schedule their own thread.

zhoulz
Highlight
Page 20: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

16 Module 3: Kernel Features

A fiber can retrieve the fiber data by calling the GetFiberData macro. A fiber can retrieve the fiber address at any time by calling the GetCurrentFiber macro.

To clean up the data associated with a fiber, call the DeleteFiber function. You must take care when calling DeleteFiber. If you call DeleteFiber for a fiber created by another thread, you can cause the other thread to terminate abnormally. If DeleteFiber is called from the currently running fiber, its thread calls ExitThread.

Page 21: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 17

Protecting Applications

Protected APIs

Certifying Trust

Another feature of kernel allows you to protect your applications and device from malicious applications. To accomplish this, the feature uses the certification security system.

Topic Objective To describe the measures that can be used to protect the Windows CE .NET applications.

Lead-in The measures that can be used to protect the Windows CE .NET applications are...

Page 22: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

18 Module 3: Kernel Features

Protected APIs

To implement trusted environment:Use OEMCertifyModuleInit and OEMCertifyModuleOEM functionsUse CeGetCurrentTrust and CeGetCallerTrust APIsCertify applications at load time with signature verification

Values returned by the OEMCertifyModule function are:OEM_CERTIFY_TRUST OEM_CERTIFY_RUN OEM_CERTIFY_FALSE

To create a trusted environment, an original equipment manufacturer (OEM) must implement two OEM functions: OEMCertifyModuleInit and OEMCertifyModule. Once these two functions are implemented, the kernel streams every module (DLL or EXE) that does not exist in a MODULES section of a .bin file to the OEM. The OEM can then implement the type of security needed to protect the system. The kernel expects the OEM to identify which applications and modules should be trusted, not trusted, or not loaded.

In addition to the OEM functions, there are two additional Application Programming Interface (APIs) that are supported: CeGetCurrentTrust and CeGetCallerTrust. These APIs enable a DLL to query the trust level of a calling application. This in turn enables a DLL to restrict an application from executing untrusted applications.

You can certify applications at load time with signature verification to protect your system from unfamiliar applications. This verification ensures that your Windows CE-based platform loads an application only if it contains a valid digital signature. The load-time signature verification functions enable you to:

Create a valid signature Embed the signature in a .dll or .exe file Verify that an application contains a valid signature.

To create a digital signature from a file, run the file through a hash function, and then sign the resulting hash with a private key. An easy way to create a digital signature from a file is to use Signfile.exe, which is included in Platform Builder. Signfile.exe is a tool for signing an executable file with a private key supplied by a CSP.

To support load-time signature verification, you must implement the OEMCertifyModuleInit and OEMCertifyModule functions. OEMCertifyModule returns the following values:

Topic Objective To describe the protected APIs.

Lead-in To implement a trusted environment use…

Page 23: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 19

OEM_CERTIFY_TRUST This value signifies that the application is trusted by the OEM to perform any operation.

OEM_CERTIFY_RUN This value signifies that the application is trusted by the OEM to run, but is restricted from making certain function calls.

OEM_CERTIFY_FALSE This value signifies that the application is not trusted by the OEM, therefore, is not allowed to run.

Page 24: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

20 Module 3: Kernel Features

Certifying Trust

OEMCertifyModule function:

Allows the platform creator to control the criteria for establishing or withholding trust

Untrusted Applications:

Cannot call CeSetThreadPriority

Cannot call CeSetThreadQuantum

Checking Trust:

DWORD CeGetCurrentTrust(void);

DWORD CeGetCallerTrust(void);

0 = None, 1 = Some, 2 = All

There are quite a few restrictions put on DLLs and EXEs based on trust, however there are two things that untrusted applications cannot do.

When a platform is created, the OEMCertifyModule function allows the platform creator to control the criteria for establishing or withholding trust.

To check the default trust and the trust for the currently executing module, you call these two functions:

CeGetCurrentTrust. This function gets the default. CeGetCallerTrust. This function gets the current module's trust level.

Incidentally, strictly speaking this is a Windows CE 2.12 feature and not Windows CE 3.0.

A module is restricted from calling the following functions if it is not trusted:

CeSetThreadPriority CeSetThreadQuantum DebugActiveProcess ForcePageout LockPages PowerOffSystem ReadProcessMemory SetCleanRebootFlag SetInterruptEvent SetKMode SetProcPermissions SetSystemMemoryDivision UnlockPages

Topic Objective To introduce the OAL component necessary for Trust.

Lead-in To implement a trusted system, you must have an OAL capable of managing it.

Page 25: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 21

VirtualCopy WriteProcessMemory

In addition, the CreateProcess debug flags DEBUG_ONLY_THIS_PROCESS and DEBUG_PROCESS are restricted. If these flags are used by a non-trusted application the identified process still launches, but it does not debug.

Windows CE prevents untrusted applications from changing registry keys or values in certain crucial registry directories. These registry directories are protected and can only be modified by applications certified as trusted by the OEM. Untrusted applications are unable to modify keys or values in the following protected registry directories or in any of their subdirectories:

HKEY_LOCAL_MACHINE\Comm HKEY_LOCAL_MACHINE\Drivers HKEY_LOCAL_MACHINE\HARDWARE HKEY_LOCAL_MACHINE\SYSTEM HKEY_LOCAL_MACHINE\Init HKEY_LOCAL_MACHINE\WDMDrivers HKEY_LOCAL_MACHINE\Servers

Untrusted applications receive the ERROR_ACCESS_DENIED error code if applications attempt to use the following registry functions in any of the above registry directories:

RegSetValueEx RegCreateKeyEx RegDeleteKey RegDeleteValue

All applications, including unauthorized applications, are able to read any registry key or value.

Because the rest of the registry is unprotected, OEMs should place all important registry information in the protected registry directories.

The following lists trusted APIs:

SetInterruptEvent CeSetThreadPriority CeSetThreadQuantum ForcePageout VirtualCopy LockPages UnlockPages SetProcPermissions SetKMode ReadProcessMemory WriteProcessMemory SetCleanRebootFlag CreateFileMapping DebugActiveProcess DeleteAndRenameFile DeleteFile RemoveDirectory CreateFile MoveFile SetFileAttributes CopyFile CryptUnprotectData

Page 26: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

22 Module 3: Kernel Features

SetCurrentUser SetUserData

File based APIs are based on a file having the SYSTEM attribute set.

Note

Page 27: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 23

Synchronization Objects

Why Synchronize?

Synchronizing with Critical Sections

Synchronizing with Mutexes

Synchronization Enhancements

When dealing with a multithreaded operating system, a scenario exists where multiple threads attempt to access the same resource. In order to guarantee stable results, you must synchronize access to this resource.

Topic Objective To define the need for synchronization.

Lead-in You will often need to use synchronization objects to ensure the accurate handling of resources.

Page 28: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

24 Module 3: Kernel Features

Why Synchronize?

WinMain(HANDLE hInstance, …){

CreateThread(…, A_Main, …);CreateThread(…, B_Main, …);

}

DWORD WINAPI A_Main(LPVOID p){

for(x=0;x<100000;x++){ /* ...Work...*/ }

}

DWORD WINAPI B_Main(LPVOID p){

for(x=1000;x>0;x--){ /* ...Work...*/ }

}

int x;

The need to synchronize can best be demonstrated with an example. Any discussion of synchronization requires two things: a shared resource, and two or more threads that access that resource.

The Shared Resource For the sake of simplicity, the shared resource in this example is the global variable x. It is declared outside the boundaries of any function, so it is visible to all functions.

The Threads The code in this example represents three threads. WinMain is the entry point for a Win32 process, replacing main. When a process starts, it always gets one thread for free. After that, calling the CreateThread function creates threads. When you call CreateThread, you always pass a function name. In the two calls shown in the example, A_Main and B_Main are the two entry points for the two threads.

Both threads are accessing global variable x.

Topic Objective To explain the need for synchronizing

Lead-in Here is a simple example of showing a potential synchronization problem.

Page 29: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 25

Synchronizing with Critical Sections

CRITICAL_SECTION cs;WinMain(HANDLE hInstance, …){InitializeCriticalSection(&cs);CreateThread(…, A_Main, …);CreateThread(…, B_Main, …);

}

DWORD WINAPI A_Main(LPVOID p){

EnterCriticalSection(&cs);for(x=0;x<100000;x++)

{ /* ...Work...*/ }LeaveCriticalSection(&cs);

}

DWORD WINAPI B_Main(LPVOID p){

EnterCriticalSection(&cs);for(x=1000;x>0;x--)

{ /* ...Work...*/ }LeaveCriticalSection(&cs);

}

int x;

One way to solve the synchronization problem is to use critical sections as shown in this example.

About Critical Sections A critical section is a process-specific object. You can use it to coordinate the activity between two threads in the same process, but not two threads in different processes. You define it as a global variable, for example, cs, in the above example. Then, you start it up by calling InitializeCriticalSection.

Why Critical Section works? Only one thread can own a critical section at any time. You gain ownership by calling EnterCriticalSection, and relinquish ownership by calling LeaveCriticalSection. If one thread already owns the critical section, the other thread – upon calling EnterCriticalSection – is blocked and stopped from running until the first thread lets it go.

Enhancements Starting in Windows CE 3.0 additional support for the TryEnterCriticalSection function exists. This function allows a thread to verify if a critical section is available. If it is, then the thread gains ownership of the critical section. Otherwise, the thread becomes available for other tasks. This provides a bit more flexibility than EnterCriticalSection, which keeps a thread in a blocked state until the critical section becomes available.

How Critical Section Can Break Down? This is not a perfect system. It is an opt-in protection mechanism. It is easy for a third piece of code to access global variable x without requesting ownership of the critical section. To get total protection, you may want to embed this code in a library or some kind of encapsulated object.

Topic Objective To describe the use of critical sections.

Lead-in One way to solve the synchronization problem is to use critical sections as shown in this example.

zhoulz
Highlight
Page 30: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

26 Module 3: Kernel Features

Synchronizing With Mutexes HANDLE hMutex;WinMain(HANDLE hInstance, …){

hMutex = CreateMutex(…);CreateThread(…, A_Main, …);CreateThread(…, B_Main, …);

}

DWORD WINAPI A_Main(LPVOID p){

WaitForSingleObject(hMutex,…);for(x=0;x<100000;x++){ /* ...Work...*/ }ReleaseMutex(hMutex);

}

DWORD WINAPI B_Main(LPVOID p){

WaitForSingleObject(hMutex,…);for(x=1000;x>0;x--){ /* ...Work...*/ }ReleaseMutex(hMutex);

}

int x;

The code in the slide shows how a mutex can play the same role as a critical section. A mutex can also be used to coordinate access to a shared resource. So why are there two such objects?

Obtaining Mutex Ownership To gain access to the resource that the mutex protects, a thread calls WaitForSingleObject. This function returns when either the resource becomes available, or the timeout expires. The timeout is specified in milliseconds as a parameter to the function.

A related function, WaitForMultipleObjects, lets you wait on more than one object.

Releasing Mutex Ownership To release mutex ownership and allow other threads to gain ownership, a thread calls the ReleaseMutex function.

Critical Sections and Mutexes Compared The most significant difference between critical sections and mutexes is that the critical section is part of the address space of a process. The critical section is a global variable. As such, critical section can only be used to synchronize between the threads in a single process. Mutexes, however, can go across process boundaries. The advantage that a Critical Section offers over a mutex is that a critical section is faster than a mutex. Drivers often use critical Sections because a device driver is often only in one process.

Topic Objective To show how the structure of the code for a mutex is identical to the code structure used for critical sections.

Lead-in Another synchronization object that you can use to guard access to shared objects is the mutex.

Note

Delivery Tip It is important to note the difference between Critical Sections and Mutexes.

zhoulz
Highlight
Page 31: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 27

Synchronization Enhancements

TryEnterCriticalSection() Allows only one thread to own a given critical sectionMakes it safer to request a critical section since it is non-blocking

SemaphoresAre mutexes with a count Are useful if you wish to limit the number of threads that can access a resource.

The two main improvements in synchronization are TryEnterCriticalSection() and semaphores.

TryEnterCriticalSection() TryEnterCriticalSection() attempts to enter a critical section without blocking. If the call is successful, the calling thread takes ownership of the critical section. As you may already know, critical sections are used as stop signs for the threads within a process. Only one thread may own a given critical section. This function, which has existed on desktop Windows for a while, makes it safer to request a critical section since it is non-blocking.

Semaphores Semaphores are mutexes with a count. Windows CE starting in version 3.0 provides a support for semaphores. A semaphore might be useful, if you wish to limit the number of threads that can access a resource. For example, to avoid performance bottlenecks a web server might limit the number of threads that can access a particular set of pages.

Topic Objective To explain the enhancements in Synchronization that are available in Windows CE .NET.

Lead-in Let us take a look at some other improvements that are made to the Windows CE schedule. The two improvements for synchronization support include…

Page 32: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

28 Module 3: Kernel Features

Memory Model

Physical Memory

Virtual Memory

In this section, you will learn about physical to virtual mapping used by the Windows CE kernel in memory mapping.

Topic Objective To describe how Windows CE kernel performs memory mapping.

Lead-in In this section, you will learn about physical to virtual mapping used by the Windows CE kernel in memory mapping.

Page 33: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 29

Physical Memory

64 MBRAM

32 MBFlash

Dbg Serial Port2 GBUser

512 MBUncached

512 MBCached

64 MB RAM

32 MB Flash

64 MB RAM

32 MB Flash

Physical MemoryKernel Virtual Address

Reserved

04000000

82000000

80000000

80000000

A0000000

C0000000

0

Windows CE is built to use both ROM, also known as flash memory, and RAM.

ROM The Platform Builder creates an operating system image for loading into ROM or flash memory. During developing, the contents of ROM or flash get stored in a file called NK.BIN. The Platform Builder BIB files have a MEMORY section that positions the ROM image in the virtual address space.

RAM Available RAM gets split into two parts:

Object store Program memory

The Windows CE object store is further divided into three parts:

A File system The Registry Windows CE databases

Topic Objective To explain how Windows CE is built to use physical memory

Lead-in Windows CE is built to use both ROM, also known as flash memory, and RAM.

Page 34: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

30 Module 3: Kernel Features

Virtual Memory

Memory Mapping(Shared)

Reserved

Slot 32:Process32

.

.

.

Slot 1:Process1

Slot 0:Active Process

2GB

2GB

32MB

Virtual memory managementWindows CE .NET provides only one virtual address space of 4 GB for all the applications it uses

Using virtual memoryAllocate large blocks of memory

Does not fragment

Windows CE .NET manages virtual memory in 64 KB blocks

Using the local heapIs a region of reserved virtual memory space that Windows CE .NET manages for your application

Using the stackIs the storage area for variables that are referenced in a function

Windows CE.NET is a protected mode operating system and therefore all threads have access only to Virtual Memory.

Virtual Memory Management Windows CE .NET provides only one virtual address space of 4 GB for all the applications it uses. This address space is divided into two parts of 2 GB each. The upper part is reserved for the system. The lower part is shared between all of the applications.

At the beginning of the virtual address space are 33 slots of 32 MB each. Slots 1 to32 correspond to applications 1to 32. This means that each application has only 32 MB of private address space. Slot 0 is a special slot that represents the memory of the current active process.

Each slot is divided into 512 blocks. Each block is a region of 64 KB. Each block is in turn divided into pages of 1 KB or 4 KB, depending on the processor being used. These pages are mapped to physical memory.

The area extending from the end of slot 32 to the 2 GB limit is shared, and is used for file mapping, shared memory, and large memory mapping.

Using Virtual Memory Use the virtual memory API to allocate large blocks of memory. The advantage of using virtual memory is that it does not fragment. Windows CE is always allocated an integral number of pages. Because Windows CE .NET manages virtual memory in 64 KB blocks, you must ensure that you use all of the memory efficiently. Also, Windows CE requires a slight overhead for managing the memory mapping.

The following represent the functions used in virtual memory management:

VirtualAlloc VirtualAlloc reserves and commits virtual memory.

Topic Objective To explain how virtual memory is managed by the kernel.

Lead-in Windows CE.NET is a protected mode operating system, therefore, all threads have access only to Virtual Memory.

Delivery Tip User process can only access Virtual Memory directly.

zhoulz
Highlight
zhoulz
Highlight
Page 35: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 31

VirtualQuery VirtualQuery determines the read/write status of a virtual memory page.

VirtualProtect VirtualProtect alters access rights on committed pages.

VirtualFree VirtualFree frees virtual memory.

VirtualCopy VirtualCopy maps virtual addresses to physical addresses.

Using the Local Heap A heap is a region of reserved virtual memory space that Windows CE .NET manages for your application. The original heap is called the local heap. Unlike VirtualAlloc, you can allocate memory on a heap in 4-byte or 8-byte units, depending on your CPU type. In addition to being more efficient for small sizes, the heap can help you avoid having to deal with the different sizes of memory pages that different microprocessors support. The heap also has no set limit. However, any heap allocations greater than 192 KB are made by calling the VirtualAlloc function. If you attempt to allocate more memory than Windows CE originally set aside for a heap, the system tries to find unreserved memory. As with virtual memory mapping, this memory might not be physically located next to the original heap. Also, because Windows CE allocates memory in fixed blocks, the heap may become fragmented over time.

Use the local heap when you need to allocate specific sizes of memory on a regular basis.

Because Windows CE reclaims a memory page only if that page is totally free, be sure that you deallocate memory blocks correctly when you are using the heap. This becomes an issue with applications that run for a long time, such as applications designed for the PocketPC.

To allocate and deallocate memory using the local heap:

1. Call the LocalAlloc function with the size of the memory block passed in the uBytes parameter. LocalAlloc returns a handle to the virtual memory block that is allocated to your application. Windows CE also maps the virtual memory block to a physical memory block at this time.

2. Call LocalLock to convert a memory handle to a memory pointer, which you need to use to access the memory allocated to your application.

3. If necessary, call the LocalSize and LocalReAlloc functions to reallocate the local heap memory.

4. If you need to increase the size of a block, call LocalSize to determine if the block contains enough space. Then, call LocalReAlloc to either add memory to the top of the allocation or move the block to a larger area.

5. Call the LocalUnlock function followed by the LocalFree function to return the memory to Windows CE.

Note

zhoulz
Highlight
zhoulz
Highlight
zhoulz
Highlight
zhoulz
Highlight
zhoulz
Highlight
Page 36: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

32 Module 3: Kernel Features

Using the Stack The stack is the storage area for variables that are referenced in a function. Windows CE allocates memory for a variable from the stack and then deallocates the memory after the function call is complete. When a thread or process begins, Windows CE allocates one page of memory to the stack for that thread. Each thread has a stack, and the default size for each stack is 65K. However, you can override this size for any application by using the /STACKSIZE linker switch.

Page 37: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 33

Structured Exception Handling

__try {

// Protected block.

}__except (/* filter */ )

{

// Exception handler.

}

__try {

// Protected block.

}__except (/* filter */ )

{

// Exception handler.

}

_try_exceptException handler

The code illustration on the slide shows the syntax of a try-except pair.

__try The __try statement precedes a compound statement that makes up the protected block. This compound statement can contain any combination of C function calls, nested exception blocks, and nested termination blocks. One restriction is that jumping - using a goto - into the body of a try block is not permitted. If any exceptions occur within the try block, the exception becomes a candidate for being handled by the exception handling code.

__except The __except statement precedes the filter expression. The role of a filter expression is to check for exceptions that the exception handler is equipped to handle. This expression can be any combination of function calls and (comma-separated) assignment statements. The final result must be one of the following:

EXCEPTION_EXECUTE_HANDLER Execute exception handler.

EXCEPTION_CONTINUE_SEARCH Pass control to next filter.

EXCEPTION_CONTINUE_EXECUTION Restart offending instruction.

Exception Handler The exception handler is a compound block made up of any combination of C statements, including C function calls, nested exception blocks, and nested termination blocks. Just like the try-block, you cannot jump into the middle of an exception handler.

Topic Objective To explain structured exception handling.

Lead-in In order to keep your system from halting when your application throws an exception, you should implement the following system.

Page 38: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

34 Module 3: Kernel Features

Structured Exception Handling: Filter

__try {......

......

}__except ( )

{..................}

// hard code a value__except (EXCEPTION_EXECUTE_HANDLER)

// hard code a value__except (EXCEPTION_EXECUTE_HANDLER)

// call a function__except (CheckIt(GetExceptionCode())...int CheckIt (DWORD dwCode) {switch (dwCode) {

case xxxx:...}

return EXCEPTION_EXECUTE_HANDLER;}

// call a function__except (CheckIt(GetExceptionCode())...int CheckIt (DWORD dwCode) {switch (dwCode) {

case xxxx:...}

return EXCEPTION_EXECUTE_HANDLER;}

// expression__except((GetExceptionCode()==

EXCEPTION_ACCESS_VIOLATION)? EXCEPTION_EXECUTE_HANDLER: EXCEPTION_CONTINUE_SEARCH)

// expression__except((GetExceptionCode()==

EXCEPTION_ACCESS_VIOLATION)? EXCEPTION_EXECUTE_HANDLER: EXCEPTION_CONTINUE_SEARCH)

The filter expression determines how a particular exception is handled.

Valid Return Values A filter expression must return one of the following three values, depending on how a particular exception is to be handled:

EXCEPTION_EXECUTE_HANDLER Execute exception handler.

EXCEPTION_CONTINUE_SEARCH Pass control to next filter.

EXCEPTION_CONTINUE_EXECUTION Restart offending instruction.

Filter Expression As shown in the figure, a filter expression could be:

• A hard-coded return value • The result of an expression, or • A call to a function, which would then return one of the three valid return

values.

Topic Objective To describe the role of the filter expression.

Lead-in The filter expression determines how a particular exception is handled.

Page 39: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 35

Structured Exception Handling: Exception API

Create an exception

Query exception

Query abnormal termination

Query exception information

VOID RaiseException(dwCode, dwFlags, cArgs, lpArgs)VOID RaiseException(dwCode, dwFlags, cArgs, lpArgs)

DWORD GetExceptionCode (VOID)DWORD GetExceptionCode (VOID)

BOOL AbnormalTermination (VOID)BOOL AbnormalTermination (VOID)

LPEXCEPTION_POINTERS GetExceptionInformation (void)LPEXCEPTION_POINTERS GetExceptionInformation (void)

Here are some functions which support exception handling.

Creating an Exception If you define your own exceptions, you can raise them by calling RaiseException. This function is defined:

VOID RaiseException (DWORD dwCode, DWORD dwFlags, DWORD cArgs, LPDWORD lpArgs)

dwCode dwCodeis the exception code.

dwFlags dwFlags is a flag field that can be ZERO or EXCEPTION_NONCONTINUABLE, when an instruction cannot be restarted.

cArgs cArgs is a count of the arguments in the DWORD array pointed to by lpArgs.

lpArgs lpArgs is a pointer to an array of DWORD arguments (NULL is OK also).

Query an Exception Code The GetExceptionCode function returns the exception code that caused an exception to be raised. This function can only be called within a filter expression or within the exception handler.

Topic Objective To describe the functions that support exception handling.

Lead-in Use these functions with exception handling.

Page 40: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

36 Module 3: Kernel Features

DWORD GetExceptionCode (VOID)

Query for Abnormal Termination For use with a termination handler, the AbnormalTermination function returns TRUE when a try block was abnormally terminated. Abnormal termination means that either an exception occurred, or control was passed using return, break, goto, or continue.

BOOL AbnormalTermination (VOID)

Query Exception Information Call GetExceptionInformation to find all the details of an exception - including any parameter information that was passed to RaiseException. This function, which can only be called within a filter expression, is defined:

LPEXCEPTION_POINTERS GetExceptionInformation (VOID) The return value is a pointer to a data structure of type.

EXCEPTION_POINTERS, defined as:

typedef struct _EXCEPTION_POINTERS PEXCEPTION_RECORD ExceptionRecord; PCONTEXT ContextRecord; } EXCEPTION_POINTERS;

Page 41: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 37

Optimizing a Windows CE Device

Optimizing Tips

Measurement APIs

Measurement Tools

Timer Resolution

You can improve the performance of the Windows CE device for real time by using measurement tools and APIs. You can also use certain tips to optimize your code for Windows CE .NET real-time performance.

Topic Objective To discuss the optimizing techniques that can be used with Windows CE .NET

Lead-in The optimizing techniques that can be used with Windows CE.NET include implementing optimizing tips, monitoring deadlines using measurement tools and measurement APIs.

Page 42: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

38 Module 3: Kernel Features

Optimizing Tips Avoid priority inversion

Avoid file I/O from RT threadsAvoid graphic calls from RT threadsAvoid UI calls from RT threads

Pre-allocate memoryPre-allocate heap memoryPre-commit stack memory

Control pagingUse LoadDriver()- not LoadLibrary()- to load all the pages of a DLLUse LockPages() for individual pages

Optimizing tips help you to optimize your code for Windows CE .NET real-time performance.

Avoid Priority Inversion While priority inversion helps avoid deadlock, it does come at a performance cost. The key is to avoid that cost in order to minimize delays.

Priority inversion occurs because a higher priority thread must wait for a lower priority thread to release an owned synchronization object. On the one hand, synchronization is needed to protect shared resources from being ripped apart in a tug of war between competing threads. On the other hand, it also forces some threads to wait. But waiting for time-critical threads can result in missing deadlines.

To eliminate priority inversion that might result in unexpected and perhaps unusually long delays, you must avoid using synchronization objects. In particular, avoid using synchronization objects in threads that have time-critical deadlines, and avoid using them on the critical path to a time-critical deadline. For this to work, hurried and harried threads should avoid making calls to system services, including file I/O, graphical output, and user-interface calls. These calls might require a wait on a synchronization object.

Pre-allocate Memory Memory allocation takes time. How much time is hard to say. For this reason, you want to allocate memory before the deadlines start arriving.

Control Paging Another type of memory to get under control is any memory that might get paged. The LoadDriver function loads all the pages of a DLL, including code and data pages, and then locks them in memory. There is a cost, of course, in terms of system memory used. But the benefit is more consistent timing results.

Topic Objective To provide the optimizing tips that must be used while implementing Real-time systems

Lead-in To optimize the code for Windows CE3.0, implement the optimizing tips that include…

Page 43: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 39

For individual pages, you can use the LockPages function. This is useful for code or resource (read-only data) pages. Read/write data pages are never paged in Windows CE and so you never need to lock them. For very large DLLs, the use of LockPages might be better than locking the whole module in memory with LoadDriver.

Page 44: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

40 Module 3: Kernel Features

Optimizing Tips (continued)

Trusted application model

Degrades performance as there is overhead involved in switching from trusted to non-trusted applications

Do not use trusted application model in a real-time application

Thread priorities and ISR levels

Map system thread priorities and ISR levels

Assures that the highest priority event takes place before any other processing

Trusted Application Model The use of the Trusted Application model when you are building a Real Time system must be architected correctly. Be careful using untrusted applications in a trusted system. This will degrade performance as there is overhead involved in switching from trusted to non-trusted applications. However a trusted system running only trusted applications can be fastest.

Thread Priorities and ISR Levels When you are finished implementing all functionality on your system, it is often useful to go back and map all your system thread priorities and ISR levels. This assures that the highest priority event takes place before any other processing.

Topic Objective To introduce some more real world tips for students.

Lead-in Some more things to consider when optimizing your device…

Page 45: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 41

Measurement APIs

QueryPerformanceFrequency()

Returns Ticks per Second

Returns zero if there is no support for a high-performance counter

QueryPerformanceCounter()

Returns Current tick count

GetTickCount()

Provides a millisecond resolution counter

The three functions that can be called to help in benchmarking are:

QueryPerformanceFrequency() QueryPerformanceCounter() GetTickCount()

The purpose of this set of functions is to help you with your own timing tests.

QueryPerformanceFrequency() This function returns the counts per second that are available from the high-resolution performance counter. It returns zero if there is no support for a high-performance counter.

To define a high-performance counter, in the OAL (in OEMInit) you set the global variable pQueryPerformanceFrequency to the address of your OEMQueryPerformanceFrequency function. This is the function that gets called when a call is made to QueryPerformanceFrequency.

QueryPerformanceCounter() Call this function to determine the current value of the high-resolution performance counter.

To define a high-performance counter, in the OAL (in OEMInit) you set the global variable pQueryPerformanceCounter to the address of your OEMQueryPerformanceCounter function. This is the function that gets called when a call is made to QueryPerformanceCounter.

GetTickCount() This provides a millisecond resolution counter (1000 ticks per second), and is the default for QueryPerformanceCounter if

Topic Objective To describe the functions of measurement APIs.

Lead-in The three functions that can be called to help in benchmarking are…

Page 46: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

42 Module 3: Kernel Features

OEMQueryPerformanceCounter and OEMQueryPerformanceFrequency are not provided in the OAL.

Page 47: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 43

Measurement Tools

ILTIMING Can be used to check interrupt latencyDetermines the ISR and the IST latencies \wince400\public\common\oak\utils\iltiming

OSBENCH Performs a series of timing tests including thread scheduling Displays the results to the debug stream. \wince400\public\common\oak\utils\osbench

When there are time deadlines that a system must meet, you must take measurements to make sure that you are on track to meet the deadlines. You can use the following resources to help you with real-time performance:

ILTIMING OSBENCH

ILTIMING You can use ILTIMING to check interrupt latency. This tool determines both the ISR and the IST latencies. Output is sent to the debug stream, which can be viewed from within the debugger. ILTIMING is a dynamic link library, and you must call from an application program (.EXE) in order to make it work. The Platform Builder provides a simple application, IT_LOAD, that loads and runs ILTIMING.DLL.

OSBENCH This tool, which builds as OSBENCH.DLL, does a series of timing tests and dumps the results to the debug stream. The 40+ tests that OSBENCH perform include timings of critical sections, mutexes, and thread scheduling. The Platform Builder provides an application to load the library, OB_LOAD, which loads and runs OSBENCH.DLL.

Topic Objective To list the measurement tools that help in optimizing real-time systems.

Lead-in The two measurement tools used to check the time deadlines are ILTIMING and OSBENCH.

Delivery Tip The output of ILTIMING is viewed in the kernel debugger output window.

Page 48: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

44 Module 3: Kernel Features

Timer Resolution

Sleep(int nMilliseconds)

1 ms granularity

Avoid SetTimer()

Not Real Time

Message-based, UI-oriented timer

Sleep(100); // block for 100 ms.Sleep(5); // block for 5 ms.Sleep(0); // yield quantum.

Sleep(100); // block for 100 ms.Sleep(5); // block for 5 ms.Sleep(0); // yield quantum.

Timers are important in Real-time systems, since timers give software the ability to schedule its own work without relying on external events.

In previous versions of Windows CE, the timer represented by the Sleep function had a granularity equal to the thread quantum. Windows CE 3.0 and greater has timers with a granularity of 1 millisecond.

Although the SetTimer function appears to be useful, but it is advisable that developers of real-time systems should avoid using it. It is a fairly low-priority timer that exists primarily to support the timing of end-user actions. For example, this timer is adequate to limit the amount of time that a user is given to enter a password, for example 30 seconds. However, it is not adequate for more precise, millisecond-range timing requirements.

Topic Objective To describe the role of timers.

Lead-in Timers are important in Real-time systems, since timers give software the ability to schedule its own work without relying on external events.

Page 49: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 45

Lab 3: Kernel Tracking Thread Priorities

In this lab, you will use the Kernel Tracker to watch several threads exchanging a synchronization object.

Topic Objective To introduce the lab.

Lead-in In this lab, you will use the kernel Tracker to watch several threads exchange a synchronization object.

Explain the lab objectives.

Page 50: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

46 Module 3: Kernel Features

Review

Definition of Real Time

Windows CE Kernel Features

Handling Processes, Threads, and Fibers

Protecting Applications

Synchronization Objects

Memory Model

Structured Exception Handling

Optimizing a Windows CE Device

1. For how many threads does Windows CE .NET guarantee a bounded, worse case latency on your system? For one thread – the highest priority thread.

2. Which synchronization objects are used to allow only one thread to access a shared resource? Critical sections and mutexes are commonly used for this purpose. A semaphore can also be used, if the count is set to 1.

3. How many thread priorities are available in Windows CE .NET? 256

4. What function calls are available to set thread priorities on Windows CE.NET? To access all 256 thread priorities, you must call CeSetThreadPriority.

5. How do you set the thread quantum, and what happens when it is set to zero? Call CeSetThreadQuantum to set the thread quantum. When set to zero, a thread runs to completion and is not preempted to allow other threads at the same priority to run. However a run-to-completion

Topic Objective To reinforce module objectives by reviewing key points.

Lead-in The review questions cover some of the key concepts taught in the module.

Page 51: Module 3: Kernel Features - read.pudn.comread.pudn.com/downloads100/ebook/409912/Microsoft内部WINCE... · Module 3: Kernel Features 1 Overview Definition of Real Time Windows CE

Module 3: Kernel Features 47

thread can be interrupted by interrupts and their corresponding ISRs, and higher priority threads that enter a ready to run state.

6. What tools are available to measure performance? ILTIMING.DLL measures latencies in the ISR and IST’s. OSBENCH measures a wide range of thread scheduling and synchronization object latencies. Outputs of both tools get set to the debug stream.

7. What API functions are available to measure performance? QueryPerformanceCounter and QueryPerformanceFrequency are used when a high-performance counter is available. Otherwise GetTickCount provides millisecond-accuracy timings.