RTX 5.

0
User’s Guide

VenturCom, Inc. Five Cambridge Center Cambridge, MA 02142 Tel: 617-661-1230 Fax: 617-577-1607 info@vci.com http://www.vci.com

RTX User’s Guide

No part of this document may be reproduced or transmitted in any form or by any means, graphic, electronic, or mechanical, including photocopying, and recording or by any information storage or retrieval system without the prior written permission of VenturCom, Inc. unless such copying is expressly permitted by federal copyright law.
©

2000 VenturCom, Inc. All rights reserved.

While every effort has been made to ensure the accuracy and completeness of all information in this document, VenturCom, Inc. assumes no liability to any party for any loss or damage caused by errors or omissions or by statements of any kind in this document, its updates, supplements, or special editions, whether such errors, omissions, or statements result from negligence, accident, or any other cause. VenturCom, Inc. further assumes no liability arising out of the application or use of any product or system described herein; nor any liability for incidental or consequential damages arising from the use of this document. VenturCom, Inc. disclaims all warranties regarding the information contained herein, whether expressed, implied or statutory, including implied warranties of merchantability or fitness for a particular purpose. VenturCom, Inc. reserves the right to make changes to this document or to the products described herein without further notice. RTX is a trademark and CENTer is a servicemark of VenturCom, Inc. Microsoft, MS, and Win32 are registered trademarks and Windows, Windows CE, and Windows NT are trademarks of Microsoft Corporation. All other companies and product names may be trademarks or registered trademarks of their respective holders.

RTX 5.0 User’s Guide 1-015-10

Table of Contents
WELCOME TO RTX 5.0 ................................................................................................IX Getting Support.............................................................................................................. ix
Technical Support ........................................................................................................................ ix VenturCom Web Site ................................................................................................................... ix

Documentation Updates.................................................................................................. x About the User’s Guide ................................................................................................... x CHAPTER 1 INTRODUCTION TO RTX............................................................................................... 1 The RTX Architecture...................................................................................................... 1
Real-Time Inter-Process Communication .....................................................................................2 HAL Extension...............................................................................................................................2 Uniprocessor and Multiprocessor Systems...................................................................................2

The RTX Application Programming Interface (API) ......................................................... 3
Win32 and Real-Time API.............................................................................................................3 RTX Executable Images ...............................................................................................................3 Run-Time Libraries........................................................................................................................4 Unicode .........................................................................................................................................4

Designing and Developing RTX Applications .................................................................. 4
RTX Device Drivers.......................................................................................................................4 Testing Real-Time Applications ....................................................................................................5 Creating and Starting an RTSS Process ......................................................................................5 Stopping an RTSS Process ..........................................................................................................5

CHAPTER 2 USING SOFTWARE DEVELOPMENT TOOLS .............................................................. 7 Using the RTX Utilities .................................................................................................... 8
Utility Task Table...........................................................................................................................8 RTSSrun Utility (Console and GUI) ..............................................................................................9 RTSSrun GUI ..............................................................................................................................10 RTSSkill Utility.............................................................................................................................11 RTSSview Utility..........................................................................................................................12
RTSSview Example ............................................................................................................................... 12

RTSS Object Viewer ...................................................................................................................13 RTSS Task Manager...................................................................................................................15 RtxServer ....................................................................................................................................16

Using the RTX AppWizard in Microsoft Visual Studio 6.0.............................................. 17
Creating a Project and Setting Options.......................................................................................17
Setting Project Options .......................................................................................................................... 18 Setting Program Options ....................................................................................................................... 19

Running an Image.......................................................................................................................20 Registering an RTDLL.................................................................................................................21

iii

....................................................................................................................................................29 Gencrash Driver ........................... 45 Event Objects ...............................................................................................................................................................................................................................................................................................................................................46 Using RtCreateEvent ............................................................................................................37 System Memory Allocation ................................40 Clock Services ................................................................................................................................................29 Usage ................................................................................................... 40 Timer Services............................................................................ 43 Object Names ........................................................RTX User’s Guide Using Microsoft Visual Studio 6........................................................................................................................................................................................................................................................................................................................................................... 42 Inter-Process Communication ................... 41 Sleep Services...............................................................................................................22 Building and Registering RTDLLs ...........................................................................................................................................21 Building and Running Images (Win32 Environment) .... 42 Programming Considerations ............................... 21 Setting up Microsoft Visual Studio ........................................................................................................................................................................................................................................................................................................ 35 System Memory Management ..........29 Testing an RTX Program with Shutdown Handlers................................................................................................................................................ 45 Environments........... 35 Thread Priorities ...........................................................................................................................................................................................................................................................................................................................0 with RTSS ........................ 38 Clocks and Timers ................................................... 33 Process and Thread Management ................................................ 44 Semaphores ............ 43 Environments........... 42 Programming Example (RTX Timer and Sleep Calls)..................................................................................................0....................................................34 Using Processes..................................... 26 Excluding debugging information....43 Inter-Process Communication via Shared Memory..................................................................................................25 Building an RTSS DLL ............ 42 APIs ............................26 Using Microsoft’s WinDbg 5....................................................... 34 Using Threads ............................... 37 System Memory Locking ............. 25 Building an RTDLL .................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 30 Using the RTX Properties Contol Panel ..............43 Shared Memory.................................... 46 Using RtPulseEvent.............................................................................................................................................................................................................................................................................................................25 Debugging an RTX Program ......................... 34 Processes and Threads .............................21 Building and Running Images (RTSS Environment).............................................................................................................................................................................................................................................................................................................................................................................................................44 Inter-Process Communication via Semaphores...........................................................................................................23 Creating RTX Dynamic Link Libraries ................................ 29 Shutdown Program ............. 46 iv ............................................... 30 CHAPTER 3 USING THE RTX FUNCTIONALITY ...............................................................................................................................

............................. 58 Using the C Run-time Library Functions........................................................................................................................ 53 CHAPTER 4 DEVELOPING AN APPLICATION ..................................................................................................................................... 58 RTDLLs ................... 50 Programming Example (Interrupt Management and Port I/O Calls)..................................................................................................................................................................... 51 Physical Memory Mapping ............................................................................................................................. 59 Enabling Floating-Point Support in RTSS Programs ........ 52 Programming Example (RTX Contiguous Memory Allocation Calls) ............................................ 48 APIs .................................... 49 Using RtAttachInterruptVectorEx .......................56 Using RTX Dynamic Link Libraries....................................... 51 General Programming Considerations....................................................................................................................................................... 50 Port IO ....................................................................................................................................................RTX User’s Guide Mutex Objects ...........46 Ownership ............................. 49 Using RtReleaseInterruptVector .................................................................................................................................................................................................................................................................................................................................................................................................................................. 55 Using the RTX Makefile ..............................................................................................................................................53 Programming Example (Bus I/O) ......50 Port I/O Control APIs ......................................................................................................................................................................................................................................................................................... 56 Variables ............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ 58 RTSS DLL and RTDLL Code Examples ............. 46 Inter-Process Communication via Mutex Objects .........................................48 Interrupt Management ............................................ 50 Port I/O Data Transfer APIs.................. 51 General Programming Considerations. 51 Programming Example .. 53 Bus IO .......................... 48 General Programming Considerations......................................................................57 RTSS DLLs...........................................................................................................................................................................................51 APIs ...............................................................................................................................................................................................................................................................................................................................57 C Run-Time Libraries: Programming Considerations for DLLs ...................................................................................................................................................................................................................................................59 v ............................................................................................................. 53 File IO.. 47 Device Management .................56 Sample Makefile........................................................................... 48 Interrupts ...................................................................................................................................................................................................................................................................................................... 49 Using RtAttachInterruptVector .........................................................................................................................................52 Programming Considerations ..................................................................................................................................................................................... 57 About RTSS DLLs and RTDLLs................................................ 52 Win32 Environment Programming Considerations ......................................................... 59 Using Floating Point .................................................................................................... 52 Programming Example (RTX Memory Mapping Calls) ................................. 47 Environments.................... 52 Contiguous Memory Mapping ................................ 49 Win32 Environment Programming Considerations .....................................................................................................................................................................53 File IO ....................................................................

...........................................................................74 Hardware Causes .................................. 66 Section 4 .......................63 RTX Exception Codes ................................................................HAL-Supplied Stop Message................................................69 Section 1 ................... 62 General User Notes for Exception Handling ................................75 vi .................................................................................... 70 Starvation Management ...................................................................... 66 Section 2 ....................................................................................................................................................................................... 71 RTX Power Management for Windows 2000...............................................65 Interpreting Windows NT Blue Screen Stop Messages ...................................................... 63 Intel Exception Codes............................59 Writing RTSS Device Drivers ....................................................................................................................................................61 Differences Between Win32 and RTSS Exception Handling ............................................................................................ 75 SRTM (System Response Time Measurement) and RTX Demo .................................................................................................. 62 About System Exception Handling........................................ 61 Nested exceptions and collided unwinds .............................................................................................62 Tables of Exceptions............................................................................................................................................................................. 73 Causes and Management of Interrupt Latencies ..................................................75 KSRTM (Kernel System Response Time Measurement) ......................................Stop Message........................................ 61 Exception caused by a thread ............................................................... 67 Interpreting Windows 2000 Stop Screens.......................................................................................................68 Interpreting RTX Green Screen Stop Messages ........................................................................RTSS-Specific Stop Message .................................60 Structured Exception Handling.....................................................System Stack Dump .......................................60 Using SEH.........................................62 RTX Handler....................................................................Driver List ....70 Watchdog Management.................................................................. 61 Debugging .............................................................................................................................................................................................................Communication........................................................................... 60 C++ Support .................................62 System Exception Handling ............................................................................RTX User’s Guide Running RTSS Programs Using Floating-Point ............. 70 Setting the Starvation Time Out Period ..........................................74 RTX Management of Interrupt Latencies ................................................................. 69 Section 2 ...................................... 64 Generate Event Log Entries ................................................................................................................................................................................................................................................................ 65 About RTX and Windows NT / Windows 2000 Stop Messages ................................................................................................................................................... 66 Section 3 ................................................................................................................................................................... 64 Alert User....................66 Section 1 .....................64 Freeze or Terminate Processing.................................. 74 Software Causes ..........................................................................................................74 Reducing Your System’s Latencies: Tools Overview........................................................... 59 C++ and Structured Exception Handling ...............................................................................................................................................................................................................................................................................................................................................................................................71 CHAPTER 5 PERFORMANCE OVERVIEW ......................................... 63 RTX Exception Handling ............................................. 61 UnhandledExceptionFilter.............................................................................................................................................................................................................................................................................................................................................................................................................................

..................................................................................c...............................................................................................................................................95 RTSS DLL Part 3: dll-test.................................................................. 104 RTX Memory Mapping Calls Programming Example...75 Timer Latency Display..................... 95 RTSS DLL Part 1: dll.....................RTX User’s Guide LTP (Latency Test Program).............................................................................................................................................................................................................................................82 Using LTP (Latency Test Program) ..................................................................................... 106 vii .................................. 90 Nmake Input File Example ........................................................................................................97 RTSS DLL Part 5: runtest.....................................................92 RTDLL Part 3: rtdll.............................................................94 RTDLL Part 4: Register the rtdll ...................................81 Interpreting the Latency display ................75 KSRTM versus SRTM............................ 83 Bus IO Programming Example ................ 92 RTDLL Part 1: sampleRtdll.................................................................................. 82 APPENDIX A CODE AND FILE EXAMPLES..................................................................................................... 91 RTDLL Code Example .............................................................................................................................................................mak..............................................................................100 RTSSkill Example 2 ...................................................................... 78 Interpreting the Max Latency Plot ............. 83 Interrupt Management and Port IO Calls Programming Example ..... 99 RTSSkill Examples................................mak ...........................................80 Using the Timer Latency Display Tool .......................................................................................................... 88 Makefile Sample ......................................................................................................................... 80 Interpreting the Histogram.................................................................................................................c ........................................ 103 RTX Locked Memory Allocation Calls Programming Example ..................................94 RTSS DLL Code Example..................................................................................79 Interpreting the Histogram Plot ................................................................................................................................................................c ........................................................................................75 Using KSRTM (Kernel System Response Time Measurement)...........................................................................................................................def.............................................96 RTSS DLL Part 4: dll..............97 RTSS DLL Makefile Example.........................................................................................................95 RTSS DLL Part 2: dll.............................................................................................................................................................. 105 RTX Process Memory Locking Calls Programming Example ............................... 76 Using SRTM (System Response Time Measurement) ....................................92 RTDLL Part 2: usingRtdll....................100 RTSSview Example ..........................c..................................................c.............. 77 Using RTX Demo (Graphical version of SRTM) ........................................................................ 100 RTSSkill Example 1 ......................................................... 101 RTX Contiguous Memory Allocation Calls Programming Example ...................................................... 102 RTX Kernel Memory Locking Calls Programming Example.........................................................................................................................................................................

............ 107 INDEX............ 109 viii ...........................................................RTX User’s Guide RTX Timer and Sleep Calls Programming Example ...........................................................................................

Experienced real-time developers will value the power of the RTX interface. along with tools for measuring and fine tuning the performance of both hardware and software. You can: Œ Œ Call technical support at 800-334-8649 between 9:00 AM and 6:00 PM (Eastern Time) Email your questions to support@vci. developers can continue to take advantage of the abundance of products available for Windows NT and Windows 2000. Please have this number available for reference when contacting VenturCom.Welcome to RTX 5. we suggest that you refer to the topics in the RTX Overview for a more detailed description of RTX and a discussion of important design decisions that need to be made in order to fully take advantage of RTX features. the Win32 runtime environment works seamlessly with the RTX real-time subsystem — enabling the integration of Win32 and real-time functionality. And. Technical Support For technical support related to installing and using RTX. Inc. Note: If you are a customer who purchased direct support. Users who purchased their product through third parties should contact those parties directly with their questions. including technical support and the VenturCom Web site. It also provides tools and utilities for building and executing real-time programs.0 Document ID: 1-015-10 © 2000 VenturCom. with the RTX inter-process communication features. All rights reserved. VenturCom’s Real-time Extension (RTX) adds real-time capabilities to Windows NT and Windows 2000 that are unparalleled in the industry. VenturCom offers several channels of communication. It offers developers a rich and powerful real-time feature set — all in a familiar Win32-compatible interface. In addition to using the real-time interfaces and tools provided by RTX. Getting Support VenturCom offers a number of support options for RTX users.com Fax your questions to 617-577-1607 Œ VenturCom Web Site The VenturCom Customer Support Web page is located at: ix . you would have received a Support ID# in the letter that comes with the software.

Using the RTX Functionality — Presents the RTX functionality. It also explains how to use the RTX performance tools. While visiting CENTer. Using Software Development Tools — Explains how to use RTX programs.com/tech_support/support_description. Check our CENTer page for updates.RTX User’s Guide http://www. and provides programming approaches for ensuring good response times in your applications. From time to time. we may provide documentation updates for our products. About the User’s Guide The RTX User’s Guide describes the RTX product and explains how to use its features. such as latency metrics and timing factors. documentation. The following list introduces the chapters in this guide. RTX Overview — Describes the RTX architecture. and release notes. utilities. discusses important realtime programming issues. Developing an Application — Explains how to use dynamic link libraries. and provides references to real-time code examples that illustrate the implementation of real-time programming techniques. CENTer also provides access to several newsgroups. Documentation Updates VenturCom is committed to providing you with the information you need to use our products. discusses how to design programs using RTX. or to obtain the status of previously reported issues. you can access the online problem report database to submit new issues. it is intended for users who are familiar with developing applications in a Win32 environment. You’ll also find free utilities and extensions that you can download.vci. x . It also contains procedures for building applications and dynamic link libraries as well as procedures for debugging and testing your application.vci.html If you are a customer with a current support contract or a member of the Real-time and Embedded Partner Program. check out the various white pages and presentations. It also describes exception handling in the RTSS and Win32 environments and techniques for managing starvation conditions.com/tech_support/support_login. With a valid Support ID#.html These pages provide electronic access to the latest product releases. and floating point when developing an application. C run-time library functions. then you should bookmark to the Web page in the Technical Support Area located at: http://www. Performance — Discusses key real-time performance issues. and tools to develop real-time applications.

With RTX. The User’s Guide can assist you in implementing RTX. Furthermore. developers must properly implement RTX in their applications. low-cost platform to satisfy a full range of real-time and embedded application requirements. throughput. such as GUI-based operator interfaces. communication with other information systems. though: Instead of using the Windows NT or Windows 2000 scheduler. make different tradeoffs between price. developers and their users can select systems that ensure their real-time requirements are met. However. and timecritical monitoring and control of equipment. and often prevented. and availability of off-the-shelf add-on components — are the the operating system platforms of choice. including Windows-managed interrupts and Deferred Procedure Calls (DPCs). the use of Windows NT and Windows 2000 are significantly restricted. Windows NT and Windows 2000 — with their advanced features. adversely impact other Windows applications and might even compromise overall system stability. known as RTSS. to Windows NT and Windows 2000 (see the figure below). if implemented in applications improperly. POSIX. Different board vendors. RTSS differs in one important area. RTX enables application components or modules that require deterministic and high-speed response times. range of supported hardware configurations. all RTSS thread scheduling occurs ahead of all Windows scheduling. Second. By extending the Windows NT and Windows 2000 operating systems. and DOS) in that it supports its own execution environment and API. because worst-case response times vary significantly among systems. in a uniprocessor environment. First. since their functionality was not targeted for "hard" real-time applications. along with other non-real-time application components. RTSS performs its own real-time thread scheduling. WOW. and deterministic behavior. you can use a single. there are two areas in which real-time application developers must take active responsibility to fully realize its benefits. to work together on a common Windows system.CHAPTER 1 Introduction to RTX Today’s real-time and embedded applications contain a broad range of functionality. 1 . With the help of VenturCom's RTX performance analysis tools. RTX provides raw power that can. RTSS is conceptually similar to other Windows NT subsystems (such as Win32. While RTX brings superior real-time capabilities to Windows NT and Windows 2000. developers and their end users must carefully select their systems. The RTX Architecture RTX adds a real-time subsystem. For both developers and end users of these applications. VenturCom's RTX product bridges this gap by adding "hard" real-time capabilities to both Windows NT and Windows 2000. for these applications. especially video card vendors.

RTX User’s Guide

57; DQG :LQGRZV 17 :RUNLQJ 7RJHWKHU

Real-Time Inter-Process Communication
RTSS also supports Inter-Process Communication (IPC) objects that can be manipulated by either RTSS or Win32 processes; this enables simple and standard communication and synchronization between real-time and non-real-time programs. Finally, RTSS provides other time-critical services — such as clocks and timers and interrupt management — to RTSS processes.

HAL Extension
RTX includes a real-time enabled Hardware Abstraction Layer (HAL) extension. This extension maintains interrupt isolation between RTSS and Windows NT or Windows 2000. Windows cannot mask (at the interrupt controller level) interrupts managed by RTSS. Windows interrupts are masked during RTSS processing. The real-time HAL extension supports high-resolution clocks and timers for RTSS, while it also supports non-real-time clocks and timers for Windows NT and Windows 2000. Other real-time HAL extension features include a software interrupt mechanism between RTSS and Windows; basic exception management; and various enhancements for determinism.

Uniprocessor and Multiprocessor Systems
RTX supports both uniprocessor and multiprocessor Windows NT and Windows 2000 systems. The run-time version of RTX, which supports multiprocessor systems, provides all of the features of the uniprocessor version, plus it exploits the features of Intel MPScompliant multiprocessor systems to provide improved performance in both Windows and RTX environments. Run-time RTX, for multiprocessor systems, implements a dedicated processor model. In this model, RTSS runs on one processor, while the remaining processors continue to run on Windows. The multiprocessor HAL acquires control of the last logical processor during the Windows boot sequence and it is reserved for RTSS. RTSS programs can then be loaded and

2

Chapter 1: Introduction

executed on the dedicated processor. The RTX Application Programming Interface for Win32 and RTSS processes, including Floating-Point Unit (FPU) and structured exception handling, is used for both uniprocessor and multiprocessor systems. This eliminates the need to recode RTX (uniprocessor) applications for a multiprocessor platform.

The RTX Application Programming Interface (API)
The RTX API is based on the Win32 API, using the same API already familiar to Windows application developers. This approach allows developers to draw upon their Win32 experience, code base, and development tools, thus expediting hard real-time application development. Both Win32 and RTSS processes support the full RTX API — albeit with different response times and performance characteristics — allowing developers to effortlessly share or move code between environments. This topic discusses: Win32_and_Real-Time_API RTX_Executable_Images Run-Time_Libraries Unicode

Win32 and Real-Time API
RTX supports a subset of Win32 API functions, plus it provides a special set of real-time functions, known as RTAPI (Real-Time API). RTAPI functions are identified by an "Rt" prefix in their names. Some RTAPI functions are semantically identical to their Win32 counterparts, while others are unique to RTX (i.e., there are no similar Win32 calls). For example, RTAPI real-time IPC functions differ from Win32 IPC functions only in the IPC name space in which they operate and in the determinism possible with real-time IPC objects. On the other hand, the Win32 API does not include any functions related to interrupt management; therefore, unique interrupt management functions are defined in RTAPI. The RTX API was carefully selected to promote efficient development of real-time application components. RTX intentionally does not include Win32 functions, such as the GUI-related calls, that are normally used by the less time-critical components of an application. In fact, Win32 functions that are not essential to real-time programming, and impractical to implement with deterministic behavior, are not included in the RTX API. It is expected that most applications will consist of at least two processes working together-one Win32-based process (to take advantage of GUI and other Win32-only functions) and an RTSS-based process to perform time-critical processing.

RTX Executable Images
RTX provides three types of executable images: RTSS applications, RTSS DLLs, and RTDLLs. RTSS applications are the real-time analogues of Win32 applications. RTSS DLLs are RTSS applications that have been linked to provide an export library that RTSS and other applications can use to call functions within an RTSS DLL. RTSS DLLs are full RTSS processes and must be launched manually prior to their use by RTSS applications. RTDLLs

3

RTX User’s Guide

are passive code containers, similar in functionality to Win32 DLLs, which run in RTSS. For details about how to choose, design, and build appropriate combinations of these types of images, see the chapters Using Software Development Tools and Developing an Application in this guide.

Run-Time Libraries
RTX also supports various run-time libraries, and provides a ’C’ run-time library based on MS Visual C++. RTSS processes can be statically linked to include these libraries, provided they do not attempt to link to unsupported Win32 functions. RTSS processes can also be linked against specialized versions of dynamic link libraries (DLLs), which can be used to modularize real-time application code or provide run-time customization of real-time software environments.

Unicode
RTX supports Unicode applications. An RTSS process can use the wmain() function and accept wide character input arguments. Support for the WCS family of functions is included as part of the RTX-supported C run-time library.

Designing and Developing RTX Applications
To ensure successful development of a real-time application, designers and developers must carefully analyze how to efficiently partition the application. They must also establish the correct balance between non-real-time (Win32) processes and real-time (RTSS) processes and determine the interface between them. If, for example, there is time-critical processing in Win32 processes, too much non-time-critical processing in RTSS processes, or too much synchronization or data flow across the process interfaces, the application’s performance, usability, and overall ease of development and maintenance will be jeopardized. An initial investment of time spent analyzing the various tradeoffs and designs in this critical architecture area will be worthwhile to both developers and their users. This topic discusses: Œ Œ Œ RTX_Device_Drivers Testing Real-Time Applications Starting an RTSS Process Stopping an RTSS Process

Œ

RTX Device Drivers
Some designs call for application components that act as device drivers to other application components, or board vendors may want to provide real-time device drivers for their boards that can be used by a variety of real-time and non-real-time applications. The device driver designer can use either DLLs or real-time IPC mechanisms to connect drivers and applications together. The real-time IPC offers the most flexible option because Win32 and RTSS processes can both access a common real-time driver using the same interface, even at the same time. The sample directory includes an RTX library for device drivers based on real-time IPC that provides a traditional device driver interface (e.g., open, close, read, write,

4

Chapter 1: Introduction and control) to either Win32 or RTSS applications. including device drivers.. you will generally use either the feature that starts specified RTSS processes at boot time (i. you will typically start RTSS processes from the command prompt with optional command line arguments or by clicking on the RTSS executable file icon in Windows Explorer. the initial development and testing of real-time application components. If extensive debugging of RTSS processes is necessary. Stopping an RTSS Process An RTSS process stops when: Œ Œ Œ The process calls the ExitProcess function A user or a Win32 process runs the RTSSkill utility A user terminates the process through the RTSS Task Manager The process generates an exception A Windows NT or Windows 2000 system shutdown occurs (either a normal shutdown sequence or an exception-initiated Windows NT "blue screen" stop or Windows 2000 stop screen) RTSS processes can register shutdown handlers that are called when Windows is shut down or stopped to allow the final sequencing of equipment and cleanup prior to full system stop and possible reboot. During development and testing.e. 5 . is most easily done in the Win32 environment. Testing Real-Time Applications In most cases. For final applications. or you will launch RTSS processes directly from a Win32 process. Creating and Starting an RTSS Process Several methods are available for starting RTSS processes. the real-time application component is simply re-linked as an RTSS process for final testing in the deterministic RTSS environment. and the best detection of misbehaving applications. and test tools. The Win32 environment provides the widest range of development. debug. when the "blue screen" starts). you will use the Win32 RTCreateProcess call to ceate and start the specified RTSS process. After all non-time-critical testing is completed. you can use Microsoft’s WinDbg. To create and launch the RTSS process directly.

RTX User’s Guide 6 .

by itself or with the RTX AppWizard.CHAPTER 2 Using Software Development Tools This chapter discusses the RTX programs. for building RTSS images and dynamic link libraries.0 Creating Dynamic Link Libraries Debugging an RTX Program Testing an RTX Program with Shutdown Handlers Using the RTX Properties Contol Panel n n n n n n 7 . This chapter contains information on: n Using the RTX Utilities Utility Task Table RTSSrun Utility RTSSkill Utility RTSSview Utility RTSS Task Manager RTSS Object Viewer RtxServer Using the RTX AppWizard in Microsoft Visual Studio 6. and RTX control panel settings that you work with when developing and testing your real-time programs. It contains procedures for using Microsoft Visual Studio. drivers.0 Using Microsoft Visual Studio 6. utilities. files. This chapter also contains instructions on debugging your programs using Microsoft’s WinDbg and testing programs with shutdown handlers.

I \RX ZDQW WR 5XQ DQ 5766 SURFHVV /RDG DQ 5766 '// 5HJLVWHU DQ 57'// 7HUPLQDWH DQ 5766 SURFHVV 8VH 5766UXQ FRQVROH RU IURP WKH 57. 6WDUW PHQX. .RTX User’s Guide Using the RTX Utilities Utility Task Table The table that follows shows which utility to use to perform a particular task.

6WDUW PHQX. 5766UXQ FRQVROH RU IURP WKH 57.

6WDUW PHQX. 5766UXQ FRQVROH RU IURP WKH 57.

5766NLOO FRQVROH.

RU 5766 7DVN 0DQDJHU RQ WKH 57. 6WDUW PHQX 8QUHJLVWHU DQ 57'// 5766NLOO FRQVROH.

RU 5766 7DVN 0DQDJHU RQ WKH 57. 6WDUW PHQX 9LHZ D OLVW RI DOO SURFHVVHV DQG UHJLVWHUHG 57'//V 5766NLOO FRQVROH.

RU 5766 7DVN 0DQDJHU RQ WKH 57. 6WDUW PHQX 9LHZ LQIRUPDWLRQ DERXW 5766 SURFHVVHV DQG WKHLU DVVRFLDWHG REMHFWV LQFOXGLQJ 7KUHDG 7LPHU 6HPDSKRUH 0XWH[ 6KDUHG PHPRU\ DQG /RDGHG 57'// 5766YLHZ FRQVROH.

RU 5766 2EMHFW 9LHZHU RQ WKH 57. 6WDUW PHQX 8 .

rtdll file is copied to a location in the %SystemRoot% directory.rtdll] where /q = Disables messages indicating success or failure to start the RTSS process. whenever you rebuild a boot-time RTSS application or an RTDLL. the current version of the . and register an RTDLL. RTSSrun returns -1. otherwise. It then copies the command line to the registry and starts the service for this RTSS process. /t = Tests loading and unloading of RTDLLs. /b = Runs the RTSS process early in the system boot sequence. 9 . arguments = Command line arguments passed to the process. This switch must be used in conjunction with the /d switch. /d = Loads an RTDLL and adds entries to the registry. It copies the RTSS executable image to the target directory for the process slot and establishes a pointer to the path.rtss or . When you use RTSSrun to run an RTSS process. Otherwise. filename = Name of the file to be run. Usage RTSSrun file [arguments] Format To run an RTSS process: RTSSrun [ /b ] <filename>[. the slot number of the new process is returned. If successful. RTSSrun Console Each time you use this utility with the /b or /d switch. it scans the RTSS process service slots for a free slot.rtss] [ arguments ] To register an RTDLL: RTSSrun /d [/s] <filename>[. Thus. load an RTSS DLL. only threads within a single process can simultaneously load a particular RTDLL.Chapter 2: Using Software Developmen Tools RTSSrun Utility (Console and GUI) Use the RTSSrun utility to run an RTSS process in the RTSS environment. /s = Allows an RTDLL to be loaded by several processes at the same time. you must rerun RTSSrun in order to access the new version.

only threads within a single process can simultaneously load a particular RTDLL. shown below. you can elect to start the process early in the system boot sequence by selecting Register to run at boot time. Results The RTSSrun window. choose RTSSRun. Otherwise. you can elect to: Share Between Processes — Allows an RTDLL to be loaded by several processes at the same time. opens.RTX User’s Guide RTSSrun GUI Usage On the VenturCom RTX SDK Start menu. however RTX must be set at boot time for this to take effect. 5766UXQ :LQGRZ Special Mode Options Run RTSS process — When running an RTSS process. See Also RTSS Task Manager 10 . Perform Load\Unload Test — Performs test loading and unloading of RTDLLs. Register RTDLL — When registering an RTDLL. click the Start Task button. or On the RTSS Task Manager window.

rtdll Format To terminate a particular process: RTSSkill [/b] [process number] To unregister an RTDLL: RTSSkill filename.rtdll where /b = Undoes the RTSSrun /b action. including registered RTDLLs that have not been loaded.Chapter 2: Using Software Developmen Tools RTSSkill Utility Use the RTSSkill utility to terminate a particular RTSS process or unregister an RTDLL that is not loaded. by omitting the process number or filename. RTSSkill Examples See the RTSSkill Examples in Code and File Examples in Appendix A. You can also use this utility to view a list of all RTSS processes. Usage To view processes and registered RTDLLs: RTSSkill To terminate process 001: RTSSkill 001 To unregister an ˆ ¯ DLL: RTSSkill myfile. The program will not start automatically at boot time. You cannot unregister an RTDLL if any RTSS process currently has it loaded. 11 .

Threads that have negative priority numbers belong to system processes. Event — Provides the state of the event. The thread flags have the following assignments: 9DOXH [ [ [ [ [ [ 0HDQLQJ 'R QRW GHDOORFDWH PHPRU\ 'R QRW IUHH WKH WKUHDG V VWDFN 7KUHDG WHUPLQDWHG 7KUHDG FDQQRW EH UHVXPHG . such as events. Usage and Format RTSSview /A (provides internal system processes and WIN32 proxy processes Results RTSSview lists each type of RTSS object. 12 . and the object name. Shared memory — Gives the base memory address. Semaphore — Provides the count. File — Provides the Windows NT handle for the file and the filename. plus the value of the flag settings which indicate certain thread behaviors. the remaining time. RTDLL — Lists the count. It also lists information specific to each particular object: Process — Gives the name or type of process. and loaded RTDLLs.QWHUUXSW WKUHDG )ORDWLQJ SRLQW Timer — Provides the clock number. maxcount. the address of the owner. followed beneath the listing by each thread object owned by that process. RTX assigns a priority value to each thread in the user's process. Mutex — Lists the count. and the object name (if there is one). with values ranging from 0 to 127 (see Thread Priorities on page 35). and the timing interval. and the object name. the size of the shared memory. address of the owner.RTX User’s Guide RTSSview Utility Use the RTSSview utility to view information about RTSS processes and their associated objects. semaphores. and its object name (if there is one). Thread — Provides the priority and state of the thread. followed by its memory address in the kernel address space and the process id. RTSSview Example See the RTSSview Example in Code and File Examples in Appendix A. whether the event is reset manually or not. and the name of the event.

choose RTSS Object Viewer. shown below. Usage On the VenturCom RTX SDK Start menu. The tree view (left panel) displays all active RTSS objects.Chapter 2: Using Software Developmen Tools RTSS Object Viewer When you start RTSS Object Viewer. 5766 2EMHFW 9LHZHU 13 . opens. Results The RTSS Object Viewer window. while the list view (right panel) displays extended information on the items checked in the tree view. it displays an explorer that allows you to navigate through all the active objects found in the Real-Time Subsystem (RTSS).

or Paused (turned off). View — Lets you specify how the information is displayed: Refresh Now — Refreshes the Explorer view. Object attributes are displayed in one column instead of each attribute in its own column. Compact style — Allows for a more condensed view of object attributes. Check All/Uncheck All — Causes all object to be displayed/removed from the list view. Help — Provides information about RTSS Object Viewer: Help Contents — Opens the help contents. 14 . About RTSS Object Viewer — Opens a pop-up with copyright information. Select Columns — Allows you to select which columns to display and their order. File — Provides standard exit option. Refresh Rate — Lets you specify a Refresh Rate of high (one second). Options — Provides extra display options: Always On Top — Keeps the RTSS Object Viewer window on top. The default is for automatic refresh to be turned off. This option is not available if Compact style is selected.RTX User’s Guide Menu The RTSS Object Viewer window contains the following menus. low (five seconds). For additional information. normal (two seconds). refer to the online help that is included in the application.

End Task — Stops/unregisters the selected process or RTDLL. choose RTSS Task Manager. opens. Usage On the VenturCom RTX SDK Start menu. Start Task — Starts up the RTSSrun graphical user interface. 15 . 5766 7DVN 0DQDJHU Buttons and Options The RTSS Task Manager window contains the following buttons and options: Always On Top — Keeps the RTSS Task Manager window on top.Chapter 2: Using Software Developmen Tools RTSS Task Manager RTSS Task Manager lets you view and control all active RTSS Processes and registered RTDLLs on your system. Results The RTSS Task Manager window. shown below.

it can not be started up by double clicking on its icon. You can use append mode or clear mode for logging. changing screen buffer size and font settings of the output. Fatal error messages are are flagged with the notification icon and logged to the Event Viewer. The GUI can also be manually brought up by double clicking on the RtxServer notification icon in the Taskbar’s Status Area. The RtxServer notification icon is visible when the RtxServer is running and displays the state of the service and show error messages. When the GUI is exited. change its path. the display buffer is purged. The RtxServer allows for the storing and viewing of RTSS output through the screen and log file. Since the RtxServer is a service. clear it. 16 . clearing the display. See the online help for additional information on using RtxServer. The service can run in GUI mode or in non-GUI mode. and put a banner containing RTX version information and start time in it. The GUI is brought up by default when the first printf or RtPrintf in an RTSS application is encountered. Because logging is independent of the GUI. The RtxServer is an RTX service that starts up at boot time if RTX is set to run at boot time or at runtime when an RTSS application is run or from the RTX control panel. You can also write to a log file. the logging will continue even if the GUI is exited.RTX User’s Guide RtxServer The RtxServer handles RTSS output and enables the user to view the output in the RtxServer output window and/or log the output to a file. Some options for writing to the screen are saving the screen buffer to a file.

RTSS Release. On the Visual Studio menu bar. On the right side of the dialog. select RTX AppWizard from the list box. Win32 Debug. The wizard sets the Project Settings for each configuration according to the program and project options selected from its dialogs. The New dialog box opens. It can also provide a basic C program framework with which to work. 17 . This program framework can include RTX program elements. To create an RTX project 1. Location — Enter the directory in which to build the workspace. which contain C code to create RTX objects and demonstrate their use.0 to create a project workspace for the development of RTX applications and dynamic link libraries. 2. and RTSS Debug. On the Projects tab. complete the following fields: Project name — Enter the name of the project. The RTX project workspace contains four configurations: Win32 Release. The topic explains how to: Create a project and set options using the RTX AppWizard and then build an image (Win32 or RTSS) or build a dynamic link library (RTDLL or Win32 DLL) Run an image Œ Register an RTDLL Creating a Project and Setting Options Use the procedure that follows to create an RTX project using the RTXAppWizard in Microsoft Visual Studio. select File | New. as shown below.$SS:L]DUG  1HZ 3URMHFWV 'LDORJ %R[ 3.Chapter 2: Using Software Developmen Tools Using the RTX AppWizard in Microsoft Visual Studio 6.0 Use the RTX AppWizard in Microsoft Visual Studio 6. 57.

4. 3. 18 . select either the single-threaded library or the multi-threaded library. If these are all the options needed. 5. Otherwise. Select which type of string format to use. Click OK to save the settings. click Next to open the second dialog box. Setting Project Options and Setting Program Options. RTX supports either UNICODE (default) or ASCII string types in RTSS programs. If your project needs this support.$SS:L]DUG  6WHS  RI  'LDORJ %R[ 1. The default is no C run-time library support. click Finish. Some programs need support for C run-time functions. Choose whether to build an RTX application (default) or a DLL by clicking the labeled radio buttons. Setting Project Options 57.RTX User’s Guide Platforms — Select the platform for which RTX AppWizard will build configurations (WCE emulation mode is not supported). 2. Complete the steps of the RTX AppWizard by selecting the appropriate options in the RTX AppWizard dialog boxes. 4. shown in the figure below. See the following instructions. you must use the multi-threaded library. The RTX AppWizard sets the Project Settings in each configuration for compiling and linking programs. If an RTDLL needs C run-time support.

The framework consists of a C source file that contains basic C construction calls and a C header file that contains #include and #define statements. These programming elements are code segments that create each RTX object and demonstrate its use. The default option is that no programming elements are to be included. The default is No program framework. Select an option by clicking on the appropriate radio button. 2. indicating the choices. Click Back to return to the first dialog in order to modify or review selections.Chapter 2: Using Software Developmen Tools Setting Program Options 57. 19 . 3. such as the one in the figure below. You can select more than one type of programming element for a single project. The RTX AppWizard displays a New Project Information confirmation box. Otherwise. RTX program elements can be included in the C program framework. Areas in the element code that need to be customized by the user are indicated by "TO DO" comments. The wizard can provide a basic C program framework by inserting some files into the project. click Finish. just Set Project Setings.$SS:L]DUG  6WHS  RI  'LDORJ %R[ 1.

20 . Click OK to save the settings. Choose Build | Execute (or click the exclamation point on the toolbar). Select Project | Settings | Debug tab. you can run it from: n n n A command prompt. In the Program Arguments field. Replace the text in Executable for debug session with: rtssrun. Run the RTSS image 5. Modify project settings for Win32 RTSS Release and Win32 RTSS Debug 1. You do not need to change any setting to run Win32 images. 2.) To run an RTSS image in Visual Studio Use this procedure to run an RTSS image from within Visual Studio. Running an Image After you have built your Win32 or RTSS image.QIRUPDWLRQ 4. Click OK. copy the executable into the arguments section box and then add any other arguments. or Visual Studio (See the procedure that follows for special instructions on changing Visual Studio settings for RTSS Debug and Release images. Windows NT Explorer. 3.RTX User’s Guide 1HZ 3URMHFW .exe 4. RTX AppWizard generates the RTX workspace and project according to the options you selected.

and then click OK. The following assumes that it was installed with the default paths. To set up Microsoft Visual Studio 1. In the Show Directories For box.0. Simply remove this option from your project settings in order to migrate a Developer Studio 5. On the Visual Studio Tools menu.0 project. enter a name. Building and Running Images (Win32 Environment) Use the procedures that follow to build and run a Win32 image. To build a Win32 image Create a new RTX Win32 project workspace 1. Include files — c:\program files\vci\rtxsdk\include Library files — c:\program files\vci\rtxsdk\lib 3. you can register it using the RTSSrun utility. choose Options and then choose the Directories tab.0 are appropriate for Developer Studio 5. If you changed the default path during installation.0 This topic explains how to: Set up Microsoft Visual Studio Build and run Win32 images Build and run RTSS images Œ Build and register RTDLLs Note: The RTX AppWizard utility provides an easy-to-use alternate for creating a project workspace for the development of RTX applications and dynamic link libraries Note: Some projects created for Microsoft Developer Studio 5. Using Microsoft Visual Studio 6. Click OK to save the settings. 2. This option is incompatible with RTSS and Microsoft Visual Studio 6.0 project to a Visual Studio 6. choose New and then choose the Projects tab. Setting up Microsoft Visual Studio Use the procedure that follows to direct Microsoft Visual Studio to the RTX include and libraries files.Chapter 2: Using Software Developmen Tools Registering an RTDLL After you have built your RTDLL. Choose Win32 Console Application. 2. specify that path below.0 as well. select the following file types and enter their paths in the Directories box. All the link options described in this topic for Visual Studio 6. Specify the project settings 21 .0 will have /GZ specified as a compiler option. On the File menu.

choose Settings to open the Project Settings dialog box.lib rtx_rtss. Select Win32 Console Application. On the Link tab. you can run it from: A command prompt.00 /debug:notmapped /debugtype:both /entry:_RtapiProcessEntry@8 ÃTvtyrUu…rhqrqÃ8ÃSˆUv€rÃTˆƒƒ‚…‡)ÃSryrh†rÃWr…†v‚ startupCRT.lib w32_dll.lib rtx_rtss.lib w32_dll. select All Configurations. On the Link tab.lib 6. Click OK to save the settings.lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native. To build an RTSS image Create a new RTX RTSS project workspace 1.lib rtapi_rtss. choose Settings to open the Project Settings dialog box.lib oldnames.lib rtx_rtss. To run a Win32 image After you have built your Win32 image.RTX User’s Guide 3.00 /RELEASE /entry:_RtapiProcessEntry@8 ÃI‚Ã8ÃSˆUv€rÃTˆƒƒ‚…‡)Ã9riˆt Versionrtapi_rtss. delete all Project Options and replace them with one of the following option sets. Building and Running Images (RTSS Environment) Use the procedures that follow to build and run an RTSS image.4.00 /RELEASE /entry:_RtapiProcessEntryCRT@8 ÃTvtyrUu…rhqrqÃ8ÃSˆUv€rÃTˆƒƒ‚…‡)Ã9riˆtÃWr…†v‚ startupCRT. 2.lib rtx_rtss. or Œ Visual Studio (you do not need to change any settings).lib oldnames. Specify the project settings 3. and then click OK. On the File menu.4. I‚Ã8ÃSˆUv€rÃTˆƒƒ‚…‡)ÃSryrh†r Versionrtapi_rtss. 5.obj RTXlibc.lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native. On the Project menu. choose New and then choose the Projects tab. Windows NT Explorer. add this library to Object/Library Modules: rtapi_w32. In the Settings For box.lib rtapi_rtss.obj RTXlibc. 5. In the Settings For box. enter a name. 4.lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native. On the Project menu. 4. select either Win32Release or Win32Debug based on the version you are building.lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO 22 .4.

Specify the project settings 1.00 /debug:notmapped /debugtype:both /entry:_RtapiProcessEntryCRT@8 ÃHˆy‡vUu…rhqrqÃ8ÃSˆUv€rÃTˆƒƒ‚…‡)ÃSryrh†rÃWr…†v‚ startupCRT.lib 32_dll.00 /RELEASE /entry:_RtapiProcessEntryCRT@8 Multi-Threaded C Run-Time Support: Debug Version startupCRT. On the Project menu. On the Build menu. To run an RTSS image After you have built your RTSS image. For example: c:\program files\microsoft visual studio\myprojects\rtsstest\release\rtsstest.exe Program Arguments — Enter the path to your . you can run it from: A command prompt. choose New and then choose the Projects tab. 7. On the File menu.obj RTXlibcmt. choose Settings to open the Project Settings dialog box. Windows NT Explorer. Click OK to save the settings. Complete the following fields: Settings For — Select either Win32 Release or Win32 Debug. or Œ Visual Studio (see the procedure that follows for instructions on changing Visual Studio settings).lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native. 23 . For example: c:\program files\vci\rtx\bin\rtssrun. Change the file extension in the Output File Name field from exe to rtss.4.rtss 3. To run an RTSS image in Visual Studio Use the procedure that follows to run the image from within Visual Studio. 2.rtss image.lib rtx_rtss.lib w32_dll. based on the version you plan to run. choose Execute RTSSrun.lib rtapi_rtss.obj RTXlibcmt.4.4.exe. To build an RTDLL Create a new project workspace 1. Building and Registering RTDLLs Use the procedures that follow to build and register an RTDLL.lib rtx_rtss.exe.lib rtapi_rtss.lib oldnames.lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native.00 /debug:notmapped /debugtype:both /entry:_RtapiProcessEntryCRT@8 6. and then choose the Debug tab.Chapter 2: Using Software Developmen Tools /driver /align:0x20 /subsystem:native. Run the RTSS image 4.lib oldnames. Click OK to save the settings. Executable for Debug Session — Enter the path to RTSSrun.

lib rtapi_rtss. choose Settings to open the Project Settings dialog box.obj RTXlibcmt.RTX User’s Guide 2.4. delete all Project Options and replace them with one of the following option sets. In the Settings For box. 7.lib w32_dll. based on the version you are building.lib oldnames.00 /RELEASE /entry:_RtapiDllEntryCRT@8 Ã8ÃSˆUv€rÃTˆƒƒ‚…‡)Ã9riˆtÃWr…†v‚ startupDllCRT. 4.00 /debug:notmapped /debugtype:both /entry:_RtapiDllEntry@8 Ã8ÃSˆUv€rÃTˆƒƒ‚…‡)ÃSryrh†rÃWr…†v‚ ÃstartupDllCRT. Specify the project settings 3.lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native.lib w32_dll. Select Win32 Console Application. you can register it using the RTSSrun utility: RTSSrun /d <filename>. enter a name. On the Link tab.lib rtapi_rtss. On the Project menu. 5.lib startupDll. Project Options on the Link Tab for an RTDLL ÃI‚Ã8ÃSˆUv€rÃTˆƒƒ‚…‡)ÃSryrh†rÃWr…†v‚ rtapi_rtss.4.lib rtx_rtss.lib rtx_rtss. To register an RTDLL After you have built your RTDLL.lib /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native. Click OK to save the settings.00 /debug:notmapped /debugtype:both /entry:_RtapiDllEntryCRT@8 6.obj RTXlibcmt.obj /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native.obj /NODEFAULTLIB /INCREMENTAL:NO /PDB:NONE /NOLOGO /driver /align:0x20 /subsystem:native.lib rtx_rtss.lib oldnames.00 /RELEASE /entry:_RtapiDllEntry@8 ÃI‚Ã8ÃSˆUv€rÃTˆƒƒ‚…‡)Ã9riˆtÃWr…†v‚ rtapi_rtss. 24 .lib rtx_rtss.lib startupDll. Change the file extension in the Output File Name field from exe to rtdll. see RTSSrun Utility on page 9.4. select either Win32Release or Win32Debug. and then click OK.4.[rtdll] [/s] For further details.

thandler. For further details about the two types of real-time DLLs. Building an RTDLL through command line invocation The following is an example of an nmake input file which will build an RTDLL and Win32 DLL from a single source file. Œ Command line invocation of nmake using special rules.c — Defines the source call for the library dll. Building an RTDLL There are two ways to build RTDLLs. RTSS DLL Makefile Example The following example shows a typical RTSS DLL makefile for dll. NODEBUG =1 !include <rtx.0 on page 17 or Using Microsoft Visual Studio 6. dll.obj thandler.dll thandler. Note that the entry point into the RTSS DLL for starting the process is MAIN.c. RTSS programs can use the RTSS DLL. You can create them through: Appropriate compile and link options in a Microsoft Visual Studio project.mak> 25 . The two required files are listed below (see the RTSS DLL Code Example in Code and File Examples in Appendix A for an example of each file).0 on page 21. see Using RTX Dynamic Link Libraries on page 57.c. Build an RTSS DLL — This type of real-time dynamic link library is an RTX process that can be loaded either at boot time or through a call to Windows NT or Windows 2000 from within a C/C++ program. follow the applicable procedures in Using the RTX AppWizard in Microsoft Visual Studio 6.mak> all: thandler.dll thankler. !include <rtx.rtdll Building an RTSS DLL You create an RTSS DLL with a 'main' entry point that performs any required initialization routines. To build an RTDLL using this method. This method is illustrated below.def — Defines the DLL name and exported functions Once executed in the RTSS environment.Chapter 2: Using Software Developmen Tools Creating RTX Dynamic Link Libraries This topic explains how to: Build an RTDLL — This type of real-time dynamic link library is an RTSS object which can be dynamically loaded and unloaded using the LoadLibrary and FreeLibrary calls.rtdll clean: -del thandler.

mak or Add NODEBUG=1 to MyProgram. To exclude debugging information from release version files At a command prompt.RTX User’s Guide all: dll. rtx.obj -del *. This topic explains how to: Exclude debugging information from a release version Use Microsoft’s WinDbg 4.0 can debug Windows NT systems only.exe -del dll. you need two systems: a host system on which to run WinDbg and a target system on which to run your driver.rtss dll. The procedures that follow show how to: Prepare the host and target systems for WinDbg Prepare the program for debugging Set up the WinDbg environment on the host system Œ Start the debug session 26 .0 with RTSS Excluding debugging information You can exclude full debugging information from your release version by using the procedure that follows.0 with RTSS Œ Use Microsoft’s WinDbg 5.0. See the Makefile Sample in Code and File Examples in Appendix A.mak in Code and File Examples) Using Microsoft’s WinDbg 4.exe. which builds programs with full debugging information in a format compatible with Microsoft’s WinDbg.mak. WinDbg 4.lib Debugging an RTX Program Each makefile should include the master makefile.rtss: dll.exp clean: -del *.exp dll.obj $(rtsslibs) del dll.rtss dll.obj lib -nodefaultlib -machine:$(CPU) -out:dll. enter: Set NODEBUG=1 nmake -nologo -f MyProgram.obj link $(rtsslflags) -out:dll.mak (as illustrated in the Makefile Sample for srtm.rtss -del *.lib -def:dll.0 with RTSS In order to debug using Microsoft’s WinDbg 4.def dll.

4. 6.Chapter 2: Using Software Developmen Tools To prepare the host and target systems for WinDbg Connect the host system to the target system 1. Using /DEBUGPORT allows you to specify which serial port to use. Connect the two systems by inserting a null modem cable into the corresponding serial ports on each (COM1 or COM2). Test the connection using an available serial communications package (such as terminal. For more information on using these switches. comment the line NODEBUG=1 (if it is there).mak 27 . For more information on null modem cables and testing a serial connection. Modify this line to contain one of the following lines of information: /DEBUG [ /BAUDRATE=<baud rate> ] /DEBUGPORT=<com port> [ /BAUDRATE=<baud rate> ] where com port = Serial port through which the host and target are connected. Note: Using /DEBUG assumes that the default serial port is COM2. For example. Reset the file attributes in boot. the line "multi (0) disk (0) rdisk (0) partition(1) \WINNT="Windows NT Version 4. baud rate = Highest rate used by the machines. refer to the section on enabling kernel debugging on the target in the Microsoft Windows NT DDK documentation. install it according to its installation instructions. the system uses a default rate. In the program’s makefile. Reboot the target system. To prepare the program for debugging 1.exe) to ensure that data is transmitted and received on both sides.00" /DEBUGPORT=COM2" /BAUDRATE=19200" sets the communications port to COM2 and the baud rate to 19200. Modify the boot. Save the file and exit the editor.ini to their original states: > attrib +r +s +h boot. At a command prompt. For example. To include debug information in the program. Change the attributes of boot. Ensure that the target system has free builds of Windows NT and RTSS installed.rtss file.ini file to enable kernel debugging 4. 5. If baud rate is not given. enter: Set NODEBUG= 5. the following line creates the file srtm.ini to permit editing. At the start of the source code.ini 8. insert a hard break instruction: _asm int 3 2. If any of one of these is not installed on the target. perform one of these steps: 3. Open the file in an editor and locate the line under the "[operating systems]" section that contains the operating system on which you run. Set up the target system 3. 7. Run NMAKE with your program’s makefile to create an . 2. refer to the section on using a serial cable for kernel debugging in the Microsoft Windows NT DDK documentation.rtss: nmake -f srtm.

RTX debug information files in %SystemRoot%\symbols\ rtx_halext. the target system will not respond until WinDbg receives a "GO" command.rtss) to the %SystemRoot%\symbols directory on the host system. For example. 4. Cache. as desired. run the application. Thread Create: Process 0 Thread 0 Kernel debugger waiting to connect on com2 @ 19200 baud Kernel Debugger connection established on com2 @ 19200 baud Kernel Version 1381 Free loaded @ 0x80100000 Module load: NT (symbols loaded) Hard coded breakpoint hit 3. 3. at a command prompt. At this point. This set of options is recommended: Ignore Case. enter: > RTSSrun srtm The following message appears in the WinDbg command window. On the View | Options tab. ensure that the values for Baud. In the Load Time box. 2. On the host Run menu. For example. if desired. copy the . copy them from your RTX installation disks. enter the location of the . open the program’s source file. ensure that the following files are in their correct locations. enter: >copy srtm. select the Defer radio button. If they are not present. Symbols Tab — In the Symbol Search Path text box.rtss file into a working directory on the target system. 4. Verbose Output. 9. Debug Child Process. On the Start menu. choose Go (or press F5). at a command prompt.dbg in %SystemRoot%\symbols\ hal. Kernel Debugger Tab — Select the Enable Kernel Debugger check box. If the program was built on the host system. set the following options.dbg in SystemRoot%\symbols\ rtx_rtss. choose Go on the Run menu (or press F5). On the host system. Click OK to save the options. To start the debug session 1. To continue the debugging session.rtss file (this is required only if the file is not in the %SystemRoot%\symbols directory). Under Communications. Debugger Tab — Select the desired Radix and Registers settings and other desired options. Copy the symbol file (. Workspace Tab — Set the Logging option. On the File menu. choose Programs | Win32 SDK Tools | WinDbg. Refer to the Microsoft WinDbg documentation for details on using WinDbg.0 environment on the host system 1. Disconnect on Exit. On the target system.dbg in %SystemRoot%\symbols\ To set up the WinDbg 4. 28 .RTX User’s Guide 6. and Abbreviated Context. Go on Thread Terminate. and Platform are correct. 2. 7. Port.rtss c:\winnt\symbols 8. Add breakpoints.

0.0 with RTSS are the same as those described above for WinDbg 4. In order to debug using Microsoft’s WinDbg 5. on your host system.. To close the debugging session. you need to install WinDbg 5. then the shutdown handler prints out a message and sleeps for 10 seconds. You must first build this program using the RTX makefile.0 with RTSS Microsoft’s WinDbg 5. cancel from the target system program and then exit from WinDbg on the host system. Using Microsoft’s WinDbg 5. Note: The message is visible only for unexpected NT stops (RT_SHUTDOWN_NT_STOP).e. the Windows 2000 debugger. If a Windows NT stop or system shutdown occurs during this time. STOP 0) the Windows NT system to demonstrate RTSS shutdown management.e. For an orderly NT shutdown (RT_SHUTDOWN_NT_SYSTEM_SHUTDOWN).0.0 can debug both Windows NT and Windows 2000 systems.Chapter 2: Using Software Developmen Tools 5.. Your host and target systems can be either a Windows 2000 or Windows NT machine. i. Gencrash Driver Use the gencrash driver to see a demonstration of RTSS shutdown management. The gencrash driver provides a pop-up warning window and then bug checks (i. you can call the gencrash driver discussed next. This program attaches a shutdown handler to a process and generates a continuous tone. Testing an RTX Program with Shutdown Handlers This topic describes the: Sample shutdown program that you use to test an RTX program with shutdown handlers by forcing a Windows NT stop Œ Gencrash driver which demonstrates RTSS shutdown management Shutdown Program Use the shutdown program to see a demonstration of RTSS shutdown handlers. the message is not visible. The tone will then stop.0. 29 . The procedures for using WinDbg 5. Usage RTSSrun "c:\program files\vci\rtx\bin\samples\shutdown\shutdown" You can view the shutdown process or stop the shutdown program and its tone without shutting down Windows NT by using RTSSkill: 7R YLHZ WKH VKXWGRZQ SURFHVV 7R NLOO WKH VKXWGRZQ SURFHVV Q 5766NLOO 5766NLOO Q Optionally.

Starvation Time Out — Controls the watchdog timer which monitors threads. If set to Boot. About tab Displays RTX product and version information. See RtSetThreadTimeQuantum and RtGetThreadTimeQuantum in the RTX 5. issues a popup exception message. RTSS Process Slots — The number of RTSS process slots that can be run on your system. RTX stops the offending thread. you cannot start or stop RTX manually (see the Control tab section below). 2. In the system Control Panel. Minimum value is 10. maximum 999. and Control. RTSS frees the memory. or Demand. reboot your system to apply the change(s). See Starvation Management on page 70. RTX does not start until an RTSS process is run. HAL Timer Period — Controls the real-time HAL extension timer period. double-click the RTX Settings icon to open the RTX Properties control panel. Debug tab 30 . Using the RTX Properties Contol Panel You use the RTX Properties control panel to set configurable RTX registry parameters. Free Stack on Terminate Thread — Controls whether RTSS frees the memory used for an RTSS thread's stack when the thread is terminated via TerminateThread. If set to Demand. To set RTX properties 1. Specify the settings on each tab (see below) and then click Apply. Debug.RTX User’s Guide Usage net start gencrash Caution: Please close all applications before using gencrash. If enabled. and then allows Windows NT to resume normal operation. 3. When using RtSetTimer and RtSetTimerRelative.0 Reference Guide. When finished. Time Quantum — The value a thread will be given for its default time quantum. It contains four tabs: About. When selected. A FAT file system will generally require checking after a Windows NT stop. Settings. the value must be a multiple of the HAL extension timer period. A value of 0 (zero) means run to completion. Settings tab Startup — Specifies whether RTX is started at system Boot.

Microsoft's WinDbg or NuMega's SoftICE. Control tab Provides buttons for starting and stopping RTX. See Debugging an RTX Program on page 26. Caution: If selected when no debugger is available. Enter Kernel Debugger on RTSS Exception — Controls whether the RTX exception handler initiates an interrupt to the debugger when a fault is raised. When Freeze the Faulting Process is selected.Chapter 2: Using Software Developmen Tools Process Exception Disposition — Controls the disposition of faulting RTSS processes. RTX raises a double fault. 31 . you can debug the process and then unload it using RTSSkill. These are available only when the RTX Startup option (on the Settings tab) is set to Demand. Kernel Debugger — Specifies which debugger is used.

RTX User’s Guide 32 .

This chapter contains: n Process and Thread Management Processes and Threads System Memory Management Clocks and Timers n Interprocess Communication Object Names Shared Memory Semaphores Event Objects Mutex Objects n Device Management Interrupts Port IO Physical Memory Mapping Contiguous Memory Mapping Bus IO n File IO 33 . It also highlights key areas to consider. for both the RTSS and Win32 environments. while developing your programs.Chapter 3 Using the RTX Functionality This chapter presents the RTX functionality along with references to real-time code examples that demonstrate the use of RTX functions (calls) and illustrates the implementation of various real-time programming techniques.

to respond to interrupts and handle asynchronous process-related events in thread context. RTSS and Win32 processes and threads can access processes and threads only within their own environment. Threads are used. This topic discusses: Using_Processes Using_Threads Œ Thread_Priorities Using Processes The sections that follow describe how processes run in the RTSS and Win32 environments. and one or more paths of execution (threads). RTSS performs the following tasks: Loads the executable as a driver Allocates process heap from the non-paged pool Œ Creates the primary thread A process can be started by either one of these methods: Loading it as a device driver during system boot (using the RTSSrun /b utility) Running the RTSS executable from the command line Œ Starting the RTSS process from Win32 applications A process exits under one of these conditions: The last thread has exited One thread calls ExitProcess Œ The process is killed with the RTSSkill utility or the RTSS Task Manager The maximum number of processes that can exist concurrently in the RTSS environment is equal to the number of RTSS process slots in the registry (the default is 10). RTSS processes and threads function much like their Win32 counterparts. for example. at least one thread. Processes in the RTSS Environment A process running in the RTSS environment consists of a set of handles to objects. and an executable. object handles.RTX User’s Guide Process and Thread Management Processes and Threads A process comprises an address space. When a process is created. process address space. Processes in the Win32 Environment A process running in the Win32 environment starts interacting with RTX when it makes an 34 .

A thread gives up the CPU when it: Waits for a synchronization object Lowers its own priority or raises another thread’s priority Suspends itself Returns from the timer or interrupt handler (applicable to timer and interrupt threads) routines Calls Sleep with an argument of 0 Recevives a notification that a time quantum is set Œ Is interrupted by a higher priority The initial thread of a process has an 8 KB stack. depending on the current execution environment of the process. Threads execute in priority order and in "first in. Using Threads The CreateThread function creates either an RTSS or a Win32 thread. it depends on your system’s configuration and resources. RTSS scheduling implements a priority inversion and deferred priority demotion mechanism to eliminate unbounded priority 35 . RTX then may allocate resources for this process. RTSS Environment The RTSS environment has no distinct priority classes. these objects can be manipulated only by processes in their own environment. alter its priorities. The returned handle and thread ID are valid only in the CreateThread caller’s environment. For instance. the thread will run for the specified time and then give up the CPU to another thread with the same priority. You can specify the stack size of subsequently created threads of that process using CreateThread. so the threads of all RTSS processes compete for CPU using the thread priority only. If a time quantum is set to 0. Thread Priorities The sections that follow describe the priorities of threads in the RTSS and Win32 environments. An RTSS thread runs until it gives up the CPU.Chapter 3: Using Using the RTX Functionality RTAPI call. RTSS Environment An RTSS thread is the unit of execution in the RTSS environment. therefore. a Win32 process cannot manipulate the priority of an RTSS thread because the handle for the thread is valid only in the RTSS environment. The number of Win32 processes that can interact with RTX is dynamic. You can. A ready-to-run RTSS thread is scheduled before all Windows NT and Windows 2000 threads. and perform other operations related to its Win32 process status. the handles for these objects are valid only in their own (Win32 or RTSS) environment. first out" order within any single priority. Timer and Interrupt Objects Timer and interrupt objects derive from the threads. semaphores. use the RTX Inter-Process Communication (IPC) mechanisms (such as mutex objects. however. If the time quantum is set to another value. events. Similarly. An RTSS thread runs at one of 128 distinct priority levels. and shared memory) to synchronize and communicate between Win32 and RTSS processes and threads. the thread will run to completion.

7<B0.25. for example. If a higher priority thread calls WFSO on a mutex object that is owned by a lower priority thread. Win32 programs should use the Rt priority calls for the Win32 thread to claim other than the lowest RTSS scheduling priority when waiting on an RTSS synchronization object.25.1   57B35.7<B0.25. 5766 9DOXH        :LQGRZV 17  :LQGRZV  6\PEROLF 3ULRULW\ 1DPH IRU 5HDO 7LPH 3ULRULW\ &ODVV 7+5($'B35. RTX provides a mapping between RTSS and Win32 subsystem priorities. For example.1   57B35. Win32 scheduling may exhibit unbounded priority inversion. Any value from RT_PRIORITY_MIN+5 to RT_PRIORITY_MIN+126 will set the thread at THREAD_PRIORITY_HIGHEST and RT_PRIORITY_MAX will result in THREAD_PRIORITY_TIME_CRITICAL priority.0(B&5.25. however. that RtSetThreadPriority(Thread. and it will return RT_PRIORITY_MIN+5 instead of RT_PRIORITY_MIN+6 through RT_PRIORITY_MIN+126.7<B0. the real-time priority specified in the call to RtSetThreadPriority returns. will always get the RTSS priority that was set. THREAD_PRIORITY_LOWEST) by the Win32 version of the RTX interfaces.25.25.25. However. There are some restrictions. If a Win32 program calls RtGetThreadPriority.7<B+.7<B1250$/ 7+5($'B35. RTSS to Win32 Thread Priority Mapping. RTSS mutex objects support a level-one priority promoting mechanism. RTSS to Win32 Thread Priority Mapping 5766 6\PEROLF 3ULRULW\ 1DPH 57B35. Table 1. the priority of the mutex owner is promoted to the same priority as the higher priority thread.1    57B35.25.7<B$%29(B1250$/ 7+5($'B35.25.7. The most likely source of confusion is when calls to RtSetThreadPriority and SetThreadPriority are mixed. Win32 Environment A Win32 RTX program starts execution in the real-time priority class. shows how RTSS symbolic priority names translate to requests for a particular Windows NT or Windows 2000 priority when RtSetThreadPriority is called by a Win32 program.25.25.7<B0$.25.'/( 7+5($'B35.1 57B35.7<B0. An attempt to demote the priority of a mutex owner thread will be deferred until the thread releases the mutex.&$/ :LQ 9DOXH        Table 1 shows.7<B.RTX User’s Guide inversion. Table 1.25.*+(67 7+5($'B35.7<B0.7<B%(/2:B1250$/ 7+5($'B35.1   57B35. These mappings are fixed and designed to preserve relative ordering among thread priorities. Threads that set and get their own RTSS priorities (such as specifying the thread with GetCurrentThread). RT_PRIORITY_MIN+1) will result in a call to SetThreadPriority(Thread.7<B/2:(67 7+5($'B35.1   57B35. For instance.7<B0.25.7<B7. The library may not always understand the RTSS priority when a duplicated thread handle is used. a Win32 thread with an RTSS priority of RT_PRIORITY_MAX will own a mutex 36 .

7<B0.1   57B35. RtSetThreadPriority.7<B0.25. Memory Allocation APIs 37 .25. Win32 to RTSS Thread Priority Mapping.7<B7.7<B0. If you need finer grain priorities.25.7<B0. Win32 Environment Programming Considerations WIn32 RTX program starts execution in the normal priority class.25. cause problems when the Win32 threads have GUI components. by making sure that your program first makes this call: SetPriorityClass( GetCurrentProcess().25.Chapter 3: Using Using the RTX Functionality before an RTSS thread waiting for the same mutex with a priority less than RT_PRIORITY_MAX.25. however.7<B%(/2:B1250$/ 7+5($'B35. 9DOXH               There are no additional priorities between THREAD_PRIORITY_IDLE and THREAD_PRIORITY_HIGHEST.1   57B35.7<B$%29(B1250$/ 7+5($'B35. Just as in Win32.7.25. When a thread in the REALTIME_PRIORITY_CLASS interacts with the GUI side of Windows NT and Windows 2000.&$/ 9DOXH 5766 6\PEROLF 3ULRULW\ 1DPH 57B35. Win32 to RTSS Thread Priority Mapping :LQGRZV 17  :LQGRZV  6\PEROLF 3ULRULW\ 1DPH IRU 5HDO 7LPH 3ULRULW\ &ODVV 7+5($'B35. you should use the RTSS priority spectrum instead.1   57B35.25.1   57B35.7<B/2:(67 7+5($'B35.25. This table describes the inverse of the mapping shown in Table 1.7<B0.7<B1250$/ 7+5($'B35. This is the desired behavior for most applications because it gives the process the best possible real-time performance. this value specifies a thread priority that is higher than all other priorities.25.25. Table 2.7<B. Table 2.*+(67 7+5($'B35. or any other real-time priority function.7<B0. slowdowns and lock-ups occur.7<B+.25.1 57B35.25. You can avoid this problem when writing a Win32 application that has a GUI component (and links to rtapi_win32. This does. thus eliminating any chance of latencies due to page faults.lib).0(B&5.7<B0$.25. shows what callers of the Win32 "set" and "get" thread priority calls should expect in the RTSS environment. The RTX memory allocation routine always allocates memory that is locked. then calls the first RtGetThreadPriority. NORMAL_PRIORITY_CLASS) System Memory Management This topic discusses: System memory allocation ΠSystem memory locking System Memory Allocation A process frequently must allocate additional memory to perform its operations.'/( 7+5($'B35.1   57B35.

RtFreeLockedMemory frees a previously allocated locked memory region. To avoid failure of large allocations. Win32 Environment Programming Considerations Unless explicitly locked into physical memory. Programming Example (RTX Locked Memory Allocation Calls) See the RTX Locked Memory Allocation Calls Programming Example in Code and File Examples in Appendix A. 38 . It demonstrates the use of RTX locked memory allocation calls. RtCommitLockHeap commits and locks the specified heap. RTSS and Win32 Programming Considerations Locked memory is always allocated from a non-paged pool of memory that is maintained by Windows NT and Windows 2000. RtCommitLockProcessHeap commits and locks the process’s heap. all process and memory objects in the RTSS environment are locked into physical memory to avoid page faults in RTSS processes. including code and data in the operating system itself. RTSS Environment Programming Considerations By default. real-time applications need to lock data and code in memory. Stack) functions will always complete with success in the RTSS environment but will perform no actual operations. then maps the memory into the virtual address space of the process. RtUnlockProcess unlocks sections of a process’s virtual address space previously locked into physical memory. all Windows NT and Windows 2000 processes and services are paged.RTX User’s Guide The following APIs are available to access RTX system memory allocation services: RtAllocateLockedMemory allocates memory that is backed by physical memory and locked. you should minimize their use and/or ensure that they are accomplished shortly after system boot. the RtLockProcess function should be utilized to prevent your real-time process from incurring page faults. Heap. In the Win32 environment. RtCommitLockStack commits and locks the specified stack. and hence unpredictable delays in critical sections of code. The Rt*Lock (Process. Process Locking APIs The following APIs are available to access RTX process memory locking services: RtLockProcess locks all pageable sections of a process into physical memory. This pool of memory is relatively small and is rapidly fragmented by the allocations of other drivers and subsystems in Windows NT and Windows 2000 shortly after system boot. System Memory Locking To prevent page faults.

Programming Example (RTX Kernel Memory Locking Calls) See the RTX Kernel Memory Locking Calls Programming Example in Code and File Examples in Appendix A. For information on non-paged pool size. Adequate memory should be included in any system to accommodate the desired performance of any non-real-time operations. It demonstrates the use of RTX process memory locking calls. In order to make drivers pageable by the system. RtUnlockKernel unlocks sections of the Windows NT and Wndows 2000 kernel previously locked into physical memory.Chapter 3: Using Using the RTX Functionality Programming Example (RTX Process Memory Locking Calls) See the RTX Process Memory Locking Calls Programming Example in Code and File Examples in Appendix A. Locking the Windows NT or Windows 2000 kernel and processes reduces the pool of available physical memory. go the Microsoft Knowledge Base or MSDN Web site. Windows` NT device drivers geneˆ ally do not page. It demonstrates the use of RTX kernel memory locking calls. including most of the kernel and the Win32 subsystem. f˘ w drivers are structuˆ ˘ d in this way. Given the complexity. RTSS Environment Programming Considerations By default. all processes and memory objects in the RTSS environment are locked into physical memory. See Also Contiguous Memory Management 39 . In order to prevent delays of your real-time processes due to kernel page faults. the developer of that driver must carefully structure the driver and manually mark the code sections that are to be paged. Win32 Environment Programming Considerations Certain Windows NT operating system components are paged. Kernel Locking APIs The following APIs are available to access RTX kernel memory locking services: RtLockKernel locks pageable sections of the Windows NT and Windows 2000 kernel into physical memory. use the RtLockKernel function. device drivers loaded at boot time never page. This can have a detrimental effect on the performance of nonreal-time system operations.

This topic discusses: Clock services Timer services Œ Sleep services Clock Services The RTX clocks are counters of specified intervals that measure the passage of time. The RTX clocks are synchronized with the RTX timer services. Relationship to Win32 Clocks The RTX clocks are updated by services provided in the real-time HAL extension. CLOCK_2 (alias CLOCK_FASTEST) — CLOCK_2 services are provided by the real-time HAL extension and have a resolution of 1 µS. RtGetClockTimerPeriod delivers the minimum timer period for the specified clock. available in the Win32 and RTSS environments. The operating system must be able to keep an accurate accounting of the passage of time. 200. and suspend threads for precise intervals. 500. The RTX clock and timer facilities provide the services necessary for threads to perform periodic tasks that correspond with the external passage of time. The clock values are delivered and set in 100ns units (ticks) and are reported as the number of ticks since 12:00 AM January 1. APIs The following APIs are available to access RTX clock services: RtGetClockTime delivers the current value of the specified clock. or 1000 µS. 1601. Clock Types The RTX clocks. You can set the HAL extension timer period using the RTX Settings control panel. The period for timers scheduled on this clock is variable and can be set to 100. the RTX clocks are not synchronized with either the Windows NT or Windows 2000 system clock or the batterybacked time-of-day clock. However. 40 . RtGetClockResolution delivers the resolution of the specified clock.RTX User’s Guide Clocks and Timers Real-time systems require a number of operating system timing services. are: CLOCK_1 (alias CLOCK_SYSTEM) — CLOCK_1 services are provided by the real-time HAL extension and have a resolution of 1 ms. RtSetClockTime sets the value of the specified clock. Threads in both the Win32 and RTSS environments may schedule timers with periods in increments of ´ ms on this clock. schedule threads at precise times.

Note: This does not apply to MP systems because they work on different processors. the timer is known to expire at fixed clock times). the interval timer is used to update the clock and every interval tick adds a fixed time increment to the clock. In addition. 41 . The RTX clock is designed to run at a rate that maintains synchronization with the specified timer period (that is. Timers are associated with a clock in the system—against which its expiration is measured— when it is created. This allows a straightforward calculation of timer expiration values and timer response latencies.Chapter 3: Using Using the RTX Functionality RTX and Windows NT / Windows 2000 Clock Accuracy (UP Systems Only) The interval timer hardware (8254 based) on standard PCs cannot be programmed to run at an even division of seconds (the fundamental interval period is 838. This means that the actual timer period is always somewhat different from the specified HAL extension timer period (the HalTimerPeriod setting in the registry).095344 nanoseconds).1 microseconds. Timer Services An RTX Timer is an implicit handling thread that receives notification from RTSS of a timer expiration and calls the handling routine specified when the timer was created. Because of this drift. 6SHFLILHG 7LPHU 3HULRG  —6  —6  —6  —6 $FWXDO 7LPHU 3HULRG :LQGRZV 17  :LQGRZV  &ORFN 'ULIW     57. The RTX clock also has drift. but at a different rate from the Windows NT and Windows 2000 clocks. The table that follows provides the actual timer periods and associated clock drift rates for the each of the possible timer periods. Windows NT and Windows 2000 periodically read the CMOS time-of-day clock on the PC and applies a drift correction. A timer begins to count down to its expiration after having been set. which leads to an accumulation of rounding errors and results in a small clock drift relative to the "true" time-of-day. unless the application is aware of these drift issues. Windows NT and Windows 2000 maintain an internal time increment resolution of 0. APIs The following APIs are available to access RTX timer services: RtCreateTimer creates a timer associated with a specified clock. &ORFN 'ULIW  —6  —6  —6  —6     General Programming Considerations: The RTX clock should not be used as a time-ofday clock. the timer can be automatically rearmed. Timers that have their repeat interval set to a valid value will execute their handling routine on an ongoing periodic basis and are referred to as "repeat" or "interval" timers. Timers that have their repeat interval set to zero execute their handling routine only once and are referred to as "one-shot" timers. Once the timer has expired and the handling routine returns.

RtCancelTimer cancels the expiration of the specified timer. you should use the appropriate notification object in the handling routine to indicate the event. Programming Example (RTX Timer and Sleep Calls) See RTX Timer and Sleep Calls Programming Example in Code and File Examples in Appendix A. RtSleepFt suspends the current thread for the specified period of time in 100 nanosecond units. Win32 and RTSS Programming Considerations If your application needs to inform other threads of a timer expiration. Programming Considerations RtSleepFt is not supported for use within a Win32 timer thread. and sleep functions is to truncate the specified interval down to the timer tick count. wait functions. RtSetTimer sets the absolute expiration time and repeat interval of the specified timer. APIs The following APIs are available to access RTX sleep services: Sleep suspends the current thread for the specified number of milliseconds. Sleep Services The sleep services let you suspend the current thread for a specified period of time. Relationship to Windows NT Timers RTX timers are not synchronization objects which means threads cannot wait for single objects with an RTX timer handle. then the count is set to one. 42 . RtSetTimerRelative sets the relative expiration time and repeat interval of the specified timer.RTX User’s Guide RtDeleteTimer deletes a previously created timer. It demonstrates the use of RTX timer and sleep calls. The rounding policy on timer expirations including timers. This is in contrast to the Windows NT waitable timer. which is an object on which a thread can wait. If the count is zero. or against which a thread can receive notification.

mutex. These handles and pointers can be obtained by calling either RtCreateSharedMemory or RtOpenSharedMemory. RtOpenMutex. Inter-Process Communication via Shared Memory RTSS shared memory objects allow you to share blocks of data among multiple processes. the function returns a handle of the existing object. When using this technique for mutex objects. use unique names and be sure to check function return values for duplicate-name errors. the function succeeds. however. when creating named objects. it can be difficult to predict which process actually gets the initial ownership. semaphore. the following occur: The memory region is returned to the pool of non-paged kernel memory. For example. Name comparison is case-sensitive. When all processes end their access to a shared memory object. except that it eliminates the need to ensure that the creating process is started first. or RtOpenSharedMemory) to open a handle to the object. additional processes may map the region of memory. the call to RtCreateMutex is equivalent to a call to RtOpenMutex. and shared-memory objects share the same name space. other processes can use the name to call the appropriate function (RtOpenEvent. If multiple processes do request immediate ownership. Therefore. The names of event. Shared Memory The RTSS shared memory object is a region of non-paged physical memory that can be mapped into the virtual address space of a process. mutex. a thread in each process must have its own process-relative handle to a single RTSS shared memory object and its own process-relative pointer to a location where the virtual address of the mapping will be stored.Chapter 3: Using Using the RTX Functionality Inter-Process Communication Object Names Named objects provide an easy way for processes to share object handles. if the name specified in a call to RtCreateMutex matches the name of an existing mutex object. If you specify a name that is in use by an object of another type when creating an object. ΠThe object ceases to exist. A shared memory object is accessed with both a handle and a virtual address. the object must be first created 43 . RtOpenSemaphore. When a shared memory object has a name. none of the calling processes should request immediate ownership of the mutex. Having multiple processes use RtCreateMutex for the same mutex is therefore equivalent to having one process that calls RtCreateMutex while the other processes call RtOpenMutex. and can include any character except the backslash path-separator character (\). Once a process has created a named event. semaphore. In this case. but GetLastError returns ERROR_ALREADY_EXISTS. The name specified by the creating process is limited to RTX_MAX_PATH characters. or shared memory object. To do this. Using RtCreateSharedMemory In order for several processes to use a shared memory object. including RTSS processes and Win32 processes. In order for a process to completely end its access to a shared memory object it must close the handle.

Environments The RTSS shared memory object is always maintained in the RTSS environment. the count is increased by a variable amount at the semaphore release. When RtCreateSharedMemory fails. when you request a resource from an RTSS semaphore. This means that waiting for semaphore objects: 44 . Like usual semaphore objects. if one or more resources are available. Win32 processes may create and open RTSS shared memory objects. the RTSS semaphore objects are used for resource counting. Using RtOpenSharedMemory RtOpenSharedMemory maps an already created shared memory object. no memory is mapped and no handles are returned. an RTSS semaphore. Other processes can then use the shared memory object’s given name to map the shared memory object. additional processes may map the shared memory into their address spaces by calling RtOpenSharedMemory. the operating system checks whether the resource is available and decrements the count of available resources without letting another thread interfere. Only one process can successfully create the shared memory object. the count of available resources is decreased. However. RTSS semaphores perform this test-and-set operation atomically.RTX User’s Guide using RtCreateSharedMemory. When the shared memory object is created. that is. RtCreateSharedMemory fails if the amount of memory requested cannot be allocated or if the named shared memory object already exists. this eliminates the explicit Win32 call to the MapViewOfFile call. The count is decreased by one each time a thread completes a wait for the semaphore object. unlike an RTSS mutex. RtOpenSharedMemory will fail if the named shared memory object does not exist. The RTSS shared memory object is its own named object. After the shared memory object has been created by a process. Semaphores The RTSS semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. cannot be owned by a thread. RtCreateSharedMemory returns a handle and sets a location to the base address of the shared memory. Because several threads can affect an RTSS semaphore’s resource count. RtOpenSharedMemory returns a handle to the shared memory object and sets a location to the base address of the shared memory. Only after the resource count has been decreased does the system allow another thread to request a resource. When the count reaches zero. They give a thread the ability to query the number of resources available. RtCreateSharedMemory does not default to RtOpenSharedMemory if a shared memory object of the same name already exists. the semaphore object’s state is no longer signaled and no more threads can complete a wait on the semaphore object until some thread increases the count. The RtCreateSharedMemory and RtOpenSharedMemory calls implicitly map the shared memory. RTSS backs the shared memory object with non-paged memory. When a process is finished with the shared memory it should close the handle to the shared memory object.

When the call to RtOpenSemaphore is made. Inter-Process Communication via Semaphores To synchronize threads running in multiple processes. including RTSS processes and Win32 processes. Win32 programs may create. open. The semaphore name space is separate from the Win32 semaphore name space. That is. the system guarantees that the order of thread obtaining the semaphore object is the order of thread priority when the RTSS semaphore object is signaled. If the system finds an RTSS semaphore object with the specified name. the RTSS semaphore objects support the waiting priority. as a result. a new RTSS semaphore object was not created. unlike the usual semaphore objects. release. However. The dwDesiredAccess parameter is ignored. Any thread in the calling process can now use this handle in any function that accepts an RTSS semaphore handle. If GetLastError reports ERROR_ALREADY_EXISTS. the system determines that an RTSS semaphore object with the specified name already exists. the system scans all existing RTSS semaphore objects to see if any of them have the same name indicated by lpName. The lpName parameter is the zero-terminated string name of the RTSS semaphore object. Using RtCreateSemaphore The first and most common way is for one thread in each process to call RtCreateSemaphore. If an RTSS semaphore object with the specified name cannot be found. it creates a process-relative handle identifying the RTSS semaphore object and returns the handle to the calling thread. As additional threads call RtCreateSemaphore. Environments The RTSS semaphore object is always maintained in the RTSS environment. A thread can determine whether RtCreateSemaphore actually created a new RTSS semaphore object by calling GetLastError immediately after the call to RtCreateSemaphore. The first thread to call RtCreateSemaphore will cause the system to create the RTSS semaphore object. when there are several threads with the different priority waiting for an RTSS semaphore object. 45 . This allows cooperation between RTSS and Win32 processes. a thread in each process must have its own process-relative handle to a single RTSS semaphore object. and wait for RTSS semaphores. it does not create a new RTSS semaphore object but returns a process-relative handle identifying the existing RTSS semaphore object. These handles can be obtained by calling either RtCreateSemaphore or RtOpenSemaphore. Using RtOpenSemaphore Another method for obtaining the handle of an RTSS semaphore object involves a call to RtOpenSemaphore.Chapter 3: Using Using the RTX Functionality Will never return WAIT_ABANDONED ΠMay lose semaphore resources if threads are terminating However. null is returned. passing the identical string for the parameter of RTSS semaphore name.

An event object is useful in sending a signal to a thread. If more than one thread is waiting for ownership. The waiter learns of an abandoned mutex by examining the wait function's return value. the wait function will not exit until the mutex owner releases the mutex. even if multiple threads are waiting. If no threads are waiting. Ownership A thread owns a mutex between the exit from a wait function and the call to RtReleaseMutex. The creating thread can also specify a name for the event object. the function releases only a single waiting thread. Threads in other processes can open a handle of an existing event object by specifying its name in a call to RtOpenEvent. or threads that subsequently specify the same event object in a call to RtWaitForSingleObject. In cases where threads with 46 . A thread that acquires an abandoned mutex should expect an inconsistent shared resource. If no threads are waiting. If another thread calls a wait function while the mutex is owned (not signaled). see Object Names on page 43.RTX User’s Guide Event Objects An event object is a synchronization object whose state can be explicitly set to signaled by using RtSetEvent or RtPulseEvent. indicating that a particular event has occurred. all waiting threads are released. For additional information about names for objects. When an owning thread terminates. For an auto-reset event object. can be released. at which time the system automatically sets the state to nonsignaled. RtPulseEvent simply sets the state of the event object to nonsignaled and returns. For a manual-reset event object. Using RtPulseEvent A thread can use RtPulseEvent to set the state of an event object to signaled and then reset it to nonsignaled after releasing the appropriate number of waiting threads. Mutex Objects The RTSS mutex object is a synchronization object whose state is signaled when it is not owned by any thread and not signaled when the mutex is owned by a thread. The two types of event objects are: Manual-reset event — An event object whose state remains signaled until it is explicitly reset to nonsignaled by RtResetEvent. the thread with the highest priority gets ownership and is the first thread to return from the wait function. While it is signaled. Auto-reset event — An event object whose state remains signaled until a single waiting thread is released. any number of waiting threads. The mutex object arbitrates exclusive access to a shared resource. the mutex is signaled and abandoned. Using RtCreateEvent A thread uses the RtCreateEvent function to create an event object. The creating thread specifies the initial state of the object and whether it is a manual-reset or auto-reset event object. the event object's state remains signaled. No other thread can own the mutex between these calls.

A thread can determine whether RtCreateMutex actually created a new RTSS mutex object by calling GetLastError right after the call to RtCreateMutex. Any thread in the calling process can now use this handle in any function that accepts an RTSS mutex handle. as a result. null is returned. The first thread to call RtCreateMutex will cause the system to create the RTSS mutex object. 47 . The RTSS mutex name space is separate from the Win32 mutex name space. If the system finds an RTSS mutex object with the specified name. and own RTSS mutex objects. When the call to RtOpenMutex is made. Using RtCreateMutex The first and most common way is for one thread in each process to call RtCreateMutex. However. Win32 processes may create. the system determines that an RTSS mutex with the specified name already exists. passing the identical string for the parameter of RTSS mutex name. If GetLastError reports ERROR_ALREADY_EXISTS. If you are expecting to share this RTSS mutex with other processes. Environments The RTSS mutex is always maintained in the RTSS environment. a thread in each process must have its own process-relative handle to a single RTSS mutex object.Chapter 3: Using Using the RTX Functionality the same priority are waiting to be owners. The lpName parameter is the zero-terminated string name of the RTSS mutex object. including RTSS processes and Win32 processes. the system scans all existing RTSS mutex objects to see if any of them have the same name indicated by lpName. the earliest request goes first. it creates a process-relative handle identifying the RTSS mutex and returns the handle to the calling thread. Inter-Process Communication via Mutex Objects To synchronize threads running in multiple processes. Using RtOpenMutex Another method for obtaining the handle of an RTSS mutex involves a call to the RtOpenMutex. it does not create a new RTSS mutex object but returns a process-relative handle identifying the existing RTSS mutex object. you can ignore this last step. a new RTSS mutex object was not created. The dwDesiredAccess parameter is ignored. If an RTSS mutex with the specified name cannot be found. These handles can be obtained by calling either RtCreateMutex or RtOpenMutex. As additional threads call RtCreateMutex. open.

The RtAttachInterruptVector call maps RTSS priorities into these twelve interrupt levels. . For the lowest level priorities. a thread is created which responds to the interrupt. 118. There are twelve interrupt levels availale to RTSS.. 119. APIs The following APIs are available to manage RTX interrupt services: RtAttachInterruptVector attaches an IST to a specified interrupt. it is often desirable to have a real-time process respond directly to the interrupts generated by these devices. When the interrupt occurs. These are. interrupts that require the highest hardware priority. Win32 and RTSS processes can attach to an interrupt handler using RtAttachInterruptVector. The priority assigned to the interrupt handler thread determines the priority execution order of the interrupt handler in both the RTSS and Win32 environments. the interrupt source is masked. You can also share interrupts exclusively attached within either the RTSS or Win32 environments (but not both) with this call. it becomes the currently executing thread..RTX User’s Guide Device Management Interrupts Real-time systems frequently are required to respond to external devices. the interrupt’s thread is resumed. This handling thread is analogous to an Interrupt Service Thread (IST). RtAttachInterruptVectorEx can attach an IST and/or an Interrupt Service Routine (ISR) to a specified interrupt. When an interrupt handler is attached to a particular interrupt. the interrupt source is unmasked and the thread is suspended. and. if its priority is greater than the priority of the currently executing thread. These interfaces let you attach a handling routine to an interrupt. RtReleaseInterruptVector releases an interrupt previously attached with RtAttachInterruptVector or RtAttachInterruptVectorEx. RtDisableInterrupts under the Win32 environment disables interrupt handling for all interrupts attached to a process. in increasing hardware priority: 0-117. In the RTSS environment. much the same way that the RTX timer routines allow you to associate a handling routine with a given timer expiration. the user may choose from a range of 118-126. After the interrupt handler returns. use 117 or less. In doing so. all interrupts are disabled at the 48 . RTX allows a process to directly interface with a device without having to write a Windows driver. Interrupt Management The RTX interrupt management routines provide interfaces that enable an application to satisfy interrupt requests from devices attached to the computer. For hardware interrupts of lesser priority. the user should assign an RTSS priority of 127 when the interrupt is attached.127 For example.

For more information. ΠInterrupt processing can be disabled for the set of interrupts attached to the RTX process by raising the thread priority level of the currently executing thread. High priority threads never mask timer interrupts. This can lead to non-deterministic scheduling latencies for the handling thread to receive and process the interrupt. RtEnableInterrupts enables all interrupts disabled by RtDisableInterrupts. Therefore. an interrupt thread can be preempted at any time by a thread that runs at a higher thread priority level. 49 . thus. the extra overhead of interrupt sharing could cause problems. To determine what interrupts Windows 2000 is using. Using RtAttachInterruptVectorEx Use RtAttachInterruptVectorEx to share interrupt vectors. You should be aware that sharing of interrupts increases the interrupt latency for the lower priority interrupt service threads. look in Device Manager. this occurs because the higher priority interrupt service thread must run and determine that a shared interrupt is to be passed along to another thread. If your device has hard real-time interrupt latency requirements. an RTSS thread and a Win32 thread cannot share the same interrupt. For buses with automatic configurations. This function lets you associate a handling routine with a hardware interrupt on one of the supported buses on the computer. General Programming Considerations As with any thread. you probably do not want it to share an interrupt line with another device. RTSS threads can share a given interrupt vector. and Win32 threads can do the same. look in the Bus I/O section of this manual. Devices that require very short interrupt latency should be assigned to unique interrupt lines. use RtAttachInterruptVector. To use this call. the timer interrupt is effectively the highest priority interrupt. For situation where very low interrupt latency is necessary. The level must be higher than all of the thread priority levels specified for the RTSS Interrupt Service Threads. you must supply bus-specific parameters. To determine what interrupts Windows NT is using. use Windows NT Diagnostics. However. An interrupt handler that signals an object may satisfy the wait conditions of a higher priority thread. In the Win32 environment. rather than a Win32 process. any time-critical interrupt processing that must be accomplished should be done with a handler running an RTSS process. Using RtAttachInterruptVector To attach an interrupt vector.Chapter 3: Using Using the RTX Functionality processor level. Resuming the higher priority thread will delay the completion of the interrupt handler and delay the time at which the interrupt source will be unmasked. Time slicing effects the execution of ISTs if there is a time quantum set for the IST. the Windows NT and Windows 2000 schedulers service RTX interrupt threads. To mask timer interrupts. use RtDisableInterrupts. Win32 Environment Programming Considerations All processing in the RTSS environment takes priority over all processing in the Win32 environment. such as PCI you can obtain the parameter information by calling RtGetBusDataByOffset.

and write data to hardware devices. see the Port I/O and Physical Memory Mapping sections that follow. a real-time application must be able to acknowledge an interrupt and control the device that generated it. and multi-byte values are entered as sequential single-byte writes to the port address. it will release a previously attached interrupt. Port IO Real-time systems require the ability to control. an RTX application can exit and leave a device enabled. read. The I/O address space is a feature found on Intel processors where each address represents an 8-bit "port. discussed below. hardware designers usually employ designs that have a single-byte port. Note: Just as in an interrupt service routine in a device driver. use RtReleaseInterruptVector. For level-triggered interrupts to operate correctly. the RtWrite* and RtRead* functions. While sequential addresses can represent the bytes in a multi-byte port. Although the RTX library usually cleans up after an application exits. This limitation is found on uniprocessor systems only. This functionality eliminates the need for creating a device driver for every device that must be accessed. may be used to transfer data to and from the enabled port I/O space. The RTX port I/O programming interfaces allow data movement in the I/O space of a processor by a user process without the need to switch to a kernel-mode code. you should consult its programming reference documentation. It demonstrates the use of RTX interrupt management and port I/O calls. Additionally. Access to port I/O devices must be enabled prior to attempting any data transfers. there are times when the exiting application can bypass the library’s attempt to detect the exit. the interrupt service routine must clear the interrupt condition before it unmasks the interrupt line. Port I/O Control APIs The following APIs are available to access Port I/O control services: RtEnablePortIo enables the direct Port I/O access for the specified range of I/O 50 . Programming Example (Interrupt Management and Port I/O Calls) See the Interrupt Management and Port I/O Calls Programming Example in Code and File Examples. To avoid such a condition. it eliminates the latencies associated with requesting device driver services for every device access." Each port typically corresponds to an 8-bit control register on a hardware device. For further details on communicating with devices. with the device attempting to deliver interrupts to the handling thread. This is accomplished with the RtEnablePortIo function by passing in the port I/O address range that will be accessed. Port I/O provides an alternate method of communicating directly with hardware. For details about a particular device. Using RtReleaseInterruptVector Unlike driver unloading. Subsequent to enabling access.RTX User’s Guide Level-triggered interrupts cannot be used by Win32 processes because the interrupt will be reasserted when RTSS tries to return to Windows NT to allow the Win32 service routine to run.

RtWritePortBufferUchar. The RTX physical memory map interface maps a section of physical memory into an application’s virtual address space. two-.RtReadPortBufferUlong copies a series of one-. or four-byte datum from the specified I/O port.RtWritePortUshort. This interface is useful for applications that need to access device memory or registers that are mapped into the physical address space of the CPU. Port I/O Data Transfer APIs (described in the section that follows) Port I/O Data Transfer APIs The following APIs are available to access Port I/O data transfer services: RtReadPortUchar. This enables the application to access a region of physical memory directly. their ports are mapped into memory addresses. Physical Memory Mapping The existence of an I/O space is dependent on the processor architecture. Rather.RtWritePortBufferUshort.RtWritePortUlong directly writes a one-. two-. Physical memory mapping can also be used to give processes access to physical memory ranges in the CPU’s address space. indicating that the subroutines handle the stack cleanup. or four-byte datum to the specified I/O port. two-. or four-byte datum from the specified I/O port to a buffer.RtReadPortUlong directly reads a one-. RtReadPortBufferUchar. as if it were a buffer in the application. Programming Example See Interrupt Managemet and Port I/O Calls Programming Example in Code and File Examples in Appendix A.Chapter 3: Using Using the RTX Functionality addresses. These architectures can use the memory mapping function to enable access to physical memory on controllers and other hardware devices. You should not use other calling conventions. It demonstrates the use of RTX interrupt management and port I/O calls. General Programming Considerations The RTX interfaces are coded in assembly and use the __stdcall convention. APIs The following APIs are available to access RTX memory mapping services: 51 .RtReadPortBufferUshort.RtWritePortBufferUlong copies a one-. two-. RtWritePortUchar. Several Windows NT and Windows 2000-supported architectures are based on processors that do not have a separate I/O space.RtReadPortUshort. RtDisablePortIo disables the direct Port I/O access for the specified range of I/O addresses. or four-byte datum from the specified I/O port to a buffer.

RtUnmapMemory removes a previously mapped physical memory object from the process’ virtual address space. particularly devices that perform DMA. You should take care not to map in and modify Windows NT or Windows 2000 address space as this may lead to corruption of either operating system. 52 . if successful. The mapping will provide precisely the base address and length specified. these devices must access the memory buffers using the actual physical address.RTX User’s Guide RtMapMemory maps a physical memory address range into the process’ virtual address space. General Programming Considerations There are no restrictions or protections on the mapped memory region. The RtAllocateContiguousMemory and RtGetPhysicalAddress functions are used to allocate physically contiguous memory and to translate the virtual address of the memory to a physical address. RtFreeContiguousMemory frees a previously allocated physically contiguous memory region. APIs The following APIs are available to access RTX contiguous memory allocation services: RtAllocateContiguousMemory allocates a physically contiguous memory address range and maps that memory into the process’ virtual address space. Programming Example (RTX Memory Mapping Calls) See the RTX Memory Mapping Calls Programming Example in Code and File Examples in Appendix A. rather than by the virtual address that is used by a Win32 or an RTSS process. To avoid failure of large allocations. you should minimize their use and/or ensure that they are accomplished shortly after system boot. require that their buffers reside in physically contiguous memory in the CPU’s address space. RtGetPhysicalAddress returns the physical address for the virtual address of a previously allocated physically contiguous memory region. Programming Considerations Contiguous memory is always allocated from the non-paged pool of memory maintained by Windows NT and Windows 2000. In addition. Win32 Environment Programming Considerations Accesses beyond the address range allocated in the mapping will result in an exception. respectively. This pool of memory is relatively small and is rapidly fragmented by the allocations of other drivers and subsystems in Windows NT and Windows 2000 shortly after system boot. Contiguous Memory Mapping Certain devices.

Chapter 3: Using Using the RTX Functionality

In the Win32 environment, RtGetPhysicalAddress operates only with addresses returned by RtAllocateContiguousMemory.
Programming Example (RTX Contiguous Memory Allocation Calls)

See the RTX Contiguous Memory Allocation Calls Programming Example in Code and File Examples in Appendix A. It demonstrates the use of RTX contiguous memory allocation calls.

Bus IO
RtGetBusDataByOffset, RtTranslateBusAddress, and RtSetBusDataByOffset facilitate the development of RTSS hardware drivers. Each function eases the gathering of specific hardware information and/or setting hardware. RtGetBusDataByOffset is used primarily in support of attaching a driver to a hardware device by obtaining device information required for input to RtAttachInterruptVector, such as the bus number, interrupt level, and interrupt vector. For example, by issuing a call to RtGetBusDataByOffset, a PCI bus can be scanned, detect a particular device, and then return the bus number where the device resides, the bus interrupt level, and interrupt vector. For further information, see RtAttachInterruptVector and RtAttachInterruptVectorEx in the RTX 5.0 Reference Guide. Setting hardware is accomplished with a call to RtSetBusDataByOffset. This function is useful when device initialization requires clearing or setting of status registers, slot, and so on. RtTranslateBusAddress is used to translate a device-specific memory address range into the logical address space of a driver.
Programming Example (Bus I/O)

See the Bus I/O Programming Example in Code and File Examples in Appendix A. The code fragment illustrates each of the Bus I/O calls in a PCI driver.

File IO
File IO

RTX allows two options for file input and output (I/O). You can write to the supported file I/O functions in the Win32 API or to the supported file I/O functions in the C run-time library. The API delivers low-overhead, fast access to Windows NT and Windows 2000 file I/O capabilities using standard APIs. A subset of CreateFile flags are supported with file I/O. Please refer to the RTX 5.0 Reference Guide for more details. File I/O does not include support for asynchronous file operations. Because RTSS applications have no current-directory notion, RTSS file I/O requests must use fully qualified path names, such as: c:\temp\MyFile.txt (for a file system object)

53

RTX User’s Guide

\\.\MyDevice0 (for a device object) RTSS file I/O calls are made from the Windows NT or the Windows 2000 kernel environment: RTX actually translates Win32 names such as c:\MyFile.txt and \\.\MyDevice0 to NT internal names \??\c:\MyFile.txt and \Device\MyDevice0, respectively. You can, therefore, use Windows NT and Windows 2000 internal names from your RTSS applications, although such calls fail in Win32. Using an internal Windows NT or Windows 2000 name lets you access a device object for which Win32 has no symbolic link, such as \Device\beep or \Device\Harddisk0\Partition1\testfile.txt. With boot-time file I/O, you may only use paths such as \\Device\\Harddisk0\\Partition1\foo.txt because paths such as \\??\\C:\\foo.txt and C:\\foo.txt are not supported.

54

Chapter 4 Developing an Application
This chapter discusses the two types of real-time dynamic link libraries (RTSS DLL and RTDLL), and provides references to code examples for each type. It also explains how to use the C run-time library functions and floating point; provides guidance on writing device drivers; explains exception handling in the RTSS and Win32 environments; and provides techniques for managing starvation conditions. This chapter contains information on: Using the RTX Makefile Using RTX Dynamic Link Libraries Using the C Run-time Library Functions Using Floating Point Writing RTSS Device Drivers C++ and Structured Exception Handling System Exception Handling About System Exception Handling RTX Handler Tables of Exceptions RTX Exception Handling About RTX and Windows NT / WIndows 2000 Stop Messages Interpreting Windows NT Blue Screen Stop Messages Interpreting RTX Green Screen Stop Messages Starvation Management Power Management

55

RTSS_OBJS. RTSS_MTCRT — Includes the RTSS C run-time library for multi-threaded applications in the final link of the RTSS executable.RTX User’s Guide Using the RTX Makefile You can use the RTX master makefile (rtx. RTSS_CRT — Includes the RTSS C run-time library for single-threaded applications in the final link of the RTSS executable.exe) files in a makefile using rtx.mak includes win32. Sample Makefile See the Makefile Sample in Code and File Examples in Appendix A. Variables The master makefile uses the following variables: NODEBUG — Calls the link using the /RELEASE option.mak because rtx.mak. Rtx. You can specify Win32 executable (.mak contains rules to compile C files and link the resulting objects.mak) to build both RTSS and Win32 versions of a particular program. respectively. RTDLL_OBJS — List of object files linked by rtss link or rtdll link makefile rules. USER_LIBS — Additional user-specified libraries that will be included in the link stage. 56 .

because RTDLLs are not RTX processes. RTDLLs — RTDLLs are RTSS objects that can be dynamically loaded and unloaded using the LoadLibrary and FreeLibrary calls. see Creating RTX Dynamic Link Libraries on page 25.rtss"). For further details about the relationship between C run-time libraries and RTDLLs see C Run-Time Libraries:Programming Considerations for DLLs below. but are cumbersome to load because they are neither loaded nor unloaded automatically when RTSS applications using them start running. it is not reliable to use C run-time functions within an RTDLL loaded by more than one RTX process simultaneously. The variation of hardware run-time configurations that an application must accommodate may also affect your choice. RTSS DLLs allow you to reference exported functions by name in a calling program.lib (see Using the C Run-time Library Functions on page 59). The Microsoft C run-time initialization code assumes that global variables have process 57 . Main for an RTSS DLL will simply issue a SuspendThread call.Chapter 4: Developing an Application Using RTX Dynamic Link Libraries This topic provides: n n n Descriptions of the two types of real-time DLLs (RTSS DLL and RTDLL) C Run-Time Libraries: Programming Considerations for DLLs References to RTSS DLL and RTDLL code examples For instructions on creating DLLs. Although similar to RTSS applications. flexible runtime accommodation of changes to RTDLLs or applications.g. C Run-Time Libraries: Programming Considerations for DLLs This section discusses considerations that you should keep in mind when designing an RTSS DLL or RTDLL that will be linked with the RTX-supplied C run-time libraries. Because RTDLLs do not require linking to an explicit export library. with RTDLLs the address of each exported function used by a calling process must be explicitly obtained through a call to GetProcAddress.. Typically. and they are compiled and linked to generate a library of exported functions that can be linked with RTSS applications. About RTSS DLLs and RTDLLs There are two types of real-time DLLs (RTSS DLL and RTDLL) that you can use to share code between processes or make run-time determinations of what libraries need to be loaded for a given hardware configuration. The choice of RTSS DLLs or RTDLLs for a particular application depends on the specific functional requirements of the application. RTSS DLLs — An RTSS DLL is actually not a DLL but an RTSS process that exports functions for use by other RTSS processes. It shares a common address space with RTSS processes. RTXlibc. their entry point is Main. System("RTSSrun LibName. Additionally. They are automatically unloaded from memory when the last RTSS process referencing them terminates. they provide a convenient. They can be loaded either at boot time or through a call to Windows NT from within a C/C++ program (e.lib or RTXlibcmt. Programming examples for RTSS DLLs and RTDLLs are provided in the sections that follow. However.

global structures created at initialization will persist during the entire life of any process depending on the RTSS DLL. Among other things. and because they never get unloaded from memory except at shutdown. the C run-time initialization creates heaps used for memory allocation. it is recommended that you never register RTDLLs linked with the C run-time libraries with the /s switch of RTSSrun. Since the behavior of C run-time functions is reliable only in an RTDLL loaded by multiple processes given strict limitations on the LoadLibrary. vsprintf(). FreeLibrary sequence. including the same RTSS image. getenv(). i. and wprintf(). printf(). a separate copy of all C run-time global variables and structures exists for each process using the libraries. RTDLLs RTDLLs are not RTSS processes. The routines that you should not use are: fprintf(). they are RTSS objects which can be dynamically loaded and unloaded. Because these routines rely on per-process global variables. These heaps persist only until the process that initially loaded the RTDLL terminates. Note that in this context "used by multiple processes" means used by more than one process at any time between system startup and shutdown. RTSS DLLs Because RTSS DLLs are RTSS processes which have been linked to generate an export library. Note: A few C run-time routines are unsafe within an RTSS DLL used by multiple processes.e. they are destroyed when that process terminates.RTX User’s Guide scope. they can yield undefined behavior that may require system reboot. running twice in succession with the same RTSS PID. Because other objects created by an RTDLL are always owned by the calling process. perror().. This is not true for RTSS DLLs or RTDLLs. 58 . RTSS DLL and RTDLL Code Examples See RTSS DLL Code Example and RTDLL Code Example in Code and File Examples in Appendix A.

RTX allows RTSS threads to use the Floating-Point Unit (FPU) to perform floating-point operations. and mapped memory. you must add the following line to your makefile before the line that includes rtx.mak: RTSS_CRT = 1 The preceding line enables Floating-Point Unit (FPU) support. Bus I/O.0 Reference Guide. Other than this improvement.0. Additionally. Because Windows NT and Windows 2000 device drivers are often user-mode drivers and rely on user-mode Windows NT and Windows 2000 services. Furthermore. The RTX-supplied C run-time libraries are based on the Microsoft Visual C++. Unlike Windows NT. Using Floating Point Threads that run in the RTSS environment always run in kernel mode. Enabling Floating-Point Support in RTSS Programs If you build RTSS programs using NMAKE.Chapter 4: Developing an Application Using the C Run-time Library Functions RTX provides support for C run-time library functions. where access to drivers 59 . If you are using Microsoft Visual Studio. including the floating-point math routines and printf with floating-point support. Whereas the Windows NT and Windows 2000 kernel does not support floating-point operations in kernel-mode code (such code causes the system to crash). they do not differ substantially from the Microsoft libraries. For a list of available functions. provide improvements to the efficiency of memory allocation (malloc). Devices can be accessed and controlled through three types of functions: Port I/O. The RTX libraries.lib (indicating single and multi-threaded libraries). follow the procedure to enable C run-time support as described in Using Microsoft Visual Studio 6. they cannot be used "as-is" with RTSS applications. named RTXlibc.lib and RTXlibcmt. The RTX device driver model is simpler than that of Windows NT and gives you greater flexibility in design. Running RTSS Programs Using Floating-Point You do not need to follow any special procedures to run an RTSS program that uses floatingpoint. it is generally not possible to access standard Windows NT and Windows 2000 device drivers from within an RTSS application. Writing RTSS Device Drivers RTX provides a number of features that enable you to quickly and easily develop device drivers. see the C Run-Time API List in the RTX 5. drivers can respond to devices by providing interrupt handlers through RtAttachInterruptVector. The program can simply issue Floating-Point Unit (FPU) instructions and call floatingpoint math routines as done by a standard Win32 program. C run-time libraries. since even kernel-mode drivers are often accessed through user-mode libraries supplied by hardware vendors.

Win32 Structured Exception Handling (SEH) API. Support is limited to libraries that depend upon the set of Win32 functions supported in the RTSS environment. RTSS drivers can be structured as static libraries. and communicates with necessary devices through standard Windows NT device drivers. GetExceptionCode. When hard real-time performance is not required for device access. Structured Exception Handling RTSS supports Structured Exception Handling and C++ exceptions. with some restrictions discussed in the note below. and network devices. In each case. Note: RTX does not claim support for all C++ libraries. UnhandledExceptionFilter. Œ Handling for the following software exceptions in RTSS: EXCEPTION_DATATYPE_MISALIGNMENT EXCEPTION_BREAKPOINT EXCEPTION_ACCESS_VIOLATION EXCEPTION_ILLEGAL_INSTRUCTION EXCEPTION_FLT_DENORMAL_OPERAND 60 . the driver writer can supply library functions directly to the RTSS application writer without the need to employ the DeviceIoControl interface. and C frame-based exception handling (try/except/finally). including: Win32 Structured Exception Handling calls. which include RaiseException. including new/delete operators and exception handling. AbnormalTermination. For many applications. This topic discusses: C++_Support Œ Structured_Exception_Handling C++ Support RTX supports the Visual C++ language. SetUnhandledExceptionHandler. You can test specific libraries to determine whether they are supported by RTX. GetExceptionInformation Frame-based exception handlers: try-except and try-finally. as described by the Win32 Platform SDK. C++ exception handling: try-catch. RTSS DLLs. the recommended approach is to develop a Win32 application that communicates with RTSS applications through IPC mechanisms. it is not necessary to write a hard real-time (RTSS) device driver for standard desktop devices. or RTDLLs. as is often the case with video. C++ and Structured Exception Handling RTX supports Microsoft C++ exceptions (catch/throw). all as defined by the Win32 Platform SDK.RTX User’s Guide occurs via calls to DeviceIoControl. sound. RTSS should support any C++ features usable in a Win32 C++ RTX API console application.

Until the user responds to the box. A stack fault in RTSS causes a system shutdown (the "green screen"). RTSS acts differently.lib which contain runtime support for the SEH frame-based exception handlers). if so configured) all threads of a process whenever any of them gets an exception. but repeated re-assertion of exceptions consumes stack space. the system displays a dialog box. emulate the Win32 behavior by using per-thread unhandled exception filter functions. Once the user has responded. or with static-linkage run-time support C++ libraries. On an exception. You can. Nested exceptions and collided unwinds RTSS follows Win32 rules for nested exceptions and "collided" unwinds. This behavior is safer and more intuitive in the RTSS context. Hardware exceptions — RTSS exception codes for hardware exceptions are tied to Pentium interrupt codes. UnhandledExceptionFilter Win32 UnhandledExceptionFilter semantics provide the option to disable the exceptionrelated dialog box pop-up via SetErrorMode with the SEM_NOGPFAULTERRORBOX flag. it freezes (or unloads. an errant Win32 application gets an EXCEPTION_ACCESS_VIOLATION 61 . Differences Between Win32 and RTSS Exception Handling The RTSS implementation follows Win32 SEH semantics where possible.Chapter 4: Developing an Application EXCEPTION_FLT_DIVIDE_BY_ZERO EXCEPTION_FLT_INEXACT_RESULT EXCEPTION_FLT_INVALID_OPERATION EXCEPTION_FLT_OVERFLOW EXCEPTION_FLT_UNDERFLOW EXCEPTION_INT_DIVIDE_BY_ZERO Using SEH To use SEH in an RTSS application. so for robustness. all threads of the application terminate. however. RTSS terminates a process that has generated a non-continuable exception. For example. and produces an informational pop-up. RTSS always displays a pop-up saying that the application has been frozen or unloaded. Exception caused by a thread When a thread of a multithreaded application causes an exception in Win32.lib or RTXlibcmt. other threads of the application continue running. Win32 repeatedly re-asserts those. an application must be linked with a Win32 staticlinkage run-time support library (such as RTXlibc. thus differing from Win32 exception codes caused by similar errors. This section describes the differences. with a few minor differences: Non-continuable exceptions — Non-continuable exceptions caused by the program directly or by exception handling run-time itself.

if the CPU encounters a divide by 0. it initiates one of the following actions: Freezes and/or terminates the process 62 . However. A Win32 EXCEPTION_ILLEGAL_INSTRUCTION is equivalent to the RTSS EXCEPTION_INVALID_OPCODE. Each exception is assigned an error code or vector number. Because stack faults in RTSS cause system shutdown. which processes the exception. therefore. RTX Handler RTX provides a handler to process exceptions that occur in an RTSS process. System Exception Handling About System Exception Handling An exception is a forced transition from normal program execution to a specialized procedure. if a filter expression always faults. so any access of that area causes an exception. or always dismisses a hardware exception which gets re-executed. rather than cause an exception. It is quite easy to write code that causes infinite re-assertion of an exception. An exception is raised (occurs) when the CPU encounters an error condition during program execution. Testing your application in Win32 becomes more important than ever to avoid stack overflows in RTSS. Debugging For debugging. an RTSS application gets EXCEPTION_PAGE_FAULT as described in the RTX Reference Guide. (If an exception occurs in a native Windows NT or Windows 2000 application. exception 0 is raised. General User Notes for Exception Handling Exception handling is a powerful mechanism with often subtle semantics. see Volume 3: Architecture and Programming of the Pentium® Processor Family Developer's Manual. called a handler. Windows NT and Windows 2000 occasionally make this area valid for kernel processes and device drivers (and. This means that a write to/read from address 0 from an RTSS process may occasionally succeed. the process continues generating exceptions until it overflows the stack. the Windows operating system handles it. Important: All discussions in this chapter ("System Exception Handling") assume that RTSS applications do not use Structured Exception Handling (SEH). see C++ and Structured Exception Handling.RTX User’s Guide as defined by Win32. For a complete discussion of exception handling.) When the RTX handler encounters an error. For example. Reads/writes of address 0 — Win32 explicitly guarantees that the first 64K of a user process's address space is unmapped. For example. see the Debug tab in the RTX Properties control panel. for RTSS). For information on SEH. you must be careful when writing exception handlers. Miscasting the handler argument to SetUnhandledException filter may be equally fatal.

&(37./$%/( (UURU &RGH . 57.16758&7. RTX will alert the user via a popup message. make an entry to the event log. ([FHSWLRQ (. and the exception handler response. IUHH]HV WKH SURFHVV .21B$&&(66B9.21B13.9.2/$7.&(37.21 (.B127B$9$.&(37.21B)/7B'(1250$/B23(5$1' (.B(5525 :LQ 0DSSLQJ (.Chapter 4: Developing an Application Modifies the application environment and continues ΠExecutes an orderly shutdown.&(37.&(37.&(37.&(37.19$/.&(37. RTX immediately initiates an RTX Green Screen stop message.21 (.21B13.21B)/7B'.19$/.I QR GHEXJJHU LV SUHVHQW 57.&(37.&(37.9.&(37.&(37.21B)/7B.21B. the RTX handler immediately initiates a double fault and Green Screen stop message.&(37. Tables of Exceptions This topic contains tables of the following types of exceptions: RTX exceptions ΠIntel exceptions RTX Exception Codes The table that follows lists the exception name. If a fault occurs during exception processing.21B)/7B81'(5)/2: (.'B23(5$7.21 (.'(B%<B=(52 (.&(37. ZLOO $OORZ IRU IORDWLQJSRLQW FDSDELOLW\ DQG FRQWLQXH H[HFXWLQJ WKH DSSOLFDWLRQ (QWHU WKH GHEXJJHU .21 (.&(37.&(37.21B.1(.&(37. [ ([FHSWLRQ (.&(37.21B'.&(37.'(B%<B=(52 (.$&7B5(68/7 (.17 [ (.//(*$/B.21B'28%/(B)$8/7 (.21B5(6(59('B75$3 (.B29(5581 (.&(37.19$/.17B'. and freeze or terminate the thread and associated process.21B.21B10. known as a "Green Screen" Note: If an exception occurs within an ISR (such as an RTX harware interrupt or RTX timer interrupt).'B23&2'( (.&(37.'(B%<B=(52 (.&(37.&(37.'('B%<B=(52 (.9.'B766 [ [ [) [$ Intel Exception Codes Following Win32 behavior. the vector number or error code. (.21B13.21B*3B)$8/7 (.21B)/7B.VVXH D *UHHQ 6FUHHQ VWRS PHVVDJH (.21B.21B)/7B'.9.21B. RTSS maps the Intel (x86) exception code to the Win32 one.'B23(5$7.19$/.21B)/7B29(5)/2: (.21B)/7B. and then invokes Structured Exception Handling.21B3$*(B)$8/7 63 .

17 (. RTX might display the following window: RTX Exception . RTX might display the following window: RTX Exception . The disposition of the thread is frozen.&(37.*10(17 RTX Exception Handling For most exceptions. The user is directed to manually terminate the process using RTSSkill.21B%5($.21B'(%8* (.Memory Access Fault at loc FEBDF229 (Proc=80452448.&(37. controls the disposition of faulting RTSS processes. the RTX handler performs the following tasks: Freezes or terminates the errant RTSS process.21B$/.21B6(*0(17B127B35(6(17 (.32. :LQ 0DSSLQJ (. Possible values are: 0 = Terminates processing (default) 1 = Freezes the thread and processing Alert User The RTX handler alerts the user of an exception with a popup message window. depending on the state of the ExceptionDisposition flag Alerts the user with a popup window Œ Writes one or more associated entries in the event log The sections that follow describe each of these tasks. Freeze or Terminate Processing The ExceptionDisposition registry flag. a memory protection fault has been detected. a memory protection fault has been detected.Memory Access Fault at loc FEBEB229 (Proc=80452448.6$/. 64 . (. The message identifies the application instruction address and the process and thread identification values. For example. The message identifies the application instruction address and the process and thread identification values. settable from the RTX Properties Control Panel. if the handler terminates processing.RTX User’s Guide [ ([FHSWLRQ (.&(37.*10(17B&+(&.&(37. The disposition of the thread is unloaded.&(37. If the RTX handler freezes processing.21B%281'B&+(&.&(37.21B'$7$7<3(B0. Thread=804526F8) Process image has been * frozen * Debug and/or use "RTSSkill" command to unload all processes In this example. Thread=804526F8) Process image has been * unloaded * In this example.

double click the System icon and then open the Startup/Shutdown tab. About RTX and Windows NT / Windows 2000 Stop Messages Stop messages. The 3 dwords of RTSS fault data are: Instruction pointer value (febdf229 in the sample) RTSS process identification (80452448 in the sample) ΠRTSS thread identification (804526f8 in the sample) Caution: To preserve event log information. The error entry contains two parts: a description and binary detail. deselect the Automatically Reboot option.Chapter 4: Developing an Application Generate Event Log Entries The event log message includes an information entry. The description for Event ID (12) in Source (Rtx_rtss) could not be found. To enable (view) stop messages. It contains the following insertion string(s): \Device\Rtx_rtss. 2. Note: You should select the Automatically Reboot option only if you want to disable stop messages and have the system reboot automatically when there is a system failure. quickly provide you with key information about a system crash. 65 . Click OK to save the settings. RTX Exception . do not filter event entries. presented via an RTX Green Screen or a Windows NT Blue Screen. In the Windows NT Control Panel. which is the text portion of the popup window. and an error entry that provides details about the error. A stop message often gives you sufficient data to determine why a system has crashed and what actions to take to resolve the problem. To enable stop messages 1. In the Recovery section. you must disable the Windows NT Automatically Reboot option as shown in the procedure that follows. as illustrated in the sample that follows. The binary detail consists of 10 dwords of message data and 3 dwords of RTSS fault data.Memory Access Fault 0000: 00100000 00620002 00000000 c004000c 0010: 00000000 c0000183 00000000 00000000 0020: 00000000 00000000 feac12e8 febdf229 0030: 80452448 804526f8 The first 10 entres in the message dump are` specific to the error logging call and are ignored.

Section 2 . that the last calls on the stack are not always the cause of the problem.System Stack Dump The System Stack Dump lists some of the calls on the stack that preceded the stop message. along with the driver list (in the second Blue Screen section). If the address falls within the base address of one of the drivers on this list.Stop Message The Stop Message section provides the bugcheck data in the form: ***STOP: #E(#1. To get a more detailed stack trace. You should always record the first few lines. its four parameters.RTX User’s Guide Interpreting Windows NT Blue Screen Stop Messages When a non-recoverable exception occurs within a native Windows NT application. The Windows NT Blue Screen contains four sections of data.Driver List The Driver List is a two-column display that lists all drivers loaded on the computer at the time the stop message occurred. use a kernel debugger such as WinDbg. then that driver may be the cause of the crash. you can often diagnose the source of a stop condition. 66 . These two lines contain the stop error code. #1 . and the text of the stop error message. Text = Best effort interpretation of the error. #4) Text interpretation of the error where #E = Actual error code. With this data.#4 = Additional parameters relating to the error. Note: Under some conditions. #3. before rebooting the computer. Section 1 . You should note. however. the first few lines indicate what component or driver caused the error. along with their base addresses in memory and date stamps of the driver file dates. with the most important information contained in the first two lines. The stack dump also provides the names of modules along with their starting addresses. Sometimes. the kernel displays only the top line of the stop message because the services required to display the rest of the information may not be available. Windows NT initiates a Blue Screen. Section 3 . #2. This section is important because many stop messages contain the address of the instruction that caused the error.

the system memory dump will be written to %SystemRoot%\memory. 2. Install the dumpexam. For more detailed system information concerning the crash. double-click the System icon and then open the Startup/Shutdown tab. 67 . The following message then appears: Restart and set the recovery options in the system control panel or the /CRASHDEBUG system start option. Reboot your system and then run the dumpexam utility. If the error persists enable the Kernel Debugger in either DEBUG or CRASHDEBUG mode on your computer. In the Windows NT Control Panel. the stop condition may not happen again. To obtain additional information about a system stop 1. Copy the system symbol files (*. consult the dumpexam text output. 5.exe utility (also on the installation CD).dbg files to %SystemRoot%\symbols.Communication The Communication section of the Blue Screen provides confirmation of the communication parameters used by a kernel debugger (if present on the target computer). Note: When this option is selected.dmp after a crash.Chapter 4: Developing an Application Section 4 . 4. select the Write Debugging Information option and then click OK to apply the change. contact your system administrator or technical support group. 3. In the Recovery section. Consult the Windows NT Debugger documentation for instructions on configuring the computer for debugging This message implies that if the computer is restarted.dbg) from the Windows NT installation CD and the RTX-supplied *. If this message reappears after you restart.

errors that were not directly caused by the thread running at the time of the problem may not be discovered by an analysis of this file. The Windows 2000 support tool dumpchk.exe will be required to generated text from the binary dump. as well as other data A list of loaded drivers Œ Œ Œ Œ The processor context (PRCB) for the processor that stopped The process information and kernel context (EPROCESS) for the process that stopped The process information and kernel context (ETHREAD) for the thread that stopped The Kernel-mode call stack for the thread that stopped This kind of dump file can be useful when space is limited. All that is needed is a small 2mb paging file on the system drive and configuring the Startup and Recovery Options for minidump on the System properties screen. The user can still obtain the same type of information by using the "minidump" or small memory dump option.RTX User’s Guide Interpreting Windows 2000 Stop Screens For Windows 2000 the traditional "Blue Screen" has been eliminated. because of the limited amount of information included. Refer to the following Microsoft documentation: Reading Small Memory Dump Files Created by Windows 2000 Windows 2000 Memory Dump Options Overview 68 . This dump file type includes the following information: The stop message and parameters. However.

NMI_EXCEPTION 12. #3. #2 = Contents of Instruction Pointer Register at the time exception was raised. PROXY_THREAD_SANITY 7. Sections 3 and 4 are similar to those sections of the Windows NT Blue Screen. #2. #4 = RTSS Process identification. LOCK_HIERARCHY_VIOLATION 4. UNHANDLED_EXCEPTION 2. #3 = RTSS Thread identification. THREAD_STACK_OVERFLOW 3.Chapter 4: Developing an Application Interpreting RTX Green Screen Stop Messages When a non-recoverable exception occurs within an RTSS process. PROXY_DISPATCHER_SANITY 6. STACK_OVERFLOW #1 = Exception code taken from Exception Table. The RTX Green Screen contains four sections of data. the most likely cause of the exception is a corrupt stack with an illegal value restored to the IP. LOCK_OWNER_VIOLATION 5. the RTX exception handler initiates a Green Screen. SYSTEM_PROCESS_EXCEPTION 11. #4) Text interpretation of the error where #E = Actual error code. 69 . Error code numbers and their associated text are: 1. Sections 1 and 2 are RTX specific. Section 1 . SERVER1_SANITY 8. If the #2 value is outside the address range of the process.RTSS-Specific Stop Message This Stop Message section provides the bugcheck data in the form: *** RTX/RTSS Stop : #E(#1. KERNEL_MODE_EXCEPTION 10. EXCEPTION_IN_ISR 9.

#3. This timer checks on every timer interrupt (which is normally always enabled) for continuous running of the same thread and/or RTSS threads to the exclusion of Windows NT (the idle thread). On a multi-processor system. Starvation Management This topic discusses the RTX watchdog timer and programming techniques that you can use to manage starvation conditions. see Volume 3: Architecture and Programming of the Pentium® Processor Family Developer's Manual. When a thread becomes CPU bound on a single-processor system. The offending process is either stopped or terminated. you can use the RTX starvation management watchdog timer. a popup message notifies you of the error. For the majority of exceptions. Watchdog Management For this type of condition. For more information. Hardware exception vector number. Other codes are reserved for internal RTX errors. the both Windows operating systems continue to run but cannot terminate the CPU-bound thread because the lower priority Service Request Interrupt (SRI) manager threads will not run. #2. Watchdog Timer When a single RTSS thread becomes CPU bound. Text = The text interpretation attempts to match one of the entries in the stop message to a loaded image base address to determine approximately where the fault was raised. this address will be the base address of the Task State Segment. an exception stack frame containing the system state information is stored on the current stack. Indicates that an RTSS process caused the exception. In the case of a double fault. an exception is raised. 70 . and then Windows NT and Windows 2000 resume normal operation. it is often the result of a program logic error (which occurs most frequently during the development phase). Stack pointer at time of fault. based on the Process Exception Disposition setting in the RTX Settings control panel. You can use the RTSSkill utility to unload the stopped process. When the watchdog timer expires. Contents of Instruction Pointer Register at time exception was raised. Windows NT and Windows 2000 both freeze.RTX User’s Guide Section 2 . Base address of the exception frame. #4) *** Address XXXXXXXX has base at YYYYYYYY-Kernel Image where #E = #1 = #2 = #3 = #4 = 0 (zero).HAL-Supplied Stop Message This Stop Message section provides the bugcheck data in the form: *** STOP: #E(#1.

demonstrates the use of the timer approach. You could suspend the thread for . N milliseconds = Enable the watchdog timer and set time period (a typical period is tens of seconds). You can easily manage this type of situation by creating a timer handler that periodically suspends the CPU bound thread(s) for short periods of time. move the mouse pointer.Chapter 4: Developing an Application Setting the Starvation Time Out Period You can set the Starvation Time Out period using from the Settings tab of the RTX Properties control panel. starve. Values are: 0 = Disable the watchdog timer. system power state transitions from working state (S0) to any sleeping state (S1-S5) will be blocked by RTX Power Management. RTX Power Management for Windows 2000 If there are RTSS processes running on UP system. Programming Techniques/Considerations An application may behave correctly. system power state transitions from working state (S0) to any sleeping state (S1-S5) will be blocked if RTSS is loaded on one processor.5 milliseconds every 10 milliseconds during the 100 milliseconds that it runs. such transitions are not blocked. However. for example. an application that runs a thread for 100 milliseconds every second. perform disk I/O. You will see a popup message box telling this fact. You can create an algorithm. This might be needed. a five percent duty cycle is a reasonable initial setting. Since the desired behavior can be quite complex. Typically. if there are no RTSS processes running on UP system. It is located in: c:\program files\vci\rtx\bin\samples\starvation Another approach to starvation management is to simply include calls to Sleep. The RTX sample program. to support starvation management. which should give small amounts of time to Windows NT and Windows 2000 within your application. an RTX-defined policy of giving Windows NT time slices may be unnecessary or may interfere with RTSS deterministic behavior. acknowledge network requests. or display something on the GUI. You can then use the algorithm to measure and adjust your starvation management. as simple or complex as desired. to allow Windows NT and Windows 2000 to empty the RS232 UART silo. yet it may have one or more threads that become CPU bound for periods of time.c. 71 . Take. On MP system. you could periodically give small amounts of time to Windows NT during these periods. In this case. for example.

RTX User’s Guide

72

Chapter 5 Performance Overview
Real-time systems have exacting performance requirements, including deterministic response times for key operations. This chapter covers the sources of interrupt latency, platformspecific timing factors, and measurement techniques an RTX developer can use to ensure good response times. This chapter contains: Causes and Management of Interrupt Latencies Reducing Your System’s Latencies: Tools Overview KSRTM versus SRTM Using KSRTM (Kernel System Response Time Measurement) Using SRTM (System Response Time Measurement) Using RTX Demo (Graphical version of SRTM) Using the Timer Latency Display Tool Using LTP (Latency Test Program)

73

RTX User’s Guide

Causes and Management of Interrupt Latencies
Interrupt latency is of particular concern to real-time systems developers. This topic examines its causes and RTX techniques for managing them. It includes: Software causes Hardware causes

Œ

Management of interrupt latencies

Software Causes
Software causes of interrupt latencies include: PIC (programmable interrupt controller)-level masking of interrupts. Windows NT and Windows 2000 kernels and drivers change interrupt masking via HAL IRQL manipulation calls. Drivers routinely mask interrupts for several µs. Processor-level masking of all interrupts. The Windows NT and Windows 2000 kernel, HAL, and special system drivers may mask interrupts for up to 100ms.

Œ

Interrupt-processing overhead.

Hardware Causes
Hardware causes of interrupt latencies include: Bus "hijacking" by peripheral devices. For example, a video card may stall the CPU's attempt to read the card's I/O space register. Burst DMA by SCSI controllers. Cache dirtying by Windows NT and applications.

Œ

Power Management features. Some systems, particularly portables, go to a low-power state after a time-out, and "wake up" with a delay that you can barely notice, but which is intolerable to a real-time application.

RTX Management of Interrupt Latencies
RTX eliminates PIC-level interrupt disabling by isolating interrupts (through the RTX HAL extension). Windows NT and Windows 2000 and their drivers cannot disable RTSS interrupts. In addition, all Windows NT and Windows 2000 interrupts are masked when RTSS is running.

74

a full thread context). it measures only the time to the beginning of the Interrupt Service Routine (ISR). and reporting instances of latencies exceeding a certain threshold. see Using KSRTM (Kernel System Response Time Measurement) on page 76. see Using the Timer Latency Display Tool on page 80. LTP (Latency Test Program) LTP finds misbehaving peripheral devices. SRTM measures the total time to an RTSS program’s timer handler (i. This application loops. see Using SRTM (System Response Time Measurement) on page 77. The performance-measurement tools introduced in this topic will help you analyze your system and determine whether it is performing as expected. For further details. best case. While KSRTM provides detailed information about the source of the worst-case latency. An SRTM histogram often shows a characteristic double peak profile: the first peak is a near-) and Using RTX Demo (Graphical version of SRTM).e. Win32 and RTSS. reading the RTX CLOCK_FASTEST.. measures its own environment. RTX Demo. The worst-case SRTM reported latencies range from 35 to 100 microseconds on most Pentium-based systems. the second is the dirty-cache case. detecting latency events caused by peripheral activities (such as burst DMA). KSRTM (Kernel System Response Time Measurement) KSRTM is a driver and a Win32 utility that measures HAL-level timer latency. see Using LTP (Latency Test Program) on page 82. SRTM (System Response Time Measurement) and RTX Demo SRTM is an RTAPI timer latency measurement tool that measures timer latency observed by an application. KSRTM versus SRTM Both KSRTM (Kernel System Response Time Measurement) and SRTM (System Response Time Measurement) measure timer latencies. 75 . The diagram occasionally shows additional "humps" from processor-level interrupt masking. See also KSRTM versus SRTM. Short code paths make it less sensitive to cache jitter than SRTM. For further details. For further details. For further details and sample outputs. It can determine which Windows NT component or device driver is causing the greatest latency event for a real-time application. Among the samples is a graphical version of SRTM. Timer Latency Display The Timer Latency Display tool performs timing measurements and outputs two displays: Histogram and Latency.Chapter 5: Performance Overview Reducing Your System’s Latencies: Tools Overview An RTX developer should be mindful of platform factors. See also KSRTM versus SRTM below. Each of the two versions of SRTM. it is the more realistic measurement of latencies encountered by RTSS applications. which measures results for both RTSS and Win32.

It can also provide a list of drivers.RTX User’s Guide Using KSRTM (Kernel System Response Time Measurement) Use KSRTM to measure timer response latencies and obtain reports and histograms of the results. It also allows the timer to drive the sound speaker (a 500microsecond timer will generate a 1000 Hz square wave). -k = Kernel (DPC-level) timer. -m = Multimedia (user-level) timer. -h = Histogram of latencies (in addition to summary). and measures and reports timer response latencies against a synchronized clock. Note: KSRTM only works in uniprocessor systems. -d = Display loaded driver information. -l = Longest latency event information. KSRTM optionally measures the latencies associated with kernel (DPC-level) and multimedia (user-level) timers. -u minutes = Minutes between display updates. See Also KSRTM versus SRTM 76 . Usage ksrtm -s 2 Format ksrtm [-r] [-k] [-m] [any of the following flags] seconds_to_sample where -r = Real-time HAL extension timer (default). -s = Sound output (square wave driven by timer). This tool exercises the real-time HAL extension. seconds_to_sample = Duration in seconds to sample timer response latencies. -n = No use of real-time priorities. Any timing jitter will produce an audible frequency wobble. -i = IRQL HIGH stalls (test interrupt isolation). It can present a histogram of such latencies and report which kernel component was running when the longest latency event occurred. -c = Cache flush/dirty and TLB shoot down stalls.

Usage RTSSrun "c:\program files\vci\rtx\bin\samples\srtm" -h -f -s 15 You can also run SRTM using Windows NT Explorer by double-clicking the srtm. you should hear a steady 1 KHz tone for five seconds.exe icon (for Win32 environment).Chapter 5: Performance Overview Using SRTM (System Response Time Measurement) Use SRTM to measure timer response latencies.rtss icon (for RTSS environment) or the srtm. When you run srtm.mak RTSSrun srtm. you can build SRTM on your system (provided that you have a compiler on it) by entering the following commands at a command prompt: cd \program files\vci\rtx\bin\samples\srtm nmake -f srtm.rtss. Format srtm [-h] [-s] [-1] [-f] seconds_to_sample where -h = Display histogram (in addition to summary). seconds_to_sample = Duration in seconds to sample timer latencies. link. You can run SRTM in the RTSS environment to measure RTSS latencies or in the Win32 environment to measure Windows NT latencies.rtss -f -h -s 5 There should be no compile. To build SRTM on your system Optionally. -s = Turn on sound (square wave driven by timer). By default. this tool generates a 15-second tone and prints a histogram of timer response latencies. -f = Use fastest available timer (1 ms or better). See Also KSRTM versus SRTM 77 . -1 = Use a 10 ms timer period (default is 1 ms). or make errors.

The timer can also be used to drive a sound speaker. along with the raw data for the histogram. RTSS process results are plotted in cyan. Windows NT. Win32 results in red. There are two types of plots: a plot showing the maximum latency values over time and a plot showing the raw data counts of maximum latency values for one sample period. and maximum values are recorded in the data area. Sound Options — Choose to hear sound or not. You can also change the sound options while the timer process is running. This option cannot be changed while the process is running. The minimum. Settings Run Timer As — Run an RTSS process. The default setting is data enabled at the start of a run. Stop — Stops the process. RTSS process results are plotted in cyan. It runs the process using either the fastest timer or a 1 ms timer. The default setting is plot enabled at the start of a run. you can choose from which process to hear sound. The selectable values for the plot's y-axis scale are 100 ms. or both processes at the same time. average. Win32 results in red. average. and maximum latency values are recorded in the data area. If running both types of processes. The default setting is sound enabled. average. You can change these options while the process is running. It measures the total time to an RTSS. Display Options — The Plot option displays graphs in the graphical output area. The default is an RTSS process. a Win32 timer process. a Win32 process.RTX User’s Guide Using RTX Demo (Graphical version of SRTM) RTX Demo graphically illustrates response time latencies in the Win32 and RTSS environments. RTX Demo runs an RTSS timer process. This option is disabled when running the histogram option. Timer to Use — Choose either the fastest timer available or the 1 ms timer. You cannot change this selection during data retrieval. The Data option writes latency values to the data area. Add Load — Simulates a disk load on the system in order to show more accurately the maximum latency times on a busy system. The results are plotted to the graphical area where minimum. or Windows 2000 program’s time handle (i. It is a realistic measurement of latencies encountered by an application. Actions Run Max Latency — Plots the maximum and average latency values at one-second intervals. The load consists of a creating a file and writing to it repeatedly with no buffering. and maximum latency values are displayed. full thread context). or both processes at once. Max Latency Y-axis Scale — This option is used with the Run Max Latency action only. 78 .e. 1000 ms. The minimum. and 10. Run Histogram — Plots the number of latency values occurring within 1 ms intervals.000 ms.. The default is 100 ms.

The solid line plots the maximum latency value in microseconds during a one-second interval. 3. It also shows the greatest maximum value over the course of the data retrieval (from clicking on the Run Max Latency button until clicking on the Stop button). The solid line plots the maximum latency value in microseconds during a one-second interval. Once the process is running. You can also click: Stop to terminate the SRTM process. average. The x-axis shows time in seconds.Chapter 5: Performance Overview Remove Load — Stops the "load" process. The dashed line plots the average latency value. Interpreting the Max Latency Plot 57. and maximum latencies for the interval. RTSS latency values are shown 79 . Exit to terminate RTX Demo. Exit — Terminates the program. 4. Click on either Run Max Latency or Run Histogram. The y-axis is the response time latency in microseconds. and then Remove Load to stop it. or Open the tool from the following directory: c:\program files\vci\rtx\bin\samples\rtxdemo 2. plot. The data area records the minimum. you can change sound. 'HPR 0D[ /DWHQF\ YLHZ The x-axis shows time in seconds. Start RTX Demo using one of these methods: Choose RTX Demo from the RTX menu. The y-axis is the response time latency in microseconds. and data options. The dashed line plots the average latency value. To run RTX Demo 1. Select the type of process to run and which type of timer to use. Add Load (if enabled) to simulate a disk load.

reads the RTSS system clock. which is called by RTSS each time the timer expires. Since the timer function is called periodically. Win32 values in red. Win32 values in red. and sleeping between tests. The thread then enters a loop. average. testing a terminate request flag in shared memory. The data is refreshed every second. The timer function.RTX User’s Guide in cyan. When Win32 values are too high. The RTSS task also accumulates shortest and longest observed latencies. along with the minimum. RTSS latency values are shown in cyan. this results in a tone with a 80 . they are plotted at the upper boundary of the window. and maximum values. The raw data for the histogram is written to the data area. which runs as an ordinary Windows NT task Œ An RTSS application. which performs the timing measurements These two tasks communicate through shared memory. Using the Timer Latency Display Tool The Timer Latency Display tool consists of: A control and presentation application. 0 to 100 when using the 1 ms timer. and sets it to expire periodically at the fastest available timer rate. and computes the difference between the time observed. Settings Enable Sound — The timer function toggles the output state of the system speaker port each time it is called. The main execution thread creates an RTX timer. and the requested scheduled time. A histogram of this difference is compiled in shared memory. The RTSS task is similar to SRTM. Interpreting the Histogram Plot The x-axis shows response time latency in microsecond intervals. The y-axis shows a count from 0 to 2000 when using the fastest timer. The histogram shows the number of latencies that fell within a particular microsecond interval.

as appropriate: To end the program — Terminate the client process and then exit from the display process. in microsecond units.exe. maximum.Chapter 5: Performance Overview period equal to one half of the timer setting value. The system timer is set to 1 ms in the demo. The vertical axis represents a count of the number of times this difference 81 . Follow these steps. You can change settings for sound and view while the timer program is running. Histogram — View the data as an accumulated histogram.rtss and then type: RTSSkill ### (where ### is the PID). To terminate the timer process — Obtain the RTSS Process ID and then kill the process by typing the following command at a command prompt: RTSSkill To obtain a list of the current RTX processes — Find the PID associated with NtRTSS. Double-click NtRTSS. To run the Timer Latency Display tool 1. Open the following directory: c:\program files\vci\rtx\bin\samples\latencydisplay 2. Interpreting the Histogram Timer Latency Display: Histogram view (Recorded on Gateway G5-233 233 MHz Pentium) The horizontal axis represents the time difference between scheduled and observed time. Latency — View a time sequence of minimum. Double-click the display program. resulting in a 500 Hz tone. and average values observed in a series of 1-second intervals. Actions Reset — Reset accumulated statistics. To end the display process — Click the X button at the far right of the title bar.rtss to start the timer program. 3. RTSSDisplay. 4. The program starts with the sound enabled.

Using LTP (Latency Test Program) Use LTP to find misbehaving peripheral devices. -h = Display message 82 . Latency is plotted on the vertical axis. the default is 20 seconds. illuminating the current second. The histogram bin size is adjusted automatically to ensure that the highest observed latency value is visible on the graph. Interpreting the Latency display Timer Latency Display: Latency view (Recorded on Gateway G5-233 233 MHz Pentium) The Latency view selects presentation of a time sequence of minimum. -s <num> = Run the test for this number of seconds. using approximately 20% of the CPU time for the duration of the test. The horizontal axis is set to display the results accumulated over the past one-minute interval. or ’bin.RTX User’s Guide is observed to fall within a particular range. The latency is expected to be two to five microseconds. and average values observed in a series of one-second intervals. A bright green vertical bar sweeps from left to right.’ Counts are displayed on a logarithmic axis. the default is 10 microseconds. This tool counts the number of instances in a given period of time that the time between clock reads exceeds a threshold value. Usage RTSSrun ltp -h Format ltp [-t <num>] [-s <num>] where -t <num> = Watch for latencies greater than this number of microseconds. maximum. Higher latencies probably indicate non-CPU related blocking.

* * Author: * * Environment: * * RTX RTSS application * * Revision History: * * Version 1 Jun 1 1998 --*/ #include <windows.h> #include <rtapi.h> #include <stdio. Developed from the pci test * and gmpt driver.h> // // Get and Set Long value macros. All rights reserved.c * * Abstract: * * Test code for processing level triggered interrupts * using the PCI-DIO-96 card. // #define PTL(x) (*(PLONG)(x)) /* DO NOT CHANGE PARAMETERS BELOW THIS POINT */ #define BASE_ADDR _base_addr /* PPI A */ #define PORTA_ADDR #define PORTB_ADDR #define PORTC_ADDR #define CNFG_ADDR ((PUCHAR) ((PUCHAR) ((PUCHAR) ((PUCHAR) BASE_ADDR BASE_ADDR BASE_ADDR BASE_ADDR + + + + 0x00) 0x01) 0x02) 0x03) // // // // Port A Port B Port C Config (Port 0) (Port 1) (Port 2) Register /* PPI B */ #define B_PORTA_ADDR #define B_PORTB_ADDR #define B_PORTC_ADDR #define B_CNFG_ADDR /* PPI C */ #define C_PORTA_ADDR #define C_PORTB_ADDR #define C_PORTC_ADDR #define C_CNFG_ADDR ((PUCHAR) ((PUCHAR) ((PUCHAR) ((PUCHAR) BASE_ADDR BASE_ADDR BASE_ADDR BASE_ADDR + + + + 0x04) 0x05) 0x06) 0x07) // // // // PPI PPI PPI PPI B B B B Port A Port B Port C Config (Port 3) (Port 4) (Port 5) Port ((PUCHAR) ((PUCHAR) ((PUCHAR) ((PUCHAR) BASE_ADDR BASE_ADDR BASE_ADDR BASE_ADDR + + + + 0x08) 0x09) 0x0A) 0x0B) // // // // PPI PPI PPI PPI C C C C Port A Port B Port C Config (Port 6) (Port 7) (Port 8) Port 83 . * * Module Name: * * RtxLevelIntTest. Inc.  /*++ * * Copyright (c) 1996-1999 VenturCom.APPENDIX A Code and File Examples Bus IO Programming Example The following code fragment illustrates the Bus I/O calls in a PCI driver.

// total int cleared BOOLEAN IntDone. ULONG IntCountDown. LARGE_INTEGER BAR0. // when we are done void main( int argc. vBAR1 = NULL.. // interrupt handler 84 . // interrupt level ULONG IrqVectr. #define BASE_ADDR _base_addr /* respond: the interrupt handler */ void _stdcall respond(PVOID addr).Port A Input Port B Input Port C Input // Note: Standard RTX time units are 100 ns long. // number of ints calls wait for clearing ULONG IntCountTotal. long cause). */ void fail(char *mesg). PCHAR *argv ) { ULONG i. // bus number BOOLEAN flag. PCHAR _base_addr. // not really needed. tBAR1. or 10 units per microsecond. // interrupt vector PVOID ihr.Port A Output Port B Output Port C Output 0x90 // p 6-10 . PPCI_COMMON_CONFIG PciData. // base port address of the MITE LARGE_INTEGER BAR1. PCI_SLOT_NUMBER SlotNumber.RTX User’s Guide /* PPI D */ #define D_PORTA_ADDR #define D_PORTB_ADDR #define D_PORTC_ADDR #define D_CNFG_ADDR /* Counter/Timer */ #define CLOCKA #define CLOCKB #define CLOCKC #define CLOCK_CTRL ((PUCHAR) ((PUCHAR) ((PUCHAR) ((PUCHAR) BASE_ADDR BASE_ADDR BASE_ADDR BASE_ADDR + + + + 0x0C) 0x0D) 0x0E) 0x0F) // // // // PPI PPI PPI PPI D D D D Port A Port B Port C Config (Port 9) (Port 10) (Port 11) Port ((PUCHAR) ((PUCHAR) ((PUCHAR) ((PUCHAR) BASE_ADDR BASE_ADDR BASE_ADDR BASE_ADDR + + + + 0x10) 0x11) 0x12) 0x13) // // // // Clock Clock Clock Clock or or or or Counter Counter Counter Counter 0 1 2 Control /* Interrupt control */ #define INTR_CTRL1 ((PUCHAR) BASE_ADDR + 0x14) // First interrupt control reg #define INTR_CTRL2 ((PUCHAR) BASE_ADDR + 0x15) // Second interrupt control reg #define INTR_CLEAR (PUCHAR) BASE_ADDR + 0x16) // Interrupt Clear Register //#define CNFG_VAL //#define CNFG_VAL #define CNFG_VAL 0x80 // 1000 0000 . #define STOP_TIME 5 // Minutes for shutdown handler to wait // after stopping before terminating. // return value from RtGetBusDataByOffset ULONG bus.. /* fail: utility routine for fatal errors. // logical slot number for the PCI adapter ULONG f. PCHAR vBAR0=NULL. UCHAR buffer[PCI_COMMON_HDR_LENGTH]. // function number on the specified adapter ULONG bytesWritten. // pointer virtual memory addresses // returned by RtMapMemory ULONG IrqLevel. // base port address of the board registers LARGE_INTEGER tBAR0.Port A Input Port B Output Port C Output 0x15 // p 6-10 . // total int count ULONG IntCountCLear. // 0 for indefinite. // indicates memory space ULONG window_data_value = 0. // translated base addresses (system // mapped addresses) returned by // RtMapMemory ULONG AddressSpace = 0. /* shutdownh: the shutdown handler */ void _stdcall shutdownh(PVOID dummy.

InterruptLine. PciData->VendorID). printf("DeviceID:\t\t0x%x\n".QuadPart = 0. 85 . tBAR0. flag = TRUE. if this is our card.type0. // new board address intbusnumb = bus. f++) { SlotNumber. // interrupt level IrqVectr = IrqLevel. BAR0. f < PCI_MAX_FUNCTION. SlotNumber. for (f = 0. printf("FunctionNumber:\t\t%d\n". printf("VendorID:\t\t0x%x\n". tBAR1.QuadPart = 0.bits. i).bits. i < PCI_MAX_DEVICES && flag. skip to next slot break.QuadPart = PciData->u. i++) { SlotNumber. // MITE address BAR1. PciData.type0.u.Appendix A: Code and File Examples ULONG intbusnumb. // interrupt IRQ // Put the BusAddresses into other variables BAR0. BAR1. f). SlotNumber. printf("DeviceNumber:\t\t%d\n". bus.Reserved = 0. bytesWritten = RtGetBusDataByOffset ( PCIConfiguration. PciData->DeviceID). printf("BusNumber:\t\t%d\n".DeviceNumber = i.BaseAddresses[0]. } if (PciData->VendorID == PCI_INVALID_VENDORID) { // no device at this slot number. break. // if ((PciData->VendorID == 0x1093) && (PciData->DeviceID == 0x0160)) { // Set IRQ values for attaching interrupt below IrqLevel = PciData->u.AsULONG. printf("------------------------------------------\n").u. printf("\nPCI-DIO-96:\n").QuadPart = 0.u.u. bus). // Interrupt bus number PciData = (PPCI_COMMON_CONFIG) buffer.QuadPart = 0. flag. // // Search for the PCI-DIO-96 card // for (bus = 0. then // print out all the PCI configuration information // and set the variables. } // // A device is found.BaseAddresses[1].type0. 0.QuadPart = PciData->u.bits.FunctionNumber = f. if (bytesWritten == 0) { // out of PCI buses flag = FALSE. bus++) { for (i = 0. PCI_COMMON_HDR_LENGTH ).

PciData->ProgIf). printf("ProgIf:\t\t\t0x%x\n". } if (! RtTranslateBusAddress(PCIBus. printf("LatencyTimer:\t\t0x%x\n".type0. PciData->LatencyTimer). PciData->CacheLineSize).PciData->u. BAR0. } else { printf("tBAR0: SystemMappedAddress: 0x%08x\n".RTX User’s Guide printf("Command:\t\t0x%x\n". printf(" BAR0: BusRelativeAddress: 0x%08x\n".LowPart). } // // Map the addresses to virtual addresses the software can use // vBAR0=RtMapMemory( tBAR0.type0. printf("BaseAddresses[5]:\t0x%08x\n". BAR1. 0.MaximumLatency).PciData->u. PciData->Command).PciData->u. 4*1024. } 86 . printf("BaseAddresses[2]:\t0x%08x\n". printf("BaseAddresses[1]:\t0x%08x\n". printf("InterruptPin:\t\t%d\n". &tBAR0 )) { fail ("tBAR0: RtTranslateBusAddress failed"). PciData->BIST).PciData->u. } else { printf(" BAR0: VirtualMemoryAddress: 0x%08x\n". // // Translate the base port addresses to system mapped addresses. printf("CacheLineSize:\t\t0x%x\n". &AddressSpace. GetLastError()).type0.type0. printf("BIST:\t\t\t0x%x\n". tBAR0.BaseAddresses[5]).type0. printf("BaseClass:\t\t0x%x\n". printf("BaseAddresses[3]:\t0x%08x\n". PciData->RevisionID). printf("BaseAddresses[0]:\t0x%08x\n". printf("SubClass:\t\t0x%x\n". // 4K.LowPart)."). printf("RevisionID:\t\t0x%x\n".LowPart).InterruptPin).ROMBaseAddress). tBAR1. } else { printf("tBAR1: SystemMappedAddress: 0x%08x\n".type0. &tBAR1 )) { fail ("tBAR1: RtTranslateBusAddress failed.PciData->u. &AddressSpace. BAR0. PciData->SubClass). printf("ROMBaseAddress:\t\t0x%08x\n".PciData->u.type0.BaseAddresses[4]).BaseAddresses[2]).BaseAddresses[1]).InterruptLine).PciData->u.type0. 0).vBAR0).BaseAddresses[3]). printf("Status:\t\t\t0x%x\n". printf("HeaderType:\t\t0x%x\n". PciData->Status). printf("MinimumGrant:\t\t%d\n". printf("BaseAddresses[4]:\t0x%08x\n". 0.LowPart).type0.MinimumGrant). printf("MaximumLatency:\t\t%d\n". PciData->BaseClass).type0.type0. printf("\n").PciData->HeaderType). // if (! RtTranslateBusAddress( PCIBus.PciData->u.PciData->u. printf("InterruptLine:\t\t%d\n".PciData->u. cache disabled if (vBAR0 == 0) { printf(" BAR0: Failure on RtMapMemory\nError=%d\n". printf(" BAR1: BusRelativeAddress: 0x%08x\n". BAR1.BaseAddresses[0]).PciData->u.

PciData. } // // Set the command parameter so we can access the PCI device’s // control registers. // bus number IrqLevel. GetLastError()). 4*1024.AsULONG. // interrupt handler NULL. RtSetBusDataByOffset(PCIConfiguration. // interface type (PCI) intbusnumb. vBAR1). // window_data_value = ( (0xffffff00 & (ULONG)BAR1. // stacksize (default) respond. PCIBus. bus. // security attributes (default) 0. 0. // interrupt level IrqVectr). // // Initialize the card // No 1 MB limit .LowPart) | (0x00000080) ). PCI_COMMON_HDR_LENGTH).u. // // Attempt to attach to this interrupt. // interrupt vector }  See Also Bus IO 87 . } else { printf(" BAR1: VirtualMemoryAddress: 0x%08x\n".Appendix A: Code and File Examples vBAR1=RtMapMemory( tBAR1. // 4K. // PciData->Command = (PCI_ENABLE_IO_SPACE | PCI_ENABLE_MEMORY_SPACE | PCI_ENABLE_BUS_MASTER | PCI_ENABLE_WRITE_AND_INVALIDATE). // Disable interrupts from counters *(INTR_CTRL2) = 0x00. cache disabled if (!vBAR1) { printf(" BAR1: Failure on RtMapMemory\nError=%d\n". using data acquired above // ihr = RtAttachInterruptVector(NULL. memory mapped. // Note: You need to use the BusRelativeAddress to set the // window_data_value. so we go ahead // and attempt to utilize the card for testing // _base_addr=vBAR1. }// dio 96 } // max_function } // max_devices } // flag // // At this point the card has been found. SlotNumber. 0).no need to remap the memory. // context argument RT_PRIORITY_MAX. PTL(vBAR0+0x000000c0) = window_data_value. // Memory already mapped // Disable interrupts from I/O ports *(INTR_CTRL1) = 0x00.

CT_PORT_9513DATA + 1) CT_BASE_PORT_9513DATA(BASE) ((unsigned CT_BASE_PORT_9513CMD(BASE) ((unsigned CT_BASE_PORT_9513STATUS(BASE) ((unsigned CT_BASE_PORT_DI(BASE) ((unsigned char CT_BASE_PORT_DO(BASE) ((unsigned char char *)((BASE) + 0)) char *)((BASE) + 1)) char *)((BASE) + 1)) *)((BASE) + 2)) *)((BASE) + 3)) int ihc = 0 .(CT_PORT + 1) CT_PORT_9513STATUS&#9.RTX User’s Guide Interrupt Management and Port IO Calls Programming Example The following programming example demonstrates the use of RTX interrupt management and port I/O calls. (void *)&TestIncrease. int ihc2 = 0 .(CT_PORT + 1) CT_PORT_DI&#9. 0x%x) failed\n". 0x00) . CT_PORT_SPACE)) { (void)printf("RtEnablePortIo(0x%x. int limit = 30 .(CT_PORT + 3) CT_PORT_SPACE (CT_PORT_DO . 7) . 0. // Enable CT range of ports if ( !RtEnablePortIo(CT_PORT. 7. } int TestIncrease = 1 .h> #include <rtapi. return 1 . void RTFCNDCL InterruptHandler(void * unused) { RtWritePortUchar(CT_BASE_PORT_DO(CT_PORT).h> #define #define #define #define #define #define #define #define #define #define #define #define CT_PORT ((unsigned char *) 0x340) CT_PORT_9513DATA&#9. int i .(CT_PORT + 2) CT_PORT_DO&#9. inc + + . CT_PORT_SPACE). InterruptHandler. if ( NULL == hInterrupt ) { 88 . 0. main() { HANDLE hInterrupt .  // // // // Generate an interrupt with the digital outs Jumper any digital out [3-10] to IR INPUT [1] Jumper GND [11] to IR ENABLE [2] #include <windows.(CT_PORT + 0) CT_PORT_9513CMD&#9. 1. CT_PORT. } // Attach the interupt vector to the interrupt handler hInterrupt = RtAttachInterruptVector(NULL. 1. printf("Simple Interrupt Attach Handler Functional Test") .

RtWritePortUchar(CT_BASE_PORT_DO(CT_PORT). }  See Also Interrupts Port IO 89 . if ( limit != ihc ) { printf("FAIL\n") . limit) . } RtReleaseInterruptVector(hInterrupt) . GetLastError()) . } for(i=0. // Pulse the interrupt RtWritePortUchar(CT_BASE_PORT_DO(CT_PORT). 0) .Appendix A: Code and File Examples printf("Could not register interrupt handler (%d)\n". i<limit. } // Determine what happened. else { printf("Got %d interrupts\n". 0xff) . return 2 . i++) { Sleep.

RTX User’s Guide Makefile Sample The following makefile is an annotated version of the one used to build srtm (a sample program that measures timer response latencies). Inc. All rights reserved.  # # # # # # # # # # # # Copyright (c) 1996 .rtss  See Also Using the RTX Makefile Debugging an RTX Program 90 .mak for rules and linking flags necessary making # RTSS executable files !include <rtx. NODEBUG # Define to remove debugging information in executable NODEBUG = 1 # RTSS_CRT # Define to link with RTSS single-threaded C run-time library # RTSS_CRT = 1 # RTSS_MTCRT # Define to link with RTSS multi-threaded C run-time library # RTSS_MTCRT = 1 # Include rtx. Module Name: srtm.mak> all: srtm.mak Abstract: nmakefile to build the SRTM demo as a RTSS process.1999 VenturCom.

mak> all: thandler. thandler.Appendix A: Code and File Examples Nmake Input File Example The following is an example of an nmake input file which will build an RTDLL and Win32 DLL from a single source file.obj thandler.rtdll clean: -del thandler.c.  !include <rtx.rtdll  See Also Creating Dynamic Link Libraries 91 .dll thandler.dll thankler.

}  RTDLL Part 2: usingRtdll.h> #include <rtapi. // Check GATE bit i^= GATE_BIT. NULL).h" #include "rtapi. It is shown in four parts: 1.h> #define NO_ERRORS 0 #define ERROR_OCCURRED -1 #define SPEAKER_PORT ((PUCHAR)0x61) FARPROC FunctionPtr = NULL. // Read PIT PORTB register i = RtReadPortUchar( SPEAKER_PORT). Simple RTDLL program source code 2.h" #define SPEAKER_PORT ((PUCHAR)0x61) #define GATE_BIT 0x02 //Port IO address for speaker //exported Rtdll Function __declspec ( dllexport ) int _stdcall Toggle(int argc. // Write it to PIT PORTB RtWritePortUchar( SPEAKER_PORT. DWORD fdwReason. LPVOID lpvReserved) { return TRUE.c  #include <windows. } //DllMain must Explicitly return True BOOL WINAPI _stdcall DllMain(HINSTANCE hinstDLL.RTX User’s Guide RTDLL Code Example This example implements the same functionality as the RTSS DLL example above using an RTDLL to provide the toggle() function. Makefile used to create the RTSS application and RTDLL 4. int RTFCNDCL TimerHandler(PVOID unused) { //call Function Toggle FunctionPtr(0. return NO_ERRORS. } //Port IO address for speaker 92 . RTSSrun command used to register the RTDLL RTDLL Part 1: sampleRtdll. i).h> #include <stdio.c  #include "windows. char* argv[]) { UCHAR i. return 0. Simple RTSS application which loads the RTDLL and calls an exported subroutine 3.

lpProcName). RT_PRIORITY_MAX. } //Enable so Win32 can use PortIO if (! RtEnablePortIo(SPEAKER_PORT.GetLastError()). 0. //*********** Sample Code: usingRtdll ***********\\ //load Library sampleRtdll hLibModule = LoadLibrary(lpLibFileName). FreeLibrary(hLibModule). lpLibFileName). //free library before exit FreeLibrary(hLibModule). return (ERROR_OCCURED). ULONG sleepTime = 10000. Get Last Error = %d\n". // 1 milliscond interval Get Last Error = if (!RtSetTimerRelative( hTimer. return (ERROR_OCCURED).CLOCK_FASTEST). TimerHandler. Get last Error = %d\n".GetLastError()). RtPrintf("The Function %s does not exist\n". char* argv[]) { HANDLE hLibModule = NULL. LARGE_INTEGER time. lpProcName). LPCSTR lpLibFileName = "sampleRtdll. } time.Appendix A: Code and File Examples /*** MAIN ****/ int main(int argc. //check if loadLibrary returned correctly if(hLibModule==NULL) { //error caused by loading a corrupt or unregistered Rtdll RtPrintf("UsingRtdll: ERROR: LoadLibrary() failed. } //Get function from Rtdll FunctionPtr = GetProcAddress(hLibModule. } 93 .dll".QuadPart = 10000. %d\n". HANDLE hTimer = NULL. //check if function was found if(FunctionPtr == NULL) { //error caused by nonexistent function name RtPrintf("UsingRtdll: Error: GetProcAddress() failed. //free library before exit FreeLibrary(hLibModule). return (ERROR_OCCURED). } // Setup and start the periodic timer. //free library before exit FreeLibrary(hLibModule).\n"). NULL. return (ERROR_OCCURED). &time. LPCSTR lpProcName = "_Toggle@8". return (ERROR_OCCURED). //check if timer was created if(hTimer == NULL) { RtPrintf("UsingRtdll: ERROR: RtCreateTimer failed.GetLastError()). &time)) { RtPrintf("UsingRtdll: ERROR: Could not set and start the RTAPI timer. hTimer = RtCreateTimer(NULL. 1)) { printf("UsingRtdll: Error: Could not enable Port IO\n"). RtPrintf("%s maybe corrupt or not registered with RTSS\n".

return (ERROR_OCCURED). } //the end return (NO_ERRORS).exe RTDLL Part 4: Register the rtdll  C:\> RTSSRun /dll sampleRtdll  94 .GetLastError()).exe clean: -del *.mak  NODEBUG = 1 RTSS_CRT = 1 !include <rtx.rtdll usingRtdll. return (ERROR_OCCURED). Sleep(sleepTime).mak> all: sampleRtdll.RTX User’s Guide // Wait for 10 seconds. Get Last Error = %d. }  Get Last Error = RTDLL Part 3: rtdll.dll -del *. if(!RtDeleteTimer(hTimer)) { RtPrintf("UsingRtdll: ERROR: RtDeleteTimer failed.rtss \ sampleRtdll. } //free the Library before exiting Process if(!FreeLibrary(hLibModule)) { //error caused by an invalid Library handle RtPrintf("UsingRtdll: Error: FreeLibrary() failed.\nGetLastError()). // Stop and delete the timer.obj  -del *.lib -del *.dll usingRtdll.rtdll -del *. //free library before exit FreeLibrary(hLibModule). %d\n".exp -del *.

which toggles the state of the PC speaker. Simple program which imports toggle() from dll. Simple dll. Win32 program to start the DLL and the application that uses it RTSS DLL Part 1: dll. A timer is used to control the frequency with which toggle() is called in order to generate a tone with a constant pitch. i). toggle().h" #include "rtapi. Makefile used to link dll. }  // Read PIT PORTB register // Change GATE bit // Write it to PIT PORTB RTSS DLL Part 2: dll. return 0. i = RtReadPortUchar( SPEAKER_PORT). Definition file (dll. char **argv) { SuspendThread( GetCurrentThread()). i ^=GATE_BIT.c  #include "windows.def) 3.h" #define SPEAKER_PORT ((PUCHAR)0x61) #define GATE_BIT 0x02 // Port IO address for speaker // // MAIN . This example is shown in five parts: 1.rtss 4.def  LIBRARY DLL. // int main(int argc.Appendix A: Code and File Examples RTSS DLL Code Example This programming example demonstrates a simple RTSS DLL that exports one function. // VOID _stdcall Toggle(VOID) { UCHAR i. } // // The exported DLL function.RTSS DESCRIPTION ’DLL RTSS’ EXPORTS Toggle  95 .just suspend the main thread for this process until its // use as a DLL is finished and the process is terminated. RtWritePortUchar( SPEAKER_PORT.c 5.c program 2.

} time. int waitTime = 10000.\n"). // Stack size .h" #include "rtapi. ULONG stackSize = 0. char *argv[]) { LARGE_INTEGER time. // 96 . // Security . } // // MAIN -.c  #include "windows. int RTFCNDCL TimerHandler(PVOID unused) { Toggle(). } // // Wait for 10 seconds. return (ERROR_OCCURED). &time)) { printf("ERROR: Could not set and start the RTAPI timer. // Sleep(waitTime).h" #define NO_ERRORS #define ERROR_OCCURRED 0 -1 // // External function prototype. //10 seconds // // Setup and start the periodic timer. // Priority CLOCK_FASTEST))) // Always use fastest available clock { printf("ERROR: Could not create the RTX timer. // if (!(hTimer = RtCreateTimer( NULL.NULL is none stackSize. return (ERROR_OCCURED).call the "Toggle" function. // int main( int argc. &time. // Call the DLL exported function return NO_ERROR.RTX User’s Guide RTSS DLL Part 3: dll-test. // VOID _stdcall Toggle(VOID).0 is use default TimerHandler.QuadPart = 10000. // Timer handler NULL.start the timer and wait 10 seconds.h" #include "stdio. // NULL context (argument to handler) RT_PRIORITY_MAX. // // Timer handler -. // 1 milliscond interval if (!RtSetTimerRelative( hTimer. HANDLE hTimer.\n").

exp dll.rtss -del *. LONG exitCode = 0.obj lib -nodefaultlib -machine:$(CPU) -out:dll. NULL. sinfo. // if (CreateProcess(NULL. PROCESS_INFORMATION pinfo. }  RTSS DLL Part 4: dll.\n").rtss RunTest.def dll. // ZeroMemory(&sinfo.lib $(rtsslibs) clean: -del *.rtss dll-test. NULL. 0.lib dll-test.Appendix A: Code and File Examples // Stop and delete the timer.exe dll.obj link $(rtsslflags) -out:dll.rtss dll. // // Initialize startup info to all zeros.rtss $*.mak  NODEBUG = 1 !include <rtx.obj $(rtsslibs) del dll.obj dll.rtss: dll.obj -del *.cb=sizeof(sinfo). } return (NO_ERRORS).exp dll-test. // if (!RtDeleteTimer( hTimer)) { printf("ERROR: Could not Delete timer.mak> all: dll.obj link $(rtsslflags) -out:$*.h" #define NO_ERRORS 0 #define ERROR_OCCURRED -1 // // Standard function to run a utility. lpCmd. FALSE.rtss: dll. // // Create the process to run the utility. sizeof(sinfo)).lib -def:dll.lib  RTSS DLL Part 5: runtest. // LONG RunUtility( PCHAR lpCmd ) { STARTUPINFO sinfo. NULL. 97 . return (ERROR_OCCURED).exe -del dll.c  #include "windows.h" #include "stdio.

&sinfo. int sleepTime = 5000. return (ERROR_OCCURED). &pinfo)==FALSE) { return (exitCode-1). INFINITE).hThread).hProcess.hProcess. dllPid). // testPid = RunUtility("RTSSrun dll-test. if (dllPid<=exitCode) { printf("DLL failed to load. // int main( int argc. // dllPid = RunUtility("RTSSrun dll. RunUtility( buf). } // // Wait for the utility to complete. sprintf( buf. char buf[50]. } // // Sleep for 5 seconds and then terminate program and dll. // Sleep(sleepTime). }  98 . return (ERROR_OCCURED). return exitCode. // GetExitCodeProcess( pinfo. &exitCode). // // Load the RTSS DLL first.hProcess). RunUtility( buf). sprintf( buf. testPid. testPid). "RTSSkill %d". char *argv[]) { LONG dllPid. if (testPid<=exitCode) { printf("DLL-TEST failed to run. CloseHandle( pinfo.rtss"). CloseHandle( pinfo. "RTSSkill %d". } // // MAIN.RTX User’s Guide NULL.rtss"). // // Get the exit code (RTSSrun returns the process slot) and close handles. // WaitForSingleObject( pinfo.\n"). return NO_ERROR. LONG exitCode = 0. } // // Now run the test program.\n").

lib -def:dll.rtss dll.lib  See Also Creating Dynamic Link Libraries 99 .rtss -del *.  NODEBUG = 1 !include <rtx.exe -del dll.obj -del *.obj $(rtsslibs) del dll.exp dll.obj lib -nodefaultlib -machine:$(CPU) -out:dll.Appendix A: Code and File Examples RTSS DLL Makefile Example The following example shows a typical RTSS DLL makefile for dll.mak> all: dll.exp clean: -del *.rtss dll.def dll.c.rtss: dll.obj link $(rtsslflags) -out:dll.

 RTSSkill RTSS process list: PID START STATE COMMAND 001 R TimerTest.rtdll Not Loaded foo.rtss .Supplemental Win32 for C runtime library RTSS Registered Dlls: STATE NAME Loaded timer.rtdll Not Loaded foo.Supplemental Win32 for C runtime library RTSS Registered Dlls: STATE NAME Not Loaded timer.RTX User’s Guide RTSSkill Examples RTSSkill Example 1 The following example illustrates information provided by RTSSkill when run with no arguments for a system running an application called TimerTest which uses a single RTDLL.rtdll  See Also RTSSkill Utility 100 .rtss Timer_test2 (terminated) 002 003 004 005 006 007 008 009 010 /boot R w32_dll.rtss Timer_test2 002 003 004 005 006 007 008 009 010 /boot R w32_dll.rtdll  RTSSkill Example 2 The following example illustrates information provided by RTSSkill 001 for the system in the preceding example.rtss .  RTSSkill RTSS process list: PID START STATE COMMAND 001 R TimerTest.

3 ============== Object(ID) Address Information 15 -------------------------Command w32_dll.rtss Timer_test2 805d6008 805d60a8 Pri=0 Flags=1 State=Sleeping 805ef490 Pri=15 Flags=0 State=WaitInternal 805f9f10 Clock=1 Remain=7000us Interval=12000us rtssview.dll" ============== End RTSSview ==============  See Also RTSSview Utility 101 . The unnamed mutexes are created by the C run-time initialization code. ============== RTSSview v4.Supplemental Win32 for C runtime library Process(010) Thread(00004) Command Process(001) Thread(0000c) Thread(0000d) Timer Command Process(002) Thread(0000e) Mutexes: 805f18f0 805efb70 805ef6d0 805f0b70 805f06d0 805f3690 805f2b70 805f26d0 805f5b70 805f56d0 805d5010 805d5690 805beb70 805bb010 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Count=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Owner=0 Name="** Name="** Name="** Name="** Name="** Name="** Name="** Name="** Name="** Name="** Name="** Name="** Name="** Name="** UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED UNNAMED **" **" **" **" **" **" **" **" **" **" **" **" **" **" 806a3c28 806a3cc8  Pri=0 Flags=1 State=Suspended timertest.rtss .rtss 805fad28 805fadc8 Pri=0 Flags=1 State=Ready Dynamically Loaded Libraries: 805fa6b0 Count=-2141245552 Owner=805f2f98 Name="Timer. linked with the C run-time library.Appendix A: Code and File Examples RTSSview Example The following example illustrates information provided by RTSSview for a system running an application called TimerTest.

maxPhyAddr). printf("Virtual memory address = 0x%08X\n".h> static PVOID vAddress.QuadPart = 0xFFFFFF. if (!vAddress) { printf("\nFailure on RtAllocateContiguousMemory\t"). vAddress). ULONG size=0. } else { printf("Success on RtGetPhysicalAddress(0x%08X). vAddress).\t.\n". }  //highest physical memory address //bytes to allocate See Also Contiguous Memory Mapping 102 . } } ExitProcess(0). vAddress"). size= 0x1000.QuadPart) { printf("\nFailure on RtGetPhysicalAddress(0x%08X).\t". printf("Error Code = %d\n". GetLastError()). if (!pAddress. printf("Error=%d\n". // Size in KB. // // // // virtual memory address returned by RtAllocateContiguousMemory physical memory address returned by RtGetPhysicalAddress static LARGE_INTEGER void main(void) { LARGE_INTEGER maxPhyAddr. // Get the physical address pAddress = RtGetPhysicalAddress(vAddress). // Allocate memory vAddress = RtAllocateContiguousMemory( size. } // Free memory if (!RtFreeContiguousMemory(vAddress)) { printf("\nFailure on RtFreeContiguousMemory(0x%08X). } else { printf("Success on RtFreeContiguousMemory(0x%X). maxPhyAddr. vAddress). vAddress). } else { printf("\nSuccess on RtAllocateContiguousMemory\n").  #include <windows.h> #include <stdio.RTX User’s Guide RTX Contiguous Memory Allocation Calls Programming Example The following programming example demonstrates the use of RTX contiguous memory allocation calls.h> #include <rtapi. GetLastError()). GetLastError()). pAddress.\n". break. printf("Error=%d\n".

} else { printf("\nSuccess on RtLockKernel\n"). RtGetLastError()).h> #include <stdio. }  See Also System Memory Management 103 .  #include <windows. RtGetLastError()).h> #include <rtapi.h> void main(void) { DWORD dwSections = RT_KLOCK_ALL.\t"). printf("Error=%d\n". } else { printf("\nSuccess on RtUnlockKernel\n"). printf("Error=%d\n".Appendix A: Code and File Examples RTX Kernel Memory Locking Calls Programming Example The following programming example demonstrates the use of RTX kernel memory locking calls. if (!RtLockKernel( dwSections)) { printf("\nFailure on RtLockKernel. if (!RtUnlockKernel( dwSections)){ printf("\nFailure on RtUnlockKernel.\t"). } } ExitProcess(0).

vAddress). } // Free memory if (!RtFreeLockedMemory(vAddress)) { printf("\nFailure on RtFreeLockedMemory(0x%08X). if (!vAddress) { printf("\nFailure on RtAllocateLockedMemory\t").h> #include <stdio. RtAllocateLockedMemory void main(void) { // virtual memory address returned by ULONG size=4096. }  See Also System Memory Management 104 .h> static PVOID vAddress. } else { printf("Success on RtFreeLockedMemory(0x%X). printf("Error Code = %d\n". GetLastError()). // bytes to allocate // Allocate memory vAddress = RtAllocateLockedMemory(size). printf("Virtual memory address = 0x%08X\n". } ExitProcess(0).  #include <windows. // Write to the memory *vAddress= 0. GetLastError()).\t". vAddress). break. printf("Error=%d\n".RTX User’s Guide RTX Locked Memory Allocation Calls Programming Example The following programming example demonstrates the use of RTX locked memory allocation calls.h> #include <rtapi. // if this fails .no use to continue } else { printf("\nSuccess on RtAllocateLockedMemory\n"). vAddress).\n".

vAddress=RtMapMemory( physAddr. %d ). }  See Also Physical Memory Mapping 105 . cacheEnable ). %d. } } ExitProcess(0). cacheEnable). vAddress). // length to map in BOOLEAN cacheEnable. success = RtUnmapMemory( vAddress). } else { printf("Success on RtMapMemory( 0x%08X.h> #include <stdio. // base physical address ULONG length. cacheEnable ). vAddress). length.LowPart. length.\n". physAddr. } else { printf("Success on RtUnmapMemory( 0x%08X)\n\n". length = 1024. vAddress). physAddr.\n". static PVOID vAddress.h> void main(void) { BOOL success=0. %d ).  #include <windows. // virtual memory address returned LARGE_INTEGER physAddr. printf("Virtual memory address = 0x%08X \n". if (vAddress==NULL) { printf("Failure on RtMapMemory( 0x%08X. length.LowPart. cacheEnable = 0.Appendix A: Code and File Examples RTX Memory Mapping Calls Programming Example The following programming example demonstrates the use of RTX memory mapping calls.h> #include <rtapi.QuadPart = 0x0000FFFFF. // cache accesses to memory ? physAddr. if (!success) { printf("Failure on RtUnmapMemory( 0x%08X)\t". %d.

 #include <windows.RTX User’s Guide RTX Process Memory Locking Calls Programming Example The following programming example demonstrates the use of RTX process memory locking calls. printf("Error=%d\n". printf("Error=%d\n". } else { printf("\nSuccess on RtLockProcess\n"). i). if (!RtLockProcess( dwSections)) { printf("\nFailure on RtLockProcess. } else { printf("\nSuccess on RtUnlockProcess\n". RtGetLastError()). if (!RtUnlockProcess( dwSections)) { printf("\nFailure on RtUnlockProcess.\t").h> void main(void) { DWORD dwSections = RT_PLOCK_ALL. RtGetLastError()).h> #include <rtapi. }  See Also System Memory Management 106 .\t").h> #include <stdio. } } ExitProcess(0).

h" #include "stdio.\n"). // RtCancelTimer( hTimer. // // Set default timer period to 500 micro seconds // Period. HANDLE hTimer. // // VOID main(int argc. ExitProcess(0).h" #include "rtapi. // Sleep(1000). &Period. RtDeleteTimer( hTimer). // LARGE_INTEGER Period. LARGE_INTEGER StartTime.TimerCounter). } if (!RtSetTimerRelative( hTimer.0 is use default TimerHandler. char **argv) { LARGE_INTEGER x. // if (!RtSetThreadPriority( GetCurrentThread(). ExitProcess(2). printf(" Value of number of timers counter is %d\n". // Priority CLOCK_2))) // RTX HAL Timer { printf("ERROR: Could not create the RTAPI timer.\n").QuadPart = 5000. // Stack size .  #include "windows. ULONG TimerCounter = 0. &Period)) { printf("ERROR: Could not set and start the RTAPI timer.\n"). ExitProcess(2). // // Stop and delete the timer. // NULL context (argument to handler) RT_PRIORITY_MAX. // if (!(hTimer = RtCreateTimer( NULL.Appendix A: Code and File Examples RTX Timer and Sleep Calls Programming Example The following example demonstrates the use of RTX timer and sleep calls.h" // // Local data. // // Set to the next to highest real-time priority. // Timer period // Start time of sampling run // Counts entries to timer handler 107 . // // Setup and start the periodic timer. } // // Wait for the sampling time. RT_PRIORITY_MAX-1)) printf("WARNING: Can’t set to highest RTAPI priority. &x). // Timer handler NULL. // Security .NULL is none 0.

RTX User’s Guide } // // timer handler function // . return 0 . }  See Also Clocks and Timers 108 .increment the tick counter // int RTFCNDCL TimerHandler( PVOID unused ) { TimerCounter++.

107 109 I Interprocess Communication. 74 Process Exception Disposition. 60 GetExceptionInformation. 78 R Real-Time Inter-Process Communication. 92 G GetCurrentProcess. 48 set. 70 Techniques/Considerations. 60 L Latency. 30 RTSS. 60 General User Notes. 43. 53 D Debugging. 33 DMA. x Control Panel. 40 HAL Timer Period. 70 Programming. 46 Interrupt Latencies. 48 Interrupt Service Routine. 75 Documentation Updates. 78 Interpreting. 34 GetExceptionCode. 1 RtAllocateContiguousMemory.Index B Book Overview. 78 Histogram Plot. 48 Interrupt Service Thread. 48 Interrupts. 75 Latency Test Program. 1 ISR. 75 KSRTM versus SRTM. 95 RtAttachInterruptVector. 70 H HAL. 4. 78 Interpreting. 33 Inter-Process Communication. 46 Exception Handling. 40 Histogram. 30 HalTimerPeriod. 82 M Max Latency Plot. 21 Developing RTX Applications. 21 Microsoft Visual Studio. 33 Management. 75 KSRTM. 30. 30 CreateFile. 59 CENTer. 102 RTAPI. 78 O Object Names. 52. 21. 74 RTX Management. 48 RtCancelTimer. 48 IPC. 74 . 21 Microsoft Visual Studio 6. 60 Graphical version SRTM. 75. 43 F Floating-Point Support. 4 Device Management. 59 FreeLibrary. 48 Issue Green Screen. 78 Microsoft Developer Studio 5. 4 Developer Studio 5. 74 Interrupt Management.0.0. 63 IST. x K Kernel System Response Time Measurement. 59 Using. 48 C C Run-time Library Functions. 75 E Event Objects. 21 Mutex. 43 P Port I/O Calls. 48 Power Management. 48 attach.0.

15 Starting. 71 RTX Process Memory Locking Calls. 75. 4 Stopping. 75 110 . 107 RTX Utilities. 34 Win32 Thread Priority Mapping. 70 SetUnhandledExceptionHandler. 60 Setting Starvation Time Out. 25 RTSS Exception Handling. 95 Tools Overview. 40 Sleep Calls Programming Example. 60. 70 RTX Settings icon. 7 debugging. 83 RtGetLastError. 57. 57 use. 75 Timer Latency Display Tool. 60 RTX AppWizard. 103. 75 RTX Device Drivers. 63 Support ID. 62. 25 designing. 106 RtGetPhysicalAddress. 59 Building. 37 RTX Makefile. 29 Sleep Calls. 77. 4 Real-Time Applications. 30 RTX Timer. 7 RTX Demo. 64 RTX Functionality. 11 RTSSrun. 60 Shutdown Handlers. 15 RTSS Thread Priority Mapping. 4. 4. 70 RtxServer. 4 RTX Exception Codes. 37 System Response Time Measurement. 51 RTX Power Management. 34 RTSSkill. 9 RTSSrun Utility. 75 T Technical Support. 34 use. 4 launch. 56 RTX Memory Mapping Calls. 60 RTSS Object Viewer. 8. 34. 25 create.RTX User’s Guide RtCreateTimer. 4. 102 RtGetBusDataByOffset. 65 Automatically Reboot. 34 starting. 9 RtTranslateBusAddress. 7. 102 RtLockKernel. 33 Timer Latency Display. ix System Exception Handling. 33 Using. 30. 57. 106 RtMapMemory. 59 Writing. ix Technical Support Area. 4 Running. 59 RTSS Task Manager. 62 System Memory Allocation. 15. 37 System Memory Management. 63 RTX Exception Handling. 33 RTX Green Screen. 107 RTDLLs. 80 S Select. 62. 37 RTX Settings. 59 RTSS DLLs. 34. 77 Starvation Management. 83 RtSetThreadPriority. 29. 107 Sleep Services. 100 RTSSkill Utility. 78 building. 8. 4 Thread Management. 65 RTX HAL Timer. 107 RtDeleteTimer. 34 RTSS Task Manager window. 70 Starvation Time Out Period. 34 RTSSkill Examples. 107 RtSetTimerRelative. 8 Unregister. 107 RTSS. 37 System Memory Locking. 15. 11. 100 Register. 40 SRTM. 34 RTX Kernel Memory Locking Calls. 70 Structured Exception Handling. 8 RtFreeContiguousMemory(vAddress. 95. 75. 7 RTX-defined. 30 RTX Startup. ix Testing. 70 SetErrorMode. 4. 16 Run Timer Latency Display tool. 103 RTX API. 71 Windows 2000. 25. 59 RTSS Device Drivers. 103 RtLockProcess. 4 RTSS Programs. 95 RTSSrun Console. 9 RTSSrun GUI. 34 RTSS application. 4. 37 RTX Locked Memory Allocation Calls. 80 TimerHandler. 44 Service Request Interrupt. 65 Semaphores. 29 Shutdown Program. 13 RTSS Process. 95. 83 RtUnlockKernel. 107 RTX Inter-Process Communication.

66 Windows NT Control Panel. 70 RTX. 59 develop. 65 Windows 2000 Stop Screens. ix W Watchdog Management. 26 Windows 2000 Stop Messages. 68 Windows NT Automatically Reboot. 70 Win32 application. 82 Using RTX Demo. 65.Index U Use RTSSkill. 7 V VenturCom Customer Support Web. 70 Watchdog Timer. 66 Interpreting. ix VenturCom Web site. 26. 70 Using LTP.0. 60 Win32Debug. 21 WinDbg. 65. 26 WinDbg 5. 26 Win32 Structured Exception Handling. 66 Write Debugging Information. 66 Windows NT Blue Screen Stop Messages.0. 59 Win32 Platform SDK. 66 111 . 66 WinDbg 4. 60 Win32 SDK Tools. 65 Windows NT Blue Screen. 78 Using Software Development Tools.

Sign up to vote on this title
UsefulNot useful