QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX...

333
QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino 6.3 2006, QNX Software Systems GmbH & Co. KG.

Transcript of QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX...

Page 1: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

QNX Neutrino Realtime

Operating SystemBuilding Embedded Systems

For targets running QNX Neutrino 6.3

2006, QNX Software Systems GmbH & Co. KG.

Page 2: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

1996–2006, QNX Software Systems GmbH & Co. KG. All rights reserved.

Published under license by:

QNX Software Systems International Corporation175 Terence Matthews CrescentKanata, OntarioK2M 1W8CanadaVoice: +1 613 591-0931Fax: +1 613 591-3579Email: [email protected]:http://www.qnx.com/

Publishing history

December 1996 First edition

July 1997 Second edition

May 1999 Third edition

June 2004 Fourth edition

Electronic edition published 2006

To obtain technical support for any QNX product, visit theTechnical Support section in theServices area on our website(www.qnx.com). You’ll find a wide range of support options, including our free web-basedDeveloper Support Center.

QNX, Neutrino, Photon, Photon microGUI, Momentics, and “Build a More Reliable World” are trademarks, registered in certain jurisdictions, of QNX

Software Systems GmbH & Co. KG and are used under license by QNX Software Systems International Corporation. All other trademarks belong to their

respective owners.

Printed in Canada.

Part Number: 002504

Page 3: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Contents

About This Book xvTypographical conventions xvii

Note to Windows users xviii

What you’ll find in this guide xix

Overview of Building Embedded1Systems 1

Introduction 3

The role of the IPL 3

The role of the startup program 5

Startup’s responsibilities 6

The role of Neutrino 9

Hardware aspects 10

Choice of processor 10

Source of initialization and configuration 10

Choice of filesystems 11

I/O devices 15

Getting started 16

Hardware design 17

Customizing the software 17

Working with a BSP 212Proprietary and simplified packaging for BSPs 23

Installing proprietary BSP source code 24

Structure of a BSP 25

November 3, 2006 Contents iii

Page 4: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

docs subdirectory (simplified BSPs only) 26

images subdirectory 27

prebuilt subdirectory 27

install subdirectory 28

src subdirectory 29

Building a BSP OS image from source 29

Building source from the command line 30

Building source within the IDE 32

Building a BSP OS image from the binary components 33

Building an image from the command line (simplified BSPs)33

Building an image from the command line (proprietary BSPs)33

Building an image in the IDE 34

Creating a working set 35

Supporting additional devices 35

Transferring an OS image onto your board 36

Transferring an OS image 36

Working with a flash filesystem 38

Testing Neutrino on your board 41

Getting Photon on your board 41

Where do I go from here? 42

Filename conventions 43

Making an OS Image 453Images, images, images 47

What is an OS image? 47

The OS image as a filesystem 48

Configuring an OS image 49

A simple buildfile 49

Plain ordinary lists of files 52

Bound multiprocessing attributes 58

The bootstrap file 59

iv Contents November 3, 2006

Page 5: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

Specifying command-line options tomkifs 60

Listing the contents of an image 60

Building a flash filesystem image 61

Usingmkefs 62

Compressing files 64

Compression rules 67

Design considerations 70

Embedding an image 70

Combining image files usingmkimage 72

Converting images usingmkrec 73

Transferring an image to flash 73

System configuration 76

Establishing an output device 77

Running drivers/filesystems 78

Running applications 82

Debugging an embedded system 83

pdebug software debugging agent 83

Hardware debuggers and Neutrino 84

Producing debug symbol information for IPL and startup 84

Writing an IPL Program 914Initial program loader (IPL) 93

Responsibilities of the IPL 93

Booting from a bank-switched device 95

Booting from a linear device 98

“Warm” vs “cold” start 98

Loading the image 99

Transferring control to the startup program 105

Customizing IPLs 105

Initialize hardware 106

Loading the image into RAM 106

Structure of the boot header 107

Relationship ofstruct startup header fields 114

November 3, 2006 Contents v

Page 6: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

IPL structure 119

Creating a new IPL 122

The IPL library 122

Customizing Image Startup Programs 1335Introduction 135

Initialize hardware 135

Initialize system page 135

Initialize callouts 136

Anatomy of a startup program 136

Structure of a startup program 138

Creating a new startup program 138

Structure of the system page 139

size 140

total size 140

type 140

num cpu 141

system private 141

asinfo 141

hwinfo 144

cpuinfo 153

syspage entry cacheattr 156

syspage entry qtime 160

callout 163

callin 163

typed strings 164

strings 164

intrinfo 164

syspage entry union un 171

un.x86 172

un.x86.smpinfo (deprecated) 173

un.ppc (deprecated) 173

un.ppc.kerinfo 173

vi Contents November 3, 2006

Page 7: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

un.mips 174

un.arm 174

un.sh 175

smp 175

pminfo 175

Callout information 176

Debug interface 177

Clock/timer interface 177

Interrupt controller interface 178

Cache controller interface 179

System reset callout 179

Power management callout 180

The startup library 180

add cache() 180

add callout() 180

add callout array() 181

add interrupt() 181

add interrupt array() 181

add ram() 181

add string() 181

add typed string() 182

alloc qtime() 182

alloc ram() 182

as add() 182

as add containing() 182

as default() 183

as find() 183

as find containing() 184

as info2off() 184

as off2info() 184

as set checker() 184

as set priority() 185

November 3, 2006 Contents vii

Page 8: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

avoid ram() 185

calc time t() 185

calloc ram() 185

callout io map indirect() 186

callout memory map indirect() 186

callout register data() 186

chip access() 187

chip done() 187

chip read8() 187

chip read16() 188

chip read32() 188

chip write8() 188

chip write16() 188

chip write32() 188

copy memory() 188

del typed string() 189

falcon init l2 cache() 189

falcon init raminfo() 189

falcon system clock() 189

find startup info() 189

find typed string() 190

handle common option() 190

hwi add device() 191

hwi add inputclk() 191

hwi add irq() 192

hwi add location() 192

hwi add nicaddr() 192

hwi add rtc() 192

hwi alloc item() 193

hwi alloc tag() 193

hwi find as() 193

hwi find item() 193

viii Contents November 3, 2006

Page 9: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

hwi find tag() 194

hwi off2tag() 194

hwi tag2off() 195

init asinfo() 195

init cacheattr() 195

init cpuinfo() 195

init hwinfo() 196

init intrinfo() 196

init mmu() 197

init pminfo() 197

init qtime() 197

init qtime sa1100() 197

init raminfo() 198

init smp() 198

init syspage memory() (deprecated) 198

init system private() 199

jtag reserve memory() 199

kprintf() 199

mips41xx set clock freqs() 199

openbios init raminfo() 200

pcnet reset() 200

ppc400 pit init qtime() 200

ppc405 set clock freqs() 200

ppc600 set clock freqs() 201

ppc700 init l2 cache() 201

ppc800 pit init qtime() 201

ppc800 set clock freqs() 202

ppc dec init qtime() 202

print syspage() 202

rtc time() 203

startup io map() 205

startup io unmap() 205

November 3, 2006 Contents ix

Page 10: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

startup memory map() 206

startup memory unmap() 206

tulip reset() 206

uncompress() 206

x86 cpuid string() 207

x86 cputype() 207

x86 enable a20() 207

x86 fputype() 208

x86 init pcbios() 208

x86 pcbios shadow rom() 208

x86 scanmem() 208

Writing your own kernel callout 209

Find out who’s gone before 210

Why are they in assembly language? 211

Starting off 211

“Patching” the callout code 213

Getting some R/W storage 214

The exception that proves the rule 216

PPC chips support 216

Adding a new CPU to the startup library 221

Customizing the Flash Filesystem 2236Introduction 225

Driver structure 226

resmgr andiofunc layers 227

Flash filesystem component 227

Socket services component 227

Flash services component 228

Probe routine component 228

Building your flash filesystem driver 228

The source tree 228

TheMakefile 231

Making the driver 231

x Contents November 3, 2006

Page 11: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

Themain() function 231

Socket services interface 233

Options parsing 237

Flash services interface 238

Choosing the right routines 247

Example: Thedevf-ram driver 248

main() 248

f3s ram open() 250

f3s ram page() 251

System Design Considerations 253AIntroduction 255

Before you design your system 255

Other design considerations 257

NMI 262

Design do’s and don’ts 263

Do: 263

Don’t: 264

Sample Buildfiles 265BIntroduction 267

Generic examples 267

Shared libraries 267

Running executables more than once 269

Multiple consoles 269

Complete example — minimal configuration 271

Complete example — flash filesystem 272

Complete example — disk filesystem 273

Complete example — TCP/IP with network filesystem 275

Processor-specific notes 278

Specifying the processor 278

Specifying the startup program 278

Specifying the serial device 279

November 3, 2006 Contents xi

Page 12: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

Glossary 281

Index 305

xii Contents November 3, 2006

Page 13: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

List of Figures

An OS image loaded by the IPL. 4

You may select as many storage options as you need. 12

The three main branches of the Neutrino source tree. 17

The complete Neutrino source tree. 18

BSP directory structure. 26

A sampleprebuilt directory. 28

Flash configuration options for your Neutrino-based embeddedsystems. 71

Linearly mapped device. 101

Bank-switched devices. 102

Large storage medium, bank-switched into a window. 103

IPL directory structure. 119

Startup directory structure. 137

Two-processor system with separate L1 instruction and datacaches. 159

Structure of the flash filesystem driver. 226

Flash directory structure. 229

November 3, 2006 List of Figures xiii

Page 14: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 15: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

About This Book

November 3, 2006 About This Book xv

Page 16: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 17: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Typographical conventions

Typographical conventionsThroughout this manual, we use certain typographical conventions todistinguish technical terms. In general, the conventions we useconform to those found in IEEE POSIX publications. The followingtable summarizes our conventions:

Reference Example

Code examples if( stream == NULL )

Command options -lR

Commands make

Environment variables PATH

File and pathnames /dev/null

Function names exit()

Keyboard chords Ctrl – Alt – Delete

Keyboard input something you type

Keyboard keys Enter

Program output login:

Programming constants NULL

Programming data types unsigned short

Programming literals 0xFF, "message string"

Variable names stdin

User-interface componentsCancel

We format single-step instructions like this:

➤ To reload the current page, pressCtrl – R.

We use an arrow (→) in directions for accessing menu items, like this:

November 3, 2006 About This Book xvii

Page 18: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Typographical conventions 2006, QNX Software Systems GmbH & Co. KG.

You’ll find the Other... menu item underPerspective→Show View.

We use notes, cautions, and warnings to highlight importantmessages:

Notes point out something important or useful.☞

CAUTION: Cautions tell you about commands or procedures thatmay have unwanted or undesirable side effects.!

WARNING: Warnings tell you about commands or proceduresthat could be dangerous to your files, your hardware, or evenyourself.

Note to Windows usersIn our documentation, we use a forward slash (/) as a delimiter inallpathnames, including those pointing to Windows files.

We also generally follow POSIX/UNIX filesystem conventions.

xviii About This Book November 3, 2006

Page 19: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. What you’ll find in this guide

What you’ll find in this guideTheBuilding Embedded Systems guide is intended for developerswho are building embedded systems that will run under the QNXNeutrino RTOS.

QNX Neutrino runs on several processor families (e.g. PowerPC,MIPS, ARM, SH-4, x86). For information on getting started withNeutrino on a particular board, refer to the appropriate BSP (BoardSupport Package) documentation for your board.

This guide is organized around these main topics:

Topic Chapter(s)

Getting the big picture Overview of BuildingEmbedded Systems

Getting started with your boardsupport package

Working with a BSP

Making an image Making an OS Image

Preparing your target Writing an IPL Program;Customizing Image StartupPrograms;Customizing the FlashFilesystem;Sample Buildfiles

Dealing with hardware issues System Design Considerations

Terms used in QNX docs Glossary

November 3, 2006 About This Book xix

Page 20: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

What you’ll find in this guide 2006, QNX Software Systems GmbH & Co. KG.

We assume that you’ve already installed QNX Neutrino and thatyou’re familiar with its architecture. For a detailed overview, see theSystem Architecture manual.

If you plan to use the Photon microGUI in your embedded system,refer to the “Photon in Embedded Systems” appendix in the PhotonProgrammer’s Guide.

xx About This Book November 3, 2006

Page 21: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Chapter 1

Overview of Building EmbeddedSystems

In this chapter. . .Introduction 3Hardware aspects 10Getting started 16

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 1

Page 22: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 23: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

IntroductionIn this chapter, we’ll take a “high-level” look at the steps necessary tobuild a complete Neutrino-based embedded system, with pointers tothe appropriate chapters for the lower-level details.

First we’ll see what a Neutrino system needs to do in order to run.Then we’ll look at the components and how they operate. Finally,we’ll do an overview of the steps you may need to follow whencustomizing certain portions.

From the software perspective, the following steps occur when thesystem starts up:

1 Processor begins executing at the reset vector. The InitialProgram Loader (IPL) locates the OS image and transferscontrol to the startup program in the image.

2 Startup program configures the system and transfers control tothe Neutrino microkernel and process manager (procnto).

3 Theprocnto module loads additional drivers and applicationprograms.

After we look at the software aspects in some more detail, we’llconsider the impact that the hardware has on this startup process.

The role of the IPLThe first step performed by the software is to load the OS image. Thisis done by a program called theInitial Program Loader (IPL).

The IPL’s initial task is to minimally configure the hardware to createan environment that will allow the startup program, and consequentlythe Neutrino microkernel, to run. Specifically, this task includes atleast the following steps:

1 Start execution from the reset vector.

2 Configure the memory controller, which may includeconfiguring chip selects and/or PCI controller.

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 3

Page 24: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Introduction 2006, QNX Software Systems GmbH & Co. KG.

3 Configure clocks.

4 Set up a stack to allow the IPL lib to perform OS verificationand setup (image download, scan, setup, and jump).

The IPL is described in detail in the chapter on Writing an IPLProgram.

Otherfiles...

procnto

Startup

An OS image loaded by the IPL.

Warm-start and cold-start IPL

There are two general types of IPL: warm-start and cold-start.Warm-start IPL is typically invoked by a ROM-monitor or BIOS;some aspects of the hardware and processor configuration will havealready been set up.

With cold-start IPL, on the other hand, nothing has been configured orinitialized — the CPU and hardware have just been reset. Naturally,the work that needs to be done within a warm-start IPL will be asubset of the work required in a cold-start IPL.

We’ll approach the discussion of the IPL’s responsibilities starting atthe end, describing the goal or final state that everything should be injust before the first component of the image is started. Then we’ll takea look at the steps necessary to get us to that final state.

Depending on the design of your target, you may have to take anumber of steps, ranging from none (e.g. you’re running on astandard platform with a ROM monitor or BIOS, and have performeda warm-start IPL via disk or network boot; the boot ROM has done all

4 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 25: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

the work described below for you) to many (e.g. you have a customembedded system without firmware and the image is stored on aspecialized piece of hardware).

The final state (just before the first component of the image is started)is characterized by the following:

� The memory controller has been configured to give access to thememory present on the system.

� Minimal hardware configuration has been performed (e.g. chipselects to map EPROMs have been programmed).

� The entire image is now located in linearly addressable memory.

� The first part of the image, the startup code, is now in RAM. (Notethat the startup code is relatively small and that the RAM area isreclaimed when the startup code is finished.)

Either the IPL or the BIOS/ROM monitor code is responsible fortransferring the image to linearly addressable memory. The OS imagemust have been built in a format that the IPL or ROM monitor codeunderstands so that it can know where to place the image in memoryand to what address to pass control after the image has been loaded.

For example, an IBM PC BIOS system typically loads a raw binaryand then jumps to the first address. Other systems may accept animage in ELF format, using the ELF header information to determinethe location to place the image as well as the starting address. Refer tothe documentation that came with your hardware to find out whatimage formats the IPL code can accept.

Once the IPL has located the image, and the entire image is now inlinearly addressable memory, control is transferred to the startupprogram. At that point, the IPL is done and is out of the picture.

The role of the startup programThe second step performed by the software is to configure theprocessor and hardware, detect system resources, and start the OS.

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 5

Page 26: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Introduction 2006, QNX Software Systems GmbH & Co. KG.

This is done by thestartup program. (For details, see the chapter onCustomizing Image Startup Programs.)

While the IPL did the bare minimum configuration necessary to getthe system to a state where the startup program can run, the startupprogram’s job is to “finish up” the configuration. If the IPL detectedvarious resources, it would communicate this information to thestartup program (so it wouldn’t have to redetect the same resources.)

To keep Neutrino as configurable as possible, we’ve given the startupprogram the ability to program such things as the base timers,interrupt controllers, cache controllers, and so on. It can also providekernel callouts, which are code fragments that the kernel can call toperform hardware-specific functions. For example, when a hardwareinterrupt is triggered, some piece of code must determine the sourceof the interrupt, while another piece of code must be able to clear thesource of the interrupt.

Note that the startup program doesnot configure such things as thebaud rate of serial ports. Nor does it initialize standard peripheraldevices like an Ethernet controller or EIDE hard disk controller —these are left for the drivers to do themselves when they start up later.

Once the startup code has initialized the system and has placed theinformation about the system in thesystem page area (a dedicatedpiece of memory that the kernel will look at later), the startup code isresponsible for transferring control to the Neutrino kernel and processmanager (procnto), which perform the final loading step.

Startup’s responsibilitiesLet’s take a look at the overall responsibilities and flow of the startupcode:

1 Copy and decompress the image, if necessary.

2 Configure hardware.

3 Determine system configuration.

4 Start the kernel.

6 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 27: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

Copying and decompressing the image

If the image isn’t in its final destination in RAM, the startup codecopies it there. If the image is compressed, the startup codeautomatically decompresses the image. Compression is optional; youcan create an image file that isn’t compressed, in which case thestartup code won’t bother trying to decompress it.

Configuring the hardware

The main task here is to set up the minimum required to be able todetermine the system configuration (and then perform the systemconfiguration).

The details of what needs to be configured during the hardwareconfiguration phase depend on your particular hardware.

Determining system configuration

Depending on the nature of the embedded system, you may wish todynamically determine the configuration on startup or (in the case of adeeply embedded system) simply “hardcode” the configurationinformation.

Regardless of the source of the information, the configuration part ofthe startup code needs to store this information into a set ofwell-defined data structures that the OS will then look at when itstarts. Collectively known as thesystem page area, these datastructures contain information about:

� memory configuration

� hardware device configuration

� processor type

� time of day

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 7

Page 28: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Introduction 2006, QNX Software Systems GmbH & Co. KG.

Establishing callouts

To keep the Neutrino kernel as portable as possible (not only todifferent processors, but also to different hardware configurations ofthose processors), a number of callouts must be supplied by thestartup code. Not all of the callouts require thatyou write code — wehave a library that provides many of these.

The following classes of callout functions can be provided forNeutrino:

� debug interface

� clock/timer interface

� interrupt controller interface

� cache controller interface

� power management

� miscellaneous

The callouts are described in detail in the chapter on CustomizingImage Startup Programs.

Starting the OS

The final step that the startup code performs is to start the operatingsystem.

The startup library

If all of the above sounds like a lot of work, well, it is! Note, however,that we’ve provided source code for some common startup programsand have created a library that performs most of the above functionsfor you.

If you have one of the many platforms that we support, then you don’thave to do any of this work — we’ve already done it for you.

To find out what processors and boards we currently support, pleaserefer to the following sources:

8 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 29: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

� theboards directory underbsp working dir/src/hardware/startup/boards.

� QNX docs (BSP docs as well asstartup-* entries in theUtilitiesReference).

If you have a nonstandard embedded system, you can look at thesource for the system that most closely resembles yours and “clone”the appropriate functionality from the examples provided.

This issue is discussed in detail in the chapter on Customizing ImageStartup Programs.

The role of NeutrinoThe third step performed by the software is to start any executablesthat you want to be running. The OS does this by reading andprocessing information stored in thestartup script — a sequence ofcommands stored within the image. The format of the startup script,as well as thebuildfile that it’s part of, is documented in detail in avariety of places in this guide:

� Making an OS Image chapter — describes the steps required tobuild a Neutrino-based system, including discussions of the scriptfile and buildfile.

� Sample Buildfiles appendix in this guide — describes common“tricks” used within the buildfile and also contains completeexamples of sample configurations.

� mkifs doc — describes themkifs utility, which is used to createthe image from the description passed to it in the buildfile. See theUtilities Reference for details.

� Building OS and Flash Images chapter in the IDEUser’s Guide —describes the how the OS and Flash images are created in the IDE.

Basically, the OS processes the startup script file, which looks like ashell script. In the startup script file, you’d specify which executablesshould be started up (and their order), the command-line options thatthey should run with, and so on.

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 9

Page 30: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Hardware aspects 2006, QNX Software Systems GmbH & Co. KG.

Hardware aspectsFrom the hardware point of view, the following components form thesystem:

� processor

� source of initialization and configuration info

� storage media

� I/O devices

Choice of processorWe support the following processor families:

� ARM (including XScale)

� MIPS

� PowerPC

� SH-4

� x86

At the “altitude” of this high-level discussion, the choice of processoris irrelevant — the same basic steps need to be performed regardlessof the particular CPU.

Source of initialization and configurationWhen the processor (re)starts, it must be able to execute instructions.This is accomplished by having some kind of nonvolatile storagemedia placed at the processor’s reset vector. There is, of course, achoice as towho supplies this particular piece of software:

� QNX Software Systems — you’ve chosen a standard, supportedhardware platform;

� 3rd party — a BIOS or ROM monitor; or

10 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 31: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Hardware aspects

� you — a custom IPL program.

Generally, the simplest development system is one in which you haveto do the least amount of work. If we’ve already done the work,meaning that the board that you’re using is a standard, supportedhardware platform, there’s very little work required from you in thisregard; you can instead focus on your software that’s going to run onthat board.

If a 3rd party supplies just the BIOS or ROM monitor, then yourresponsibilities are increased by having to write the software thatstarts the operating system. As mentioned earlier, we call this a“warm-start,” because the system is already “warmed-up” — variousdevices are configured and initialized.

If you’re supplying a custom IPL, then your responsibilities arefurther increased by also having to deal with configuration issues forthe hardware. This we call a “cold-start,” because you are responsiblefor everything to do with initialization and configuration.

Choice of filesystemsOnce you’ve sorted out how the system is going to boot, you may stillhave additional decisions to make regarding the system’s storagecapabilities:

� none

� read-only

� read/write nonpersistent

� read/write persistent

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 11

Page 32: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Hardware aspects 2006, QNX Software Systems GmbH & Co. KG.

No

No

Yes

Yes

Yes

No

Yes

Flashfilesystem

QNX

filesystem

No

Yes

Network

filesystem

Done

No

Is afilesystemneeded?

Iswrite accessrequired?

Ispersistentstorage

required?

Willa rotatingmediumbe used?

Is anetwork

filesystemused?

procnto memoryobjects

procnto imagefilesystem

You may select as many storage options as you need.

No additional storage required

If you don’t require any additional storage (i.e. your system is entirelyself-contained and doesn’t need to access any other files once it’srunning), then your work in this regard is done.

12 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 33: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Hardware aspects

Additional read-only storage required

The simplest filesystem scenario is one where read-only access isrequired. There’s no work for you to do — Neutrino provides thisfunctionality as part of the OS itself. Simply place the files that youwish to access/execute directly into the image (see the chapter onMaking an OS Image), and the OS will be able to access them.

Additional read/write nonpersistent storage required

If you require write access (perhaps for temporary files, logs, etc.),and the storage doesn’t have to bepersistent in nature (meaning that itdoesn’t need to survive a reset), then once again the work is done foryou.

Neutrino allows the RAM in your system to be used as a RAM-disk,without any additional coding or device drivers. The RAM-disk isimplemented via the Process Manager — you simply set up a ProcessManager link (using theln command).

For example, to mount the/tmp directory as a RAM-disk, execute thefollowing command:

ln -Ps /dev/shmem /tmp

Or place the following line in your buildfile (we’ll talk aboutbuildfiles over the next few chapters):

[type=link] /tmp=/dev/shmem

This instructs the Process Manager to take requests for any files under/tmp and resolve them to the shared memory subsystem. Forexample,/tmp/AAA4533.tmp becomes a request for/dev/shmem/AAA4533.tmp.

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 13

Page 34: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Hardware aspects 2006, QNX Software Systems GmbH & Co. KG.

In order to minimize the size of the RAM filesystem code inside theProcess Manager, the shared memory filesystem specifically doesn’tinclude “big filesystem” features such as file locking and directorycreation.

If you need a relatively full-featured, POSIX-style filesystem on aRAM disk, usedevf-ram or the builtin RAM disk viaio-blkinstead.

Additional read/write persistent storage required

If you do require storage that must survive a power failure orprocessor reset, then you’ll need to run an additional driver. Wesupply these classes of filesystems:

� flash filesystems

� rotating disk filesystems

� network filesystems

All of these filesystems require additional drivers. The SampleBuildfiles appendix in this guide gives detailed examples showinghow to set up these filesystem drivers.

Flash filesystems and media

The flash driver can interface to the flash memory devices (boot blockand regular) in all combinations of bus widths (8, 16, and 32 bits) andinterleave factors (1, 2, and 4).

To find out what flash devices we currently support, please refer to thefollowing sources:

� theboards andmtd-flash directories underbsp working dir/src/hardware/flash.

� QNX docs (devf-* entries inUtilities Reference).

� the QNX Software Systems web site (www.qnx.com).

14 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 35: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Hardware aspects

Using the source code provided, you may be able to tailor one of ourfilesystems (e.g.devf-generic) to operate on your particularembedded system (if it isn’t currently supported).

Rotating media and filesystems

Neutrino currently supports several filesystems, including DOS,Linux, QNX 4, CD-ROM, and more. For details, see thefs-* entriesin theUtilities Reference.

Drivers are available for many block-oriented devices. For up-to-dateinformation, see thedevb-* entries in theUtilities Reference as wellas the Developer Support Center area of our website (www.qnx.com).

Network media and filesystems

During development, or perhaps in a distributed data-gatheringapplication, you may wish to have a filesystem located on onemachine and to be able to access that filesystem from other machines.A network filesystem lets you do this.

In addition to its own transparent distributed processing system(Qnet), QNX Neutrino also supports network filesystems such asCIFS (SMB), NFS 2, and NFS 3.

Drivers are available for the several Ethernet controllers. For details,see thedevn-* entries in theUtilities Reference as well as theDeveloper Support Center area of our website (www.qnx.com).

I/O devicesUltimately, your Neutrino-based system will need to communicatewith the outside world. Here are some of the more common ways todo this:

� serial/parallel port

� network (described above)

� data acquisition/generation

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 15

Page 36: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Getting started 2006, QNX Software Systems GmbH & Co. KG.

� multimedia

Character I/O devices

For standard serial ports, Neutrino supports several devices (8250family, Signetics, etc.) For details, see thedevc-* entries in theUtilities Reference as well as the Developer Support Center area ofour website (www.qnx.com).

Special/custom devices

One design issue you face is whether you can get off-the-shelf driversfor the hardware or whether you’ll have to write your own. If it turnsout that you need to write your own, then the Writing a ResourceManager chapter in theProgrammer’s Guide can help you do that.

Getting startedDepending on the ultimate system you’ll be creating, you may have aton of work to do or you may have very little. In any case, werecommend that you start with a supported evaluation board. Thisapproach minimizes the amount of low-level work that you have to doinitially, thereby allowing you to focus on your system rather than onimplementation details.

Start with an evaluation platform that most closely resembles yourtarget platform — there are many supported evaluation platformsfrom various vendors.

Once you’re comfortable with the development environment and havedone a very rudimentary “proof of concept,” you can move on to suchdevelopment efforts as creating your own hardware, writing your ownIPL and startup code, writing drivers for your hardware, and so on.

Your proof of concept should address such issues as:

� How much memory will be required?

� How fast a CPU will be required?

� Can standard off-the-shelf hardware do the job?

16 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 37: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Getting started

Once these are addressed, you can then decide on your plan of attack.

Hardware designThere are a number of ways of designing your hardware. We’ve seenmany boards come in from the field and have documented some ofour experiences with them in the System Design Considerationsappendix in this book. You may be able to realize certain savings (inboth cost and time) by reading that appendix first.

Customizing the softwareIdeally, the system you’re designing will look identical to a supportedevaluation platform. In reality, this isn’t always the case, so you’llneed to customize some of the components in that system.

We’ve provided the source code to a large number of the“customizable” pieces of the OS. This diagram gives you thehigh-level view of the directory structure for the source tree we ship:

flashstartupipl

bsp_working_dir/src/hardware

The three main branches of the Neutrino source tree.

As you can see, we’ve divided the source tree into three majorbranches:ipl, startup, andflash. Each branch consists of furthersubdirectories:

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 17

Page 38: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Getting started 2006, QNX Software Systems GmbH & Co. KG.

bsp_working_dir/src/hardware

startup

boards

403evb800fadsbios

ddb-vrc4373explr2mbx800p5064ppaq

vme603vr41xx...

bootfile

mipsbemipsleppcbex86

flash

boards

800fadsexplr2ppaqram

sc400vr41xx...

mipsppc

x86

mtd-flash

amdfujitsuintel

sharp

romsram

...

ipl

boards

800fads...

arm

sh

The complete Neutrino source tree.

Customizing the source

The following table relates the source tree branches to the individualchapters in this book:

Source tree branch Relevant chapter

ipl Customizing IPL Programs

startup Customizing Image Startup Programs

continued. . .

18 Chapter 1 � Overview of Building Embedded Systems November 3, 2006

Page 39: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Getting started

Source tree branch Relevant chapter

flash Customizing the Flash Filesystem

For detailed information on the format of theMakefile present inthese directories, please see Conventions for Makefiles andDirectories in theProgrammer’s Guide.

November 3, 2006 Chapter 1 � Overview of Building Embedded Systems 19

Page 40: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 41: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Chapter 2

Working with a BSP

In this chapter. . .Proprietary and simplified packaging for BSPs 23Installing proprietary BSP source code 24Structure of a BSP 25Building a BSP OS image from source 29Building a BSP OS image from the binary components33Supporting additional devices 35Transferring an OS image onto your board 36Testing Neutrino on your board 41Getting Photon on your board 41Where do I go from here? 42Filename conventions 43

November 3, 2006 Chapter 2 � Working with a BSP 21

Page 42: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 43: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Proprietary and simplified packaging for BSPs

Once you’ve installed the QNX Momentics development suite, youcan download processor-specific Board Support Packages (BSPs)from our website,http://www.qnx.com/. These BSPs aredesigned to help you get Neutrino running on certain platforms.

A BSP typically includes the following:

� IPL

� Startup

� default buildfile

� networking support

� suite of device drivers, system managers, utilities, etc.

The BSP is contained in an archive named after theindustry-recognized name of the board and/or reference platform thatthe BSP supports. BSP packages are available for QNX Neutrino,Windows, Solaris, or Linux hosts. If your board includes flash, you’llalso need the Flash Filesystem & Embedding TechnologyDevelopment Kit (TDK).

You can build a BSP from the source code or the binary componentscontained in the BSP package.

Proprietary and simplified packaging forBSPsWe provide BSP packages in bothproprietary andsimplified styles.

Here’s how to determine which style a BSP is:

� Simplified BSPs are packaged as azip file, and the same archiveapplies to all hosts. As described in the installation notes, you needto use thesetupbsp command to install the BSP. ProprietaryBSPs are packaged as host-specific archives that use InstallShieldon Windows, Linux, and Solaris, or an installation script onNeutrino.

November 3, 2006 Chapter 2 � Working with a BSP 23

Page 44: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Installing proprietary BSP source code 2006, QNX Software Systems GmbH & Co. KG.

Thesetupbsp script puts two copies of the BSP on your system, inthese locations:

- in a directory of your choosing, for use with the command-linetools

- under$QNX TARGET, for importing into the IDE

Decide whether to use the command-line tools or the IDE, and don’twork with the other copy.

� Once installed, a simplified BSP optionally includes adocs

directory.

� Proprietary BSPs install any binaries in the appropriate directoryunder$QNX TARGET, potentially overwriting binaries placedthere by other BSPs.

� The source (if included) for a proprietary BSP is installed as azip

file that you must expand before you build the BSP; any source fora simplified BSP is simply part of the installed directory structure.

� To build a proprietary BSP, you must run thesetenv script in theroot directory of the BSP before you runmake; in a simplifiedBSP, we’ve incorporatedsetenv right in theMakefiles.

The sections that follow point out any other differences between thestyles.

Installing proprietary BSP source codeWhen you install a proprietary BSP, the binaries are copied to theappropriate directory under$QNX TARGET, potentially overwritingbinaries placed there by other BSPs.

The source code (if included) is azip file that’s placed in$QNX TARGET/usr/src/archives/qnx. To install the source fora proprietary BSP, you must manually expand its directory structurefrom this archive.

24 Chapter 2 � Working with a BSP November 3, 2006

Page 45: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of a BSP

If you aren’t using the IDE and you want to manually install a BSParchive, we recommend that you create a default directory with thesame name as your BSP and unzip the archive from there:

1 Change the directory to where you want to extract the BSP (e.g./home/joe).

The archive will extract to the current directory, so you should createa directory specifically for your BSP.

For example:mkdir /home/joe/bspname

2 In the directory you’ve just created, extract the BSP:unzip $QNX TARGET/usr/src/archives/qnx/bspname.zip

Each BSP is rooted in whatever directory you copy it to. If you typemake within this directory, you’ll generate all of the buildable entitieswithin that BSP no matter where you move the directory.

Proprietary BSPs include asetenv script that you must run so thattypingmake or make install doesn’t affect the host system. If youuse this script, all binaries are placed in aninstall area within theBSP directory that mimics the layout of a target system.

When you build a BSP, everything it needs, aside from standardsystem headers, is pulled in from within its own directory. Nothingthat’s built is installed outside of the BSP’s directory. The makefilesshipped with the BSPs copy the contents of theprebuilt directoryinto theinstall directory. The binaries are built from the sourceusing include files and link libraries in theinstall directory.

Structure of a BSPIf you install a simplified BSP, or a proprietary BSP that includessource code, the resulting directory structure looks like this:

November 3, 2006 Chapter 2 � Working with a BSP 25

Page 46: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of a BSP 2006, QNX Software Systems GmbH & Co. KG.

bsp_working_dir

images prebuiltinstall src

devcdevnflashipl

startup

hardware

docs

usr

help

product

bsp_name

usr

dll

lib

usr

includebin sbin

binlibsbin

targetusr

dll

libbin sbin

binlibsbin

BSP directory structure.

In our documentation, we refer to the directory where you’ve installeda BSP (e.g./home/myID/my BSPs/integrator) as thebsp working dir. Depending on what’s shipped in the BSP, thisdirectory could include the following subdirectories:

� docs (simplified BSPs only)

� images

� prebuilt

� install

� src

docs subdirectory (simplified BSPs only)Thedocs subdirectory contains the documentation for the BSP. Thesetupbsp script copies the documentation to$QNX TARGET/usr/help/product, so that it will automaticallyappear in the Photon helpviewer.

26 Chapter 2 � Working with a BSP November 3, 2006

Page 47: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of a BSP

images subdirectoryTheimages subdirectory is where the resultant boot images areplaced. It contains (as a minimum) theMakefile needed to build theimage(s). Other files that could reside in this directory include:

� custom buildfiles (for flash, etc.)

� EFS buildfiles

� IPL build scripts

prebuilt subdirectoryTheprebuilt subdirectory contains the binaries, system binaries,buildfiles, libraries, and header files that are shipped with the BSP.

Before the BSP is built, all of the files from theprebuilt directoryare copied into theinstall directory, maintaining the path structure.

In order to handle dependencies, the libraries, headers, and other filesfound in the./prebuilt directory need to be copied correctly toyour./install directory. To do this, you’ll need to runmake at thebsp working dir directory level.

The “root” of theprebuilt directory requires the same structure asthe system root. The target-specific andusr directories mirror thestructure of/.

All processor-specific binaries are located under the directory namedfor that processor type.

For example, theprebuilt directory might look like this:

November 3, 2006 Chapter 2 � Working with a BSP 27

Page 48: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of a BSP 2006, QNX Software Systems GmbH & Co. KG.

prebuilt

usr

includesbin

ppcbe

ppcdrvr sys

lib

libdrvrS.alibstartup.a

devb-eide

eth.hmdi.h

support.h

util.ah dcmd_io-net.hnic.h

platform.htypes.h

sys

boot

build

ipl-boardstartup-board

board.build

sbin

devc-ser*devc-tser*

pci-*

A sample prebuilt directory.

install subdirectoryTheinstall directory gets populated at the beginning of the BSPbuild process. All the files in theprebuilt directory are copied, thenall generated binaries are installed here as they’re compiled. The filesstored in theinstall directory are taken first whenmkifs executes.

Before you make any components for your particular board, you mustfirst make the BSP sourcesat the top level:

cd bsp working dirmake

This builds everything under./src and sets up the./installdirectory correctly.

After this initial build is complete, you can build any of the sourcefiles individually.

28 Chapter 2 � Working with a BSP November 3, 2006

Page 49: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a BSP OS image from source

If you change a library or header, be sure to runmake install torebuild the source and copy the changes to your./install

directory.

src subdirectoryIf the BSP includes source code, it’s stored in this directory. Thehardware directory contains separate directories for character, flash,and network drivers, IPL, startup code, and so on, depending on theBSP.

Thesrc directory contains a buildfile,src/hardware/startup/boards/board/build, that overridesthe one in theprebuilt directory.

Building a BSP OS image from sourceIf you’re building the BSP OS image from source code on the host,you can:

� use the command line

� import the source code within the IDE

November 3, 2006 Chapter 2 � Working with a BSP 29

Page 50: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building a BSP OS image from source 2006, QNX Software Systems GmbH & Co. KG.

When you build a BSP from the source code, you may occasionallyobserve warnings from some of the tools used to generate the BSP,such as:

� objcopy: Warning: Output file cannot represent

architecture UNKNOWN!

� ntosh-ld: Warning: could not find any targets

that match endianness requirement

These warnings result when information that’s contained in oneparticular file format (endianness, CPU architecture, etc.) can’t beretained when converting that file to a different format, or when theoriginating file format doesn’t contain information that the tool doingthe conversion expects. These warnings are normal and expected, andare no cause for concern.

Building source from the command lineIn order to build a BSP from the command line, you must go to theroot directory for the BSP.

Building the source is similar for proprietary and simplified BSPs,except that for a proprietary BSP, youmust run thesetenv.sh scriptin the BSP’s root directory. This script configures your environmentto build the BSP. On Windows, youmust run the Bash shell(bash.exe) before you runsetenv.sh.

Run thesetenv.sh script as a “dot” file, so that it configures yourcurrent shell:

. ./setenv.sh

Simplified BSPs don’t includesetenv.sh; we’ve included it in theMakefile.

30 Chapter 2 � Working with a BSP November 3, 2006

Page 51: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a BSP OS image from source

Use themake command to build the source code. TheMakefile

defines the following targets:

all Invokes theinstall, links, andimages targets.

prebuilt This recursively copies theprebuilt directory’scontents (including a buildfile) to theinstalldirectory.

install Invokes theprebuilt target. If the BSP includes thesource code, this target then performs the following inthesrc directory:

� make hinstall to copy all headers fromsrcinto theinstall directory.

� make install to build all binaries insrc andcopy the results into theinstall directory. Thistarget also copies the buildfile fromsrc/hardware/startup/boards/board/buildand renames itboard.build.

links Creates a symbolic link (a copy on Windows) frominstall/cpu/boot/build/board.build toimages/board.build.

images Changes to theimages directory and runs theMakefile there. ThisMakefile creates an IFS filebased on the buildfile linked in during themakelinks target. Any extra work required (e.g. IPLpadding, conversion to an alternate format) is alsohandled from within thisMakefile.

If you don’t specify a target,make invokes theall target.

November 3, 2006 Chapter 2 � Working with a BSP 31

Page 52: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building a BSP OS image from source 2006, QNX Software Systems GmbH & Co. KG.

We recommend that you usemake to build the OS image. If you usemkifs directly, you need to use the-r option to specify where to findthe binaries. For more information, see the entry formkifs in theUtilities Reference.

Building source within the IDETo build a BSP, you must first import the source code into the IDE.When you import the BSP source, the IDE creates aSystem Builderproject.

To import the BSP source code:

1 SelectFile→Import.

2 SelectQNX Board Support Package from the list. ClickNext.

3 Choose the BSP you want. You’ll see a description of the BSPyou’ve chosen.

4 Click Next.

If you want to add more packages to the list, click theSelectPackage... button and select the.zip archive you want.

5 Uncheck the entries you don’t want. (By default all the entriesare selected.)

6 Click Next.

7 Select a working set. Default names are provided for theWorking Set Name and theProject Name Prefix that you canoverride if you choose.

8 Click Finish. All the projects will be created and the sourcesbrought from the archive. You’ll then be asked if you want tobuild all the projects you’ve imported.

32 Chapter 2 � Working with a BSP November 3, 2006

Page 53: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a BSP OS image from the binarycomponents

If you answer Yes, the IDE will start the build process. If youdecide to build at a later time, you can do aRebuild All fromthe mainProject menu when you’re ready to build.

When you import a QNX BSP, the IDE opens the QNX BSPPerspective. This perspective combines the minimum elements fromthe C�C++ Development Perspective and the System BuilderPerspective.

For more information, see the IDEUser’s Guide in yourdocumentation set. (Within the IDE itself, go to:Help→HelpContents→QNX Documentation Roadmap).

Building a BSP OS image from the binarycomponentsIf you’re building a BSP OS image from the binary components onthe host, you can use:

� the command line for a simplified BSP

� the command line for a proprietary BSP

� the IDE

Building an image from the command line (simplifiedBSPs)Once you’ve installed a simplified binary-only BSP, you can build itby using the samemake targets as for one with source code; see“Building source from the command line,” earlier in this chapter.

Building an image from the command line (proprietaryBSPs)After you’ve installed a proprietary binary-only BSP, you can buildthe BSP OS image from the command line:

1 Change directories to:

November 3, 2006 Chapter 2 � Working with a BSP 33

Page 54: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building a BSP OS image from the binary components 2006, QNX Software Systems

GmbH & Co. KG.

$QNX TARGET/processor type/boot/build

whereprocessor type is the BSP board type, e.g.ppcbe.

2 Enter:mkifs -vvvv BSP-buildfile-name OS-image-name

For example:mkifs -vvvv integrator.build integrator.ifs

Note that after you enter the command, the BSP OS image isgenerated, and the contents of the buildfile appear in the displayterminal.

Building an image in the IDETo build a BSP OS image from the binary components in the IDE:

1 Start the IDE.

2 SelectFile→New→Project.

3 SelectQNX in the left column, thenQNX System BuilderProject in the right column. ClickNext.

4 Name your project (e.g.Integrator) and clickNext.

5 Leave the default location as it is (e.g.workspace/Integrator).

6 Click Next.

7 ChooseImport Existing Buildfile.

8 Click Browse to locate and select the buildfile to import (e.g.integrator.build).

9 Click Finish. The BSP OS image is automatically generatedand your project (e.g. “Integrator”) appears within theQNXSystem Builder window.

34 Chapter 2 � Working with a BSP November 3, 2006

Page 55: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Supporting additional devices

Creating a working setYou can optionally create a working set in order to select from a listof BSP projects.

To create a working set:

1 In the System Builder Projects view, click the menu dropdown

button ( ).

2 Click Select Working Set..., then clickNew.

3 SelectQNX Sources.

4 Click Next.

5 Enter aWorking set name and check the entry for theWorking set contents. Typically this will be the BSP you’vejust imported.

6 Click Finish. Note that theFinish button is availableonly afteryou choose aWorking set contents entry.

7 Click OK.

Supporting additional devicesAll boards have some devices, whether they’re input, serial, flash, orPCI. Every BSP includes a buildfile that you can use to generate anOS image that will run on the board it was written for. The location ofthe buildfile depends on the type of BSP:

Proprietary BSPs with binaries only

$QNX TARGET/target/boot/build/

Simplified BSPs with binaries only

bsp working dir/prebuilt/boot/build/

Proprietary and simplified BSPs with source and binaries

bsp working dir/src/hardware/startup/boards/board

November 3, 2006 Chapter 2 � Working with a BSP 35

Page 56: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Transferring an OS image onto your board 2006, QNX Software Systems GmbH & Co. KG.

When youmake the BSP, the buildfile is copied into theimagesdirectory.

A BSP’s buildfile typically contains the commands — possiblycommented out — for starting the drivers associated with the devices.You might need to edit the buildfile to modify or uncomment thesecommands. For more information, see the documentation for eachBSP as well as the buildfile itself; for general information aboutbuildfiles, see the entry formkifs in theUtilities Reference.

Once you’ve modified the buildfile, follow the instructions givenearlier in this chapter for building an OS image.

Transferring an OS image onto your boardOnce you’ve built an OS image, you’ll need to transfer it to yourboard.

The IDE lets you communicate with your target and download yourOS image using either a serial connection, or a network connectionusing the Trivial File Transfer Protocol (TFTP). If your board doesn’thave a ROM monitor, you probably can’t use the download servicesin the IDE; you’ll have to get the image onto the board some otherway (e.g. JTAG).

Transferring an OS imageThere are several ways to transfer an OS image:

To: Use the:

Load an image from your network (e.g.TFTP)

Network

Load an image serially (e.g. COM1, COM2) ROM monitor

Burn both the IPL and the OS image into theflash boot ROM, then boot entirely from flash

IPL and OS

continued. . .

36 Chapter 2 � Working with a BSP November 3, 2006

Page 57: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Transferring an OS image onto your board

To: Use the:

Burn an IPL (Initial Program Loader) intothe flash boot ROM, then load the OS imageserially

IPL and boot ROM

Generate a flash filesystem, and then placevarious files and utilities within it

Flash filesystem

The method you use to transfer an OS image depends on what comeswith the board. The BSP contains information describing the methodthat you can use for each particular board. Each board will have all orsome of these options for you to use.

To load an image serially:

1 Connect your target and host machine with a serial cable.Ensure that both machines properly recognize the connection.

2 Specify the device (e.g.COM1) and the communicationssettings (e.g. the baud rate, parity, data bits, stop bits, and flowcontrol) to match your target machine’s capabilities. You cannow interact with your target by typing in the view.

To transfer a file using theSerial Terminal view:

1 Using either the serial terminal view or another method (outsidethe IDE), configure your target so that it’s ready to receive animage.

2 In the serial terminal view, clickSend File.

3 In theSelect File to Send dialog, enter the name or your file (orclick Browse).

4 Select a protocol (e.g.sendnto).

5 Click OK. The Builder transmits your file over the serialconnection.

November 3, 2006 Chapter 2 � Working with a BSP 37

Page 58: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Transferring an OS image onto your board 2006, QNX Software Systems GmbH & Co. KG.

Working with a flash filesystemThe flash filesystem drivers implement a POSIX-like filesystem onNOR flash memory devices. The flash filesystem drivers arestandalone executables that contain both the flash filesystem code andthe flash device code. There are versions of the flash filesystem driverfor different embedded systems hardware as well as PCMCIAmemory cards.

The naming convention for the drivers isdevf-system, wheresystemdescribes the embedded system. For example, thedevf-800fads

driver is for the 800FADS PowerPC evaluation board.

To find out what flash devices we currently support, please refer to thefollowing sources:

� theboards andmtd-flash directories underbsp working dir/src/hardware/flash.

� QNX Neutrino OS docs (devf-* entries inUtilities Reference).

� the QNX Software Systems website (www.qnx.com).

The flash filesystem drivers support one or more logical flash drives.Each logical drive is called asocket, which consists of a contiguousand homogeneous region of flash memory. For example, in a systemcontaining two different types of flash device at different addresses,where one flash device is used for the boot image and the other for theflash filesystem, each flash device would appear in a different socket.

Each socket may be divided into one or more partitions. Two types ofpartitions are supported:

� raw partitions

� flash filesystem partitions

Raw partitions

A raw partition in the socket is any partition that doesn’t contain aflash filesystem. The flash filesystem driver doesn’t recognize anyfilesystem types other than the flash filesystem. A raw partition maycontain an image filesystem or some application-specific data.

38 Chapter 2 � Working with a BSP November 3, 2006

Page 59: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Transferring an OS image onto your board

The flash filesystem uses a raw mountpoint to provide access to anypartitions on the flash that aren’t flash filesystem partitions. Note thatthe flash filesystem partitions are available as raw partitions as well.

Flash filesystem partitions

A flash filesystem partition contains the POSIX-like flash filesystem,which uses a QNX-proprietary format to store the filesystem data onthe flash devices. This format isn’t compatible with either theMicrosoft FFS2 or PCMCIA FTL specification.

The flash filesystem allows files and directories to be freely createdand deleted. It recovers space from deleted files using a reclaimmechanism similar to garbage collection.

The flash filesystem supports all the standard POSIX utilities such asls, mkdir, rm, ln, mv, andcp. There are also some QNX Neutrinoutilities for managing the flash filesystem:

flashctl Erase, format, and mount flash partitions.

deflate Compress files for flash filesystems.

mkefs Create flash filesystem image files.

The flash filesystem supports all the standard POSIX I/O functionssuch asopen(), close(), read(), andwrite(). Special functions such aserasing are supported using thedevctl() function.

Flash filesystem source

Each BSP contains the binary and the source code for the appropriateflash filesystem driver, but the Flash Filesystem & Embedding TDKcontains the associated header files and libraries.

Typingmake in thebsp working dir generates the flash filesystembinary. Normally, you won’t need to remake the flash filesystemdriver unless you’ve changed the size or configuration of the flash onthe board — this can include the number of parts, size of parts, typeof parts, interleave, etc.

November 3, 2006 Chapter 2 � Working with a BSP 39

Page 60: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Transferring an OS image onto your board 2006, QNX Software Systems GmbH & Co. KG.

CAUTION: When an IPL/IFS (image filesystem) image is combined,you’ll need to offset the beginning of the flash filesystem by at leastthe size of the IPL and IFS. For example, if the combined IPL/IFSimage is loaded at offset 0 on the flash, to avoid overwriting the IPLand IFS, the flash filesystem must begin at an offset of the IPL/IFSimage size +1. If it doesn’t begin at an offset of the IPL/IFS imagesize +1, you’ll need to create a partition.

!

How do I create a partition?

Regardless of which BSP you’re working with, the procedure requiresthat you:

1 Start the flash filesystem driver.

2 Erase the entire flash.

3 Format the partition.

4 Slay the flash filesystem driver.

5 Restart the flash filesystem driver.

The following example applies specifically to the Renesas Biscayneboard, which can be booted from DMON or flash.

1 To boot from DMON, enter the following command to start theflash filesystem driver:devf-generic -s0xe8000000,32M &

2 To boot from flash, enter the following command to start theflash system driver:devf-generic -s0x0,32M

You should now see anfs0p0 entry under/dev.

3 To prepare the area for the partition, you must erase the entireflash. Enter the following command:

40 Chapter 2 � Working with a BSP November 3, 2006

Page 61: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Testing Neutrino on your board

flashctl -p/dev/fs0 -ev

4 To format the partition, enter the following command:flashctl -p/dev/fs0p0 -f

5 Now slay the flash filesystem driver:slay devf-generic

6 Finally, restart the driver:devf-generic &

You should now see the following entries:

Entry Description

/dev/fs0p0 OS image (32 MB)

/dev/fs0p1 Flash filesystem partition (32 MB)

Testing Neutrino on your boardYou can test Neutrino simply by executing any shell builtin commandor any command residing within the OS image. For example, type:

ls

You’ll see a directory listing, since thels command has beenprovided in the default system image.

Getting Photon on your boardFor instructions on adding the Photon microGUI to your embeddedsystem, see the documentation for the particular BSP; the buildfilecould include the specific commands (commented out) that you need

November 3, 2006 Chapter 2 � Working with a BSP 41

Page 62: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Where do I go from here? 2006, QNX Software Systems GmbH & Co. KG.

to run. For even more details, see the “Photon in Embedded Systems”appendix in the PhotonProgrammer’s Guide.

Where do I go from here?Now that you have a better understanding of how BSPs work in anembedded system, you’ll want to start working on your applications.The following table contains references to the QNX documentationthat may help you find the information you’ll need to get going.

For information on: Go to:

Writing “hello world” The section “A simple example” in thechapter Compiling and Debugging inthe NeutrinoProgrammer’s Guide, ortheIDE User’s Guide.

Debugging your programs The section “Debugging” in the chapterCompiling and Debugging in theNeutrinoProgrammer’s Guide.

Setting up NFS The section “Complete example —TCP/IP with network filesystem” in theappendix Sample Buildfiles in thismanual. See also thefs-nfs2 utilitypage in theUtilities Reference.

Setting up an Ethernet driver The section “Complete example —TCP/IP with network filesystem” in theappendix Sample Buildfiles in thismanual. See also the various networkdrivers (devn*) in theUtilitiesReference.

Writing device drivers and/or resourcemanagers

The chapter Writing a ResourceManager in the NeutrinoProgrammer’sGuide.

If you need more information, see these chapters in this guide:

42 Chapter 2 � Working with a BSP November 3, 2006

Page 63: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Filename conventions

For more information on: Go to:

Building flash filesystems Customizing the FlashFilesystem

IPL Writing an IPL program

Startup Customizing Image StartupPrograms

Filename conventionsIn QNX Neutrino BSPs, we use the following conventions for namingfiles:

Part of filename Description Example

.bin Suffix for binaryformat file

ifs-artesyn.bin

.build Suffix for buildfile sandpoint.build

efs- Prefix for QNXEmbedded Filesystemfile; generated bymkefs

efs-sengine.srec

.elf Suffix for ELF(Executable andLinking Format) file

ipl-ifs-mbx800.elf

ifs- Prefix for QNX ImageFilesystem file;generated bymkifs

ifs-800fads.elf

ipl- Prefix for IPL (InitialProgram Loader) file

ipl-eagle.srec

continued. . .

November 3, 2006 Chapter 2 � Working with a BSP 43

Page 64: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Filename conventions 2006, QNX Software Systems GmbH & Co. KG.

Part of filename Description Example

.openbios Suffix for OpenBIOSformat file

ifs-walnut.openbios

.prepboot Suffix for MotorolaPRePboot format file

ifs-prpmc800.prepboot

.srec Suffix for S-recordformat file

ifs-malta.srec

44 Chapter 2 � Working with a BSP November 3, 2006

Page 65: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Chapter 3

Making an OS Image

In this chapter. . .Images, images, images 47What is an OS image? 47The OS image as a filesystem 48Configuring an OS image 49Building a flash filesystem image 61Embedding an image 70System configuration 76Debugging an embedded system 83

November 3, 2006 Chapter 3 � Making an OS Image 45

Page 66: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 67: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. What is an OS image?

Making an OS image involves a number of steps, depending on thehardware and configuration of your target system.

In this chapter, we’ll take a look at the steps necessary to build an OSimage. Then we’ll examine the steps required to get that image to thetarget, whether it involves creating a boot disk/floppy, a network boot,or burning the image into an EPROM or flash device. We’ll alsodiscuss how to put together some sample systems to show you how touse the various drivers and resource managers that we supply.

For more information on using the various utilities described in thischapter, see theUtilities Reference.

Images, images, imagesIn the embedded Neutrino world, an “image” can mean either of thefollowing:

Image type Description

OS image A bootable or nonbootable structure thatcontains files; created by themkifsutility.

Flash filesystem image A structure that can be used in aread-only, read/write, orread/write/reclaim flash filesystem;created by themkefs utility.

What is an OS image?An OS image is simply a file. When you’ve created your executables(programs) that you want your embedded system to run, you need toplace them somewhere where they can be loaded from. An OS imageis the file that contains the OS, your executables, and any data filesthat might be related to your programs. Actually, you can think of theimage as a small “filesystem” — it has a directory structure and somefiles in it.

November 3, 2006 Chapter 3 � Making an OS Image 47

Page 68: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The OS image as a filesystem 2006, QNX Software Systems GmbH & Co. KG.

An image can bebootable or nonbootable. A bootable image is onethat contains the startup code that the IPL can transfer control to (seethe chapter on customizing IPL programs in this book). Generally, asmall embedded system will have only the one (bootable) OS image.

A nonbootable image is usually provided for systems where aseparate, configuration-dependent setup may be required. Think of itas a second “filesystem” that has some additional files in it (we’lldiscuss this in more depth later). Since it’s nonbootable, this imagewill typically not contain the OS, startup file, etc.

The OS image as a filesystemAs previously mentioned, the OS image can be thought of as afilesystem. In fact, the image contains a small directory structure thattellsprocnto the names and positions of the files contained within it;the image also contains the files themselves. When the embeddedsystem is running, the image can be accessed just like any otherread-only filesystem:

# cd /proc/boot# ls.script ping cat data1 pidin

ksh ls ftp procnto devc-ser8250-ixp2400# cat data1This is a data file, called data1, contained in the image.Note that this is a convenient way of associating datafiles with your programs.

The above example actually demonstrates two aspects of having theOS image function as a filesystem. When we issued thels command,the OS loadedls from the image filesystem (pathname/proc/boot/ls). Then, when we issued thecat command, the OSloadedcat from the image filesystem as well, and opened the filedata1.

Let’s now take a look at how we configure the image to contain files.

48 Chapter 3 � Making an OS Image November 3, 2006

Page 69: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Configuring an OS image

Configuring an OS imageThe OS image is created by a program calledmkifs (make imagef ilesystem), which accepts information from two main sources: itscommand line and abuildfile.

For more information, seemkifs in theUtilities Reference.☞

A simple buildfileLet’s look at a very simple buildfile, the one that generated the OSimage used in the example above:

# A simple "ls", "ping", and shell.

# This file is "shell.bld"

[virtual=armbe,srec] .bootstrap = {startup-ixdp425

PATH=/proc/boot procnto -vv

}[+script] .script = {

procmgr symlink ../../proc/boot/libc.so.2 /usr/lib/ldqnx.so.2

devc-ser8250-ixp2400 -F -e -c14745600 -b115200 0xc8000000 ˆ2,15 &

reopen

display msg Serial Driver Started

}

[type=link] /dev/console=/dev/ser1

[type=link] /tmp=/dev/shmem

libc.so

[data=copy]devc-ser8250-ixp2400

ksh

lscat

data1

pingftp

pidin

November 3, 2006 Chapter 3 � Making an OS Image 49

Page 70: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Configuring an OS image 2006, QNX Software Systems GmbH & Co. KG.

In a buildfile, a pound sign (#) indicates a comment; anythingbetween it and the end of the line is ignored. Make sure there’s aspace between a buildfile command and the pound sign.

This buildfile consists of these sections:

� a bootfile — starting with[virtual=armbe,srec]

� a script — starting with[+script]

� a list of links and files to include in the image — starting with[type=link] /dev/console=/dev/ser1

Inline files

Although the three sections in the buildfile above seem to be distinct,in reality all three are similar in that they’re lists of files.

Notice also how the buildfile itself is structured:

optional attributes filename optional contents

For example, the line:

[virtual=armbe,srec] .bootstrap = {

has an attribute of[virtual=armbe,srec], a filename of.bootstrap, and anoptional contents part (from the= { to thecorresponding closing brace).

Let’s examine these elements in some detail.

The first part (starting with[virtual=armbe,srec]) specifies thata virtual address system is being built. The CPU type appears next;“armbe” indicates a big-endian ARM processor. Then after thecomma comes the name of the bootfile (srec).

The rest of the line specifies aninline file (as indicated by the openbrace) named “.bootstrap”, which consists of the following:

startup-ixdp425PATH=/proc/boot procnto -vv

50 Chapter 3 � Making an OS Image November 3, 2006

Page 71: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Configuring an OS image

The second part starts with the[+script] attribute — this tellsmkifs that the specified file is ascript file, a sequence ofcommands—including the microkernel,procnto—that should beexecuted when the Process Manager has completed its startup.

Script files look just like regular shell scripts, except that:

� special modifiers can be placedbefore the actual commands to run

� some commands are builtin

� the script file’s contents are parsed bymkifs before being placedinto the image.

In this case, the script file is, again, another inline file (again indicatedby the open brace). The file (which happens to be called “.script”)contains the following:

devc-ser8250-ixp2400 -F -e -c14745600 -b115200 0xc8000000ˆ2,15 &reopen[+session] PATH=:/proc/boot esh &

This script file begins by starting a serial driver(devc-ser8250-ixp2400) in edited mode with hardware flowcontrol disabled at a baud rate of 115200bps at a particular physicalmemory address. The script then does areopen to redirect standardinput, output, and error. The last line tellsmkifs to make theembedded shell program (esh) a session leader (as per POSIX).

November 3, 2006 Chapter 3 � Making an OS Image 51

Page 72: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Configuring an OS image 2006, QNX Software Systems GmbH & Co. KG.

� In order to run a command, its executable must be available whenthe script is executed. You can add the executable to the image orget it from a filesystem that’s started before the executable isrequired. The latter approach results in a smaller image.

� If you specify an ampersand (&) after the command line, theprogram runs in the background, and Neutrino doesn’t wait for theprogram to finish before continuing with the next line in the script.If you don’t specify the ampersand, and the program doesn’t exit,then the rest of the script is never executed. The system isn’t fullyoperational until the boot script finishes.

Generating the image

To generate the image file from our sample buildfile, you couldexecute the command:

mkifs shell.bld shell.ifs

This tellsmkifs to use the buildfileshell.bld to create the imagefile shell.ifs.

Plain ordinary lists of filesLet’s return to our example. Notice the “list of files” (i.e. from“[type=link] /dev/console=/dev/ser1” to “ pidin”).

Including files from different places

In the example above, we specified that the files at the end were to bepart of the image, andmkifs somehow magically found them.Actually, it’s not magic —mkifs simply looked for the environmentvariableMKIFS PATH. This environment variable contains a list ofplaces to look for the files specified in the buildfile. If the environmentvariable doesn’t exist, then the following are searched in this order:

1 current working directoryif the filename contains a slash (butdoesn’t start with one).

52 Chapter 3 � Making an OS Image November 3, 2006

Page 73: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Configuring an OS image

2 ${QNX TARGET}/${PROCESSOR}/sbin

3 ${QNX TARGET}/${PROCESSOR}/usr/sbin

4 ${QNX TARGET}/${PROCESSOR}/boot/sys

5 ${QNX TARGET}/${PROCESSOR}/bin

6 ${QNX TARGET}/${PROCESSOR}/usr/bin

7 ${QNX TARGET}/${PROCESSOR}/lib

8 ${QNX TARGET}/${PROCESSOR}/lib/dll

9 ${QNX TARGET}/${PROCESSOR}/usr/lib

10 ${QNX TARGET}/${PROCESSOR}/usr/photon/bin

(The${PROCESSOR} component is replaced with the name of theCPU, e.g.arm.)

Since none of the filenames that we used in our examplestarts withthe “/” character, we’re tellingmkifs that it should search for files(on the host) within the path list specified by theMKIFS PATHenvironment variable as described above. Regardless of where thefiles came from on the host, in our example they’ll all be placed onthe target under the/proc/boot directory (there are a few subtletieswith this, which we’ll come back to).

For our example,devc-con will appear on the target as the file/proc/boot/devc-con, even though it may have come from thehost as${QNX TARGET}/armbe/sbin/devc-con.

To include files from locations other than those specified in theMKIFS PATH environment variable, you have a number of options:

� Change theMKIFS PATH environment variable (use the shellcommandexport MKIFS PATH=newpath on the host).

� Modify the search path with the[search=] attribute.

� Specify the pathname explicitly (i.e. with a leading “/” character).

� Create the contents of the file in line.

November 3, 2006 Chapter 3 � Making an OS Image 53

Page 74: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Configuring an OS image 2006, QNX Software Systems GmbH & Co. KG.

Modifying the search path

By specifying the[search=newpath] attribute, we can causemkifsto look in places other than what the environment variableMKIFS PATH specifies. Thenewpath component is acolon-separated list of pathnames and can include environmentvariable expansion. For example, to augment the existingMKIFS PATH pathname to also include the directory/mystuff,you would specify:

[search=${MKIFS PATH}:/mystuff]

Specifying the pathname explicitly

Let’s assume that one of the files used in the example is actuallystored on your development system as/release/data1. If yousimply put/release/data1 in the buildfile,mkifs would includethe file in the image, but would call it/proc/boot/data1 on thetarget system, instead of/release/data1.

Sometimes this is exactly what you want. But at other times you maywant to specify theexact pathname on the target (i.e. you may wish tooverride the prefix of/proc/boot). For example, specifying/etc/passwd would place the host filesystem’s/etc/passwd filein the target’s pathname space as/proc/boot/passwd — mostlikely not what you intended. To get around this, you could specify:

/etc/passwd = /etc/passwd

This tellsmkifs that the file/etc/passwd on the host should bestored as/etc/passwd on the target.

On the other hand, you may in fact want a different source file (let’ssay/home/joe/embedded/passwd) to be the password file for theembedded system. In that case, you would specify:

/etc/passwd = /home/joe/embedded/passwd

54 Chapter 3 � Making an OS Image November 3, 2006

Page 75: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Configuring an OS image

Creating the contents of the file in line

For our tinydata1 file, we could just as easily have included it in line— that is to say, we could have specified its contents directly in thebuildfile itself, without the need to have a realdata1 file residesomewhere on the host’s filesystem. To include the contents in line,we would have specified:

data1 = {This is a data file, called data1, contained in the image.Note that this is a convenient way of associating datafiles with your programs.}

A few notes. If your inline file contains the closing brace (“}”), thenyou must escape that closing brace with a backslash (“\”). This alsomeans that all backslashes must be escaped as well. To have an inlinefile that contains the following:

This includes a {, a }, and a \ character.

you would have to specify this file (let’s call itdata2) as follows:

data2 = {This includes a {, a \}, and a \\ character.}

Note that since we didn’t want thedata2 file to contain leadingspaces, we didn’t supply any in the inline definition. The following,while perhaps “better looking,” would be incorrect:

# This is wrong, because it includes leading spaces!data2 = {

This includes a {, a \}, and a \\ character.}

If the filename that you’re specifying has “weird” characters in it,then you must quote the name with double quote characters ("). Forexample, to create a file calledI "think" so (note the spaces andquotation marks), you would have to specify it as follows:

"I \"think\" so" = ...

November 3, 2006 Chapter 3 � Making an OS Image 55

Page 76: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Configuring an OS image 2006, QNX Software Systems GmbH & Co. KG.

But naming files like this is discouraged, since the filenames aresomewhat awkward to type from a command line (not to mention thatthey look goofy).

Specifying file ownership and permissions

The files that we included (in the example above) had the owner,group ID, and permissions fields set to whatever they were set to onthe host filesystem they came from. The inline files (data1 anddata2) got the user ID and group ID fields from the user who ran themkifs program. The permissions are set according to the user’sumask.

If we wanted to explicitly set these fields on particular files within thebuildfile, we would prefix the filenames with an attribute:

[uid=0 gid=0 perms=0666] file1[uid=5 gid=1 perms=a+xr] file2

This marks the first file (file1) as being owned byroot (the user ID0), group zero, and readable and writable by all (the mode of octal666). The second file (file2) is marked as being owned by user ID5, group ID1, and executable and readable by all (thea+xr

permissions).

Notice how when we combine attributes, we place all of the attributeswithin one open-square/close-square set. The following is incorrect:

# Wrong way to do it![uid=0] [gid=0] [perms=0666] file1

If we wanted to set these fields for a bunch of files, the easiest way todo that would be to specify theuid, gid, andperms attributes on asingle line, followed by the list of files:

[uid=5 gid=1 perms=0666]file1file2file3file4

56 Chapter 3 � Making an OS Image November 3, 2006

Page 77: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Configuring an OS image

which is equivalent to:

[uid=5 gid=1 perms=0666] file1[uid=5 gid=1 perms=0666] file2[uid=5 gid=1 perms=0666] file3[uid=5 gid=1 perms=0666] file4

Including a whole whack of files

If we wanted to include a large number of files, perhaps from apreconfigured directory, we would simply specify the name of thedirectory instead of the individual filenames. For example, if we had adirectory called/release 1.0, and we wanted all the files underthat directory to be included in the image, our buildfile would havethe line:

/release 1.0

This would put all the files that reside under/release 1.0 into/proc/boot on the target. If there were subdirectories under/release 1.0, then they too would be created under/proc/boot,and all the files in those subdirectories would also be included in thetarget.

Again, this may or may not be what you intend. If you really want the/release 1.0 files to be placed under/, you would specify:

/=/release 1.0

This tellsmkifs that it should grab everything from the/release 1.0 directory and put it into a directory called/. Asanother example, if we wanted everything in the host’s/release 1.0 directory to live under/product on the target, wewould specify:

/product=/release 1.0

November 3, 2006 Chapter 3 � Making an OS Image 57

Page 78: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Configuring an OS image 2006, QNX Software Systems GmbH & Co. KG.

The script file on the target

The script file stored on the target isn’t the same as the originalspecification of the script file within the buildfile. That’s because ascript file is “special” —mkifs parses the text commands in thescript file and stores only the parsed output on the target, not theoriginal ASCII text. The reason we did this was to minimize the workthat the process manager has to do at runtime when it starts up andprocesses the script file — we didn’t want to have to include acomplete shell interpreter within the process manager!

Bound multiprocessing attributesYou can now specify which CPU to bind processes when launchingprocesses from the startup script through the[CPU=] attribute.

The[CPU=] is used as any other attribute, and specifies the CPU onwhich to launch the following process (or , if the attribute is usedalone on a line without a command, sets the default CPU for allfollowing processes). The CPU is specified as a (Octal-based)processor number, a value of * resets this.

cpu=processorcpu=*

Example:

cpu=1

If, at boot time, the given CPU is not valid, a warning message will bedisplayed and the command will be launched without any runmaskrestriction. Note that due to a limitation in the boot image records,this syntax allows only the specification of a single CPU and not amore generic runmask.

Use theon utility to spawn a process within a fully specified runmask.

58 Chapter 3 � Making an OS Image November 3, 2006

Page 79: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Configuring an OS image

The bootstrap fileAlong the lines of the startup script file, our bootstrap specification:

[virtual=armbe,srec] .bootstrap = {startup-ixdp425PATH=/proc/boot procnto -vv

}

also constructs an inline file (.bootstrap) that contains two lines:startup-ixdp425 andPATH=/proc/boot procnto -vv.

You can bind in optional modules toprocnto by using the[module=...] attribute. For example, to bind in the adaptivepartitioning scheduler, change theprocnto line to this:

[module=aps] PATH=/proc/boot procnto -vv

� Optional modules toprocnto were introduced in the QNXNeutrino Core OS 6.3.2.

� For more information about the adaptive partitioning scheduler,see the Adaptive PartitioningUser’s Guide.

As with the script filename, the actual name of the bootstrap file isirrelevant. However, nowhere else in the buildfile did we specify thosetwo files — they’re included automatically when specified by a[virtual] or [physical] attribute.

The “virtual” attribute (and its sibling the “physical” attribute)specifies the target processor (in our example, thearmbe part) and thebootfile (thesrec part), a very small amount of code between the IPLand startup programs. The target processor is put into the environmentvariable$PROCESSOR and is used during pathname expansion.You can omit the target processor specification, in which case itdefaults to the same as the host processor. For example:

[virtual=bios] .bootstrap = {...

November 3, 2006 Chapter 3 � Making an OS Image 59

Page 80: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Configuring an OS image 2006, QNX Software Systems GmbH & Co. KG.

would assume an ARM target if you’re on an ARM host system.

Both examples find a file called$PROCESSOR/sys/bios.boot (the.boot part is added automatically bymkifs), and process it forconfiguration information.

Compressing the image

While we’re looking at the bootstrap specification, it’s worthmentioning that you can apply the+compress attribute to compressthe entire image. The image is automatically uncompressed beforebeing started. Here’s what the first line would look like:

[virtual=armbe,srec +compress] .bootstrap = {

Specifying command-line options to mkifsAs mentioned above, you can also specify command-line options tomkifs. Since these command-line options are interpretedbefore theactual buildfile, you can add lines before the buildfile. You would dothis if you wanted to use a makefile to change the defaults of a genericbuildfile.

The following sample changes the address at which the image startsto 64K (hex0x10000):

mkifs -l "[image=0x10000]" buildfile image

For more information, seemkifs in theUtilities Reference.

Listing the contents of an imageIf you’d like to see the contents of an image, you can use thedumpifs

utility. The output fromdumpifs might look something like this:

Offset Size Name0 100 Startup-header flags1=0x1 flags2=0 paddr bias=0x80000000

100 a008 startup.*

a108 5c Image-header mountpoint=/a164 264 Image-directory

---- ---- Root-dirent

60 Chapter 3 � Making an OS Image November 3, 2006

Page 81: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a flash filesystem image

---- 12 usr/lib/ldqnx.so.2 -> /proc/boot/libc.so---- 9 dev/console -> /dev/ser1

a3c8 80 proc/boot/.script

b000 4a000 proc/boot/procnto55000 59000 proc/boot/libc.so.2

---- 9 proc/boot/libc.so -> libc.so.2

ae000 7340 proc/boot/devc-ser8250b6000 4050 proc/boot/esh

bb000 4a80 proc/boot/lsc0000 14fe0 proc/boot/data1

d5000 22a0 proc/boot/data2

Checksums: image=0x94b0d37b startup=0xa3aeaf2

The more-v (“verbose”) options you specify todumpifs, the moredata you’ll see.

For more information ondumpifs, see its entry in theUtilitiesReference.

Building a flash filesystem imageIf your application requires a writable filesystem and you have flashmemory devices in your embedded system, then you can use aNeutrino flash filesystem driver to provide a POSIX-compatiblefilesystem. The flash filesystem drivers are described in thefilesystems chapter of theSystem Architecture guide. The chapter oncustomizing the flash filesystem in this book describes how you canbuild a flash filesystem driver for your embedded system.

You have two options when creating a flash filesystem:

� Create a flash filesystem image file on the host system and thenwrite the image into the flash on the target.

� Run the flash filesystem driver for your target system and copyfiles into the flash filesystem on the target.

In this section we describe how to create a flash filesystem image fileusing themkefs (for make embeddedf ilesystem) utility and abuildfile. How to transfer the flash filesystem image onto your targetsystem is described in the “Embedding an image” section. For detailson how to use the flash filesystem drivers, see theUtilities Reference.

November 3, 2006 Chapter 3 � Making an OS Image 61

Page 82: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building a flash filesystem image 2006, QNX Software Systems GmbH & Co. KG.

Using mkefsThemkefs utility takes a buildfile and produces a flash filesystemimage file. The buildfile is a list of attributes and files to include in thefilesystem.

mkefs buildfile

The syntax of the buildfile is similar to that formkifs, butmkefssupports a different set of attributes, including the following:

block size=bsize

Specifies the block size of the flash device being used; defaultsto 64K. We’ll talk about interleave considerations for flashdevices below.

max size=msize

Specifies the maximum size of the flash device; is used to checkfor overflows. The default is 4 Gbytes.

spare blocks=sblocks

Specifies the number of spare blocks that will be set aside forthe flash filesystem. Ifsblocks is set to0, this implies a“read/write” flash filesystem, whereas a value greater than0implies a “read/write/reclaim” filesystem. The default is1.Spare blocks also replace bad blocks, i.e. blocks that fail.)

min size=tsize

Specifies the minimum size of the filesystem. If the resultantimage is smaller thantsize, the image is padded out totsizebytes. The default is unspecified, meaning that the image won’tbe padded.

Refer to theUtilities Reference for a complete description of thebuildfile syntax and attributes supported bymkefs.

Here’s a very simple example of a buildfile:

[block size=128k spare blocks=1 filter=inflator/deflate]/home/ejm/products/sp1/callp/imagedir

62 Chapter 3 � Making an OS Image November 3, 2006

Page 83: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a flash filesystem image

In this example, the attributes specify that the flash devices have ablock size of 128 KB, that there should be one spare block, and thatall the files should be processed using theinflator anddeflateutilities, which will compress/decompress the files. A single directoryis given. Just as withmkifs, when we specify a directory, all files andsubdirectories beneath it are included in the resulting image. Most ofthe other filename tricks shown above formkifs also apply tomkefs.

Block size

The value you should specify for theblock size attribute dependson the physical block size of the flash device given in themanufacturer’s data sheet and on how the flash device is configured inyour hardware (specifically the interleave).

Here are some examples:

If you have: Set block size to:

an 8-bit flash interface and are using an 8-bitdevice with a 64K block size

64K

a 16-bit flash interface and are using twointerleaved 8-bit flash devices with a 64Kblock size

128K

a 16-bit flash interface and are using a 16-bitflash device with a 64K block size

64K

a 32-bit flash interface and are using fourinterleaved 8-bit flash devices with a 64Kblock size

256K

Notice that you don’t have to specify any details (other than the blocksize) about the actual flash devices used in your system.

November 3, 2006 Chapter 3 � Making an OS Image 63

Page 84: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building a flash filesystem image 2006, QNX Software Systems GmbH & Co. KG.

Spare blocks

Thespare blocks attribute indicates how many blocks should beleft as spare. A spare block isn’t used by the filesystem until it’s timeto perform a reclaim operation. A nonspare block is then selected for“reclamation” — the data contained in that block is coalesced intoone contiguous region in the spare block. The nonspare block is thenerased; it becomes the new spare block. The former spare block takesthe place of the reclaimed block.

If you specify a spare block (i.e. for thespare blocks attribute)equal to 0, then the flash filesystem driver won’t be able to reclaimspace — it won’t have any place to put the new copy of the data.Therefore, you’ll be left with a read/write filesystem, which willeventually fill up since there’s no way to reclaim space.

flashcmp utility

You can use theflashcmp utility to compress files in the flashfilesystem. You can do this from a shell or you can use thefilter

attribute tomkefs.

The flash filesystem drivers know how to transparently decompressfiles that have been compressed withflashcmp, which means thatyou can access compressed files in the flash filesystem without havingto decompress them first. This can result in significant space savings.But there’s a tradeoff to file access performance — compressed fileswill be accessed a bit slower.

Compressing filesThe file compression mechanism provided with our flash filesystem isa convenient way to cut flash memory costs for customers. The flashfilesystem uses popular deflate/inflate algorithms for fast and efficientcompression/decompression.

In short, the deflate algorithm is a combination of two algorithms.The first one takes care of removing data duplication in files; the

64 Chapter 3 � Making an OS Image November 3, 2006

Page 85: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a flash filesystem image

second algorithm advantages data sequences that appear the mostoften by giving them shorter symbols.

Those two algorithms combined provide excellent losslesscompression of data and executable files. The inflate algorithm, whichis actually part of the flash filesystem per se, reverses what the deflatealgorithm does.

Abstraction layer

The flash filesystem never compresses any files. It only detectscompressed files on the media and decompresses themas they areaccessed. An abstraction layer embedded in the flash filesystem codeachieves efficiency and preserves POSIX compliance. Specialcompressed data headers on top of the flash files provide fast seektimes.

This layering is quite straightforward. Specific I/O functions includehandling the three basic access calls for compressed files:

� read()

� lseek()

� lstat()

The compression headers contain a synchronization cue, flags,compressed size, and normal size for the data that follows the header.These headers can be used by the three basic access calls to readdecompressed data, seek into the file using a virtual offset, and findthe effective size of the file.

Two sizes

This is where compression gets tricky. A compressed file will havetwo sizes:

� virtual size — this is, for the end user, the real size of thedecompressed data.

� media size — the size that the file actually occupies on the media.

November 3, 2006 Chapter 3 � Making an OS Image 65

Page 86: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building a flash filesystem image 2006, QNX Software Systems GmbH & Co. KG.

As a convenience, our flash filesystems offer a handy namespace thattotally replicates the regular flash file’s namespace, but gives themedia sizes when the files arestat()’ed (rather than the virtual oreffective size). Using this new namespace, files are neverdecompressed, so read operations will yield raw compressed datainstead of the decompressed data. This namespace is accessible bydefault through the.cmp mountpoint directory, right under theregular flash mountpoint.

For instance, running the disk usage utilitydu would be practicallymeaningless under a flash directory with data that is decompressed onthe fly. It wouldn’t reflect flash media usage at all. But running thedu

utility under.cmp would render a better approximation of mediausage.

As mentioned earlier, you can compress files by using any of thesemethods:

� mkefs utility

� flashcmp utility

The first method, which is the high-runner case, is to use themkefs

utility. Theflashcmp utility can be used as a filter formkefs tocompress the files that get built into the flash filesystem. The files canalso bepre-compressed by theflashcmp utility — this will bedetected bymkefs and the data will be put on the flash filesystemwith the proper information. What information? A simple bit thattells the flash filesystem that the file should be handled by the flashdecompression layer.

Compression example using mkefs

This line builds a 16-megabyte filesystem with compression:

[block size=128K spare blocks=1 min size=16m filter=flashcmp]/bin/

Themkefs utility detects a compression signature in the files listed inthe buildfile. This means that when files are precompressed, the filter

66 Chapter 3 � Making an OS Image November 3, 2006

Page 87: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a flash filesystem image

can be omitted. When this signature is detected, the proper bit is set inthe metadata area for on-the-fly decompression.

Compression example using flashcmp

The second method is to put compressed files on the media by usingflashcmp, but on board, straight with the flash filesystem. This iswhere the.cmp mountpoint is reused. Any file created under thismountpoint will have the compressed attribute bit. Needless to say,these files should be written using the compression headers, which theflashcmp utility does well.

In this example, we useflashcmp at the command line to compressthels file from the image filesystem into a flash filesystem:

$ flashcmp /proc/boot/ls > /fs0p0/.cmp/ls

Note that the.cmp mountpoint is used for the flash filesystem. Thistells the flash filesystem to set the compression bit in the metadataarea, enabling further decompression on the fly.

Compression rulesYou use the.cmp mountpoint to create previously compressed files,write previously compressed data, and check the size of compressedfiles. If you read a file from this mountpoint, the file won’t bedecompressed for you, as it is in the regular mountpoint. Now this iswhere we start talking about rules. All this reading and getting thesize of files is fairly simple; things get ugly when it’s time towritethose files.

1 When you write to a file created under the.cmp mountpoint,the data must be compressed.

2 You can’t write all over the place! Although the flash filesystemsupports random writes, the same is not true for compressedfiles.

3 Only appends are permitted when writing to a file created fromthe.cmp mountpoint. This has to be clear and respected,

November 3, 2006 Chapter 3 � Making an OS Image 67

Page 88: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building a flash filesystem image 2006, QNX Software Systems GmbH & Co. KG.

because the flash filesystem will reject any random writes tocompressed files.

4 The flash filesystem will never transparently compress any data.

5 If compressed data needs to be put on the flash during the lifeof a product, this data has to be precompressed.

Writing uncompressed data to a compressed file?

What if you need to writeuncompressed data to acompressed file?You can do this, but it has to be from the regular mountpoint. And theappend-only rule applies for this file as well.

Writing uncompressed data to a compressed file can be quitewasteful, because the uncompressed data will still be encapsulatedinto compressed headers, so a layer of code will be used for nothing.This means that at system design time, files that are meant to bewritable during the product life should not be compressed. Preferably,compressed files will remain read-only.

As a convenience, though, it’s still possible to append compressed oruncompressed data to compressed files. But we have to emphasizethat this might not always be the most efficient way to store data.Actually, the compression algorithms need a minimum data set to beable to compress, so the result has to be good enough to justify theheader abstraction overhead. Buffering isn’t possible withcompressed files, so there can’t be any assumptions for limitedoverhead when appending to compressed files.

68 Chapter 3 � Making an OS Image November 3, 2006

Page 89: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building a flash filesystem image

Although it’s possible to write uncompressed data without the headeroverhead to a compressed file (provided if done from the.cmp

namespace), this isn’t a very good idea. The file will loose thecapability of rendering virtual uncompressed size and will becomeunseekable to positions after the first chunk of uncompressed data.The file data will still be readable, but the lost POSIX functionalityshould dissuade you from trying this.

The exception

So those are the rules, and here is the exception. Truncation is aspecial case. If a compressed file is opened withO TRUNC from theregular virtual namespace, the file status will become just as if it werecreated from this namespace. This gives you full POSIX capabilitiesand no compression with accompanying restrictions.

The opposite is true: If a non-compressed file is opened withtruncation on the.cmp side, then compression rules apply. By theway, theftruncate() functionality isn’t provided with compressedfiles, but is supported with regular files.

Buffer size

The buffer size is also selectable. This buffer represents thedecompressed data size that will be associated with each compressionheader. Of course, a larger buffer size might allow bettercompression, but RAM usage will be increased for the flashfilesystem driver. The default buffer size is 4K.

On a slightly different note, don’t be tempted to reuse the flashfilesystem as a decompression engine over a block-oriented or anetwork filesystem. These filesystems are often available in veryhigh-storage capacity and high-bandwidth formats. Compression overthese media is pure overkill and will always be a waste of CPUresources. The flash filesystem with compression is really meant forrestrained systems — the best approach for long-term life of a productis to read Moore’s Law* carefully. This law is true for flash as well,so plan ahead.

November 3, 2006 Chapter 3 � Making an OS Image 69

Page 90: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Embedding an image 2006, QNX Software Systems GmbH & Co. KG.

* In 1965, Intel co-founder Gordon Moore observed that the pace ofmicrochip technology change is such that the amount of data storagea microchip can hold doubles every year.

Design considerationsAlways consider the slowdown of compressed data access andincreased CPU usage when designing a system. We’ve seen systemswith restricted flash budget increase their boot time by large factorswhen using compression.

Inflator/deflate utilities

To compress files, you can also use theinflator anddeflate pairof utilities, which can compress/decompress files forany filesystem,including flash. For details, see their entries in theUtilities Reference.

Embedding an imageAfter you’ve created your bootable OS image on the host system,you’ll want to transfer it to the target system so that you can bootNeutrino on the target. The various ways of booting the OS on atarget system are described in the chapter on customizing IPLprograms in this guide.

If you’re booting the OS from flash, then you’ll want to write theimage into the flash devices on the target. The same applies if youhave a flash filesystem image — you’ll want to write the image intoflash on the target.

70 Chapter 3 � Making an OS Image November 3, 2006

Page 91: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Embedding an image

Use mkifs to create Neutrino

image

No

YesIs flash

filesystemrequired?

Use mkefs tocreate flash

filesystem image

No

Yes

Areflash

filesystem imageand Neutrino imageto go in the same

flashdevice?

Done

Use mkimageto combine images

Flash configuration options for your Neutrino-based embedded systems.

Depending on your requirements and the configuration of your targetsystem, you may want to embed:

� the IPL

� the boot image

� the boot image and other image filesystem

� the boot image and flash filesystem

� some other combination of the above.

Also, you may wish to write the boot image and the flash filesystemon the same flash device or different devices. If you want to write theboot image and the flash filesystem on the same device, then you can

November 3, 2006 Chapter 3 � Making an OS Image 71

Page 92: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Embedding an image 2006, QNX Software Systems GmbH & Co. KG.

use themkimage utility to combine the image files into a single imagefile.

During the initial development stages, you’ll probably need to writethe image into flash using a programmer or a download utility. Lateron if you have a flash filesystem running on your target, you can thenwrite the image file into a raw flash partition.

If your programmer requires the image file to be in some format otherthan binary, then you can use themkrec utility to convert the imagefile format.

Combining image files using mkimageThemkimage utility combines multiple input image files into a singleoutput image file. It recognizes which of the image files contains theboot image and will place this image at the start. Note that instead ofusingmkimage, some developers rely on a flash programmer to burnthe separate images with appropriate alignment.

For example:

mkimage nto.ifs fs.ifs > flash.ifs

will take thento.ifs andfs.ifs image files and output them to theflash.ifs file.

If you want more control over how the image files are combined, youcan use other utilities, such as:

� cat

� dd

� mkrec

� objcopy

72 Chapter 3 � Making an OS Image November 3, 2006

Page 93: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Embedding an image

Combining image files using the IDE

You’ll use the System Builder to generate OS images for your targetboard’s RAM or flash. You can create:

� an OS image

� a Flash image

� a combined image.

For more information about this process, please see thedocumentation that comes with the QNX Momentics IDE.

Converting images using mkrecThemkrec utility takes a binary image file and converts it to eitherMotorola S records or Intel hex records, suitable for a flash orEPROM programmer.

For example:

mkrec -s 256k flash.ifs > flash.srec

will convert the image fileflash.ifs to an S-record format filecalledflash.srec. The-s 256k option specifies that the EPROMdevice is 256K in size.

If you have multiple image files that you wish to download, then youcan first usemkimage to combine the image files into a single filebefore downloading. Or, your flash/EPROM programmer may allowyou to download multiple image files at different offsets.

Transferring an image to flashThere are many ways to transfer your image into your flash:

� Use an EPROM burner that supports your socketed flash.

� Use a flash burner that supports onboard flash via a special bus,such as JTAG.

November 3, 2006 Chapter 3 � Making an OS Image 73

Page 94: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Embedding an image 2006, QNX Software Systems GmbH & Co. KG.

� Use a low-level monitor or a BIOS page with a flash burncommand.

� Use the flash filesystem raw mountpoints.

The details on how to transfer the image with anything other than thelast method is beyond the scope of this document. Using the rawmountpoint is a convenient way that comes bundled with your flashfilesystem library. You can actually read and write raw partitions justlike regular files, except that when the raw mountpoint is involved,remember to:

� go down one level in the abstraction ladder

� perform the erase commands yourself.

For the sake of this discussion, we can use thedevf-ram driver. Thisdriver simulates flash using regular memory. To start it, log in asroot and type:

# devf-ram &

You can use theflashctl command to erase a partition. You don’tneed to beroot to do this. For instance:

$ flashctl -p /dev/fs0 -e

CAUTION: Be careful when you use this command. Make sure youaren’t erasing something important on your flash — like your BIOS!!On normal flash, theflashctl command on a raw partition shouldtake a while (about one second for each erase block). This commanderases the/dev/fs0 raw flash array. Try thehd command on thisnewly erased flash array; everything should be0xFF:

$ hd /dev/fs0

0000000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ................

*

74 Chapter 3 � Making an OS Image November 3, 2006

Page 95: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Embedding an image

For more information onflashctl, see theUtilities Reference.☞

Let’s make a dummy IPL for the purpose of this example:

$ echo Hello, World! > ipl$ mkrec -s 128k -f full ipl > ipl imageReset jmps to 0x1FFE0 (jmp 0xFFED)ROM offset is 0x1FFE0

Of course, this IPL won’t work for real — it’s just for trying out theflash filesystem. In any event, an IPL wouldn’t be very useful inRAM. Let’s make a dummy flash filesystem for the purpose of thisexample (the D meansCtrl – D):

$ mkefs -v - flash image[block size=128k spare blocks=1 min size=384k]/bin/ls/bin/catˆDwriting directory entry ->writing file entry -> ls **writing file entry -> cat *Filesystem size = 384Kblock size = 128K1 spare block(s)

This flash filesystem actually works (unlike the IPL). Now, the flashpartition images can be transfered to the flash using any file-transferutility (such ascp or ftp). We have an IPL image created withmkrec (and properly padded to an erase block boundary) and a flashimage created withmkefs, so we can usecat to combine andtransfer both images to the flash:

$ cat ipl image flash image > /dev/fs0

If you use thehd utility on the raw mountpoint again, you’ll see thatyour flash that had initially all bits set to ones (0xFF) now containsyour partition images. To use the flash filesystem partition, you needto slay the driver and start it again so it can recognize the partitionsand mount them. For instance, withdevf-ram:

November 3, 2006 Chapter 3 � Making an OS Image 75

Page 96: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

System configuration 2006, QNX Software Systems GmbH & Co. KG.

$ slay devf-ram$ devf-ram &

From this point, you have a/fs0p1 mountpoint that’s in fact adirectory and contains the files you specified withmkefs to createyour flash image. There’s no/fs0p0, because the boot image isn’trecognized by the flash filesystem. It’s still accessible as a rawmountpoint via/dev/fs0p0. You can do the same operations on/dev/fs0p0 that you could do with/dev/fs0. Even/dev/fs0p1is accessible, but be careful not to write to this partition whileapplications are using the flash filesystem at/fs0p1. Try:

$ /fs0p1/ls /fs0p1

You’ve just executedls from your flash filesystem and you’ve listedits contents. To conclude, let’s say that what we did in this example isa good starting point for when you customize the flash filesystem toyour own platforms. These baby steps should be the first steps tousing a full-blown filesystem on your target.

System configurationIn this section, we’ll look at some of the ways you can configureNeutrino systems. Please refer to the Sample Buildfiles appendix inthis guide for more detailed examples.

What you want to do will, of course, depend on the type of systemyou’re building. Our purpose in this section is to offer some generalguidelines and to help clarify which executables should be used inwhich circumstances, as well as which shared libraries are requiredfor their respective executables.

The general procedure to set up a system is as follows:

1 Establish an output device.

2 Run drivers.

3 Run applications.

76 Chapter 3 � Making an OS Image November 3, 2006

Page 97: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. System configuration

Establishing an output deviceOne of the very first things to do in a buildfile is to start a driver thatyou then redirect standard input, output, and error to. This allows allsubsequent drivers and applications to output their startup messagesand any diagnostics messages they may emit to a known place whereyou can examine the output.

Generally, you’d start either the console driver or a serial port driver.The console driver is used when you’re developing on a fairlycomplete “desktop” type of environment; the serial driver is suitablefor most “embedded” environments.

But you may not even have any such devices in your deeplyembedded system, in which case you would omit this step. Or youmay have other types of devices that you can use as your outputdevice, in which case you may require a specialized driver (that yousupply). If you don’t specify a driver, output will go to the debugoutput driver provided by the startup code.

A simple desktop example

This example starts the standard console driver in edited mode (the-e

option, which is the default). To set up the output device, you wouldinclude the driver in your startup script (the[+script] file). Forexample:

devc-con -e &reopen /dev/con1

The following starts the8250 serial port driver in edited mode (the-eoption), with an initial baud rate of 115200 baud (the-b option):

devc-ser8250 -e -b115200 &reopen /dev/ser1

In both cases, thereopen command causes standard input, output,and error to be redirected to the specified pathname (either/dev/con1 or /dev/ser1 in the above examples). This redirectionholds until otherwise specified with anotherreopen command.

November 3, 2006 Chapter 3 � Making an OS Image 77

Page 98: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

System configuration 2006, QNX Software Systems GmbH & Co. KG.

Thereopen used above is amkifs internal command, not the shellbuiltin command of the same name.

Running drivers/filesystemsThe next thing you’ll want to run are the drivers and/or filesystemsthat will give you access to the hardware. Note that the console orserial port that we installed in the previous section is actually anexample of such a driver, but it was a special case in that it shouldgenerally be the first one.

We support several types of drivers/filesystems, including:

� disk drivers (devb-*)

� flash filesystems (devf-*)

� network drivers (devn-*)

� input drivers (devi-*)

� USB drivers (devu-*)

� filesystems (fs-*)

Which one you install first is generally driven by where yourexecutables reside. One of the goals for the image is to keep it small.This means that you generally don’t put all the executables and sharedlibraries you plan to load directly into the image — instead, you placethose files into some other medium (whether a flash filesystem,rotating disk, or a network filesystem). In that case, you should startthe appropriate driver to get access to your executables. Once youhave access to your executables on some medium, you wouldthenstart other drivers from that medium.

The alternative, which is often found in deeply embedded systems, isto put all the executables and shared librariesdirectly into the image.You might want to do this if there’s no secondary storage medium orif you wanted to have everything available immediately, without theneed to start a driver.

78 Chapter 3 � Making an OS Image November 3, 2006

Page 99: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. System configuration

Let’s examine the steps required to start the disk, flash, and networkdrivers. All these drivers share a common feature: they rely on oneprocess that loads one or more.so files, with the particular.so filesselected either via the command line of the process or via automaticconfiguration detection.

Since the various drivers we’re discussing here use.so files (not justtheir own driver-specific ones, but also standard ones like the Clibrary), these.so files must be presentbefore the driver starts.Obviously, this means that the.so file cannot be on the samemedium as the one you’re trying to start the driver for! Werecommend that you put these.so files into the image filesystem.

Disk drivers

The first thing you need to determine is which hardware you havecontrolling the disk interface. We support a number of interfaces,including various flavors of SCSI controllers and the EIDE controller.For details on the supported interface controllers, see the variousdevb-* entries in theUtilities Reference.

The only action required in your buildfile is to start the driver (e.g.devb-aha7). The driver will then dynamically load the appropriatemodules (in this order):

1 libcam.so — Common Access Method library

2 cam-*.so — Common Access Method module(s)

3 io-blk.so — block I/O module

4 fs-*.so — filesystem personality module(s)

The CAM.so files are documented undercam-* in theUtilitiesReference. Currently, we support CD-ROMs (cam-cdrom.so), harddisks (cam-disk.so), and optical disks (cam-optical.so).

Theio-blk.so module is responsible for dealing with a disk on ablock-by-block basis. It includes caching support.

November 3, 2006 Chapter 3 � Making an OS Image 79

Page 100: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

System configuration 2006, QNX Software Systems GmbH & Co. KG.

Thefs-* modules are responsible for providing the high-levelknowledge about how a particular filesystem is structured. Wecurrently support the following:

Filesystem Module

ISO-9660 CD-ROM fs-cd.so

CIFS (Common Internet File System)fs-cifs

MS-DOS fs-dos.so

Linux fs-ext2.so

NFS (Network File System) fs-nfs2, fs-nfs3

Neutrino Package Filesystem fs-pkg

QNX4 fs-qnx4.so

Flash filesystems

To run a flash filesystem, you need to select the appropriate flashdriver for your target system. For details on the supported flashdrivers, see the variousdevf-* entries in theUtilities Reference.

Thedevf-generic flash driver that can be thought of as a universaldriver whose capabilities make it accessible to most flash devices.

The flash filesystem drivers don’t rely on any flash-specific.so files,so the only module required is the standard C library (libc.so).

Since the flash filesystem drivers are written for specific targetsystems, you can usually start them without command-line options;they’ll find the flash for the specific system they were written for.

Network drivers

Network services are started from theio-net command, which isresponsible for loading in the required.so files.

80 Chapter 3 � Making an OS Image November 3, 2006

Page 101: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. System configuration

For dynamic control of network drivers, you can simply usemount

andumount to start and stop drivers at the command line. Forexample:

mount -T io-net devn-ne2000.so

For more information, seemount in theUtilities Reference.

Two levels of.so files are started, based on the command-lineoptions given toio-net:

� -d specifies driver.so files

� -p specifies protocol.so files.

The-d option lets you choose the hardware driver that knows how totalk to a particular card. For example, choosing-d ne2000 willcauseio-net to loaddevn-ne2000.so to access anNE-2000-compatible network card. You may specify additionalcommand-line options after the-d, such as the interrupt vector to beused by the card.

The-p option lets you choose the protocol driver that deals with aparticular protocol. For example, choosing-p ttcpip will causeio-net to loadnpm-ttcpip.so, which will provide the tinyTCP/IP stack. As with the-d option, you would specifycommand-line options after the-p for the driver, such as the IPaddress for a particular interface.

For more information about network services, see thedevn-*,io-net, andnpm-* entries in theUtilities Reference.

Network filesystems

We support two types of network filesystems:

� NFS (fs-nfs2 /fs-nfs3), which allows file access over anetwork to a UNIX or other system running an NFS server.

November 3, 2006 Chapter 3 � Making an OS Image 81

Page 102: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

System configuration 2006, QNX Software Systems GmbH & Co. KG.

� CIFS (fs-cifs), which allows file access over a network to aWindows 98 or NT system or to a UNIX system running an SMBserver.

The CIFS protocol makes no attempt to conform to POSIX.☞

Although NFS is primarily a UNIX-based filesystem, you may findsome versions of NFS available for Windows.

Running applicationsThere’s nothing special required to run your applications. Generally,they’ll be placed in the script fileafter all the other drivers havestarted. If you require a particular driver to be present and “ready,”you would typically use thewaitfor command in the script.

Here’s an example. An application calledpeelmaster needs to waitfor a driver (let’s call itdriver-spud) to be ready before it shouldstart. The following sequence is typical:

driver-spud &waitfor /dev/spudpeelmaster

This causes the driver (driver-spud) to be run in the background(specified by the ampersand character). The expectation is that whenthe driver is ready, it will register the pathname/dev/spud. Thewaitfor command tries tostat() the pathname/dev/spudperiodically, blocking execution of the script until the pathnameappears or a predetermined timeout has occurred. Once the pathnameappears in the pathname space, we assume that the driver is ready toaccept requests. At that point, thewaitfor will unblock, and the nextprogram in the list (in our case,peelmaster) will execute.

Without thewaitfor command, thepeelmaster program wouldrun immediately after the driver was started, which could causepeelmaster to miss the/dev/spud pathname and fail.

82 Chapter 3 � Making an OS Image November 3, 2006

Page 103: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Debugging an embedded system

Debugging an embedded systemWhen you’re developing embedded systems under some operatingsystems, you often need to use ahardware debugger, a physicaldevice that connects to target hardware via a JTAG (Joint Test ActionGroup) interface. This is necessary for development of drivers, andpossibly user applications, because they’re linked into the samememory space as the kernel. If a driver or application crashes, thekernel and system may crash as a result. This makes using softwaredebuggers difficult, because they depend on a running system.

Debugging target systems with Neutrino is different because itsarchitecture is significantly different from other embeddable realtimeoperating systems:

� All Neutrino applications (including drivers) run in their ownmemory-protected virtual address space. This has the advantagethat the software is more reliable and fault tolerant. However,conventional hardware debuggers rely on decoding physicalmemory addresses, making them incompatible with debugginguser applications based in a virtual memory environment.

� Neutrino lets you develop multi-threaded applications, whichhardware debuggers generally don’t support.

Under Neutrino, you typically use:

� a hardware debugger for the IPL and startup

� a software debugger for the rest of the software.

In other words, you rarely have to use a JTAG hardware debugger,especially if you’re using one of our board support packages.

pdebug software debugging agentWe provide a software debugging agent calledpdebug that makes iteasier for you to debug system drivers and user applications. Thepdebug agent runs on the target system and communicates with thehost debugger over a serial or Ethernet connection.

November 3, 2006 Chapter 3 � Making an OS Image 83

Page 104: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Debugging an embedded system 2006, QNX Software Systems GmbH & Co. KG.

For more information, see “The process-level debug agent” in theCompiling and Debugging chapter of theProgrammer’s Guide.

Hardware debuggers and NeutrinoThe major constraint of usingpdebug is that the kernel must alreadybe running on the target. In other words, you can’t usepdebug untilthe IPL and startup have successfully started the kernel.

However, the IPL and startup program run with the CPU in physicalmode, so you can use conventional hardware debuggers to debugthem. This is the primary function of the JTAG debugger throughoutthe Neutrino software development phase. You use the hardwaredebugger to debug the BSP (IPL and startup), andpdebug to debugdrivers and applications once the kernel is running. You can also use ahardware debugger to examine registers and view memory while thekernel and applications are running, if you know the physicaladdresses.

If hardware debuggers, such as SH or AMC have builtin Neutrinoawareness, you can use a JTAG to debug applications. Thesedebuggers can interpret kernel information as well as perform thenecessary translation between virtual and physical memory addressesto view application data.

Producing debug symbol information for IPL and startupYou can use hardware debuggers to debug Neutrino IPL and startupprograms without any extra information. However, in this case, you’relimited to assembly-level debugging, and assembler symbols such assubroutine names aren’t visible. To perform full source-leveldebugging, you need to provide the hardware debugger with thesymbol information and C source code.

This section describes the steps necessary to generate the symbol anddebug information required by a hardware debugger for source-leveldebugging. The steps described are based on the PPC (PowerPC)Board Support Package available for Neutrino 6.3.0 for both IPL andstartup of the Motorola Sandpoint MPC750 hardware referenceplatform.

84 Chapter 3 � Making an OS Image November 3, 2006

Page 105: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Debugging an embedded system

The examples below are described for a Neutrino 6.3.0 self-hostedenvironment, and assume that you’re logged in on the developmenthost withroot privileges.

Generating IPL debug symbols

To generate symbol information for the IPL, you must recompile boththe IPL library and the Sandpoint IPL with debug information. Thegeneral procedure is as follows:

1 Modify the IPL source.

2 Build the IPL library and Sandpoint IPL.

3 Burn the IPL into the flash memory of the Sandpoint boardusing a flash burner or JTAG.

4 Modify thesandpoint.lnk file to output ELF format.

5 Recompile the IPL library and Sandpoint IPL source withdebug options.

6 Load the Sandpoint IPL ELF file containing debug informationinto the hardware debugger.

Be sure to synchronize the source code, the IPL burned into flash, andthe IPL debug symbols.

To build the IPL library with debug information:

# cd bsp working dir/src/hardware/ipl/lib/ppc/a.be# make clean# make CCOPTS=-g# cp libipl.a bsp working dir/sandpoint/install/ppcbe/lib# make install

The above steps recompile the PowerPC IPL library (libipl.a) withDWARF debug information and copy this library to the Sandpointinstall directory. The Sandpoint BSP is configured to look for thislibrary first in its install directory. Themake install is optional,and copieslibipl.a to /ppcbe/usr/lib.

November 3, 2006 Chapter 3 � Making an OS Image 85

Page 106: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Debugging an embedded system 2006, QNX Software Systems GmbH & Co. KG.

The Sandpoint BSP has been set up to work with SREC format files.However, to generate debug and symbol information to be loaded intothe hardware debugger, you must generate ELF-format files.

Modify thesandpoint.lnk file to output ELF format:

# cd bsp working dir/sandpoint/src/hardware/ipl/boards/sandpoint

Edit the filesandpoint.lnk, changing the first lines from:

TARGET(elf32-powerpc)OUTPUT FORMAT(srec)ENTRY(entry vec)

to:

TARGET(elf32-powerpc)OUTPUT FORMAT(elf32-powerpc)ENTRY(entry vec)

You can now rebuild the Sandpoint IPL to produce symbol and debuginformation in ELF format. To build the Sandpoint IPL with debuginformation:

# cd bsp working dir/sandpoint/src/hardware/ipl/boards/sandpoint/ppc/be# make clean

# make CCOPTS=-g

Theipl-sandpoint file is now in ELF format with debug symbolsfrom both the IPL library and Sandpoint IPL.

To rebuild the BSP, you need to change thesandpoint.lnk fileback to outputting SREC format. It’s also important to keep the IPLthat’s burned into the Sandpoint flash memory in sync with thegenerated debug information; if you modify the IPL source, you needto rebuild the BSP, burn the new IPL into flash, and rebuild the IPLsymbol and debug information.

You can use theobjdump utility to view the ELF information. Forexample, to view the symbol information contained in theipl-sandpoint file:

86 Chapter 3 � Making an OS Image November 3, 2006

Page 107: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Debugging an embedded system

# objdump -t ipl-sandpoint | less

You can now import theipl-sandpoint file into a hardwaredebugger to provide the symbol information required for debugging.In addition, the hardware debugger needs the source code listingsfound in the following directories:

� bsp working dir/sandpoint/src/hardware/ipl/boards/sandpoint

� bsp working dir/src/hardware/ipl/lib

� bsp working dir/src/hardware/ipl/lib/ppc

Generating startup debug symbols

To generate symbol information for startup, you must recompile boththe startup library and the Sandpoint startup with debug information.The general procedure is as follows:

1 Modify the startup source.

2 Build the startup library and Sandpoint startup with debuginformation.

3 Rebuild the image and symbol file.

4 Load the symbol file into the hardware debugger program.

5 Transfer the image to the Sandpoint target (burn into flash,transfer over a serial connection).

To build the startup library with debug information:

# cd bsp working dir/src/hardware/startup/lib/ppc/a.be# make clean# make CCOPTS=-g

# cp libstartup.a bsp working dir/sandpoint/install/ppcbe/lib# make install

The above steps recompile the PowerPC startup library(libstartup.a) with DWARF debug information and copy thislibrary to the Sandpoint install directory. The Sandpoint BSP isconfigured to look for this library first in its install directory. The

November 3, 2006 Chapter 3 � Making an OS Image 87

Page 108: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Debugging an embedded system 2006, QNX Software Systems GmbH & Co. KG.

make install is optional, and copieslibstartup.a to/ppcbe/usr/lib.

To build the Sandpoint startup with debugging information:

# cd bsp working dir/sandpoint/src/hardware/startup/boards/sandpoint/ppc/be# make clean

# make CCOPTS=-g# make install

The above steps generate the file startup-sandpoint with symbol anddebug information. Again, you can use the-gstabs+ debug optioninstead of-g. Themake install is necessary, and copiesstartup-sandpoint into the Sandpoint install directory,bsp working dir/sandpoint/install/ppcbe/boot/sys.

You can’t load the startup-sandpoint ELF file into the hardwaredebugger to obtain the debug symbols, because themkifs utility addsan offset to the addresses defined in the symbols according to theoffset specified in the build file.

Modify the build file to include the+keeplinked attribute forstartup:

# cd bsp working dir/sandpoint/images

Modify the startup line of your build file to look like:

[image=0x10000][virtual=ppcbe,binary +compress] .bootstrap = {

[+keeplinked] startup-sandpoint -vvv -D8250PATH=/proc/boot procnto-600 -vv

}

The+keeplinked option makesmkifs generate a symbol file thatrepresents the debug information positioned within the imagefilesystem by the specified offset.

To rebuild the image to generate the symbol file:

# cd bsp working dir/sandpoint/images# make clean

88 Chapter 3 � Making an OS Image November 3, 2006

Page 109: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Debugging an embedded system

Then, if you’re using one of the provided.build files:

# make all

otherwise:

# mkifs -v -r ../install myfile.build image

These commands create the symbol file,startup-sandpoint.sym.You can use theobjdump utility to view the ELF information.

To view the symbol information contained in thestartup-sandpoint.sym file:

# objdump -t startup-sandpoint.sym | less

You can now import thestartup-sandpoint.sym file into ahardware debugger to provide the symbol information required fordebugging startup. In addition, the hardware debugger needs thesource code listings found in the following directories:

� bsp working dir/src/hardware/startup/lib

� bsp working dir/src/hardware/startup/lib/public/ppc

� bsp working dir/src/hardware/startup/lib/public/sys

� bsp working dir/src/hardware/startup/lib/ppc

� bsp working dir/sandpoint/src/hardware/startup/boards/sandpoint

November 3, 2006 Chapter 3 � Making an OS Image 89

Page 110: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 111: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Chapter 4

Writing an IPL Program

In this chapter. . .Initial program loader (IPL) 93Customizing IPLs 105The IPL library 122

November 3, 2006 Chapter 4 � Writing an IPL Program 91

Page 112: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 113: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Initial program loader (IPL)

Initial program loader (IPL)In this section, we’ll examine the IPL program in detail, includinghow to customize it for your particular hardware, if you need to.

Responsibilities of the IPLThe initial task of the IPL is to minimally configure the hardware tocreate an environment that allows the startup program (e.g.startup-bios, startup-ixdp425, etc.), and consequently theNeutrino microkernel, to run. This includes at least the following:

1 Start execution from the reset vector.

2 Configure the memory controller. This may include configuringthe chip selects and/or PCI controller.

3 Configure clocks.

4 Set up a stack to allow the IPL library to perform OSverification and setup (download, scan, set up, and jump to theOS image).

The IPL’s initialization part is written entirely in assembly language(because it executes from ROM with no memory controller). Afterinitializing the hardware, the IPL then calls themain() function toinitiate the C-language environment.

Once the C environment is set up, the IPL can perform different tasks,depending on whether the OS is booting from a linearly mappeddevice or a bank-switched device:

Linearly mapped The entire image is in the processor’s linearaddress space.

Bank-switched The image isn’t entirely addressable by theprocessor (e.g. bank-switched ROM, disk device,network, etc.).

November 3, 2006 Chapter 4 � Writing an IPL Program 93

Page 114: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Initial program loader (IPL) 2006, QNX Software Systems GmbH & Co. KG.

Note that we use the term “ROM” generically to mean any nonvolatilememory device used to store the image (Flash, RAM, ROM, EPROM,flash, battery-backed SRAM, etc.).

Linearly mapped images

For linearly mapped images, we have the following sources:

� ROM

Bank-switched images

For bank-switched images, we have the following sources:

� PC-Card (PCMCIA) (some implementations)

� ROM, RAM, bank-switched

� Network device

� Serial or parallel port

� Disk device

� Other.

Processors & configurations

In conjunction with the above, we have the following processors andconfigurations:

� 386 and higher processors, which power up in 16-bit real mode.

� PowerPC family of processors, (some are physical and some arevirtual processors), which power up in 32-bit physical or virtualmode.

� ARM family of processors (StrongARM, XScale), which power upin 32-bit physical mode.

� MIPS architecture processors, which power up with virtualaddressing enabled, but mapped one-to-one.

� SH-4 family of processors, which power up with virtual addressingenabled, but mapped one-to-one.

94 Chapter 4 � Writing an IPL Program November 3, 2006

Page 115: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Initial program loader (IPL)

Booting from a bank-switched deviceLet’s assume we’re booting from a bank-switched or paged device(e.g. paged flash, disk device, network, etc.), and that the image isuncompressed. The IPL needs to handle these main tasks:

1 The IPL must first use a C function to talk to the device inquestion. We’ll use a serial download for this discussion. Forserial downloads, the IPL usesimage download 8250(), afunction that specifically knows how to configure and controlthe 8250 class of serial controllers.

Once the controller is set up, the function’s task is to copy theimage via the serial controller to a location in RAM.

2 We now have an OS image in RAM. The IPL then uses theimage scan() function, which takes a start address and endaddress as its parameters. It returns the address at which itfound the image:unsigned long image scan (unsigned long start, unsigned long end)

Theimage scan() function:

� Scans for a valid OS signature over the range provided. Notethat this can be multiple OS images.

� Copies the startup header from the image to astruct

startup header variable.

� Authenticates the startup signature(STARTUPHDR SIGNATURE).

� Performs a checksum on the startup.

� Performs a checksum on the OS image filesystem.

� Saves the address and version number of the OS in case it’sset up to scan for multiple OS images.

3 Once the OS image has been found and validated, the IPL’snext function to call isimage setup(), which takes the addressof the image as its parameter and always returns 0:int image setup (unsigned long address)

Theimage setup() function:

November 3, 2006 Chapter 4 � Writing an IPL Program 95

Page 116: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Initial program loader (IPL) 2006, QNX Software Systems GmbH & Co. KG.

� Copies the startup header from the image to astruct

startup header variable. Although this was performed inimage scan() (andstartup header is a global), it’s necessaryhere becauseimage scan() can scan for multiple images,which will overwrite this structure.

� Calculates the address to which startup is to be copied,based on theram paddr andpaddr bias structure members(from the startup header).

� Fills in theimagefs paddr structure member, based on wherethe image is stored. The startup program relies on thismember, because it’s the one responsible for copying the OSimage filesystem to its final location in RAM. The startupprogram doesn’t necessarily know where the image is stored.

� Copies the final startup structure to theram paddr address,and then copies the startup program itself.

At this phase, the startup program has been copied to RAM(and it mustalways execute from RAM), and the startup headerhas been patched with the address of the OS image.

96 Chapter 4 � Writing an IPL Program November 3, 2006

Page 117: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Initial program loader (IPL)

Since the startup program is responsible for copying the imagefilesystem to its final destination in RAM, the IPL must copy theimage to a location that’slinearly accessible by the startup program,which has no knowledge of paged devices (serial, disk, parallel,network, etc.).

Note also that if the image is compressed, then the IPL can copy thecompressed image to a location that won’t interfere with startup’sdecompression of the image to its final destination in RAM. When theimage lives in flash (or ROM or whatever linear storage device), thisisn’t an issue. But when the image is stored on a paged device, morecare must be taken in placing the image in a RAM location that won’tinterfere with startup’s decompression of the image. Here are therules:

Uncompressed If the image is uncompressed, then the IPL cancopy the image from the paged device directlyto its destined location. Startup will comparethe addresses and realize that the imagedoesn’t need to be copied.

Compressed If the image is compressed, then startup mustcopy and decompress the imageusing adifferent location than the final RAM location.

4 The last phase is to jump to the startup entry point. This isaccomplished by callingimage start():int image start (unsigned long address)

Theimage start() function should never return; it returns -1 if itfails.

The function jumps to thestartup vaddr address as defined inthe startup header.

November 3, 2006 Chapter 4 � Writing an IPL Program 97

Page 118: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Initial program loader (IPL) 2006, QNX Software Systems GmbH & Co. KG.

Booting from a linear deviceFor a system that boots from a linearly mapped device (e.g. linearflash, ROM, etc.), the IPL’s tasks are the same as in the paged-devicescenario above, but with one notable exception: the IPL doesn’t needto concern itself with copying a full OS image from the device toRAM.

“Warm” vs “cold” startYour IPL code may be quite simple or fairly elaborate, depending onhow your embedded system is configured. We’ll use the termswarmstart andcold start to describe the different types of IPL:

Warm-start IPL If there’s a BIOS or ROM monitor alreadyinstalled at the reset vector, then your IPL code issimply an extension to the BIOS or ROM monitor.

Cold-start IPL The system doesn’t have (or doesn’t use) a BIOSor ROM monitor program. The IPL must belocated at the reset vector.

Warm-start IPL

In this case, the IPL doesn’t get control immediately after the reset,but instead gets control from the BIOS or ROM monitor.

The x86 PC BIOS allows extensions, as do various ROM monitors.During the power-up memory scan, the BIOS or ROM monitorattempts to detect extensions in the address space. To be recognizedas an extension, the extension ROM must have a well-definedextension signature (e.g. for a PC BIOS, this is the sequence0x55

and then0xAA as the first two bytes of the extension ROM). Theextension ROM must be prepared to receive control at theextensionentry offset (e.g. for a PC BIOS, this is an offset of0x0003 into theextension ROM).

Note that this method is used by the various PC BOOTP ROMsavailable. The ROM presents itself as an extension, and then, whencontrol is transferred to it, gets an image from the network and loadsit into RAM.

98 Chapter 4 � Writing an IPL Program November 3, 2006

Page 119: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Initial program loader (IPL)

Cold-start IPL

One of the benefits of Neutrino, especially in a cost-reducedembedded system, is that you don’trequire a BIOS or ROM monitorprogram. This discussion is primarily for developers who must writetheir own IPL program or who (for whatever reason) don’t wish to usethe default IPL supplied by their BIOS/monitor.

Let’s take a look at what the IPL does in this case.

When power is first applied to the processor (or whenever theprocessor is reset), some of its registers are set to a known state, and itbegins executing from a known memory location (i.e. theresetvector).

Your IPL software must be located at the reset vector and must beable to:

1 Set up the processor.

2 Locate the OS image.

3 Copy the startup program into RAM.

4 Transfer control to the startup program.

For example, on an x86 system, the reset vector is located at address0xFFFFFFF0. The device that contains the IPL must be installedwithin that address range. In a typical x86 PC BIOS, the reset vectorcode contains aJMP instruction that then branches to the code thatperforms diagnostics, setup, and IPL functionality.

Loading the imageRegardless of the processor being used, once the IPL code is started,it has to load the image in a manner that meets the requirements of theNeutrino microkernel as described above. The IPL code may alsohave to support a backup way of loading the image (e.g. an.altboot in the case of a hard/floppy boot). This may also have tobe an automatic fallback in the case of a corrupted image.

November 3, 2006 Chapter 4 � Writing an IPL Program 99

Page 120: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Initial program loader (IPL) 2006, QNX Software Systems GmbH & Co. KG.

Note, however, that the amount of work your IPL code has to doreally depends on the location of the image; there may be only a smallamount of work for the IPL or there may be a lot.

Let’s look again at the two classifications of image sources.

If the source is a linearly mapped device

This is the simplest scenario. In this case, the entire image is stored insome form of directly addressable storage — either a ROM device ora form of PC-Card device that maps its entire address space into theprocessor’s address space. All that’s required is to copy the startupcode into RAM. This is ideal for small or deeply embedded systems.

Note that on x86 architectures, the device isnot required to beaddressable within the first megabyte of memory. The startupprogram also needn’t be in the first megabyte of RAM.

Note also that for PC-Card devices, some form of setup may berequired before the entire PC-Card device’s address space will appearin the address space of the processor. It’s up to your IPL code toperform this setup operation. (We provide library routines for severalstandard PC-Card interface chips.)

100 Chapter 4 � Writing an IPL Program November 3, 2006

Page 121: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Initial program loader (IPL)

RAM

Flash ROM

Startup

procnto

Prog1

Prog2

IPLjmpjmp

Flash/ROM

File

Low memory

High memory

Linearly mapped device.

If the source is a bank-switched device

In this scenario, the image is stored in a device that isn’t directlymapped into linear memory. An additional factor needs to beconsidered here — how will your IPL code get at the image stored inthe device?

Many types of hardware devices conform to this model:

� ROM

� Network boot

� Serial or parallel port

� Traditional disk

November 3, 2006 Chapter 4 � Writing an IPL Program 101

Page 122: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Initial program loader (IPL) 2006, QNX Software Systems GmbH & Co. KG.

Let’s look at the common characteristics. In such systems, the IPLcode knows how to fetch data from some piece of hardware. Theprocess is as follows:

1 The IPL receives control.

2 The IPL loads the image from the hardware into RAM.

3 The IPL then transfers control to the newly loaded image.

RAM

Startup

procnto

Prog1

Prog2

File

IPLjmpjmp

Flash/ROM Low memory

High memory

Paged ROM,Network,

Serial/Parallel port,or Disk

Bank-switched devices.

ROM devices

In this scenario, a solid-state storage device (ROM, EPROM, flash,etc.) contains the image, but the processor can see only a smallportion of the contents of the device. How is this implemented? Thehardware has a small window (say 32K) into the address space of the

102 Chapter 4 � Writing an IPL Program November 3, 2006

Page 123: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Initial program loader (IPL)

processor; additional hardware registers control which portion of thedevice is manifested into that window.

Window

Top of address space

FFFC FFFFTop of window

FFFC 8000Bottom of window

Bottom of address space

Window

mapping

hardware

20M

storage

medium

Large storage medium, bank-switched into a window.

In order to load the image, your IPL code must know how to controlthe hardware that maps the window. Your IPL code then needs tocopy the image out of the window into RAM and transfer control.

If possible, avoid the use of any mapping hardware (whethercustom-designed or “industry-standard”) — it only serves tocomplicate the hardware and software designs. We stronglyrecommend linearly mapped devices. (Please see the appendix onSystem Design Considerations for more information.)

Network boot

Depending on your embedded system’s requirements or on yourdevelopment process, you can load the image via an Ethernetnetwork. On some embedded boards, the ROM monitor contains theBOOTP code. On a PC with an ISA or PCI network card, some formof boot ROM is placed into the address space of the processor, wherewe assume the PC BIOS will transfer control to it. The BOOTP codeknows how to talk to the networking hardware and how to get theimage from a remote system.

November 3, 2006 Chapter 4 � Writing an IPL Program 103

Page 124: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Initial program loader (IPL) 2006, QNX Software Systems GmbH & Co. KG.

Using a BOOTP server

To boot a Neutrino system using BOOTP, you’ll need a BOOTP ROMfor your OS client and a BOOTP server (e.g.bootpd) for your server.Since the TFTP protocol is used to move the image from the server tothe client, you’ll also need a TFTP server — this is usually providedwith a BOOTP server on most systems (Neutrino, UNIX, Windows95/98/NT.)

Serial port

A serial port on the target can be useful during development fordownloading an image or as a failsafe mechanism (e.g. if a checksumfails, you can simply reload the image via the serial port).

A serial loader can be built into the IPL code so that the code canfetch the image from an external hardware port. This generally has aminimal impact on the cost of an embedded system; in most cases, theserial port hardware can be left off for final assembly. Evaluationboards supplied by hardware chip vendors often have serial ports. Wesupply source code for an embedded serial loader for the 8250 chip.

The IPL process in this case is almost identical to the one discussedabove for the Network boot, except that the serial port is used to fetchthe image.

Traditional disk

In a traditional PC-style embedded system with a BIOS, this is thesimplest boot possible. The BIOS performs all the work for you — itfetches the image from disk, transfers it to RAM, and starts it.

On the other hand, if you don’t have a BIOS but you wish toimplement this kind of a boot, then this method involves the mostcomplicated processing discussed so far. This is because you’ll need adriver that knows how to access the disk (whether it’s a traditionalrotating-medium hard disk or a solid-state disk). Your IPL code thenneeds to look into the partition table of the device and figure outwhere the contents of the image reside. Once that determination hasbeen made, the IPL then needs to either map the image portions into a

104 Chapter 4 � Writing an IPL Program November 3, 2006

Page 125: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

window and transfer bytes to RAM (in the case of a solid-state disk)or fetch the data bytes from the disk hardware.

None of the above?

It’s entirely conceivable that none of the above adequately describesyour particular embedded system. In that case, the IPL code you’llwrite must still perform the same basic steps as described above —handle the reset vector, fetch the image from some medium, andtransfer control to the startup routine.

Transferring control to the startup programOnce the image has either been loaded into RAM or is available forexecution in ROM, we must transfer control to thestartup code(copied from the image to RAM).

For detailed information about the different types of startup programs,see the chapter on Customizing Image Startup Programs.

Once the startup code is off and running, the work of the IPL processis done.

Customizing IPLsThis section describes in detail the steps necessary to write the IPL foran embedded system that boots from ROM or Flash.

Systems that boot from disk or over the network typically come witha BIOS or ROM monitor, which already contains a large part of theIPL within it. If your embedded system fits this category, you canprobably skip directly to the chapter on Customizing Image StartupPrograms.

Your IPL loader gets control at reset time and performs the followingmain functions:

1 Initialize hardware (via assembly-language code).

2 Download the image into RAM (e.g. via serial usingimage download 8250()).

November 3, 2006 Chapter 4 � Writing an IPL Program 105

Page 126: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

3 Locate the OS image (viaimage scan()).

4 Copy the startup program (viaimage setup()).

5 Jump to the loaded image (viaimage start()).

Initialize hardwareBasic hardware initialization is done at this time. This includesgaining access to the system RAM, which may not be addressableafter reset. The amount of initialization done here will depend onwhat was done by any code before this loader gained control. Onsome systems, the power-on-reset will point directly to this code,which will have to do everything. On other systems, this loader maybe called by an even more primitive loader, which may have alreadyperformed some of these tasks.

Note that it’s not necessary to initialize standard peripheral hardwaresuch as an IDE interface or the baud rate of serial ports. This will bedone by the OS drivers when they’re started later. Technically, youneed to initialize only enough hardware to allow control to betransferred to the startup program in the image.

The startup program is written in C and is provided in fullsource-code format. The startup code is structured in a readilycustomizable manner, providing a simple environment for performingfurther initializations, such as setting up thesystem page in-memorydata structure.

Loading the image into RAMThe IPL code must locate the boot image (made with themkifs

utility) and copy part or all of it into memory.

The loader uses information in the header to copy theheader andstartup into RAM. The loader would be responsible for copying theentire image into RAM if the image weren’t located in linearlyaddressable memory.

106 Chapter 4 � Writing an IPL Program November 3, 2006

Page 127: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

Structure of the boot headerThe boot header structurestruct startup header is defined inthe include file<sys/startup.h>. It is 256 bytes in size andcontains the following members, which are examined by the IPLand/or startup code:

unsigned long signature

unsigned short version

unsigned char flags1

unsigned char flags2

unsigned short header size

unsigned short machine

unsigned long startup vaddr

unsigned long paddr bias

unsigned long image paddr

unsigned long ram paddr

unsigned long ram size

unsigned long startup size

unsigned long stored size

unsigned long imagefs paddr

unsigned long imagefs size

unsigned short preboot size

unsigned short zero0

unsigned long zero [3]

unsigned long info [48]

A valid image (for bootable images) is detected by performing achecksum (via the function callchecksum()) over the entire image, asfollows:

checksum (image paddr, startup size);checksum (image paddr + startup size, stored size - startup size);

November 3, 2006 Chapter 4 � Writing an IPL Program 107

Page 128: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

signature

This is the first 32 bits in the header and always contains0x00FF7EEB in native byte order. It’s used to identify the header. Ona machine that can be either big-endian or little-endian (abi-endianmachine, e.g. MIPS), there’s typically a hardware strap that gets seton the board to specify the endianness.

version

The version ofmkifs that made the image.

flags1 and flags2

The following flags are defined forflags1 (flags2 is currently notused):

STARTUP HDR FLAGS1 VIRTUAL

If this flag is set, the operating system is to run with theMemory Management Unit (MMU) enabled.

For this release of Neutrino, you should always specify a virtualsystem (by specifying thevirtual= attribute in your buildfile, whichthen sets theSTARTUP HDR FLAGS1 VIRTUAL flag).

STARTUP HDR FLAGS1 BIGENDIAN

The processor is big-endian. Processors should always examinethis flag to check that the ENDIAN is right for them.

STARTUP HDR FLAGS1 COMPRESSNONE

The image isn’t compressed.

STARTUP HDR FLAGS1 COMPRESSZLIB

The image is compressed usinglibz (gzip).

STARTUP HDR FLAGS1 COMPRESSLZO

The image is compressed withliblzo.

108 Chapter 4 � Writing an IPL Program November 3, 2006

Page 129: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

STARTUP HDR FLAGS1 COMPRESSUCL

The image is compressed withlibucl. This is the formatchosen when using the[+compress] attribute in themkifsbuild script.

Currently, thestartup-* programs are built to understand only theUCL compression method. By twiddling theSUPPORTCMP * macrodefinitions instartup/lib/uncompress.c, you can change to oneof the other supported compression methods.

TheSTARTUP HDR FLAGS1 COMPRESS* constants aren’t reallyflags because they may set more than one bit; they’re used as anenumeration of the types of compression.

Note that both flagflags1 andflags2 are single-byte; this ensures thatthey’re endian-neutral.

header size

The size of the startup header (sizeof (struct

startup header)).

machine

Machine type, from<sys/elf.h>.

startup vaddr

Virtual address to transfer to after IPL is done.

paddr bias

Value to add to physical address to get a value to put into a pointerand indirect through.

image paddr

Physical address of the image.

November 3, 2006 Chapter 4 � Writing an IPL Program 109

Page 130: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

ram paddr

The physical address in RAM to copy the image to. You should copystartup size bytes worth of data.

ram size

The number of bytes the image will occupy when it’s loaded intoRAM. This value is used by the startup code in the image and isn’tcurrently needed by the IPL code. This size may be greater thanstored size if the image was compressed. It may also be smaller thanstored size if the image is XIP.

startup size

This is the size of the startup code. Copy this number of bytes fromthe start of the image into RAM. Note that the startup code is nevercompressed, so this size is true in all cases.

stored size

This is the size of the image including the header. Thestored sizemember is also used in the copy/decompress routines for non-XIPimages.

imagefs paddr

Set by the IPL to the physical address of the image filesystem. Usedby the startup.

imagefs size

Size of uncompressed image filesystem.

preboot size

Contains the number of bytes from the beginning of the loaded imageto the startup header. Note that this value will usually be zero,indicating that nothing precedes the startup portion. On an x86 with aBIOS, it will be nonzero, because there’s a small piece of code thatgets data from the BIOS in real mode and then switches into protectedmode and performs the startup.

110 Chapter 4 � Writing an IPL Program November 3, 2006

Page 131: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

zero and zero0

Zero filler; reserved for future expansion.

info

An array ofstartup info* structures. This is the communicationsarea between the IPL and the startup code. When the IPL code detectsvarious system features (amount of memory installed, current time,information about the bus used on the system, etc.), it stores thatinformation into theinfo array so that the startup code can fetch itlater. This saves the startup code from performing the same detectionlogic again.

Note that theinfo is declared as an array oflongs — this is purely toallocate the storage space. In reality, theinfo storage area contains aset of structures, each beginning with this header:

struct startup info hdr {unsigned short type;unsigned short size;

};

Thetype member is selected from the following list:

STARTUP INFO SKIP

Ignore this field. If the correspondingsize member is0, itmeans that this is the end of theinfo list.

STARTUP INFO MEM

A struct startup info mem structure is present.

STARTUP INFO MEM EXTENDED

A struct startup info mem extended structure ispresent.

STARTUP INFO DISK

A struct startup info disk structure is present.

STARTUP INFO TIME

A struct startup info time structure is present.

November 3, 2006 Chapter 4 � Writing an IPL Program 111

Page 132: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

STARTUP INFO BOX

A struct startup info box structure is present.

Note that thestruct startup info hdr header (containing thetype andsize members) is encapsulated within each of the abovementionedstruct startup info* structures as the first element.

Let’s look at the individual structures.

struct startup info skip

Contains only the header as the memberhdr.

struct startup info mem

Contains the following:

struct startup info mem {struct startup info hdr hdr;unsigned long addr;unsigned long size;

};

Contains an address (addr) and size (size) pair defining a chunk ofmemory that should be added toprocnto’s free memory pool. Morethan onestruct startup info mem may be present toaccommodate systems that have free memory located in variousblocks throughout the address space.

struct startup info mem

Contains the following:

struct startup info mem {struct startup info hdr hdr;unsigned long addr;unsigned long size;

};

Contains an address (addr) and size (size) pair defining a chunk ofmemory that should be added toprocnto’s free memory pool.Memory is limited to 32bits. More than onestruct

112 Chapter 4 � Writing an IPL Program November 3, 2006

Page 133: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

startup info mem may be present to accommodate systems thathave free memory located in various blocks throughout the addressspace.

struct startup info mem extended

Contains the following:

struct startup info mem extended {struct startup info mem mem;unsigned long addr hi;unsigned long size hi;

};

Contains an address (addr hi) and size (size hi) pair defining a chunkof memory that should be added toprocnto’s free memory pool.Memory is extended to a 64bit limit. More than onestructstartup info mem may be present to accommodate systems thathave free memory located in various blocks throughout the addressspace.

struct startup info disk

Contains the following:

struct startup info disk {struct startup info hdr hdr;unsigned char drive;unsigned char zero;unsigned short heads;unsigned short cylinders;unsigned short sectors;unsigned long blocks;

};

Contains information about any hard disks detected (on a PC with aBIOS). The members are as follows:

drive Drive number.

zero Reserved; must be zero.

heads Number of heads present.

November 3, 2006 Chapter 4 � Writing an IPL Program 113

Page 134: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

cylinders Number of cylinders present.

sectors Number of sectors present.

blocks Total blocksize of device. Computed by the formulaheads � cylinders � sectors. Note that this assumes512 bytes per block.

struct startup info time

Contains the following:

struct startup info time {struct startup info hdr hdr;unsigned long time;

};

Thetime member contains the current time as the number of secondssince 1970 01 01 00:00:00 GMT.

struct startup info box

Contains the following:

struct startup info box {struct startup info hdr hdr;unsigned char boxtype;unsigned char bustype;unsigned char spare [2];

};

Contains theboxtype andbustype information. For valid values,please see the chapter on Customizing Image Startup Programs.

Thespare fields are reserved and must be zero.

Relationship of struct startup header fieldsThe following explains some of the fields used by the IPL and startupfor various types of boot. These fields are stuffed bymkifs.

Note that we’ve indicated which steps are performed by the IPL andwhich are done by the startup.

114 Chapter 4 � Writing an IPL Program November 3, 2006

Page 135: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

Linear ROM execute-in-place boot image

The following illustration shows an XIP image:

RAM

ram_size

ram_paddrROM

Startupstartup_size

stored_size

Startupheader

Imagefsheader

Imagefsimagefs_size

image_paddr

Startup

Startupheader

Reservedfor

imagefsdata

startup_vaddr

Low memory

High memory

In the following pseudo-code examples,image paddr represents thesource location of the image in linear ROM, andram paddrrepresents the image’s destination in RAM.

Here are the steps required in the IPL:

checksum (image paddr, startup size)checksum (image paddr + startup size, stored size - startup size)copy (image paddr, ram paddr, startup size)jump (startup vaddr)

Linear ROM compressed boot image

Here’s the same scenario, but with a compressed image:

November 3, 2006 Chapter 4 � Writing an IPL Program 115

Page 136: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

RAM

ram_size

ram_paddrROM

Startupstartup_size

stored_size

Startupheader

Compressedimagefsheader

Imagefs

image_paddr

Startup

Startupheader

startup_vaddr

Imagefsheader

Imagefs

imagefs_size

Low memory

High memory

Here are the steps required in the IPL:

checksum (image paddr, startup size)checksum (image paddr + startup size, stored size - startup size)copy (image paddr, ram paddr, startup size)jump (startup vaddr)

And here’s the step required in the startup:

uncompress (ram paddr + startup size, image paddr + startup size,stored size - startup size)

ROM non-XIP image

In this scenario, the image doesn’t execute in place:RAM

ram_size

ram_paddrROM

Startupstartup_size

stored_size

Startupheader

Imagefsheader

Imagefs

image_paddr

Startup

Startupheader

startup_vaddr

Imagefsheader

Imagefs imagefs_size

imagefs_size

Low memory

High memory

116 Chapter 4 � Writing an IPL Program November 3, 2006

Page 137: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

Here are the steps required in the IPL:

checksum (image paddr, startup size)checksum (image paddr + startup size, stored size - startup size)copy (image paddr, ram paddr, startup size)jump (startup vaddr)

And here’s the step required in the startup:

copy (ram paddr + startup size, image paddr + startup size,stored size - startup size)

Disk/network image (x86 BIOS)

In this case our full IPL isn’t involved. An existing BIOS IPL loadsthe image into memory and transfers control to our IPL. Since theexisting IPL doesn’t know where in startup to jump, it always jumpsto the start of the image. On the front of the image we build a tiny IPLthat jumps tostartup vaddr:

Startupstartup_size

stored_size,ram_size

Startupheader

Imagefsheader

Imagefs

image_paddr,ram_paddr

startup_vaddr

imagefs_size

jump ipl

RAMLow memory

High memory

Here’s the step required in the IPL:

jump (startup vaddr)

November 3, 2006 Chapter 4 � Writing an IPL Program 117

Page 138: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

Disk/network compressed image

This is identical to the previous case, except that we need todecompress the image in the startup:

Startupstartup_size

stored_size,ram_size

Startupheader

Compressedimagefsheader

Imagefs

image_paddr

startup_vaddr

imagefs_size

jump ipl

RAM

Imagefsheader

Imagefs

RAM

ram_paddr

Low memory

High memory

Here’s the step required in the startup:

uncompress (ram paddr + startup size, image paddr + startup size,stored size - startup size)

The case of a bank-switched ROM is much like a disk/network bootexcept you get to write the code that copies the image into RAMusing the following steps in the IPL:

bankcopy (image paddr, ram paddr, startup size)checksum (image paddr, startup size)checksum (image paddr + startup size, stored size - startup size)jump (startup vaddr)

Your next step is to go to the disk/network or disk/networkcompressed scenario above.

You’ll need to map the physical addresses and sizes intobank-switching as needed. Have fun and next time DON’TBANK-SWITCH YOUR ROM! Make it linear in the address space.

118 Chapter 4 � Writing an IPL Program November 3, 2006

Page 139: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

IPL structureIn this section, we’ll examine the structure of the IPL source treedirectory, and also the structure of a typical IPL source file.

IPL source directory structure

The Neutrino source tree structure looks like this:

startup flashipl

boards

800fads...

bsp_working_dir/src/hardware

IPL directory structure.

Thebsp working dir/src/hardware/ipl/boards directory iswhere the IPL source code is stored for a particular board (e.g.bsp working dir/src/hardware/ipl/boards/800fads containsthe source code for the Motorola MPC8xxFADS PowerPCmotherboard.)

IPL code structure

The IPL code is structured in two stages. The first stage is written inassembly language; it sets up just enough of an environment for thesecond stage, written in C, to run. Generally, the minimum work done

November 3, 2006 Chapter 4 � Writing an IPL Program 119

Page 140: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Customizing IPLs 2006, QNX Software Systems GmbH & Co. KG.

here is to set up the DRAM controllers, initialize the various registers,and set up the chip selects so that you can address your hardware.

Generally, the IPL assembly-language source name begins with“init” (e.g. init8xx.s for the MPC8xxFADS board); the C file isalways calledmain.c.

Once your assembly-language routine has set up the minimumamount required to transfer control to the C language portion, themain() program calls the following functions in order:

image download 8250()

This function is responsible for getting the imagefrom wherever it may be located. If the image islocated in linear memory, this function isn’trequired (the image is already “downloaded”).

If you’re downloading the image from a custompiece of hardware, you should call your functionimage download hw(), where thehw part isreplaced with a descriptive name for the hardware,e.g. image download x25().

image scan() This function is given a start- and end-address tosearch for a boot image. If successful, it returns apointer to the start of the image. It’s possible tosearch within an address range that contains morethan one image. If there are multiple images, andone of them has a bad checksum, then the nextimage is used. If there are multiple images withgood checksums, the startup header is examined,and the one with the higher version number is used.Note that the scan will occuronly between thespecified addresses.

image setup() This function does the work of copying thenecessary part of the image into RAM.

120 Chapter 4 � Writing an IPL Program November 3, 2006

Page 141: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Customizing IPLs

image start() This function will jump to the start of the imageloaded into RAM, which will turn control over tothe startup program.

An example

Take themain.c from the FADS8xx system:

#include "ipl.h"

unsigned int image;

intmain (void){/** Image is located at 0x2840000* Therefore, we don’t require an image download 8250 function*/

image = image scan (0x2840000, 0x2841000);

/** Copy startup to ram; it will do any necessary work on the image*/

image setup (image);

/** Set up link register and jump to startup entry point*/

image start (image);

return (0);}

In this case, we have a linearly addressable flash memory device thatcontains the image — that’s why we don’t need theimage download 8250() function.

The next function called isimage scan(), which is given a verynarrow range of addresses to scan for the image. We give it such asmall range because weknow where the image is on this system —there’s very little point searching for it elsewhere.

Then we callimage setup() with the address that we got from theimage scan(). This copies the startup code to RAM.

November 3, 2006 Chapter 4 � Writing an IPL Program 121

Page 142: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The IPL library 2006, QNX Software Systems GmbH & Co. KG.

Finally, we callimage start() to transfer control to the startupprogram. We don’t expect this function to return — the reason wehave thereturn (0); statement is to keep the C compiler happy(otherwise it would complain about “Missing return value fromfunction main”).

Creating a new IPLTo create a new IPL, it’s best to start with one we’ve provided that’ssimilar to the type of CPU and board you have in your design.

The basic steps are:

1 Create a new directory underbsp working dir/src/hardware/ipl/boards with yourboard name.

2 Copy all files and subdirectories from a similar board into thenew directory.

3 Modify the files as appropriate.

The IPL libraryThe IPL library contains a set of routines for building a custom IPL.Here are the available library functions:

Function Description

enable cache Enable the on-chip cache (x86 only).

image download 8250() Download an image from the specifiedserial port.

image scan() Scan memory for a valid system image.

image scan ext() BIOS extension version ofimage scan().

continued. . .

122 Chapter 4 � Writing an IPL Program November 3, 2006

Page 143: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The IPL library

Function Description

image setup() Prepare an image for execution.

image setup ext() BIOS extension version ofimage setup().

image start() Transfer control to the image.

image start ext() BIOS extension version ofimage start().

int15 copy() Copy data from high (above 1M)memory to a buffer or to low (below1M) memory (x86 only).

print byte() Print a byte to video (x86 only).

print char() Print a character to video (x86 only).

print long() Print a long to video (x86 only).

print sl() Print a string, followed by a long tovideo (x86 only).

print string() Print a string to video (x86 only).

print var() Print a variable to video (x86 only).

print word() Print a word to video (x86 only).

protected mode Switch the processor to protected mode(x86 only).

uart hex8 Output an 8-bit hex number to theUART (x86 only).

uart hex16 Output a 16-bit hex number to theUART (x86 only).

uart hex32 Output a 32-bit hex number to theUART (x86 only).

uart init Initialize the on-chip UART (x86 only).

continued. . .

November 3, 2006 Chapter 4 � Writing an IPL Program 123

Page 144: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The IPL library 2006, QNX Software Systems GmbH & Co. KG.

Function Description

uart put Output a single character to the UART(x86 only).

uart string Output a NULL-terminated string to theUART (x86 only).

uart32 hex8 Output an 8-bit hex number to theUART (for 32-bit protected modeenvironment; x86 only).

uart32 hex16 Output a 16-bit hex number to theUART (for 32-bit protected modeenvironment; x86 only).

uart32 hex32 Output a 32-bit hex number to theUART (for 32-bit protected modeenvironment; x86 only).

uart32 init Initialize the on-chip UART (for 32-bitprotected mode environment; x86 only).

uart32 put Output a single character to the UART(for 32-bit protected mode environment;x86 only).

uart32 string Output a NULL-terminated string to theUART (for 32-bit protected modeenvironment; x86 only).

enable cache

enable cache

Theenable cache function takes no parameters. The function ismeant to be called before the x86 processor is switched to protectedmode. Note that the function is for a non-BIOS system.

124 Chapter 4 � Writing an IPL Program November 3, 2006

Page 145: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The IPL library

image download 8250()

unsigned int image download 8250 (port, span, address)

Downloads an image from the specified serial port (port) to thespecified address (address) using a custom protocol. On the host side,this protocol is implemented via the utilitysendnto (you may need aNULL-modem cable — the protocol uses only TX, RX, and GND).Thespan parameter indicates the offset from one port to the next porton the serial device.

image scan()

unsigned long image scan (unsigned long start, unsigned long end)

Theimage scan() function scans memory for a valid system image. Itlooks on 4K boundaries for the image identifier bytes and then does achecksum on the image.

The function scans betweenstart andend. If a valid image is found,image scan() returns the image’s address. If no valid image is found,it returns -1.

Note thatimage scan() will search forall images within the givenrange, and will pick the “best” one as described above (in the “IPLcode structure” section).

image scan ext()

unsigned long image scan ext (unsigned long start, unsigned long end)

This is a BIOS extension version of theimage scan() function. Theimage scan ext() function operates in a 16-bit real-mode environment.

image setup()

int image setup (unsigned long address)

Theimage setup() function prepares an image for execution. It copiesthe RAM-based startup code from ROM.

November 3, 2006 Chapter 4 � Writing an IPL Program 125

Page 146: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The IPL library 2006, QNX Software Systems GmbH & Co. KG.

The function takes the image’s address as its parameter and alwaysreturns 0.

image setup ext()

int image setup ext (unsigned long address)

This is a BIOS extension version of theimage setup() function. Theimage setup ext() function operates in a 16-bit real-modeenvironment and makes use of theint15 copy() function to perform itstasks on the OS image.

image start()

int image start (unsigned long address)

Theimage start() function starts the image by jumping to thestartup vaddr address as defined in the startup header.

The function should never return; if it fails, it returns -1.

image start ext()

int image start ext (unsigned long address)

This is a BIOS extension version of theimage start() function. Theimage start ext() function operates in a 16-bit real-mode environment.

int15 copy()

unsigned char int15 copy (long from, long to, long len)

Theint15 copy() function is intended for an x86 system with a BIOSrunning in real mode. The function lets you copy data from highmemory (above 1M) to a buffer or to low memory (below 1M).

Theint15 copy() function also allows functions such asimage scan()andimage setup() to perform scanning and setup of images living inhigh memory.

126 Chapter 4 � Writing an IPL Program November 3, 2006

Page 147: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The IPL library

print byte()

void print byte (int n)

Using int10, this function displays a byte to video (x86 only).

print char()

void print char (int c)

Using int10, this function displays a character to video (x86 only).

print long()

void print long (unsigned long n)

Using int10, this function displays a long to video (x86 only).

print sl()

void print sl (char *s, unsigned long n)

Using int10, this function displays to video a string, followed by along (x86 only).

print string()

void print string (char *msg)

Using int10, this function displays a string to video (x86 only).

print var()

void print var (unsigned long n, int l)

Using int10, this function displays a variable to video (x86 only).

November 3, 2006 Chapter 4 � Writing an IPL Program 127

Page 148: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The IPL library 2006, QNX Software Systems GmbH & Co. KG.

print word()

void print word (unsigned short n)

Using int10, this function displays a word to video (x86 only).

protected mode

This assembly call switches the x86 processor into protected mode.The function is for non-BIOS systems.

Upon return, the DS and ES registers will be set to selectors that canaccess the entire 4G address space. This code is designed to becompletely position-independent.

This routine must be called with a pointer to a 16-byte area ofmemory that’s used to store the GDT. The pointer is inds:ax.

The following selectors are defined:

8 Data selector for 0-4G.

16 Code selector for 0-4G.

uart hex8

This assembly call outputs an 8-bit hex number to the UART. Thefunction is set up for a 16-bit real-mode environment (x86 only).

On entry:

DX UART base port.

AL Value to output.

uart hex16

This assembly call outputs a 16-bit hex number to the UART. Thefunction is set up for a 16-bit real-mode environment (x86 only).

On entry:

128 Chapter 4 � Writing an IPL Program November 3, 2006

Page 149: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The IPL library

DX UART base port.

AX Value to output.

uart hex32

This assembly call outputs a 32-bit hex number to the UART. Thefunction is set up for a 16-bit real-mode environment (x86 only).

On entry:

DX UART base port.

EAX Value to output.

uart init

This assembly call initializes the on-chip UART to 8 data bits, 1 stopbit, and no parity (8250 compatible). The function is set up for a16-bit real-mode environment (x86 only).

On entry:

EAX Baud rate.

EBX Input clock in Hz (normally 1843200).

ECX UART internal divisor (normally 16).

DX UART base port.

uart put

This assembly call outputs a single character to the UART. Thefunction is set up for a 16-bit real-mode environment (x86 only).

On entry:

AL Character to output.

DX UART base port.

November 3, 2006 Chapter 4 � Writing an IPL Program 129

Page 150: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The IPL library 2006, QNX Software Systems GmbH & Co. KG.

uart string

This assembly call outputs a NULL-terminated string to the UART.The function is set up for a 16-bit real-mode environment (x86 only).

On entry:

DX UART base port address, return address, string.

For example:

mov UART BASE PORT, %dxcall uart string.ascii "string\r\n"...

uart32 hex8

This assembly call outputs an 8-bit hex number to the UART. Thefunction is set up for a 32-bit protected-mode environment (x86 only).

On entry:

DX UART base port.

AL Value to output.

uart32 hex16

This assembly call outputs a 16-bit hex number to the UART. Thefunction is set up for a 32-bit protected-mode environment (x86 only).

On entry:

DX UART base port.

AX Value to output.

130 Chapter 4 � Writing an IPL Program November 3, 2006

Page 151: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The IPL library

uart32 hex32

This assembly call outputs a 32-bit hex number to the UART. Thefunction is set up for a 32-bit protected-mode environment (x86 only).

On entry:

DX UART base port.

EAX Value to output.

uart32 init

This assembly call initializes the on-chip UART to 8 data bits, 1 stopbit, and no parity (8250 compatible). The function is set up for a32-bit protected-mode environment (x86 only).

On entry:

EAX Baud rate.

EBX Input clock in Hz (normally 1843200).

ECX UART internal divisor (normally 16).

DX UART base port.

uart32 put

This assembly call outputs a single character to the UART. Thefunction is set up for a 32-bit protected-mode environment (x86 only).

On entry:

AL Character to output.

DX UART base port.

November 3, 2006 Chapter 4 � Writing an IPL Program 131

Page 152: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The IPL library 2006, QNX Software Systems GmbH & Co. KG.

uart32 string

This assembly call outputs a NULL-terminated string to the UART.The function is set up for a 32-bit protected-mode environment (x86only).

On entry:

DX UART base port address, return address, string.

For example:

mov UART BASE PORT, %dxcall uart string.ascii "string\r\n"...

132 Chapter 4 � Writing an IPL Program November 3, 2006

Page 153: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Chapter 5

Customizing Image StartupPrograms

In this chapter. . .Introduction 135Anatomy of a startup program 136Structure of the system page139Callout information 176The startup library 180Writing your own kernel callout 209PPC chips support 216

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 133

Page 154: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 155: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

IntroductionThe first program in a bootable Neutrino image is astartup programwhose purpose is to:

1 Initialize the hardware.

2 Initialize the system page.

3 Initialize callouts.

4 Load and transfer control to the next program in the image.

You can customize Neutrino for different embedded-system hardwareby changing the startup program.

Initialize hardwareYou do basic hardware initialization at this time. The amount ofinitialization done here will depend on what was done in the IPLloader.

Note that you don’t need to initialize standard peripheral hardwaresuch as an IDE interface or the baud rate of serial ports. This will bedone by the drivers that manage this hardware when they’re started.

Initialize system pageInformation about the system is collected and placed in an in-memorydata structure called the system page. This includes information suchas the processor type, bus type, and the location and size of availablesystem RAM.

The kernel as well as applications can access this information as aread-only data structure. The hardware/system-specific code tointerrogate the system for this information is confined to the startupprogram. This code doesn’t occupy any system RAM after it has run.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 135

Page 156: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Anatomy of a startup program 2006, QNX Software Systems GmbH & Co. KG.

Initialize calloutsAnother key function of the startup code is that the system pagecallouts arebound in. These callouts are used by the kernel toperform various hardware- and system-specific functions that must bespecified by the systems integrator.

Anatomy of a startup programEach release of Neutrino ships with a growing number of startupprograms for many boards. To find out what boards we currentlysupport, please refer to the following sources:

� theboards directory underbsp working dir/src/hardware/startup.

� QNX docs (BSP docs as well asstartup-* entries inUtilitiesReference).

� the Developer Support Center area of our website(www.qnx.com).

Each startup program is provided as a ready-to-execute binary. Fullsource and a Makefile are also available so you can customize andremake each one. The files are kept in this directory structure asillustrated:

136 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 157: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Anatomy of a startup program

flashstartupipl

boards

403evb800fadsbios

ddb-vrc4373explr2mbx800p5064ppaq

vme603vr41xx...

bootfile

mipsbemipsleppcbex86

bsp_working_dir/src/hardware

Startup directory structure.

Generally speaking, the following directory structure applies in thestartup source for thestartup-boardname module:

bsp working dir/src/hardware/startup/boards/boardname

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 137

Page 158: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Anatomy of a startup program 2006, QNX Software Systems GmbH & Co. KG.

Structure of a startup programEach startup program consists of amain() with the following structure(in pseudo code):

Global variables

main(){

Call add callout array()

Argument parsing (Call handle common option())

Call init raminfo()Remove ram used by modules in the image

if (virtual) Call init mmu() to initialize the MMU

Call init intrinfo()Call init qtime()Call init cacheattr()Call init cpuinfo()

Set hardware machine name

Call init system private()

Call print syspage() to print debugging output}

You should examine the commented source for each of the functionswithin the library to see if you need to replace a library function withone of your own.

Creating a new startup programTo create a new startup program, you should make a new directoryunderbsp working dir/src/hardware/startup/boards andcopy the files from one of the existing startup program directories.For example, to create something close to the Intel PXA250TMDPboard, calleddaytona, you would:

1 cd bsp working dir/src/hardware/startup/boards

138 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 159: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

2 mkdir daytona

3 cp -r pxa250tmdp/* daytona

4 cd daytona

5 make clean

For descriptions of all the startup functions, see “The startup library”section in this chapter.

Structure of the system pageAs mentioned earlier (see the section “Initialize system page”), one ofthe main jobs of the startup program is to initialize thesystem page.

The system page structurestruct syspage entry is defined inthe include file<sys/syspage.h>. The structure contains a numberof constants, references to other structures, and a union sharedbetween the various processor platforms supported by Neutrino.

It’s important to realize that there are two ways of accessing the datawithin the system page, depending on whether you’re adding data tothe system page at startup time or reading data from the system pagelater (as would be done by an application program running after thesystem has been booted). Regardless of which access method you use,the fields are the same.

Here’s the system page structure definition, taken from<sys/syspage.h>:

/** contains at least the following:*/

struct syspage entry {uint16 t size;uint16 t total size;uint16 t type;uint16 t num cpu;syspage entry info system private;syspage entry info asinfo;syspage entry info hwinfo;syspage entry info cpuinfo;syspage entry info cacheattr;

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 139

Page 160: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

syspage entry info qtime;syspage entry info callout;syspage entry info callin;syspage entry info typed strings;syspage entry info strings;syspage entry info intrinfo;syspage entry info smp;syspage entry info pminfo;

union {struct x86 syspage entry x86;struct ppc syspage entry ppc;struct mips syspage entry mips;struct arm syspage entry arm;struct sh syspage entry sh;

} un;};

Note that some of the fields presented here may be initialized by thecode provided in the startup library, while some may need to beinitialized by code provided by you. The amount of initializationrequired really depends on the amount of customization that you needto perform.

Let’s look at the various fields.

sizeThe size of the system page entry. This member is set automaticallyby the library.

total sizeThe size of the system page entryplus the referenced substructures;effectively the size of the entire system page database. This memberis set automatically by the library and adjusted later (grown) asrequired by other library calls.

typeThis is used to indicate the CPU family for determining which unionmember in theun element to use. Can be one of:

140 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 161: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

SYSPAGEARM, SYSPAGEMIPS, SYSPAGEPPC, SYSPAGESH4, orSYSPAGEX86.

This member is set automatically by the library.

num cpuThenum cpu member indicates the number of CPUs present on thegiven system. This member is initialized to the default value1 in thelibrary and adjusted by the library callinit smp() if additionalprocessors are detected.

system privateThesystem private area contains information that the operatingsystem needs to know when it boots. This is filled in by the startuplibrary’s init system private() function.

Member Description

user cpupageptr User address (R/O) forcpupage pointer

user syspageptr User address (R/O) forsyspage pointer

kern cpupageptr Kernel address (R/W) forcpupage pointer

kern syspageptr Kernel address (R/W) forsyspage pointer

pagesize Granularity of the OS memory allocator(usually 16 in physical mode or 4096 in virtualmode).

asinfoTheasinfo section consists of an array of the following structure.Each entry describes the attributes of one section of address space onthe machine.

struct asinfo entry {uint64 t start;uint64 t end;

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 141

Page 162: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

uint16 t owner;uint16 t name;uint16 t attr;uint16 t priority;int (*alloc checker)(struct syspage entry * sp,

uint64 t * base,uint64 t * len,size t size,size t align);

uint32 t spare;};

Member Description

start Gives the first physical address of the range beingdescribed.

end Gives the last physical address of the range beingdescribed. Note that this is the actual last byte,not onebeyond the end.

owner An offset from the start of the section giving the ownerof this entry (its “parent” in the tree). It’s set toAS NULL OFFif the entry doesn’t have an owner (it’sat the “root” of the address space tree).

name An offset from the start of thestrings section of thesystem page giving the string name of this entry.

attr Contains several bits affecting the address range (seebelow).

priority Indicates the speed of the memory in the addressrange. Lower numbers mean slower memory. ThemacroAS PRIORITY DEFAULT is defined to use adefault value for this field (currently defined as 100).

142 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 163: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

Thealloc checker isn’t currently used. When implemented, it will letyou provide finer-grain control over how the system allocates memory(e.g. making sure that ISA memory used for DMA doesn’t cross 64Kboundaries.).

The attr field

Theattr field can have the following bits:

#define AS ATTR READABLE 0x0001

Address range is readable.

#define AS ATTR WRITABLE 0x0002

Address range is writable.

#define AS ATTR CACHABLE 0x0004

Address range can be cached (this bit should be off if you’reusing device memory).

#define AS ATTR KIDS 0x0010

Indicates that there are other entries that use this one as theirowner. Note that the library turns on this bit automatically; youshouldn’t specify it when creating the section.

#define AS ATTR CONTINUED 0x0020

Indicates that there are multiple entries being used to describeone “logical” address range. This bit will be on in all but thelast one. Note that the library turns on this bit and uses itinternally; you shouldn’t specify it when creating the section.

Address space trees

Theasinfo section contains trees describing address spaces (whereRAM, ROM, flash, etc. are located).

The general hierarchy for address spaces is:

/memory/memclass/....

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 143

Page 164: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

Or:

/io/memclass/....

Or:

/memory/io/memclass/....

Thememory or io indicates whether this is describing something inthe memory or I/O address space (the third form is used on a machinewithout separate in/out instructions and where everything ismemory-mapped).

Thememclass is something like:ram, rom, flash, etc. Below thatwould be further classifications, allowing the process manager toprovide typed memory support.

hwinfoThehwinfo area contains information about the hardware platform(type of bus, devices, IRQs, etc). This is filled in by the startuplibrary’s init hwinfo() function.

This is one of the more elaborate sections of the Neutrino systempage. Thehwinfo section doesn’t consist of a single structure or anarray of the same type. Instead, it consists of a sequence ofsymbolically “tagged” structures that as a whole describe thehardware installed on the board. The following types and constantsare all defined in the<hw/sysinfo.h> file.

Thehwinfo section doesn’t have to describeall the hardware. Forinstance, the startup program doesn’t have to do PCI queries todiscover what’s been plugged into any slots if it doesn’t want to. It’sup to you as the startup implementor to decide how full to make thehwinfo description. As a rule, if a component is hardwired on yourboard, consider putting it intohwinfo.

144 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 165: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

Tags

Each structure (ortag) in the section starts the same way:

struct hwi prefix {uint16 t size;uint16 t name;

};

Thesize field gives the size, in 4-byte quantities, of the structure(including thehwi prefix).

Thename field is an offset into thestrings section of the system page,giving a zero-terminated string name for the structure. It might seemwasteful to use an ASCII string rather than an enumerated type toidentify the structure, but it actually isn’t. The system page istypically allocated in 4K granularity, so the extra storage required bythe strings doesn’t cost anything. On the upside, people can add newstructures to the section without requiring QNX Software Systems toact as a central repository for handing out enumerated type values.When processing the section, code should ignore any tag that itdoesn’t recognize (using thesize field to skip over it).

Items

Each piece of hardware is described by a sequence of tags. Thisconglomeration of tags is known as anitem. Each item describes onepiece of hardware. The first tag in each item always starts out with thefollowing structure (note that the first thing in it is ahwi prefixstructure):

struct hwi item {struct hwi prefix prefix;uint16 t itemsize;uint16 t itemname;uint16 t owner;uint16 t kids;

};

Theitemsize field gives the distance, in 4-byte quantities, until thestart of the next item tag.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 145

Page 166: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

Theitemname gives an offset into thestrings section of the systempage for the name of the item being described. Note that this differsfrom theprefix.name field, which tells what type of the structure thehwi item is buried in.

Theowner field gives the offset, in bytes, from the start of thehwinfosection to the item that this item is owned by. This field allows groupsof items to be organized in a tree structure, similar to a filesystemdirectory hierarchy. We’ll see how this is used later. If the item is atthe root of a tree of ownership, theowner field is set toHWI NULL OFF.

Thekids field indicates how many other items call this one “daddy.”

The code currently requires that the tag name of any item structuremust start with an uppercase letter; nonitem tags have to start with alowercase letter.

Device trees

Thehwinfo section contains trees describing the various hardwaredevices on the board.

The general hierarchy for devices is:

/hw/bus/devclass/device

where:

hw the root of the hardware tree.

bus the bus the hardware is on (pci, eisa, etc.).

devclass the general class of the device (serial, rtc, etc.).

device the actual chip implementing the device (8250,mc146818, etc.).

146 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 167: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

Building the section

Two basic calls in the startup library are used to add things to thehwinfo section:

� hwi alloc tag()

� hwi alloc item()

void *hwi alloc tag(const char *name, unsigned size, unsigned align);

This call allocates a tag of sizesize with the tag name ofname. If thestructure contains any 64-bit integer fields within it, thealign fieldshould be set to8; otherwise, it should be4. The function returns apointer to memory that can be filled in as appropriate. Note that thehwi prefix fields are automatically filled in by thehwi alloc tag()function.

void *hwi alloc item(const char *name, unsigned size,unsigned align, const char *itemname,unsigned owner);

This call allocates anitem structure. The first three parameters are thesame as in thehwi alloc tag() function.

Theitemname andowner parameters are used to set theitemname andowner fields of thehwi item structure. Allhwi alloc tag() calls doneafter ahwi alloc item() call are assumed to belong to that item and theitemsize field is adjusted appropriately.

Here are the general steps for building an item:

1 Call hwi alloc item() to build a top-level item (one with theowner field to beHWI NULL OFF).

2 Add whatever other tag structures you want in the item.

3 Usehwi alloc item() to start a new item. This item could beeither another top-level one or a child of the first.

Note that you can build the items in any order you wish, provided thatthe parent is builtbefore the child.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 147

Page 168: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

When building a child item, suppose you’ve remembered its owner ina variable or you know only its item name. In order to find out thecorrect value of theowner parameter, you can use the followingfunction (which is defined in the C library, since it’s useful for peopleprocessing the section):

unsigned hwi find item(unsigned start, ...);

Thestart parameter indicates where to start the search for the givenitem. For an initial call, it should be set toHWI NULL OFF. If theitem found isn’t the one wanted, then the return value from the firsthwi find item() is used as thestart parameter of the second call. Thesearch will pick up where it left off. This can be repeated as manytimes as required (the return value from the second call going into thestart parameter of the third, etc). The item being searched is identifiedby a sequence ofchar * parameters followingstart. The sequence isterminated by a NULL. The last string before the NULL is thebottom-levelitemname being searched for, the string in front of that isthe name of the item that owns the bottom-level item, etc.

For example, this call finds the first occurrence of an item called“foobar”:

item off = hwi find item(HWI NULL OFF, "foobar", NULL);

The following call finds the first occurrence of an item called “foobar”that’s owned by “sam”:

item off = hwi find item(HWI NULL OFF, "sam", "foobar", NULL);

If the requested item can’t be found,HWI NULL OFFis returned.

Other functions

The following functions are in the C library for use in processing thehwinfo section:

unsigned hwi tag2off(void *);

Given a pointer to the start of a tag, return the offset, in bytes,from the beginning of the start of thehwinfo section.

148 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 169: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

void *hwi off2tag(unsigned);

Given an offset, in bytes, from the start of thehwinfo section,return a pointer to the start of the tag.

unsigned hwi find tag(unsigned start, int curr item,const char *tagname);

Find the tag namedtagname. Thestart parameter works thesame as the one inhwi find item(). If curr item is nonzero, thesearch stops at the end of the current item (whatever item thestart parameter points into). Ifcurr item is zero, the searchcontinues until the end of the section. If the tag isn’t found,HWI NULL OFFis returned.

Defaults

Beforemain() is invoked in the startup program, the library adds someinitial entries to serve as a basis for later items.

HWI TAG INFO() is a macro defined in the<startup.h> headerand expands out to the threename, size, align parameters forhwi alloc tag() andhwi alloc item() based on some clever macronames.

voidhwi default() {

hwi tag *tag;hwi tag *tag;

hwi alloc item(HWI TAG INFO(group), HWI ITEM ROOT AS,HWI NULL OFF);

tag = hwi alloc item(HWI TAG INFO(group), HWI ITEM ROOT HW,HWI NULL OFF);

hwi alloc item(HWI TAG INFO(bus), HWI ITEM BUS UNKNOWN,hwi tag2off(tag));

loc = hwi find item(HWI NULL OFF, HWI ITEM ROOT AS, NULL);

tag = hwi alloc item(HWI TAG INFO(addrspace),HWI ITEM AS MEMORY, loc);

tag->addrspace.base = 0;tag->addrspace.len = (uint64 t)1 << 32;#ifndef X86

loc = hwi tag2off(tag);#endif

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 149

Page 170: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

tag = hwi alloc item(HWI TAG INFO(addrspace), HWI ITEM AS IO,loc);

tag->addrspace.base = 0;#ifdef X86

tag->addrspace.len = (uint64 t)1 << 16;#else

tag->addrspace.len = (uint64 t)1 << 32;#endif

}

Predefined items and tags

These are the items defined in thehw/sysinfo.h file. Note thatyou’re free to create additional items — these are just what we neededfor our own purposes. You’ll notice that all things are defined asHWI TAG NAME *, HWI TAG ALIGN *, andstruct hwi *. Thenames are chosen that way so that theHWI TAG INFO() macro instartup works properly.

Group item

#define HWI TAG NAME group "Group"#define HWI TAG ALIGN group (sizeof(uint32 t))struct hwi group {

struct hwi item item;};

The Group item is used when you wish to group a number of itemstogether. It serves the same purpose as a directory in a filesystem. Forexample, thedevclass level of the/hw tree would use a Group item.

Bus item

#define HWI TAG NAME bus "Bus"#define HWI TAG ALIGN bus (sizeof(uint32))struct hwi bus {

struct hwi item item;};

The Bus item tells the system about a hardware bus. Item names canbe (but are not limited to):

150 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 171: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

#define HWI ITEM BUS PCI "pci"#define HWI ITEM BUS ISA "isa"#define HWI ITEM BUS EISA "eisa"#define HWI ITEM BUS MCA "mca"#define HWI ITEM BUS PCMCIA "pcmcia"#define HWI ITEM BUS UNKNOWN "unknown"

Device item

#define HWI TAG NAME device "Device"#define HWI TAG ALIGN device (sizeof(uint32))struct hwi device {

struct hwi item item;uint32 t pnpid;

};

The Device item tells the system about an individual device (thedevice level from the “Trees” section — thedevclass level is donewith a “Group” tag). Thepnpid field is the Plug and Play deviceidentifier assigned by Microsoft.

location tag

#define HWI TAG NAME location "location"#define HWI TAG ALIGN location (sizeof(uint64))struct hwi location {

struct hwi prefix prefix;uint32 t len;uint64 t base;uint16 t regshift;uint16 t addrspace;

};

Note thatlocation is a simple tag, not an item. It gives the locationof the hardware device’s registers, whether in a separate I/O space ormemory-mapped. There may be more than one of these tags in anitem description if there’s more than one grouping of registers.

Thebase field gives the physical address of the start of the registers.Thelen field gives the length, in bytes, of the registers. Theregshifttells how much each register access is shifted by. If a register is

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 151

Page 172: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

documented atoffset of a device, then the driver will actually accessoffsetoffset2ˆregshift to get to that register.

Theaddrspace field is an offset, in bytes, from the start of theasinfosection. It should identify either thememory or io address space itemto tell whether the device registers are memory-mapped.

irq tag

#define HWI TAG NAME irq "irq"#define HWI TAG ALIGN irq (sizeof(uint32))struct hwi irq {

struct hwi prefix prefix;uint32 t vector;

};

Note that this is a simple tag, not an item. Thevector field gives thelogical interrupt vector number of the device.

diskgeometry tag

#define HWI TAG NAME diskgeometry "diskgeometry"#define HWI TAG ALIGN diskgeometry (sizeof(uint32))struct hwi diskgeometry {

struct hwi prefix prefix;uint8 t disknumber;uint8 t sectorsize; /* as a power of two */uint16 t heads;uint16 t cyls;uint16 t sectors;uint32 t nblocks;

};

Note that this is a simple tag, not an item. This is an x86-onlymechanism used to transfer the information from the BIOS about diskgeometry.

pad tag

#define HWI TAG NAME pad "pad"#define HWI TAG ALIGN pad (sizeof(uint32))struct hwi pad {

struct hwi prefix prefix;};

152 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 173: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

Note that this is a simple tag, not an item. This tag is used whenpadding must be inserted to meet the alignment constraints for thesubsequent tag.

cpuinfoThecpuinfo area contains information about each CPU chip in thesystem, such as the CPU type, speed, capabilities, performance, andcache sizes. There are as many elements in thecpuinfo structure asthenum cpu member indicates (e.g. on a dual-processor system, therewill be two cpuinfo entries).

This table is filled automatically by the library functioninit cpuinfo().

Member Description

cpu This is a number that represents the type of CPU.Note that this number will vary with the CPUarchitecture. For example, on the x86 processorfamily, this number will be the processor chipnumber (e.g.386, 586). On MIPS and PowerPC, thisis filled with the contents of the version registers.

speed Contains the MHz rating of the processor. Forexample, on a 300 MHz MIPS R4000, this numberwould be300.

flags See below.

name Contains an index into thestrings member in thesystem page structure. The character string at thespecified index contains an ASCII, NULL-terminatedmachine name (e.g. on a MIPS R4000 it will be thestring “R4000”).

continued. . .

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 153

Page 174: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

Member Description

ins cache Contains an index into thecacheattr array, describedbelow. This index points to the first definition in a listfor theinstruction cache.

data cache Contains an index into thecacheattr array, describedbelow. This index points to the first definition in a listfor thedata cache.

Theflags member contains a bitmapped indication of the capabilitiesof the CPU chip. Note that the prefix for the manifest constantindicates which CPU family it applies to (e.g.PPC indicates thisconstant is for use by the PowerPC family of processors). In the caseof no prefix, it indicates that it’s generic to any CPU.

Here are the constants and their defined meanings:

This constant: Means that the CPUhas or supports:

CPU FLAG FPU Floating Point Unit(FPU).

CPU FLAG MMU Memory ManagementUnit (MMU), and theMMU is enabled (i.e.the CPU is currently invirtual addressingmode).

X86 CPU CPUID CPUID instruction.

X86 CPU RDTSC RDTSC instruction.

X86 CPU INVLPG INVLPG instruction.

X86 CPU WP WP bit in theCR0register.

continued. . .

154 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 175: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

This constant: Means that the CPUhas or supports:

X86 CPU BSWAP BSWAP instruction.

X86 CPU MMX MMX instructions.

X86 CPU CMOV CMOVxx instructions.

X86 CPU PSE Page size extensions.

X86 CPU PGE TLB (TranslationLookaside Buffer)global mappings.

X86 CPU MTRR MTRR (Memory TypeRange Register)registers.

X86 CPU SEP SYSENTER/SYSEXITinstructions.

X86 CPU SIMD SIMD instructions.

X86 CPU FXSR FXSAVE/FXRSTORinstructions.

X86 CPU PAE Extended addressing.

PPCCPU EAR EAR (External AddressRegister) register.

PPCCPU HW HT Hardware hash table.

PPCCPU HW POW Power management.

PPCCPU FPREGS Floating point registers.

PPCCPU SW HT Software hash table.

PPCCPU ALTIVEC AltiVec extensions.

PPCCPU XAEN Extended addressing.

PPCCPU SW TLBSYNC Sync TLBs.

continued. . .

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 155

Page 176: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

This constant: Means that the CPUhas or supports:

PPCCPU TLB SHADOW Shadow registers inTLB handler.

PPCCPU DCBZ NONCOHERENT DCBZ problems.

MIPS CPU FLAG PFNTOPSHIFTMASK Construct TLB entries.

MIPS CPU FLAG MAX PGSIZEMASK Maximum number ofmasks.

MIPS CPU FLAGS MAX PGSIZESHIFT Maximum number ofshifts.

MIPS CPU FLAG L2 PAGE CACHE OPS L2 cache.

MIPS CPU FLAG 64BIT 64-bit registers.

MIPS CPU FLAG 128BIT 128-bit registers.

MIPS CPU FLAG SUPERVISOR Supervisor mode.

MIPS CPU FLAG NO WIRED No wired register.

MIPS CPU FLAG NO COUNT No count register.

syspage entry cacheattrThecacheattr area contains information about the configuration of theon-chip and off-chip cache system. It also contains thecontrol()callout used for cache control operations. This entry is filled by thelibrary routinesinit cpuinfo() andinit cacheattr().

Note thatinit cpuinfo() deals with caches implemented on the CPUitself; init cacheattr() handles board-level caches.

Each entry in thecacheattr area consists of the following:

156 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 177: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

Member Description

next index to next lower level entry

line size size of cache line in bytes

num lines number of cache lines

flags See below

control callout supplied by startup code (see below).

The total number of bytes described by a particularcacheattr entry isdefined byline size � num lines.

Theflags parameter is a bitmapped variable consisting of thefollowing:

This constant: Means that the cache:

CACHE FLAG INSTR Holds instructions.

CACHE FLAG DATA Holds data.

CACHE FLAG UNIFIED Holds both instructions anddata.

CACHE FLAG SHARED Is shared between multipleprocessors in an SMP system.

CACHE FLAG SNOOPED Implements a bus-snoopingprotocol.

CACHE FLAG VIRTUAL Is virtually tagged.

CACHE FLAG WRITEBACK Does write-back, notwrite-through.

CACHE FLAG CTRL PHYS Takes physical addresses via itscontrol() function.

continued. . .

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 157

Page 178: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

This constant: Means that the cache:

CACHE FLAG SUBSET Obeys thesubset property. Thismeans that one cache levelcaches something from anotherlevel as well. As you go up eachcache level, if something is in aparticular level, it will also be inall the lower-level caches aswell. This impacts the flushingoperations of the cache in that a“subsetted” level can beeffectively “ignored” by thecontrol() function, since itknows that the operation will beperformed on the lower-levelcache.

CACHE FLAG NONCOHERENT Is noncoherent on SMP.

CACHE FLAG NONISA Doesn’t obey ISA cacheinstructions.

Thecacheattr entries are organized in a linked list, with thenextmember indicating the index of the next lower cache entry. This wasdone because some architectures will have separate instruction anddata caches at one level, but a unified cache at another level. Thislinking allows the system page to efficiently contain the information.Note that the entry into thecacheattr tables is done through thecpuinfo’s ins cache anddata cache. Since thecpuinfo is an arrayindexed by the CPU number for SMP systems, it’s possible toconstruct a description of caches for CPUs with different cachearchitectures. Here’s a diagram showing a two-processor system, withseparate L1 instruction and data caches as well as a unified L2 cache:

158 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 179: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

L1instruction

cache

Memory

L1datacache

L2 unified

L1instruction

cache

L1datacache

L2 unified

CPU 1 CPU 2

Two-processor system with separate L1 instruction and data caches.

Given the above memory layout, here’s what thecpuinfo andcacheattr fields will look like:

/** CPUINFO*/

cpuinfo [0].ins cache = 0;cpuinfo [0].data cache = 1;

cpuinfo [1].ins cache = 0;cpuinfo [1].data cache = 1;

/** CACHEATTR*/

cacheattr [0].next = 2;cacheattr [0].linesize = linesize;cacheattr [0].numlines = numlines;cacheattr [0].flags = CACHE FLAG INSTR;

cacheattr [1].next = 2;cacheattr [1].linesize = linesize;cacheattr [1].numlines = numlines;

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 159

Page 180: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

cacheattr [1].flags = CACHE FLAG DATA;

cacheattr [2].next = CACHE LIST END;cacheattr [2].linesize = linesize;cacheattr [2].numlines = numlines;cacheattr [2].flags = CACHE FLAG UNIFIED;

Note that the actual values chosen forlinesize andnumlines will, ofcourse, depend on the actual configuration of the caches present onthe system.

syspage entry qtimeTheqtime area contains information about the timebase present on thesystem, as well as other time-related information. The library routineinit qtime() fills these data structures.

Member Description

intr Contains the interrupt vector that the clock chipuses to interrupt the processor.

boot time Seconds since Jan 1 1970 00:00:00 GMT whenthe system was booted.

nsec This 64-bit field holds the number ofnanoseconds since the system was booted.

nsec tod adjust When added to thensec field, this field gives thenumber of nanoseconds from the start of theepoch (1970).

nsec inc Number of nanoseconds deemed to have elapsedeach time the clock triggers an interrupt.

adjust Set to zero at startup — contains any currenttimebase adjustment runtime parameters (asspecified by the kernel callClockAdjust()).

timer rate Used in conjunction withtimer scale (seebelow).

continued. . .

160 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 181: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

Member Description

timer scale See below.

timer load Timer chip divisor value. The startup programleaves this zero. The kernel sets it based on thelastClockPeriod() andtimer rate/timer scalevalues to a number, which is then put into thetimer chip by thetimer load/timer reloadkernel callouts.

cycles per sec For ClockCycles().

epoch Currently set to 1970, but not used.

flags Indicates when timer hardware is specific toCPU0.

Thensec field is always monotonically increasing and is neveraffected by setting the current time of day viaClockTime() orClockAdjust(). Since bothnsec andnsec tod adjust are modified inthe kernel’s timer interrupt handler and are too big to load in anatomic read operation, to inspect them you must either:

� disable interrupts

or:

� get the value(s) twice and make sure that they haven’t changedbetween the first and second read.

The parameterstimer rate andtimer scale relate to the externalcounter chip’s input frequency, in Hz, as follows:

1

timer_scaletimer_rate x 10

Yes, this does imply thattimer scale is a negative number. The goalwhen expressing the relationship is to maketimer rate as large as

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 161

Page 182: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

possible in order to maximize the number of significant digitsavailable during calculations.

For example, on an x86 PC with standard hardware, the values wouldbe838095345UL for thetimer rate and-15 for thetimer scale. Thisindicates that the timer value is specified in femtoseconds (the-15

means “ten to the negative fifteen”); the actual value is 838,095,345femtoseconds (approximately 838 nanoseconds).

If you need to change the number ofnsecs that the OS adds to thetime when a tick fires, you can manually adjust theSYSPAGEENTRY (qtime)nsec inc value.

The idea is to adjust for differences between the clock interval and thereal expired time. The closer they become the less need there is forClockAdjust() calls.

What you’ll need to do is find out the physical address of the syspage.If it’s already innsec inc you won’t need to modify startup. If not,modify startup to put it there. Then use themmap device memory()function to make the physical address of the syspage writable. That is,get the offset to the read-only page, and map a new block of memoryto the address.

You could giveClockAdjust() a value of 0 for the number of ticks, toindicate that you want to make this adjustment “permanent”. If youdon’t want to do that, you can give theClockAdjust() function themaximum possible value fortick count.

When you call and modifynsec inc, you overwrite theClockPeriod()function. Thetimer rate andtimer scale fields are used as the inputfrequency to the clock hardware. The code uses these fields and therequested tick rate to calculate the number of input frequency clocksto count before generating an interrupt. The number of inputfrequency clocks that are counted, combined withtimer rate andtimer scale provides thensec inc value. For example:

timer load = requested ticksize / (timer rate ** timer scale)

nsec inc = timer load * (timer rate ** timer scale)

Thensec inc value is used to adjust the time of day when the clockinterrupt goes off.

162 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 183: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

The changed value inClockPeriod() is used to determine the newticksize.

calloutThecallout area is where various callouts get bound into. Thesecallouts allow you to “hook into” the kernel and gain control when agiven event occurs. The callouts operate in an environment similar tothat of an interrupt service routine — you have a very limited stack,and you can’t invoke any kernel calls (such as mutex operations, etc.).On standard hardware platforms (MIPS and PowerPC eval boards,x86-PC compatibles), you won’t have to supply any functionality —it’s already provided by the startup code we supply.

Member Description

reboot Used by the kernel to reset the system.

power Provided for power management.

timer loadtimer reloadtimer value

The kernel uses thesetimer * callouts to dealwith the hardware timer chip.

debug Used by the kernel when it wishes to interactwith a serial port, console, or other device (e.g.when it needs to print out some internaldebugging information or when there’s a fault).

For details about the characteristics of the callouts, please see thesections “Callout information” and “Writing your own kernel callout”later in this chapter.

callinFor internal use.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 163

Page 184: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

typed stringsThetyped strings area consists of several entries, each of which is anumber and a string. The number is 4 bytes and the string isNULL-terminated as per C. The number in the entry corresponds to aparticular constant from the system include file<confname.h> (seethe C functionconfname() for more information).

Generally, you wouldn’t access this member yourself; the variousinit *() library functions put things into the typed strings literal poolthemselves. But if you need to add something, you can use thefunction calladd typed string() from the library.

stringsThis member is a literal pool used for nontyped strings. Users of thesestrings would typically specify an index intostrings (for example,cpuinfo’s name member).

Generally, you wouldn’t access this member yourself; the variousinit *() library functions put things into the literal pool themselves.But if you need to add something, you can use the function calladd string() from the library.

intrinfoTheintrinfo area is used to store information about the interruptsystem. It also contains the callouts used to manipulate the interruptcontroller hardware.

This area is automatically filled in by the library routineinit intrinfo().

If you need to override some of the defaults provided byinit intrinfo(), or if the function isn’t appropriate for your customenvironment, you can calladd interrupt array() directly with a tableof the following format:

164 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 185: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

In all probability, youwill need to modify this for non-x86 platforms.☞

Member Description

vector base The base number of the logical interrupt numbersthat programs will use (e.g. the interrupt vectorpassed toInterruptAttach()).

num vectors The number of vectors starting atvector basedescribed by this entry.

cascade vector If this interrupt entry describes a set of interruptsthat are cascaded into another interruptcontroller, then this variable contains the logicalinterrupt number that this controller cascadesinto.

cpu intr base The association between this set of interrupts andthe CPU’s view of the source of the interrupt (seebelow).

cpu intr stride The spacing between interrupt vector entries forinterrupt systems that do autovectoring. On anx86 platform with the standard 8259 controllersetup, this is the value 1, meaning that theinterrupt vector corresponding to the hardwareinterrupt sources is offset by 1 (e.g. interruptvector 0 goes to interrupt 0x30, interrupt vector 1goes to interrupt 0x31, and so on). On non-x86systems it’s usually 0, because those interruptsystems generally don’t do autovectoring. Avalue of 0 indicates that it’s not autovectored.

flags Used by the startup code when generating thekernel’s interrupt service routine entry points.See below underINTR FLAG * andPPCINTR FLAG *.

continued. . .

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 165

Page 186: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

Member Description

id A code snippet that gets copied into the kernel’sinterrupt service routine used to identify thesource of the interrupt, in case of multiplehardware events being able to trigger oneCPU-visible interrupt. Further modified by theINTR GENFLAG * flags, defined below.

eoi A code snippet that gets copied into the kernel’sinterrupt service routine that provides theEOI(End Of Interrupt) functionality. This codesnippet is responsible for telling the controllerthat the interrupt is done and for unmasking theinterrupt level. For CPU fault-as-an-interrupthandling,eoi identifies the cause of the fault.

mask An outcall to mask an interrupt source at thehardware controller level. The numbers passed tothis function are the interrupt vector numbers(starting at 0 tonum vectors - 1).

unmask An outcall to unmask an interrupt source at thehardware controller level. Same vector numbersasmask, above.

config Provides configuration information on individualinterrupt levels. Passed the system page pointer(1st argument), a pointer to this interrupt infoentry (2nd argument), and the zero-basedinterrupt level. Returns a bitmask; seeINTR CONFIG FLAG* below.

patch data Provides information about patched data. Thepatched data is passed to thepatcher() routinethat gets called once for each callout in astartup intrinfo() structure.

166 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 187: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

Each group of callouts (i.e.id, eoi, mask, unmask) for each level ofinterrupt controller deals with a set of interrupt vectors that start at 0(zero-based). Set the callouts for each level of interruptionaccordingly.

Interrupt vector numbers are passed without offset to the calloutroutines. The association between the zero-based interrupt vectors thecallouts use and the system-wide interrupt vectors is configuredwithin the startup-intrinfo structures. These structures are found in theinit intrinfo() routine of startup.

The cpu intr base member

The interpretation of thecpu intr base member varies with theprocessor:

Processor Interpretation

x86 TheIDT (Interrupt Descriptor Table) entry,typically 0x30.

PPC The offset from the beginning of the exceptiontable where execution begins when an externalinterrupt occurs. A sample value is0x0140,calculated by0x0500 � 4.

continued. . .

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 167

Page 188: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

Processor Interpretation

PPC/BE Interrupts no longer start at fixed locations in lowmemory. Instead there’s a set of IVOR (InterruptVector Offset Register) registers. Each exceptionclass has a different IVOR. When you specify theinterrupt layout to startup, you’ll need to identifythe particular IVOR register the processor willuse when the interrupt occurs. For example,PPCBKESPRIVOR4 is used for normal externalinterrupts;PPCBKESPRIVOR10 is used fordecrementer interrupts. Seestartup/boards/440rb/init intrinfo.cfor an example of what to do on bookE CPUs.

PPC/ NON-BE

MIPS The value in the “cause” register when anexternal interrupt occurs. A sample value is 0.

ARM This value should be 0, since all ARM interruptsare handled via the IRQ exception.

SH The offset from the beginning of the exceptiontable where execution starts when an interruptoccurs. For example, for 7750, the value is0x600.

The flags member

Theflags member takes two sets of flags. The first set deals with thecharacteristics of the interrupts:

INTR FLAG NMI

Indicates that this is a NonMaskable Interrupt (NMI). An NMIis an interrupt which can’t be disabled by clearing the CPU’sinterrupt enable flag, unlike most normal interrupts.NonMaskable interrupts are typically used to signal events thatrequire immediate action, such as a parity error, a hardwarefailure, or imminent loss of power. The address for the handler’s

168 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 189: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

NMI is stored in the BIOS’s Interrupt Vector table at position02H. For this reason an NMI is often referred to as INT 02H.

The code in the kernel needs to differentiate between normalinterrupts and NMIs, because with an NMI the kernel needs toknow that it can’t protect (mask) the interrupt (hence the “N” inNonMaskable Interrupt). We strongly discourage the use of theNMI vector in x86 designs; we don’t support it on any non-x86platforms.

Regular interrupts that are normally used and referred to by numberare called maskable interrupts. Unlike non maskable interrupts,maskable interrupts are those that can be masked, or ignored, to allowthe processor to complete a task.

INTR FLAG CASCADE IMPLICIT EOI

Indicates that an EOI to the primary interrupt controller is notrequired when handling a cascaded interrupt (e.g. it’s doneautomatically). Only used if this entry describes a cascadedcontroller.

INTR FLAG CPU FAULT

Indicates that one or more of the vectors described by this entryis not connected to a hardware interrupt source, but rather isgenerated as a result of a CPU fault (e.g. bus fault, parity error).Note that we strongly discourage designing your hardware thisway. The implication is that a check needs to be inserted for anexception into the generated code stream; after the interrupt hasbeen identified, an EOI needs to be sent to the controller. TheEOI code burst has the additional responsibility of detectingwhat address caused the fault, retrieving the fault type, and thenpassing the fault on. The primary disadvantage of this approachis that it causes extra code to be inserted into the code path.

PPCINTR FLAG 400ALT

Similar toINTR FLAG NMI, this indicates to the code generatorthat a different kernel entry sequence is required. This isbecause the PPC400 series doesn’t have an NMI, but rather has

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 169

Page 190: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

a critical interrupt thatcan be masked. This interrupt shows updifferently from a “regular” external interrupt, so this flagindicates this fact to the kernel.

PPCINTR FLAG CI

Same asPPCINTR FLAG 400ALT, whereCI refers to criticalinterrupt.

PPCINTR FLAG SHORTVEC

Indicates that exception table doesn’t have normal 256 bytes ofmemory space between this and the next vector.

The second set of flags deals with code generation:

INTR GENFLAG LOAD SYSPAGE

Before the interrupt identification or EOI code sequence isgenerated, a piece of code needs to be inserted to fetch thesystem page pointer into a register so that it’s usable within theidentification code sequence.

INTR GENFLAG LOAD INTRINFO

Same asINTR GENFLAG LOAD SYSPAGE, except that it loadsa pointer to this structure.

INTR GENFLAG LOAD INTRMASK

Used only by EOI routines for hardware that doesn’tautomatically mask at the chip level. When the EOI routine isabout to reenable interrupts, it should reenable only thoseinterrupts that are actually enabled at the user level (e.g.managed by the functionsInterruptMask() andInterruptUnmask()). When this flag is set, the existing interruptmask is stored in a register for access by the EOI routine. Azero in the register indicates that the interrupt should beunmasked; a nonzero indicates it should remain masked.

INTR GENFLAG NOGLITCH

Used by the interrupt ID code to cause a check to be made tosee if the interrupt was due to a glitch or to a different controller.

170 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 191: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

If this flag is set, the check is omitted — you’re indicating thatthere’s no reason (other than the fact that the hardware actuallydid generate an interrupt) to be in the interrupt service routine.If this flag is not set, the check is made to verify that thesuspected hardware really is the source of the interrupt.

INTR GENFLAG LOAD CPUNUM

Same asINTR GENFLAG LOAD SYSPAGE, except that it loadsa pointer to the number of the CPU this structure uses.

config return values

Theconfig callout may return zero or more of the following flags:

INTR CONFIG FLAG PREATTACH

Normally, an interrupt is masked off until a routine attaches to itvia InterruptAttach() or InterruptAttachEvent(). If CPU faultindications are routed through to a hardware interrupt (notrecommended!), the interrupt would, by default, be disabled.Setting this flag causes a “dummy” connection to be made tothis source, causing this level to become unmasked.

INTR CONFIG FLAG DISALLOWED

Prevents user code from attaching to this interrupt level.Generally used withINTR CONFIG FLAG PREATTACH, butcould be used to prevent user code from attaching to anyinterrupt in general.

INTR CONFIG FLAG IPI

Identifies the vector that’s used as the target of aninter-processor interrupt in an SMP system.

syspage entry union unTheun union is where processor-specific system page information iskept. The purpose of the union is to serve as a demultiplexing pointfor the various CPU families. It is demultiplexed based on the valueof thetype member of the system page structure.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 171

Page 192: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

Member Processor type

x86 The x86 family SYSPAGEX86

ppc PowerPC family SYSPAGEPPC

mips The MIPS family SYSPAGEMIPS

arm The ARM family SYSPAGEARM

sh The Hitachi SHfamily ofprocessors.

SYSPAGESH

un.x86This structure contains the x86-specific information. On a standardPC-compatible platform, the library routines (described later) fillthese fields:

smpinfo Contains info on how to manipulate the SMP controlhardware; filled in by the library callinit smp().

gdt Contains the Global Descriptor Table (GDT); filled inby the library.

idt Contains the Interrupt Descriptor Table (IDT); filled inby the library.

pgdir Contains pointers to the Page Directory Table(s); filledin by the library.

real addr The virtual address corresponding to the physicaladdress range0 through0xFFFFF inclusive (the bottom1 megabyte).

172 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 193: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

un.x86.smpinfo (deprecated)The members of this field are filled automatically by the functioninit smp() within the startup library.

un.ppc (deprecated)This structure contains the PowerPC-specific information. On asupported evaluation platform, the library routines (described later)fill these fields. On customized hardware, you’ll have to supply theinformation.

smpinfo Contains info on how to manipulate the SMP controlhardware; filled in by the library callinit smp().

kerinfo Kernel information, filled by the library.

exceptptr Points at system exception table, filled by the library.

un.ppc.kerinfoContains information relevant to the kernel:

pretend cpu Allows us to specify an override for the CPU IDregister so that the kernel can pretend it is a “known”CPU type. This is done because the kernel “knows”only about certain types of PPC CPUs; differentvariants require specialized support. When a newvariant is manufactured, the kernel will not recognizeit. By stuffing thepretend cpu field with a CPU IDfrom a known CPU, the kernel will pretend that it’srunning on the known variant.

init msr Template of what bits to have on in the MSR whencreating a thread. Since the MSR changes among thevariants in the PPC family, this allows you to specifysome additional bits that the kernel doesn’tnecessarily know about.

ppc family Indicates what family the PPC CPU belongs to.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 173

Page 194: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Structure of the system page 2006, QNX Software Systems GmbH & Co. KG.

asid bits Identifies what address space bits are active.

callout ts clear

Lets callouts know whether to turn off datatranslation to get at their hardware.

un.mipsThis structure contains the MIPS-specific information:

shadow imask A shadow copy of the interrupt mask bits for thebuiltin MIPS interrupt controller.

un.armThis structure contains the ARM-specific information:

L1 vaddr Virtual address of the MMU level 1 page table usedto map the kernel.

L1 paddr Physical address of the MMU level 1 page tableused to map the kernel.

startup base Virtual address of a 1-1 virtual-physical mappingused to map the startup code that enables the MMU.This virtual mapping is removed when the kernel isinitialized.

startup size Size of the mapping used forstartup base.

cpu Structure containing ARM core-specific operationsand data. Currently this contains the following:

page flush A routine used to implementCPU-specific cache/TLB flushing whenthe memory manager unmaps orchanges the access protections to avirtual memory mapping for a page.

174 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 195: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Structure of the system page

This routine is called for each page in arange being modified by the virtualmemory manager.

page flush deferred

A routine used to perform anyoperations that can be deferred whenpage flush is called. For example on theSA-1110 processor, anIcache flush isdeferred until all pages being operatedon have been modified.

un.shThis structure contains the Hitachi SH-specific information:

exceptptr Points at system exception table, filled by the library.

smpThesmp is CPU-independent. Thesmp area contains the followingelements:

This element Description

send ipi Send an inter-process interrupt (IPI) to the CPU.

start address Get the starting address for the IPI.

pending Identify the pending interrupts for the smp processor.

cpu Identify the smp CPU.

pminfoThepminfo area is a communication area between the power managerand startup/power callout.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 175

Page 196: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Callout information 2006, QNX Software Systems GmbH & Co. KG.

Thepminfo area contains the following elements which arecustomizable in the power manager structure and are power-managerdependent:

This element Description

wakeup pending Notifies the power callout that a wakeup condition hasoccurred. The power manager requires write access so it canmodify this entry.

wakeup condition Indicates to the power manager what has caused the wakeupi.e. whether it’s a power-on reset, or an interrupt fromperipherals or other devices. The value is set by the powercallout.

managed storage This entry is an area where the power manager can store anydata it chooses. This storage is not persistent storage; it needsto be manually stored and restored by the startup and powercallout.Themanaged storage element is initialized by theinit pminfo() function call in startup and can be modified atstartup. The value passed intoinit pminfo() determines the sizeof themanaged storage array.

Callout informationAll the callout routines share a set of similar characteristics:

� coded in assembler

� position-independent

� no static read/write storage

Callouts are basically binding standalone pieces of code for the kernelto invoke without having to statically link them to the kernel.

The requirement for coding the callouts in assembler stems from thesecond requirement (i.e. that they must be written to be

176 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 197: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Callout information

position-independent). This is because the callouts are provided aspart of the startup code, which will get overwritten when the kernelstarts up. In order to circumvent this, the startup program will copythe callouts to a safe place — since they won’t be in the location thatthey were loaded in, they must be coded to be position-independent.

We need to qualify the last requirement (i.e. that callouts not use anystatic read/write storage). There’s a mechanism available for a givencallout to allocate a small amount of storage space within the systempage, but the callouts cannot have any static read/write storage spacedefined within themselves.

Debug interfaceThe debug interface consists of the following callouts:

� display char()

� poll key()

� break detect().

These three callouts are used by the kernel when it wishes to interactwith a serial port, console, or other device (e.g. when it needs to printout some internal debugging information or when there’s a fault).Only thedisplay char() is required; the others are optional.

Clock/timer interfaceHere are the clock and timer interface callouts:

� timer load()

� timer reload()

� timer value().

The kernel uses these callouts to deal with the hardware timer chip.

Thetimer load() callout is responsible for stuffing the divisor valuepassed by the kernel into the timer/counter chip. Since the kerneldoesn’t know the characteristics of the timer chip, it’s up to the

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 177

Page 198: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Callout information 2006, QNX Software Systems GmbH & Co. KG.

timer load() callout to take the passed value and validate it. Thekernel will then use the new value in any internal calculations itperforms. You can access the new value in theqtime entry element ofthe system page as well as through theClockPeriod() function call.

Thetimer reload() callout is called after the timer chip generates aninterrupt. It’s used in two cases:

� Reloading the divisor value (because some timer hardware doesn’thave an automatic reload on the timer chip — this type ofhardware should be avoided if possible).

� Telling the kernel whether the timer chip caused the interrupt ornot (e.g. if you had multiple interrupt sources tied to the same lineused by the timer — not the ideal hardware design, but. . . ).

Thetimer value() callout is used to return the value of the timer chip’sinternal count as a delta from the last interrupt. This is used onprocessors that don’t have a high-precision counter built into the CPU(e.g. 80386, 80486).

Interrupt controller interfaceHere are the callouts for the interrupt controller interface:

� mask()

� unmask()

� config()

In addition, two “code stubs” are provided:

� id

� eoi

Themask() andunmask() perform masking and unmasking of aparticular interrupt vector.

Theconfig() callout is used to ascertain the configuration of aninterrupt level.

178 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 199: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Callout information

For more information about these callouts, refer to theintrinfostructure in the system page above.

Cache controller interfaceDepending on the cache controller circuitry in your system, you mayneed to provide a callout for the kernel to interface to the cachecontroller.

On the x86 architecture, the cache controller is integrated tightly withthe CPU, meaning that the kernel doesn’t have to talk to the cachecontroller. On other architectures, like the MIPS and PowerPC, thecache controllers need to be told to invalidate portions of the cachewhen certain functions are performed in the kernel.

The callout for cache control iscontrol(). This callout gets passed:

� a set of flags (defining the operation to perform)

� the address (either in virtual or physical mode, depending on flagsin thecacheattr array in the system page)

� the number of cache lines to affect.

The callout is responsible for returning the number of cache lines thatit affected — this allows the caller (the kernel) to call thecontrol()callout repeatedly at a higher level. A return of0 indicates that theentire cache was affected (e.g. all cache entries were invalidated).

System reset calloutThe miscellaneous callout,reboot(), gets called whenever the kernelneeds to reboot the machine.

Thereboot() callout is responsible for resetting the system. Thiscallout lets developers customize the events that occur when procneeds to reboot - like turn off a watchdog, bang the right registers etc.without customizing proc each time.

A “shutdown” of the binary will callsysmgr reboot(), which willeventually trigger thereboot() callout.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 179

Page 200: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

Power management calloutThepower() callout gets called whenever power management needsto be activated.

Thepower() callout is used for power management.

The startup libraryThe startup library contains a rich set of routines consisting ofhigh-level functions that are called by yourmain() through to utilityfunctions for interrogating the hardware, initializing the system page,loading the next process in the image, and switching to protectedmode. Full source is provided for all these functions, allowing you tomake local copies with minor modifications in your target startupdirectory.

The following are the available library functions (in alphabeticalorder):

add cache()int add cache(int next,

unsigned flags,unsigned line size,unsigned num lines,const struct callout rtn *rtn);

Add an entry to thecacheattr section of the system page structure.Parameters map one-to-one with the structure’s fields. The returnvalue is the array index number of the added entry. Note that if there’salready an entry that matches the one you’re trying to add, that entry’sindex is returned — nothing new is added to the section.

add callout()void add callout(unsigned offset,

const struct callout rtn *callout);

Add a callout to thecallout info section of the system page. Theoffsetparameter holds the offset from the start of the section (as returned bytheoffsetof() macro) that the new routine’s address should be placedin.

180 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 201: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

add callout array()void add callout array (const struct callout slot *slots,

unsigned size)

Add the callout array specified byslots (for size bytes) into the calloutarray in the system page.

add interrupt()struct intrinfo entry

*add interrupt(const struct startup intrinfo*startup intr);

Add a new entry to theintrinfo section. Returns a pointer to the newlyadded entry.

add interrupt array()void add interrupt array (const struct startup intrinfo *intrs,

unsigned size)

Add the interrupt array callouts specified byintrs (for size bytes) intothe interrupt callout array in the system page.

add ram()void add ram(paddr t start,

paddr t size);

Tell the system that there’s RAM available starting at physical addressstart for size bytes.–>

add string()unsigned add string (const char *name)

Add the string specified byname into the string literal pool in thesystem page and return the index.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 181

Page 202: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

add typed string()unsigned add typed string (int type index,

const char *name)

Add the typed string specified byname (of typetype index) into thetyped string literal pool in the system page and return the index.

alloc qtime()struct qtime entry *alloc qtime(void);

Allocate space in the system page for theqtime section and fill in theepoch, boot time, andnsec tod adjust fields. Returns a pointer to thenewly allocated structure so that user code can fill in the other fields.

alloc ram()paddr t alloc ram (paddr t addr,

paddr t size,paddr t align)

Allocate memory from the free memory pool initialized by the call toinit raminfo(). The RAM isnot cleared.

as add()unsigned as add(paddr t start,

paddr t end,unsigned attr,const char *name,unsigned owner);

Add an entry to theasinfo section of the system page. Parametersmap one-to-one with field names. Returns the offset from the start ofthe section for the new entry.

as add containing()unsigned as add containing(paddr t start,

paddr t end,unsigned attr,const char *name,const char *container);

182 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 203: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

Add new entries to theasinfo section, with the owner field set towhatever entries are named by the string pointed to bycontainer. Thisfunction can add multiple entries because thestart andend values areconstrained to stay within thestart andend of the containing entry(e.g. they get clipped such that they don’t go outside the parent). Ifmore than one entry is added, theAS ATTR CONTINUED bit will beturned on in all but the last. Returns the offset from the start of thesection for the first entry added.

as default()unsigned as default(void);

Add the defaultmemory andio entries to theasinfo section of thesystem page.

as find()unsigned as find(unsigned start, ...);

Thestart parameter indicates where to start the search for the givenitem. For an initial call, it should be set toAS NULL OFF. If the itemfound isn’t the one wanted, then the return value from the firstas find item() is used as thestart parameter of the second call. Thesearch will pick up where it left off. This can be repeated as manytimes as required (the return value from the second call going into thestart parameter of the third, etc). The item being searched is identifiedby a sequence ofchar * parameters followingstart. The sequence isterminated by a NULL. The last string before the NULL is thebottom-levelitemname being searched for, the string in front of that isthe name of the item that owns the bottom-level item, etc.

For example, this call finds the first occurrence of an item called“foobar”:

item off = as find item(AS NULL OFF, "foobar", NULL);

The following call finds the first occurrence of an item called “foobar”that’s owned by “sam”:

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 183

Page 204: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

item off = as find item(AS NULL OFF, "sam", "foobar", NULL);

If the requested item can’t be found,AS NULL OFFis returned.

as find containing()unsigned as find containing(unsigned off,

paddr t start,paddr t end,const char *container);

Find anasinfo entry with the name pointed to bycontainer that atleast partially covers the range given bystart andend. Follows thesame rules asas find() to know where the search starts. Returns theoffset of the matching entry orAS NULL OFFif none is found. (Theas add containing() function uses this to find what the owner fieldsshould be for the entries it’s adding.)

as info2off()unsigned as info2off(const struct asinfo entry *);

Given a pointer to anasinfo entry, return the offset from the start ofthe section.

as off2info()struct asinfo entry *as off2info(unsigned offset);

Given an offset from the start of theasinfo section, return a pointer tothe entry.

as set checker()void as set checker(unsigned off,

const struct callout rtn *rtn);

Set thechecker callout field of the indicatedasinfo entry. If theAS ATTR CONTINUED bit is on in the entry, advance to the next entryin the section and set its priority as well (seeas add containing() forwhy AS ATTR CONTINUED would be on). Repeat until an entrywithoutAS ATTR CONTINUED is found.

184 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 205: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

as set priority()void as set priority(unsigned as off,

unsigned priority);

Set thepriority field of the indicated entry. If theAS ATTR CONTINUED bit is on in the entry, advance to the next entryin the section and set its priority as well (seeas add containing() forwhy AS ATTR CONTINUED would be on). Repeat until an entrywithoutAS ATTR CONTINUED is found.

avoid ram()void avoid ram( paddr32 t start,

size t size);

Make startup avoid using the specified RAM for any of its internalallocations. Memory remains available forprocnto to use. Thisfunction is useful for specifying RAM that the IPL/ROM monitorneeds to keep intact while startup runs. Because it takes only apaddr32 t, addresses can be specified in the first 4 GB. It doesn’tneed a fullpaddr t because startup will never use memory above 4GB for its own storage requirements.

calc time t()unsigned long calc time t(const struct tm *tm);

Given astruct tm (with values appropriate for the UTC timezone),calculate the value to be placed in theboot time field of theqtimesection.

calloc ram()paddr32 t calloc ram (size t size,

unsigned align)

Allocate memory from the free memory pool initialized by the call toinit raminfo(). The RAM is cleared.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 185

Page 206: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

callout io map indirect()uintptr t callout io map indirect(unsigned size,

paddr t phys);

Same asmmap device io() in the C library — provide access to anI/O port on the x86 (for other systems,callout io map() is the same ascallout memory map indirect()) at a given physical address for agiven size. The return value is for use in the CPU’s equivalent ofin/out instructions (regular moves on all but the x86). The value is foruse in any kernel callouts (i.e. they live beyond the end of the startupprogram and are maintained by the OS while running).

callout memory map indirect()void *callout memory map indirect(unsigned size,

paddr t phys,unsigned prot flags);

Same asmmap device memory() in the C library — provide access toa memory-mapped device. The value is for use in any kernel callouts(i.e. they live beyond the end of the startup program and aremaintained by the OS while running).

callout register data()void callout register data( void *rp,

void *data );

This function lets you associate a pointer to arbitrary data with acallout. This data pointer is passed to the patcher routine (see“Patching the callout code,” below.

Therp argument is a pointer to the pointer where the callout addressis stored in the system page you’re building. For example, say youhave a pointer to a system page section that you’re working on calledfoo. In the section there’s a fieldbar that points to a callout when thesystem page is finished. Here’s the code:

// This sets the callout in the syspage:

foo->bar = (void *)&callout routine name;

186 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 207: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

// This registers data to pass to the patcher when we’re// building the final version of the system page:

callout register data(&foo->bar, &some interesting data for patcher);

When the patcher is called to fix up the callout that’s pointed at byfoo->bar, &some interesting data for patcher is passed to it.

chip access()void chip access(paddr t base,

unsigned reg shift,unsigned mem mapped,unsigned size);

Get access to a hardware chip at physical addressbase with a registershift value ofreg shift (0 if registers are one byte apart;1 if registersare two bytes apart, etc. Seedevc-ser8250 for more information).

If mem mapped is zero, the function usesstartup io map() to getaccess; otherwise, it usesstartup memory map(). Thesize parametergives the range of locations to be given access to (the value is scaledby thereg shift parameter for the actual amount that’s mapped). Afterthis call is made, thechip read*() andchip write*() functions canaccess the specified device. You can have only onechip access() ineffect at any one time.

chip done()void chip done(void);

Terminate access to the hardware chip specified bychip access().

chip read8()unsigned chip read8(unsigned off);

Read one byte from the device specified bychip access(). Theoffparameter is first scaled by thereg shift value specified inchip access() before being used.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 187

Page 208: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

chip read16()unsigned chip read16(unsigned off);

Same aschip read8(), but for 16 bits.

chip read32()unsigned chip read32(unsigned off);

Same aschip read16(), but for 32 bits.

chip write8()void chip write8(unsigned off,

unsigned val);

Write one byte from the device specified bychip access(). Theoffparameter is first scaled by thereg shift value specified inchip access() before being used.

chip write16()void chip write16(unsigned off,

unsigned val);

Same aschip write8(), but for 16 bits.

chip write32()void chip write32(unsigned off,

unsigned val);

Same aschip write16(), but for 32 bits.

copy memory()void copy memory (paddr t dst,

paddr t src,paddr t len)

Copy len bytes of memory from physical memory atsrc to dst.

188 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 209: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

del typed string()int del typed string(int type index);

Find the string in thetyped strings section of the system pageindicated by the typetype index and remove it. Returns the offsetwhere the removed string was, or -1 if no such string was present.

falcon init l2 cache()void falcon init l2 cache(paddr t base);

Enable the L2 cache on a board with a Falcon system controller chip.The base physical address of the Falcon controller registers are givenby base.

falcon init raminfo()void falcon init raminfo(paddr t falcon base);

On a system with the Falcon system controller chip located atfalcon base, determine how much/where RAM is installed and calladd ram() with the appropriate parameters.

falcon system clock()unsigned falcon system clock(paddr t falcon base);

On a system with a Falcon chipset located at physical addressfalcon base, return the speed of the main clock input to the CPU (inHertz). This can then be used in turn to set thecpu freq, timer freq,andcycles freq variables.

find startup info()const void *find startup info (const void *start,

unsigned type)

Attempt to locate the kind of information specified bytype in the dataarea used by the IPL code to communicate such information. Passstart asNULL to find the first occurrence of the given type ofinformation. Passstart as the return value from a previous call inorder to get the next information of that type. Returns 0 if noinformation of that type is found starting fromstart.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 189

Page 210: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

find typed string()int find typed string(int type index);

Return the offset from the beginning of thetype strings section of thestring with thetype index type. Return -1 if no such string is present.

handle common option()void handle common option (int opt)

Take the option identified byopt (a single ASCII character) andprocess it. This function assumes that the global variableoptargpoints to the argument string for the option.

Valid values foropt and their actions are:

A Reboot switch. If set, an OS crash will cause the system toreboot. If not set, an OS crash will cause the system to hang.

D Output channel specification (e.g.kprintf(), stdout, etc.).

f [cpu freq][,[ cycles freq][,timer freq]]

Specify CPU frequencies. All frequencies can be followed byH

for hertz,K for kilohertz, orM for megahertz (these suffixesaren’t case-sensitive). If no suffix is given, the library assumesmegahertz if the number is less than 1000; otherwise, itassumes hertz.

If they’re specified,cpu freq, cycles freq, andtimer freq areused to set the corresponding variables in the startup code:

cpu freq — the CPU clock frequency. Also sets the speedfield in thecpuinfo section of the system page.cycles freq — the frequency at which the value returned byClockCycles() increments. Also sets thecycles per secfield in theqtime section of the system page.timer freq — the frequency at which the timer chip inputruns. Also sets thetimer rate andtimer scale values of theqtime section of the system page.

190 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 211: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

K kdebug remote debug protocol channel.

M Placeholder for processing additional memory blocks. Theparsing of additional memory blocks is deferred untilinit system private().

N Add the hostname specified to the typed name string spaceunder the identifierCS HOSTNAME.

R Used for reserving memory at the bottom of the address space.

r Used for reserving memory at any address space you specify.

S Placeholder for processing debug code’s-S option.

P Specify maximum number of CPUs in an SMP system.

j Add Jtag-related options. Reserves four bytes of memory at thespecified location and copies thephysical address of the systempage to this location so the hardware debugger can retrieve it.

v Increment the verbosity global flag,debug flag.

hwi add device()void hwi add device(const char *bus,

const char *class,const char *name,unsigned pnp);

Add anhwi device item to thehwinfo section. Thebus andclassparameters are used to locate where in the device tree the new deviceis placed.

hwi add inputclk()void hwi add inputclk(unsigned clk,

unsigned div);

Add anhwi inputclk tag to thehw item currently being constructed.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 191

Page 212: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

hwi add irq()void hwi add irq(unsigned vector);

Add an irq tag structure to thehwinfo section. The logical vectornumber for the interrupt will be set tovector.

hwi add location()void hwi add location(paddr t base,

paddr t len,unsigned reg shift,unsigned addr space);

Add a location tag structure to thehwinfo section. The fields of thestructure will be set to the given parameters.

hwi add nicaddr()void hwi add nicaddr(const uint8 *addr,

unsigned len);

Add anhwi nicaddr tag to thehw item currently being constructed.

hwi add rtc()void hwi add rtc(const char *name,

paddr t base,unsigned reg shift,unsigned len,int mmap,int cent reg);

Add anhwi device item describing the realtime clock to thehwinfosection. The name of the device isname. Thehwi location tag itemsare given bybase, reg shift, len, andmmap. Themmap parameterindicates if the device is memory-mapped or I/O-space-mapped and isused to set theaddrspace field.

If the cent reg parameter is not -1, it’s used to add anhwi regname tagwith theoffset field set to its value. This indicates the offset from thestart of the device where the century byte is stored.

192 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 213: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

hwi alloc item()void *hwi alloc item(const char *tagname,

unsigned size,unsigned align,const char *itemname,unsigned owner);

Add an item structure to thehwinfo section.

hwi alloc tag()void *hwi alloc tag(const char *tagname,

unsigned size,unsigned align);

Add a tag structure to thehwinfo section.

hwi find as()unsigned hwi find as(paddr t base,int mmap);

Given a physical address ofbase andmmap (indicating 1 formemory-mapped and 0 for I/O-space-mapped), return the offset fromthe start of theasinfo section indicating the appropriateaddrspacefield value for anhwi location tag.

hwi find item()unsigned hwi find item(unsigned start, ...);

Although thehwi find item() function resides in the C library (protoin <hw/sysinfo.h>), the function is still usable from startupprograms.

Search for a given item in thehwinfo section of the system page. Ifstart is HWI NULL OFF, the search begins at the start of thehwinfosection. If not, it starts from the item after the offset of the one passedin (this allows people to find multiple tags of the same type; it worksjust like thefind startup info() function). Thevar args portion is a listof character pointers, giving item names; the list is terminated with a

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 193

Page 214: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

NULL. The order of the item names gives ownership information. Forexample:

item = hwi find item(HWI NULL OFF, "foobar", NULL);

searches for an item name called “foobar.” The following:

item = hwi find item(HWI NULL OFF, "mumblyshwartz","foobar", NULL);

also searches for “foobar,” but this time it has to be owned by an itemcalled “mumblyshwartz.”

If the item can’t be found,HWI NULL OFFis returned; otherwise, thebyte offset within thehwinfo section is returned.

hwi find tag()unsigned hwi find tag(unsigned start,

int curr item,const char *tagname);

Although thehwi find tag() function resides in the C library (proto in<hw/sysinfo.h>), the function is still usable from startupprograms.

Search for a given tagname in thehwinfo section of startup. Thestartparameter works just like inhwi find item(). If curr item is nonzero,the tagname must occur within the current item. If zero, the tagnamecan occur anywhere from the starting point of the search to the end ofthe section. If the tag can’t be found, thenHWI NULL OFFisreturned; otherwise, the byte offset within thehwinfo section isreturned.

hwi off2tag()void *hwi off2tag(unsigned off);

194 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 215: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

Although thehwi off2tag() function resides in the C library (proto in<hw/sysinfo.h>), the function is still usable from startupprograms.

Given a byte offset from the start of thehwinfo section, return apointer to thehwinfo tag structure.

hwi tag2off()unsigned hwi tag2off(void *tag);

Although thehwi tag2off() function resides in the C library (proto in<hw/sysinfo.h>), the function is still usable from startupprograms.

Given a pointer to the start of ahwinfo tag instruction, convert it to abyte offset from the start of thehwinfo system page section.

init asinfo()void init asinfo(unsigned mem);

Initialize theasinfo section of the system page. Themem parameter isthe offset of thememory entry in the section and can be used as theowner parameter value foras add()s that are adding memory.

init cacheattr()void init cacheattr (void)

Initialize thecacheattr member. For all platforms, this is a do-nothingstub.

init cpuinfo()void init cpuinfo (void)

Initialize the members of thecpuinfo structure with information aboutthe installed CPU(s) and related capabilities. Most systems will beable to use this function directly from the library.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 195

Page 216: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

init hwinfo()void init hwinfo (void)

Initialize the appropriate variant of thehwinfo structure in the systempage.

init intrinfo()void init intrinfo (void)

Initialize theintrinfo structure.

x86 You would need to change this only if your hardwaredoesn’t have the standard PC-compatible dual 8259configuration.

MIPS The default library version sets up the internal MIPSinterrupt controller.

PowerPC No default version exists; you must supply one.

ARM No default version exists; you must supply one.

SH The default library version sets up the SH-4 on-chipperipheral interrupt. You need to provide the externalinterrupt code.

If you’re providing your own function, make sure it initializes:

� the interrupt controller hardware as appropriate (e.g. on the x86 itshould program the two 8259 interrupt controllers)

� theintrinfo structure with the details of the interrupt controllerhardware.

This initialization of the structure is done via a call to the functionadd interrupt array().

196 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 217: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

init mmu()void init mmu (void)

Sets up the processor for virtual addressing mode by setting uppage-mapping hardware and enabling the pager.

On the x86 family, it sets up the page tables as well as specialmappings to “known” physical address ranges (e.g. sets up a virtualaddress for the physical address ranges0 through0xFFFFF inclusive).

The 400 and 800 series processors within the PowerPC family arestubs; the others, i.e. the 600 series and BookE processors, are not.On the MIPS, and SH families, this function is currently a stub. Onthe PowerPC family, this function may be a stub.

On the ARM family, this function simply sets up the page tables.

init pminfo()*init pminfo (unsigned managed size)

Initialize thepminfo section of the system page and set the number ofelements in themanaged storage array.

init qtime()void init qtime (void)

Initialize theqtime structure in the system page. Most systems will beable to use this function directly from the library.

This function doesn’t exist for ARM. Specific functions exist forARM processors with on-chip timers; currently, this includes onlyinit qtime sa1100().

init qtime sa1100()void init qtime sa1100 (void)

Initialize theqtime structure and kernel callouts in the system page touse the on-chip timer for the SA1100 and SA1110 processors.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 197

Page 218: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

init raminfo()void init raminfo (void)

Determine the location and size of available system RAM andinitialize theasinfo structure in the system page.

If you know the exact amount and location of RAM in your system,you can replace this library function with one that simply hard-codesthe values via one or moreadd ram() calls.

x86 If the RAM configuration is known (e.g. set by the IPLcode, or the multi-boot IPL code gets set by the gnuutility), then the library version ofinit raminfo() willcall the library routinefind startup info() to fetch theinformation from a known location in memory. If theRAM configuration isn’t known, then a RAM scan (viax86 scanmem()) is performed looking for valid memorybetween locations0 and0xFFFFFF, inclusive. (Notethat the VGA aperture that usually starts at location0xB0000is specifically ignored.)

MIPSPowerPCARMSH There’s no library default. You must supply your own

init raminfo() function.

init smp()void init smp (void)

Initialize the SMP functionality of the system, assuming the hardware(e.g. x86, PPC, MIPS) supports SMP.

init syspage memory() (deprecated)void init syspage memory (void *base,

unsigned size)

198 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 219: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

Initialize the system page structure’s individual member pointers topoint to the data areas for the system page substructures (e.g.typed strings). Thebase parameter is a pointer to where the systempage is currently stored (it will be moved to the kernel’s address spacelater); thesize indicates how big this area is. On all platforms, thisroutine shouldn’t require modification.

init system private()void init system private (void)

Find all the boot images that need to be started and fill a structurewith that information; parse any-M options used to specify memoryregions that should be added; tell Neutrino where the image filesystemis located; and finally allocate room for the actual storage of thesystem page. On all platforms, this shouldn’t require modification.

Note that this must be thelast init *() function called.☞

jtag reserve memory()void jtag reserve memory (unsigned long resmem addr,

unsigned long resmem size,uint8 t resmem flag)

Reserve a user-specified block of memory at the location specified inresmem addr, if the resmem flag is set to 0.

kprintf()void kprintf (const char *fmt, ... )

Display output using theput char() function you provide. It supportsa very limited set ofprintf() style formats.

mips41xx set clock freqs()void mips41xx set clock freqs(unsigned sysclk);

On a MIPS R41xx series chip, set thecpu freq, timer freq, andcycles freq variables appropriately, given a system clock inputfrequency ofsysclk.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 199

Page 220: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

openbios init raminfo()void openbios init raminfo(void);

On a system that contains an OpenBIOS ROM monitor, add thesystem RAM information.

pcnet reset()void pcnet reset(paddr t base,

int mmap);

Ensure that a PCnet-style Ethernet controller chip at the givenphysical address (either I/O or memory-mapped as specified bymmap) is disabled. Some ROM monitors leave the Ethernet receiverenabled after downloading the OS image. This causes memory to becorrupted after the system starts and before Neutrino’s Ethernet driveris run, due to the reception of broadcast packets. This function makessure that no further packets are received by the chip until the Neutrinodriver starts up and properly initializes it.

ppc400 pit init qtime()void ppc400 pit init qtime(void);

On a PPC 400 series chip, initialize theqtime section and timer kernelcallouts of the system page to use the on-board ProgrammableInterval Timer.

ppc405 set clock freqs()void ppc405 set clock freqs(unsigned sys clk, unsigned timer clk);

Initialize thetimer freq andcycles freq variables based on a giventimer clk. Thecpu freq variable is initialized using a multiplication ofa given system clock (system clk). The multiplication value is foundusing theCPCOPSRDCR.

200 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 221: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

ppc600 set clock freqs()void ppc600 set clock freqs(unsigned sysclk);

On a PPC 600 series chip, set thecpu freq, timer freq, andcycles freqvariables appropriately, given a system clock input frequency ofsysclk.

ppc700 init l2 cache()void ppc700 init l2 cache(unsigned flags);

On a PPC 700 series system, initialize the L2 cache. Theflagsindicate which bits in the L2 configuration register are set. Inparticular, they decide the L2 size, clock speed, and so on. For details,see the Motorola PPC 700 series user’s documentation for theparticular hardware you’re using.

For example, on a Sandpoint board,flags might be:

PPC700 SPR L2CR 1M | PPC700 SPR L2CR CLK2 | PPC700 SPR L2CR OH05

This would set the following for L2CR:

� 1MB L2 cache

� clock speed of half of the core speed

� “output-hold” value of 0.5 nsec.

ppc800 pit init qtime()void ppc800 pit init qtime(void);

On a PPC 800 series chip, initialize theqtime section and timer kernelcallouts of the system page to use the on-board ProgrammableInterval Timer.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 201

Page 222: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

ppc800 set clock freqs()void ppc800 set clock freqs(unsigned extclk freq,

unsigned extal freq,int is extclk);

On a PPC 800 series chip, set thecpu freq, timer freq, andcycles freqvariables appropriately, given input frequencies ofextclk freq at theEXTCLK pin andextal freq at theXTAL/EXTAL pins.

If is extclk is nonzero, then theextclk freq is used for the main timingreference (MODCLK1 signal is one at reset). If zero,extal freq is usedat the main timing reference (MODCLK1 signal is zero at reset).

Note that the setting of the frequency variables assumes that theppc800 pit init qtime() routine is being used. If some otherinitialization of theqtime section and timer callouts takes place, thevalues in the frequency variables may have to be modified.

ppc dec init qtime()void ppc dec init qtime(void);

On a PPC, initialize theqtime section and timer kernel callouts of thesystem page to use the decrementer register.

Theppc dec init qtime() routine may not be used on a PPC 400 serieschip, which omits the decrementer register.

print syspage()void print syspage (void)

Print the contents of all the structures in the system page. The globalvariabledebug level is used to determine what gets printed. Thedebug level must be at least2 to print anything; adebug level of 3will print the information within the individual substructures.

Note that you can set the debug level at the command line byspecifying multiple-v options to the startup program.

You can also use the startup program’s-S command-line option toselect which entries are printed from the system page:-Sname selects

202 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 223: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

name to be printed, whereas-S˜name disablesname from beingprinted. Thename can be selected from the following list:

Name Processors Syspage entry

cacheattr all Cache attributes

callout all Callouts

cpuinfo all CPU info

gdt x86 Global Descriptor Table

hwinfo all Hardware info

idt x86 Interrupt Descriptor Table

intrinfo all Interrupt info

kerinfo PPC Kernel info

pgdir x86 Page directory

qtime all System time info

smp all SMP info

strings all Strings

syspage all Entire system page

system private all System private info

typed strings all Typed strings

rtc time()unsigned long rtc time (void)

This is a user-replaceable function responsible for returning thenumber of seconds since January 1 1970 00:00:00 GMT.

x86 This function defaults to callingrtc time mc146818(),which knows how to get the time from an IBM-PCstandard clock chip.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 203

Page 224: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

MIPSPowerPCARM The default library version simply returns zero.

SH The default function callsrtc time sh4(), which knowshow to get the time from the SH-4 on-chip rtc.

Currently, these are the chip-specific versions:

rtc time ds1386()

Dallas Semiconductor DS-1386 compatible

rtc time m48t5x()

SGS-Thomson M48T59 RTC/NVRAM chip

rtc time mc146818()

Motorola 146818 compatible

rtc time rtc72423()

FOX RTC-72423 compatible

rtc time rtc8xx()

PPC 800 onboard RTC hardware

There’s also a “none” version to use if your board doesn’t have RTChardware:

unsigned long rtc time none(void);

For the PPC 800 onboard RTC hardware, the function is simply asfollows:

unsigned long rtc time rtc8xx(void);

If you’re supplying thertc time() routine, you should call one of thechip-specific routines or write your own. The chip-specific routinesall share the same parameter list:

204 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 225: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

(paddr t base, unsigned reg shift, int mmap, int cent reg);

Thebase parameter indicates the physical base address or I/O port ofthe device. Thereg shift indicates the register offset as a power oftwo.

A typical value would be0 (meaning 20, i.e. 1), indicating that theregisters of the device are one byte apart in the address space. Asanother example, a value of2 (meaning 22, i.e. 4) indicates that theregisters in the device are four bytes apart.

If the mmap variable is0, then the device is in I/O space. Ifmmap is1, then the device is in memory space.

Finally, cent reg indicates which register in the device contains thecentury byte (-1 indicates no such register). If there’s no century byteregister, then the behavior is chip-specific. If the chip is year2000-compliant, then we will get the correct time. If the chip isn’tcompliant, then if the year is less than 70, we assume it’s in the range2000 to 2069; else we assume it’s in the range 1970 to 1999.

startup io map()uintptr t startup io map(unsigned size,

paddr t phys);

Same asmmap device io() in the C library — provide access to anI/O port on the x86 (for other systems,startup io map() is the same asstartup memory map()) at a given physical address for a given size.The return value is for use in thein*/out* functions in the C library.The value is for use during the time the startup program is running (asopposed tocallout io map(), which is for use after startup iscompleted).

startup io unmap()void startup io unmap(uintptr t port);

Same asunmap device io() in the C library — remove access to anI/O port on the x86 (on other systems,unmap device io() is the sameasstartup memory unmap()) at the given port location.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 205

Page 226: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

startup memory map()void *startup memory map(unsigned size,

paddr t phys,unsigned prot flags);

Same asmmap device io memory() in the C library — provide accessto a memory-mapped device. The value is for use during the time thestartup program is running (as opposed tocallout memory map(),which is for use after startup is completed).

startup memory unmap()void startup memory unmap(void *vaddr);

Same asunmap device memory() in the C library — remove access toa memory-mapped device at the given location.

tulip reset()void tulip reset(paddr t phys,

int mem mapped);

Ensure that a Tulip Ethernet chip (Digital 21x4x) at the given physicaladdress (either I/O or memory-mapped as specified bymem mapped)is disabled. Some ROM monitors leave the Ethernet receiver enabledafter downloading the OS image. This causes memory to be corruptedafter the system starts and before Neutrino’s Ethernet driver is run,due to the reception of broadcast packets. This function makes surethat no further packets are received by the chip until the Neutrinodriver starts up and properly initializes it.

uncompress()int uncompress(char *dst,

int *dstlen,char *src,int srclen,char *win);

This function resides in the startup library and is responsible forexpanding a compressed OS image out to full size (this is invokedbeforemain() gets called). If you know you’re never going to be givena compressed image, you can replace this function with a stub versionin your own code and thus make a smaller startup program.

206 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 227: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. The startup library

x86 cpuid string()int x86 cpuid string (char *buf,

int max)

Place a string representation of the CPU in the stringbuf to amaximum ofmax characters. The general format of the string is:

manufacturer part Ffamily Mmodel Sstepping

This information is determined using thecpuid instruction. If it’s notsupported, then a subset (typically only thepart) will be placed in thebuffer (e.g. 386).

x86 cputype()unsigned x86 cputype (void)

An x86 platform-only function that determines the type of CPU andreturns the number (e.g.386).

x86 enable a20()int x86 enable a20 (unsigned long cpu,

int only keyboard)

Enable address line A20, which is often disabled on many PCs onreset. It first checks if address line A20 is enabled and if so returns 0.Otherwise, it sets bit0x02 in port0x92, which is used by manysystems as a fast A20 enable. It again checks to see if A20 is enabledand if so returns 0. Otherwise, it uses the keyboard microcontroller toenable A20 as defined by the old PC/AT standard. It again checks tosee if A20 is enabled and if so returns 0. Otherwise, it returns -1.

If cpu is a 486 or greater, it issues awbinvd opcode to invalidate thecache when doing a read/write test of memory to see if A20 isenabled.

In the rare case where setting bit0x02 in port0x92 may affect otherhardware, you can skip this by settingonly keyboard to 1. In thiscase, it will attempt to use only the keyboard microcontroller.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 207

Page 228: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

The startup library 2006, QNX Software Systems GmbH & Co. KG.

x86 fputype()unsigned x86 fputype (void)

An x86-only function that returns the FPU type number (e.g.387).

x86 init pcbios()void x86 init pcbios(void);

Perform initialization unique to an IBM PC BIOS system.

x86 pcbios shadow rom()int x86 pcbios shadow rom(paddr t rom,

size t size);

Given the physical address of a ROM BIOS extension, this functionmakes a copy of the ROM in a RAM location and sets the x86 pagetables in the syspage ptr->un.x86.real addr range to refer tothe RAM copy rather than the ROM version. When something runs inV86 mode, it’ll use the RAM locations when accessing the memory.

The amount of ROM shadowed is the maximum of thesize parameterand the size indicated by the third byte of the BIOS extension.

The function returns:

0 if there’s no ROM BIOS extension signature at the addressgiven

1 if you’re starting the system in physical mode and there’s noMMU to make a RAM copy be referenced

2 if everything works.

x86 scanmem()unsigned x86 scanmem (paddr t beg,

paddr t end)

An x86-only function that scans memory betweenbeg andendlooking for RAM, and returns the total amount of RAM found. It

208 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 229: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Writing your own kernel callout

scans memory performing a R/W test of 3 values at the start of each4K page. Each page is marked with a unique value. It then rescans thememory looking for contiguous areas of memory and adds them totheasinfo entry in the system page.

A special check is made for a block of memory between addresses0xB0000 and0xBFFFF, inclusive. If memory is found there, theblock is skipped (since it’s probably the dual-ported memory of aVGA card).

The callx86 scanmem (0, 0xFFFFFF) would locate all memoryin the first 16 megabytes of memory (except VGA memory). You maymake multiple calls tox86 scanmem() to different areas of memory inorder to step over known areas of dual-ported memory with hardware.

Writing your own kernel calloutIn order for the Neutrino microkernel to work on all boards, allhardware-dependent operations have been factored out of the code.Known askernel callouts, these routines must be provided by thestartup program.

The startup can actually have a number of different versions of thesame callout available — during hardware discovery it can determinewhich one is appropriate for the board it’s running on and make thatparticular instance of the callout available to the kernel. Alternatively,if you’re on a deeply embedded system and the startup knows exactlywhat hardware is present, only one of each callout might be present;the startup program simply tells the kernel about them with nodiscovery process.

The callout code is copied from the startup program into the systempage and after this, the startup memory (text and data) is freed.

At the point where the reboot callout is called:

� the MMU is enabled (the callout would have to disable it ifnecessary)

� you are running on the kernel stack

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 209

Page 230: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Writing your own kernel callout 2006, QNX Software Systems GmbH & Co. KG.

� you are executing code copied into the system page so nofunctions in the startup program are available.

The patch code is run during execution of the startup program itself,so regular calls work as normal.

Once copied, your code must be completely self-contained andposition independent. The purpose of the patch routines is to allowyou to patch up the code with constants, access to RW data storageetc. so that your code is self-contained and contains all thevirtual-physical mappings required.

Find out who’s gone beforeThe startup library provides a number of different callout routines thatwe’ve already written. You should check the source tree (originallyinstalled inbsp working dir/src/hardware/startup/lib/) tosee if a routine for your device/board is already available beforeembarking on the odyssey of writing your own. This directoryincludes generic code, as well as processor-specific directories.

In the CPU-dependent level of the tree for all the source files, look forfiles that match the pattern:

callout *.[sS]

Those are all the callouts provided by the library. Whether a file endsin .s or .S depends on whether it’s sent through the C preprocessorbefore being handed off to an assembler. For our purposes here, we’llsimply refer to them as.s files.

The names break down further like this:

callout category device.s

wherecategory is one of:

cache cache control routines

debug kernel debug input and output routines

interrupt interrupt handling routines

210 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 231: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Writing your own kernel callout

timer timer chip routine

reboot rebooting the system

Thedevice identifies the unique hardware that the callouts are for.Typically, all the routines in a particular source file would be used (ornot) as a group by the kernel. For example, thecallout debug 8250.s file contains thedisplay char 8250(),poll key 8250(), andbreak detect 8250() routines for dealing with an8250-style UART chip.

Why are they in assembly language?Since the memory used by the startup executable is reclaimed by theOS after startup has finished, the callouts that are selected for use bythe kernel can’t be used in place. Instead, they must be copied to asafe location (the library takes care of this for you). Therefore, thecallout code must be completely position-independent, which is whycallouts have to be written in assembly language. We need to knowwhere the callout begins and where it ends; there isn’t a portable wayto tell where a C function ends.

The other issue is that there isn’t a portable way to control thepreamble/postamble creation or code generation. So if an ABI changeoccurs or a build configuration issue occurs, we could have a verylatent bug.

For all but two of the routines, the kernel invokes the callouts with thenormal function-calling conventions. Later we’ll deal with the twoexceptions (interrupt id() andinterrupt eoi()).

Starting offFind a callout source file of the appropriate category that’s close towhat you want and copy it to a new filename. If the new routines willbe useful on more than one board, you might want to keep the sourcefile in your own private copy of the startup library. If not, you can justcopy to the directory where you’ve put your board-specific files.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 211

Page 232: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Writing your own kernel callout 2006, QNX Software Systems GmbH & Co. KG.

Now edit the new source file. At the top you’ll see something thatlooks like this:

#include "callout.ah"

Or:

.include "callout.ah"

The difference depends on the assembler syntax being used.

This include file defines theCALLOUT START andCALLOUT ENDmacros. TheCALLOUT START macro takes three parameters andmarks the start of one callout. The first parameter is the name of thecallout routine (we’ll come back to the two remaining parameterslater).

TheCALLOUT END macro indicates the end of the callout routinesource. It takes one parameter, which has to be the same as the firstparameter in the precedingCALLOUT START. If this particularroutine is selected to be used by the kernel, the startup library willcopy the code between theCALLOUT START andCALLOUT END toa safe place for the kernel to use. The exact syntax of the two macrosdepends on exactly which assembler is being used on the source. Twocommon versions are:

CALLOUT START(timer load 8254, 0, 0)CALLOUT END(timer load 8254)

Or:

CALLOUT START timer load 8254, 0, 0CALLOUT END timer load 8254

Just keep whatever syntax is being used by the original file you startedfrom. The original file will also have C prototypes for the routines ascomments, so you’ll know what parameters are being passed in. Nowyou should replace the code from the original file with what will workfor the new device you’re dealing with.

212 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 233: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Writing your own kernel callout

“Patching” the callout codeYou may need to write a callout that deals with a device that mayappear in different locations on different boards. You can do this by“patching” the callout code as it is copied to its final position. Thethird parameter of theCALLOUT START macro is either a zero or theaddress of apatcher() routine. This routine has the followingprototype:

void patcher(paddr t paddr,paddr t vaddr,unsigned rtn offset,unsigned rw offset,void *data,struct callout rtn *src );

This routine is invoked immediately after the callout has been copiedto its final resting place. The parameters are as follows:

paddr Physical address of the start of the system page.

vaddr Virtual address of the system page that allowsread/write access (usable only by the kernel).

rtn offset Offset from the beginning of the system page to the startof the callout’s code.

rw offset See the section on “Getting some R/W storage” below.

data A pointer to arbitrary data registered bycallout register data() (see above).

src A pointer to thecallout rtn structure that’s beingcopied into place.

Thedata andsrc arguments were added in the QNX Neutrino CoreOS 6.3.2. Earlier patcher functions can ignore them.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 213

Page 234: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Writing your own kernel callout 2006, QNX Software Systems GmbH & Co. KG.

Here’s an example of a patcher routine for an x86 processor:patch debug 8250:

movl 0x4(%esp),%eax // get paddr of routineaddl 0xc(%esp),%eax // ...

movl 0x14(%esp),%edx // get base info

movl DDI BASE(%edx),%ecx // patch code with real serial portmovl %ecx,0x1(%eax)movl DDI SHIFT(%edx),%ecx // patch code with register shiftmovl $REG LS,%edxshll %cl,%edxmovl %edx,0x6(%eax)ret

CALLOUT START(display char 8250, 0, patch debug 8250)movl $0x12345678,%edx // get serial port base (patched)movl $0x12345678,%ecx // get serial port shift (patched)

....CALLOUT END(display char 8250)

After thedisplay char 8250() routine has been copied, thepatch debug 8250() routine is invoked, where it modifies theconstants in the first two instructions to the appropriate I/O portlocation and register spacing for the particular board. The patcherroutines don’t have to be written in assembler, but they typically areto keep them in the same source file as the code they’re patching. Byarranging the first instructions in a group of related callouts all thesame (e.g.debug char *(), poll key *(), break detect *()), the samepatcher routine can be used for all of them.

Getting some R/W storageYour callouts may need to have access to some static read/writestorage. Normally this wouldn’t be possible because of theposition-independent requirements of a callout. But you can do it byusing the patcher routines and the second parameter toCALLOUT START. The second parameter toCALLOUT START is the

214 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 235: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Writing your own kernel callout

address of a four-byte variable that contains the amount of read/writestorage the callout needs. For example:

rw interrupt:.long 4

patch interrupt:add a1,a1,a2j rash a3,0+LOW16(a1)

/** Mask the specified interrupt*/

CALLOUT START(interrupt mask mips, rw interrupt, patch interrupt)/** Input Parameters :* a0 - syspage ptr* a1 - Interrupt Number* Returns:* v0 - error status*/

/** Mark the interrupt disabled*/

la t3,0x1234(a0) # get enabled levels addr (patched)li t1, MIPS SREG IMASK0....CALLOUT END(interrupt mask mips)

Therw interrupt address as the second parameter tells the startuplibrary that the routine needs four bytes of read/write storage (sincethe contents at that location is a4). The startup library allocates spaceat the end of the system page and passes the offset to it as therw offset parameter of the patcher routine. The patcher routine thenmodifies the initial instruction of the callout to the appropriate offset.While the callout is executing, thet3 register will contain a pointer tothe read/write storage. The question you’re undoubtedly asking at thispoint is: Why is the CALLOUT START parameter the address of alocation containing the amount of storage? Why not just pass theamount of storage directly?

That’s a fair question. It’s all part of a clever plan. A group of relatedcallouts may want to have access to shared storage so that they can

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 215

Page 236: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

PPC chips support 2006, QNX Software Systems GmbH & Co. KG.

pass information among themselves. The library passes the samerw offset value to the patcher routine for all routines that share thesame address as the second parameter toCALLOUT START. In otherwords:

CALLOUT START(interrupt mask mips, rw interrupt, patch interrupt)....CALLOUT END(interrupt mask mips)

CALLOUT START(interrupt unmask mips, rw interrupt, patch interrupt)....CALLOUT END(interrupt unmask mips)

CALLOUT START(interrupt eoi mips, rw interrupt, patch interrupt)....CALLOUT END(interrupt eoi mips)

CALLOUT START(interrupt id mips, rw interrupt, patch interrupt)....CALLOUT END(interrupt id mips)

will all get the samerw offset parameter value passed topatch interrupt() and thus will share the same read/write storage.

The exception that proves the ruleTo clean up a final point, theinterrupt id() andinterrupt eoi()routines aren’t called as normal routines. Instead, for performancereasons, the kernel intermixes these routines directly with kernel code— the normal function-calling conventions aren’t followed. Thecallout interrupt *.s files in the startup library will have adescription of what registers are used to pass values into and out ofthese callouts for your particular CPU. Note also that you can’t returnfrom the middle of the routine as you normally would. Instead, you’rerequired to “fall off the end” of the code.

PPC chips supportThe PPC startup library has been modified in order to:

� minimize the number of locations that check the PVR SPR.

� minimize duplication of code.

216 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 237: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. PPC chips support

� make it easier to leave out unneeded chip-dependent code.

� make it easier to add support for new CPUs.

� remove the notion of a PVR split into “family” and “member”fields.

� automatically take care of as much CPU-dependent code aspossible in the library.

The new routines and data variables all begin withppcv for PPCvariant, and are separated out into one function or data variable persource file. This separation allows maximum code reuse andminimum code duplication.

There are two new data structures:

� ppcv chip

� ppcv config

The first is:

struct ppcv chip {unsigned short chip;uint8 t paddr bits;uint8 t cache lsize;unsigned short icache lines;unsigned short dcache lines;unsigned cpu flags;unsigned pretend cpu;const char *name;void (*setup)(void);

};

Every supported CPU has a statically initialized variable of this type(in its own source file, e.g.<ppvc chip 603e7.c>).

If the chip field matches the upper 16 bits of the PVR register, thisppcv chip structure is selected and thepccv global variable in thelibrary is pointed at it. Only the upper 16 bits are checked so you canuse the constants likePPC750defined in<ppc/cpu.h> wheninitializing the field.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 217

Page 238: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

PPC chips support 2006, QNX Software Systems GmbH & Co. KG.

Thepaddr bits field is the number of physical address lines on thechip, usually 32.

Thecache lsize field is the number of bits in a cache line size of thechip, usually 5, but sometimes 4.

Theicache lines anddcache lines are the number of lines in theinstruction and data cache, respectively.

Thecpu flags field holds thePPCCPU * flag constants from<ppc/syspage.h> that are appropriate for this CPU. Note that theolder startups sometimes left out flags likePPCCPU HW HT anddepended on the kernel to check the PVR and turn them on ifappropriate. This is no longer the case. The kernel will continue toturn on those bits if it detects an old style startup, but will NOT with anew style one.

Thepretend cpu field goes into theppc kerinfo entry.pretendcpufieldof the system page and as before, it’s used to tell the kernel that eventhough you don’t know the PVR, you can act like it’s the pretend one.

Thename field is the string name of the CPU that gets put in thecpuinfo section.

Thesetup function is called when a particularppcv chip structure hasbeen selected by the library as the one to use. It continues the librarycustomization process by filling the second new structure.

The second data structure is:

struct ppcv config {unsigned family;void (*cpuconfig1)(int cpu);void (*cpuconfig2)(int cpu);void (*cpuinfo)(struct cpuinfo entry *cpu);void (*qtime)(void);void *(*map)(unsigned size, paddr t phys,

unsigned prot flags);void (*unmap)(void *);int (*mmu info)(enum mmu info info, unsigned tlb);

//NYI: tlb read/write};

There’s a single variable defined of this type in the library, calledppcv config. The setup function identified by the selected ppcvchip

218 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 239: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. PPC chips support

is responsible for filling in the fields with the appropriate routines forthe chip. The variable is statically initialized with a set of do-nothingroutines, so if a particular chip doesn’t need something done in onespot (typically thecpuconfig[1/2] routines), the setup routine doesn’thave to fill anything in).

The general design rules for the routines are that they should performwhatever chip-specific actions that they can perform that are not alsoboard-specific. For example, the old startupmain() functions wouldsometimes turn off data translation, since some IPLs turned it on.With the new startups this is handled automatically by the library. Onthe other hand, both the old and new startups call theppc700 init l2 cache() manually inmain(), since the exact bits to putin the L2CR register are board-specific. The routines in the librariesshould be modified to work with the IPL and initialize the CPUproperly, rather than modifying the board-specific code to hackaround it (e.g. the aforementioned disabling of data translation).

The setup routine might also initialize a couple of other freestandingvariables that other support routines use to avoid them having tocheck the PVR value again (e.g. see theppc600 set clock freqs() andppcv setup 7450() functions for an example).

The new startup (and kernel, when used with a new startup) no longerdepends on the PVR to identify the chip family. Instead the “family”field is filled in with aPPCFAMILY * value from<ppc/syspage.h>. This is transferred to theppc kerinfo entry.family field on the system page, which thekernel uses to verify that the right version ofprocnto is being used.

If the kernel sees a value ofPPCFAMILY UNKNOWN (zero) in thesystem page, it assumes that an old style startup is being used and willattempt to determine the family (andcpuinfo->flags) fields on itsown. DO NOT USE that feature with new startups.

Fill in the ppcv config.family andppcv chip.cpu flags field properly.Thecpuconfig1 routine is used to configure the CPU for use instartup, and is called early beforemain() is called. For example, itmakes sure that instruction and data translation is turned off, theexception table is pointed at low memory, etc. It’s called once for

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 219

Page 240: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

PPC chips support 2006, QNX Software Systems GmbH & Co. KG.

every CPU in an SMP system, with thecpu parm indicating the CPUnumber being initialized.

Thecpuconfig2 routine is called just before startup transfers control tothe first bootstrap executable in the image file system. It configuresthe CPU for running in the bootstrap environment, e.g. turning onCPU-specific features such as HID0 and HID1 bits. Again it’s calledonce per CPU in an SMP system with thecpu parm indicating whichone.

Thecpuinfo routine is called byinit one cpuinfo() to fill in thecpuinfo entry structure for each CPU. Theqtime routine is calledby init qtime() to set up theqtime syspage section.

Themap andunmap routines used to create/delete memory mappingsfor startup and callout use, are called by:

� startup map io

� startup map memory

� startup unmap io

� startup unmap memory

� callout map io

� callout map memory

There’s one more data variable to mention. This isppcv list, which isa statically initialized array of pointers toppcv chip structures. Thedefault version of the variable in the library has a list of all theppcv chip variables defined by the library so, by default, the library iscapable of handling any type of PPC chip.

By defining appcv list variable in the board-specific directory andadding only theppcv chip * variable(s) that can be used with thatboard, all the chip-specific code for the processors that can’t possiblybe there will be left out.

For example, the new shasta-ssc startup with the defaultppcv list isabout 1K bigger than the old version. By restricting theppcv list to

220 Chapter 5 � Customizing Image Startup Programs November 3, 2006

Page 241: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. PPC chips support

only ppcv chip 750, the new startup drops to 1K smaller than theoriginal.

Adding a new CPU to the startup libraryFor a CPU calledxyz, create a<ppcv chip xyz.c> and in it put anappropriately initialized structppcv chip ppcv chip xyz variable. Addtheppcv chip xyz variable to the defaultppcv list (in<ppcv list.c>).

If you were able to use an already existingppcv setup *() function fortheppcv chip xyz initialization, you’re done. Otherwise, create a<ppcv setup xyz.c> file with the properly codedppcv setup xyz()function in it (don’t forget to add the prototype to<cpu startup.h>).

If you were able to use already existingppcv * routines in theppcv setup xyz() function, you’re done. Otherwise, create the routinesin the appropriate<ppcv * xyz.c> files (don’t forget to add theprototype(s) to<cpu startup.h>). When possible, code theroutines in an object-oriented manner, calling already existingroutines to fill more generic information, e.g.ppcv cpuconfig2 700()usesppcv cpuconfig2 600() to do most of the work and then it justfills in the 700 series-specific info.

With the new design, the following routines are now deprecated (andthey spit out a message to that effect if you call them):

ppc600 init features(), ppc600 init caches(), ppc600 flush caches()Handled automatically by the library now.

ppc7450 init l2 cache()

Useppc700 init l2 cache() instead.

November 3, 2006 Chapter 5 � Customizing Image Startup Programs 221

Page 242: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 243: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Chapter 6

Customizing the Flash Filesystem

In this chapter. . .Introduction 225Driver structure 226Building your flash filesystem driver 228Example: Thedevf-ram driver 248

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 223

Page 244: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 245: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

IntroductionNeutrino ships with a small number of prebuilt flash filesystemdrivers for particular embedded systems. For the currently availabledrivers, look in the${QNX TARGET}/${PROCESSOR}/sbin

directory. The flash filesystem drivers are nameddevf-system, wheresystem is derived from the name of the embedded system. You’ll finda general description of the flash filesystem in theSystem Architecturebook and descriptions of all the flash filesystem drivers in theUtilitiesReference.

If a driver isn’t provided for your particular target embedded system,you should first try our “generic” driver (devf-generic). Thisdriver often — but not always — works with standard flash hardware.The driver assumes a supported memory technology driver (MTD)and linear memory addressing.

If none of our drivers works for your hardware, you’ll need to buildyour own driver. We provide all the source code needed for you tocustomize a flash filesystem driver for your target. After installation,look in thebsp working dir/src/hardware/flash/boardsdirectory — you’ll find a subdirectory for each board we support.

Besides theboards directory, you should also refer to the followingsources to find out what boards/drivers we currently support:

� QNX docs (BSP docs as well asdevf-* entries inUtilitiesReference).

� the Developer Support Center area of our website(www.qnx.com).

Note that we currently support customizing a driver only forembedded systems with onboard flash memory (also called a residentflash array or RFA). If you need support forremovable media likePCMCIA or compact or miniature memory cards, then please contactus.

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 225

Page 246: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Driver structure 2006, QNX Software Systems GmbH & Co. KG.

Driver structureEvery flash filesystem driver consists of the following components:

� dispatch, resmgr, andiofunc layers

� flash filesystem

� socket services

� flash services

� probe routine

When customizing the flash filesystem driver for your system, you’llbe modifying themain() routine for the flash filesystem and providingan implementation of the socket services component. The othercomponents are supplied as libraries to link into the driver.

/fs0p0 /dev/fs0p0

Flash filesystem

Socket services

Flash

services

Hardware

dispatch*,resmgr*, iofunc*

Probe

routine

Applications

Structure of the flash filesystem driver.

226 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 247: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Driver structure

resmgr and iofunc layersLike all Neutrino device managers, the flash filesystem uses thestandardresmgr/iofunc interface and accepts the standard set ofresource manager messages. The flash filesystem turns thesemessages into read, write, and erase operations on the underlyingflash devices.

For example, anopen message would result in code being executedthat would read the necessary filesystem data structures on the flashdevice and locate the requested file. A subsequentwrite message willmodify the contents of the file on flash. Special functions, such aserasing the flash device, are implemented usingdevctl messages.

Flash filesystem componentThe flash filesystem itself is the “personality” component of the flashfilesystem driver. The filesystem contains all the code to processfilesystem requests and to manage the filesystem on the flash devices.The socket and flash services components are used by the flashfilesystem to access the flash devices.

The code for the flash filesystem component is platform-independentand is provided in thelibfs-flash3.a library.

Socket services componentThe socket services component is responsible for any system-specificinitialization required by the flash devices at startup and for providingaddressability to the flash devices (this applies mainly to windowedflash interfaces).

Before reading/writing the flash device, other components will usesocket services to make sure the required address range can beaccessed. On systems where the flash device is linearly mapped intothe processor address space, addressability is trivial. On systemswhere the flash is either bank-switched or hidden behind some otherinterface (such as PCMCIA), addressability is more complicated.

The socket services component is the one that will require the mostcustomization for your system.

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 227

Page 248: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

Flash services componentThe flash services component contains the device-specific coderequired to write and erase particular flash devices. This component isalso called the memory technology driver (MTD).

The directory${QNX TARGET}/${PROCESSOR}/lib contains theMTD library libmtd-flash.a to handle the flash devices wesupport.

bsp working dir/src/hardware/flash/mtd-flash containssource for thelibmtd-flash.a library.

Probe routine componentThe probe routine uses a special algorithm to estimate the size of theflash array. Since the source code for the probe routine is available,you should be able to readily identify any failures in the sizingalgorithm.

Building your flash filesystem driverBefore you start customizing your own flash filesystem driver, youshould examine the source of all the sample drivers supplied. Mostlikely, one of the existing drivers can be easily customized to supportyour system. If not, thedevf-ram source provides a good template tostart with.

The source treeThe source files are organized as follows:

228 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 249: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

startupipl flash

bsp_working_dir/src/hardware

boards

800fadsexplr2ppaqramsc400vr41xx...

mipsppc

x86

mtd-flash

amdfujitsuintel

sharp

romsram

...

arm

sh

Flash directory structure.

The following pathnames apply to the flash filesystems:

Pathname Description

${QNX TARGET}/usr/include/sys Header filef3s mtd.h.

${QNX TARGET}/usr/include/fs Header filesf3s api.h,f3s socket.h, andf3s flash.h.

continued. . .

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 229

Page 250: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

Pathname Description

${QNX TARGET}/${PROCESSOR}/lib Libraries for flashfilesystem and flashservices.

bsp working dir/src/hardware/flash/boards Source code for socketservices.

bsp working dir/src/hardware/flash/mtd-flash Source code for flashservices as well as forprobe routine and helperfunctions.

Before you modify any source, you should:

1 Create a new directory for your driver in thebsp working dir/src/hardware/flash/boards directory.

2 Copy the files from the sample directory you want into yournew directory.

For example, to create a driver calledmyboard based on the800FADS board example, you would:

cd bsp working dir/hardware/flash/boardsmkdir myboardcp -cRv 800fads myboardcd myboardmake clean

The copy command (cp) specified a recursive copy (the-R option).This will copy all files from the specified source directoryincludingthe subdirectory indicating which CPU this driver should be built for.In our example above, the800fads directory has appc subdirectory— this will cause the new driver (myboard in our example) to bebuilt for the PowerPC.

230 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 251: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

The MakefileWhen you go to build your new flash filesystem driver, you don’t needto change theMakefile. Our recursive makefile structure ensuresyou’re linking to the appropriate libraries.

Making the driverYou should use the following command to make the driver:

make F3S VER=3 MTD VER=2

For more information, see the technical noteMigrating to the NewFlash Filesystem.

The main() functionThemain() function for the driver, which you’ll find in themain.cfile in the sample directories, is the first thing that needs to bemodified for your system. Let’s look at themain.c file for the800FADS board example:

/*** File: main.c for 800FADS board*/#include <sys/f3s mtd.h>#include "f3s 800fads.h"

int main(int argc, char **argv){

int error;static f3s service t service[]={

{sizeof(f3s service t),f3s 800fads open,f3s 800fads page,f3s 800fads status,f3s 800fads close

},{

/* mandatory last entry */0, 0, 0, 0, 0

}};

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 231

Page 252: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

static f3s flash v2 t flash[] ={

{sizeof(f3s flash v2 t),f3s a29f040 ident, /* Common Ident */f3s a29f040 reset, /* Common Reset */

/* v1 Read/Write/Erase/Suspend/Resume/Sync (Unused) */NULL, NULL, NULL, NULL, NULL, NULL,

NULL, /* v2 Read (Use default) */

f3s a29f040 v2write, /* v2 Write */f3s a29f040 v2erase, /* v2 Erase */f3s a29f040 v2suspend, /* v2 Suspend */f3s a29f040 v2resume, /* v2 Resume */f3s a29f040 v2sync, /* v2 Sync */

/* v2 Islock/Lock/Unlock/Unlockall (not supported) */NULL, NULL, NULL, NULL

},

{/* mandatory last entry */0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

}};

/* init f3s */f3s init(argc, argv, flash);

/* start f3s */error = f3s start(service, flash);

return error;}

Theservice array contains one or moref3s service t structures,depending on how many different sockets your driver has to support.Thef3s service t structure, defined in<fs/f3s socket.h>,contains function pointers to the socket services routines.

Theflash array contains one or moref3s flash t structures,depending on how many different types of flash device your driverhas to support. Thef3s flash t structure, defined in

232 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 253: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

<fs/f3s flash.h>, contains function pointers to the flash servicesroutines.

Thef3s init() andf3s start() functions are defined in the<fs/f3s api.h> header file.

Don’t use the<fs/f3s socket.h>, <fs/f3s flash.h>, and<fs/f3s api.h> header files directly. Instead, you should include<sys/f3s mtd.h> for backward and forward compatibility.

f3s init()f3s init (int argc,

char **argv,f3s flash t *flash vect)

This function passes the command-line arguments to the flashfilesystem component, which then initializes itself.

f3s start()f3s start (f3s service t *service,

f3s flash t *flash)

This function passes theservice andflash arrays to the filesystemcomponent so it can make calls to the socket and flash services, andthen starts the driver. This function returns only when the driver isabout to exit.

When writing yourmain.c, you’ll need to enter:

� the socket services functions for each socket in theservice array

� the flash services functions for each flash device in theflash array.

If you have a system with only one socket consisting of the same flashdevices, then there will be only a single entry in each array.

Socket services interfaceThe socket services interface, defined in the<fs/f3s socket.h>

header file, consists of the following functions:

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 233

Page 254: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

� f3s open()

� f3s page()

� f3s status()

� f3s close()

� f3s socket option()

� f3s socket syspage()

f3s open()int32 t f3s open (f3s socket t *socket,

uint32 t flags)

This function is called to initialize a socket or a particular window ina socket. The function should process any socket options, initializeand map in the flash devices, and initialize thesocket structure.

f3s page()uint8 t *f3s page (f3s socket t *socket,

uint32 t flags,uint32 t offset,int32 t *size)

This function is called to access awindow size sized window ataddressoffset from the start of the device; it must be provided for bothbank-switched and linearly mapped flash devices. If thesizeparameter is non-NULL, you should set it to the size of the window.The function must return a pointer suitable for accessing the device ataddressoffset. On error, it should return NULL and seterrno toERANGE.

f3s status()int32 t f3s status (f3s socket t *socket,

uint32 t flags)

This function is called to get the socket status. It’s used currently onlyfor interfaces that support dynamic insertion and removal. Foronboard flash, you should simply returnEOK.

234 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 255: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

f3s close()void f3s close (f3s socket t *socket,

uint32 t flags)

This function is called to close the socket. If you need to, you candisable the flash device and remove any programming voltage, etc.

The following flags are defined for theflags parameter in the socketfunctions:

F3S POWERVCC

Apply read power.

F3S POWERVPP

Apply program power.

F3S OPERSOCKET

Operation applies to socket given insocket index.

F3S OPERWINDOW

Operation applies to window given inwindow index.

Thesocket parameter is used for passing arguments and returningresults from the socket services and for storing information abouteach socket. To handle complex interfaces such as PCMCIA, thestructure has been defined so that there can be more than one socket;each socket can have more than one window. A simple linear flasharray would have a single socket and no windows.

Thesocket structure is defined as:

typedef struct f3s socket s{/** these fields are initialized by the flash file system* and later validated and set by the socket services*/Uint16t struct size; /* size of this structure */Uint16t status; /* status of this structure */Uint8t *option; /* option string from flashio */Uint16t socket index; /* index of socket */

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 235

Page 256: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

Uint16t window index; /* index of window */

/** these fields are initialized by the socket services and later* referenced by the flash file system*/Uint8t *name; /* name of driver */Paddr64t address; /* physical address 0 for allocated */Uint32t window size; /* size of window power of two mandatory */Uint32t array offset; /* offset of array 0 for based */Uint32t array size; /* size of array 0 for window size */Uint32t unit size; /* size of unit 0 for probed */Uint32t flags; /* flags for capabilities */Uint16t bus width; /* width of bus */Uint16t window num; /* number of windows 0 for not windowed */

/** these fields are initialized by the socket services and later* referenced by the socket services*/Uint8t* memory; /* access pointer for window memory */

void *socket handle; /* socket handle pointer for externallibrary */

void *window handle; /* window handle pointer for externallibrary */

/** this field is modified by the socket services as different window* pages are selected*/Uint32t window offset; /* offset of window */

}f3s socket t;

Here’s a description of the fields:

option Option string from command line; parse using thef3s socket option() function.

socket index Current socket.

window index Current window.

name String containing name of driver.

address Base address of flash array.

236 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 257: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

window size Size of window in bytes.

array size Size of array in bytes; 0 indicates unknown.

unit size Size of unit in bytes; 0 indicates probed.

flags Theflags field is currently unused.

bus width Width of the flash devices in bytes.

window num Number of windows in socket; 0 indicatesnon-windowed.

memory Free for use by socket services; usually storescurrent window address.

socket handle Free for use by socket services; usually storespointer to any extra data for socket.

window handle Free for use by socket services; usually storespointer to any extra data for window.

window offset Offset of window from base of device in bytes.

Options parsingThe socket services should parse any applicable options beforeinitializing the flash devices in thef3s open() function. Two supportfunctions are provided for this:

f3s socket option()int f3s socket option (f3s socket t *socket)

Parse the driver command-line options that apply to the socketservices.

Currently the following options are defined:

-s baseaddress,windowsize, arrayoffset, arraysize, unitsize, buswidth, interleave

where:

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 237

Page 258: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

baseaddress Base address of the socket/window.

windowsize Size of the socket/window.

arrayoffset Offset of window from base of devices in bytes.

arraysize Size of array in bytes, 0 indicates unknown.

buswidth Memory bus attached to the flash chips.

interleave Number of physical chips interleaved to form alarger logical chip (e.g. two 16-bit chips interleavedto form a 32-bit logical chip).

f3s socket syspage()int f3s socket syspage (f3s socket t *socket)

Parse the syspage options that apply to the socket services.

Thesyspage options allow the socket services to get any informationabout the flash devices in the system that is collected by the startupprogram and stored in the syspage. See the chapter on CustomizingImage Startup Programs for more information.

Flash services interfaceThe flash services interface, defined in the<fs/f3s flash.h>

header file, consists of the following functions:

� f3s ident()

� f3s reset()

� f3s v2read()

� f3s v2write()

� f3s v2erase()

� f3s v2suspend()

� f3s v2resume()

238 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 259: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

� f3s v2sync()

� f3s v2islock()

� f3s v2lock()

� f3s v2unlock()

� f3s v2unlockall()

The values for theflags parameter are defined in<fs/s3s flash.h>. The most important one isF3SVERIFY WRITE. If this is set, the routine must perform aread-back verification after the write as a double check that the writesucceeded. Occasionally, however, the hardware reports success evenwhen the write didn’t work as expected.

f3s ident()int32 t f3s ident (f3s dbase t *dbase,

f3s access t *access,uint32 t text offset,uint32 t flags)

Identifies the flash device at addresstext offset and fills in thedbasestructure with information about the device type and geometry.

f3s reset()void f3s reset (f3s dbase t *dbase,

f3s access t *access,uint32 t text offset)

Resets the flash device at addresstext offset into the defaultread-mode after calling thefs3 ident() function or after a device error.

f3s v2read()int32 t f3s v2read (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset,Int32t buffer size,Uint8t *buffer);

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 239

Page 260: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

This optional function is called to readbuffer size bytes from addresstext offset into buffer. Normally the flash devices will be read directlyvia memcpy().

On success, it should return the number of bytes read. If an erroroccurs, it should return -1 witherrno set to one of the following:

EIO Recoverable I/O error (e.g. failed due to low power,but corruption is localized and block will be usableafter an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2write()int32 t f3s v2write (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset,Int32t buffer size,Uint8t *buffer);

This function writesbuffer size bytes frombuffer to addresstext offset.

On success, it should return the number of bytes written. If an erroroccurs, it should return -1 witherrno set to one of the following:

EIO Recoverable I/O error (e.g. failed due to low power orwrite failed, but corruption is localized and block willbe usable after an erase)

240 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 261: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EROFS Block is write protected

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2erase()int f3s v2erase (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

This function begins erasing the flash block containing thetext offset.It can optionally determine if an error has already occurred, or it canjust return EOK and letf3s v2sync() detect any error.

On success, it should return EOK. If an error occurs, it should returnone of the following:

EIO Recoverable I/O error (e.g. failed due to low power orerase failed, but corruption is localized and block willbe usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EROFS Block is write protected

EINVAL Invalid command error

EBUSY Flash busy, try again (e.g. erasing same block twice)

ERANGE Flash memory access out of range (via service->pagefunction)

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 241

Page 262: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2suspend()int f3s v2suspend (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

This function suspends an erase operation, when supported, for a reador for a write.

On success, it should return EOK. If an error occurs, it should returnone of the following:

EIO Recoverable I/O error (e.g. failed due to low power orerase failed, but corruption is localized and block willbe usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EINVAL Invalid command error

ECANCELED

Suspend canceled because erase has alreadycompleted

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

242 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 263: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

f3s v2resume()int f3s v2resume (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

This function resumes an erase operation after a suspend commandhas been issued.

On success, it should return EOK. If an error occurs, it should returnone of the following:

EIO Recoverable I/O error (e.g. failed due to low power orerase failed, but corruption is localized and block willbe usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2sync()int f3s v2sync (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

This function determines whether an erase operation has completedand returns any detected error.

On success, it should return EOK. If an error occurs, it should returnone of the following:

EAGAIN Still erasing

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 243

Page 264: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

EIO Recoverable I/O error (e.g. failed due to low power orerase failed, but corruption is localized and block willbe usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EROFS Block is write protected

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2islock()int f3s v2islock (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

This function determines whether the block containing the addresstext offset can be written to (we term it as success) or not.

On success, it should return EOK. If the block cannot be written to, itshould return EROFS. Otherwise, an error has occurred and it shouldreturn one of the following:

EIO Recoverable I/O error (e.g. failed due to low power orlock failed, but corruption is localized and block willbe usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

244 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 265: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2lock()int f3s v2lock (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

This function write-protects the block containing the addresstext offset (if supported). If the block is already locked, it doesnothing.

On success, it should return EOK. If an error occurs, it should returnone of the following:

EIO Recoverable I/O error (e.g. failed due to low power orlock failed, but corruption is localized and block willbe usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2unlock()int f3s v2unlock (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 245

Page 266: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Building your flash filesystem driver 2006, QNX Software Systems GmbH & Co. KG.

This function clears write-protection of the block containing theaddresstext offset (if supported). If the block is already unlocked, itdoes nothing. Note that some devices do not support unlocking ofarbitrary blocks. Instead all blocks must be unlocked at the sametime. In this case, usef3s v2unlockall() instead.

On success, it should return EOK. If an error occurs, it should returnone of the following:

EIO Recoverable I/O error (e.g. failed due to low power orunlock failed, but corruption is localized and blockwill be usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

f3s v2unlockall()int f3s v2unlockall (f3s dbase t *dbase,

f3s access t *access,Uint32t flags,Uint32t text offset);

This function clears all write-protected blocks on the devicecontaining the addresstext offset. Some boards use multiple chips toform one single logical device. In this situation, each chip will havef3s v2unlockall() invoked on it separately.

On success, it should return EOK. If an error occurs, it should returnone of the following:

246 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 267: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Building your flash filesystem driver

EIO Recoverable I/O error (e.g. failed due to low power orunlock failed, but corruption is localized and blockwill be usable after an erase)

EFAULT Unrecoverable I/O error (e.g. block no longer usable)

EINVAL Invalid command error

ERANGE Flash memory access out of range (via service->pagefunction)

ENODEV Flash no longer accessible (e.g. flash removed)

ESHUTDOWN

Critical error, shutdown flash driver

We currently don’t support user-customized flash services, nor do wesupply detailed descriptions of the flash services implementation.

Choosing the right routinesWe provide several device-specific variants of the core set of flashservices:

� f3s ident()

� f3s reset()

� f3s v2write()

� f3s v2erase()

� f3s v2suspend()

� f3s v2resume()

� f3s v2sync()

� f3s v2islock()

� f3s v2lock()

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 247

Page 268: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Example: The devf-ram driver 2006, QNX Software Systems GmbH & Co. KG.

� f3s v2unlock()

� f3s v2unlockall().

For example, if you have a 16-bit Intel device and you want to usef3s v2erase(), you’d use thef3s iCFI v2erase() routine.

For more information, see the technical noteChoosing the correctMTD Routine for the Flash Filesystem.

The file<sys/f3s mtd.h> can be found in:

bsp working dir/src/hardware/flash/mtd-flash/public/sys/f3s mtd.h.

Example: The devf-ram driverThis driver uses main memory rather than flash for storing the flashfilesystem. Therefore, the filesystem isnot persistent — all data islost when the system reboots or/dev/shmem/fs0 is removed. Thisdriver is used mainly for test purposes.

main()In themain() function, we declare a singleservices array entry for thesocket services functions and a null entry for the flash servicesfunctions.

/*** File: f3s ram main.c**** Description:**** This file contains the main function for the f3s** flash filesystem***/#include "f3s ram.h"

int main(int argc, char **argv){

int error;static f3s service t service[] =

248 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 269: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Example: The devf-ram driver

{{

sizeof(f3s service t),f3s ram open,f3s ram page,f3s ram status,f3s ram close

},

{/* mandatory last entry */0, 0, 0, 0, 0

}};

static f3s flash v2 t flash[] ={

{sizeof(f3s flash v2 t),f3s sram ident, /* Common Ident */f3s sram reset, /* Common Reset */NULL, /* v1 Read (Deprecated) */NULL, /* v1 Write (Deprecated) */NULL, /* v1 Erase (Deprecated) */NULL, /* v1 Suspend (Deprecated) */NULL, /* v1 Resume (Deprecated) */NULL, /* v1 Sync (Deprecated) */NULL, /* v2 Read (Use default) */f3s sram v2write, /* v2 Write */f3s sram v2erase, /* v2 Erase */NULL, /* v2 Suspend (Unused) */NULL, /* v2 Resume (Unused) */f3s sram v2sync, /* v2 Sync */f3s sram v2islock, /* v2 Islock */f3s sram v2lock, /* v2 Lock */f3s sram v2unlock, /* v2 Unlock */f3s sram v2unlockall /* v2 Unlockall */

},

{/* mandatory last entry */0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

}};

/* init f3s */f3s init(argc, argv, (f3s flash t *)flash);

/* start f3s */error = f3s start(service, (f3s flash t *)flash);

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 249

Page 270: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Example: The devf-ram driver 2006, QNX Software Systems GmbH & Co. KG.

return (error);}

f3s ram open()In the socket servicesopen() function, we assign a name for the driverand then process any options. If no options are specified, a defaultsize is assigned and the memory for the (virtual) flash is allocated.

/*** File: f3s ram open.c**** Description:**** This file contains the open function for the ram library***/#include "f3s ram.h"

int32 t f3s ram open(f3s socket t *socket,uint32 t flags)

{static void * memory;char name[8];int fd;int flag;

/* check if not initialized */if (!memory){

/* get io privileges */ThreadCtl( NTO TCTL IO, NULL);

/* setup socket name */socket->name = "RAM (flash simulation)";

/* check if there are socket options */if (f3s socket option(socket))

socket->window size = 1024 * 1024;

/* check if array size was not chosen */if (!socket->array size)

socket->array size = socket->window size;

/* check if array size was not specified */if (!socket->array size) return (ENXIO);

250 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 271: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Example: The devf-ram driver

/* set shared memory name */sprintf(name, "/fs%X", socket->socket index);

/* open shared memory */fd = shm open(name, O CREAT | O RDWR, 0777);

if (fd < 0) return (errno);

/* set size of shared memory */flag = ftruncate(fd, socket->array size);

if (flag){

close(fd);return (errno);

}

/* map physical address into memory */memory = mmap(NULL, socket->array size,

PROT READ | PROT WRITE,MAP SHARED, fd, socket->address);

if (!memory){

close(fd);return (errno);

}

/* copy socket handle */socket->socket handle = (void *)fd;

}

/* set socket memory pointer to previously initializedvalue */

socket->memory = memory;return (EOK);

}

f3s ram page()In the socket servicespage() function, we first check that the givenoffset doesn’t exceed the bounds of the allocated memory, and thenassign the windowsize if required. The function returns the offsetaddress modulo the window size.

/*

November 3, 2006 Chapter 6 � Customizing the Flash Filesystem 251

Page 272: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Example: The devf-ram driver 2006, QNX Software Systems GmbH & Co. KG.

** File: f3s ram page.c**** Description:**** This file contains the page function for the ram library***/#include "f3s ram.h"

uint8 t *f3s ram page(f3s socket t *socket,uint32 t flags,uint32 t offset,int32 t *size)

{/* check if offset does not fit in array */if (offset >= socket->window size){

errno = ERANGE;return (NULL);

}

/* select proper page */socket->window offset = offset & ˜(socket->window size - 1);

/* set size properly */*size = min((offset & ˜(socket->window size - 1)) +

socket->window size - offset, *size);

/* return memory pointer */return (socket->memory + offset);

}

The socket servicesstatus() andclose() don’t do anything interestingin this driver.

252 Chapter 6 � Customizing the Flash Filesystem November 3, 2006

Page 273: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Appendix A

System Design Considerations

In this appendix. . .Introduction 255NMI 262Design do’s and don’ts 263

November 3, 2006 Appendix: A � System Design Considerations 253

Page 274: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 275: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

IntroductionSince Neutrino is a protected-mode 32-bit operating system, manylimiting design considerations won’t apply (particularly on the x86platform, which is steeped in DOS and 8088 legacy concerns). Bynoting the various “do’s” and “don’ts” given in this appendix, you’llbe able to design and build an embedded system tailored for Neutrino.

You may also be able to realize certain savings, in terms of designtime, hardware costs, and software customization effort.

Before you design your systemBefore you begin designing your system, here are some typicalquestions you might consider:

� What speed of processor do you need?

� How much memory is required?

� What peripherals are required?

� How will you debug the platform?

� How will you perform field upgrades?

Naturally, your particular system will dictate whether all of these (orothers) are relevant. But for the purposes of this discussion, we’llassume all these considerations apply.

Processor speed

Although Neutrino is a realtime operating system, this fact alonedoesn’t necessarily mean that any givenapplication will run quickly.Graphical user interface applications can consume a reasonableamount of CPU and are particularly sensitive to the end-user’sperception of speed.

If at all possible, try to prototype the system on either a standard PC(in the case of x86-based designs) or a supported evaluation board (inthe case of x86, PPC, ARM, SH, and MIPS designs). This will veryquickly give you a “feel” for the speed of a particular processor.

November 3, 2006 Appendix: A � System Design Considerations 255

Page 276: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Introduction 2006, QNX Software Systems GmbH & Co. KG.

Memory requirements

During initial prototyping, you should plan on more memory on thetarget than during the final stages. This is because you’ll often berunningdebugging versions of software, which may be larger. Also,you’ll want to include diagnostics and utility programs, which againwill consume more memory than expected. Once your prototypesystem is up and running, you can then start thinking about how muchmemory you “really” need.

Peripherals

Given a choice, you should use peripherals that are listed as supportedby Neutrino. This includes such items as disk controllers, networkcards, PC-Card controllers, flash memory chips, and graphicscontrollers. Look in the Developer Support Center area of our website(www.qnx.com) for supported hardware and the Download Center forthird-party products.

Graphics controllers are one of the particularly delicate areas in thedesign of an embedded system, often because a chip may be very newwhen it’s selected and we may not yet have a driver for it. Also, ifyou’re using a graphics controller in conjunction with an LCD panel,beware that this is perhaps the most complicated setup because of themany registers that must be programmed to make it work.

Note that QNX Software Systems can do custom development workfor you; for more information, contact your sales representative. Otherconsulting houses offer similar services to the QNX community.

Debugging

In many cases, especially in cost-sensitive designs, you won’t want toprovide any additional functionality beyond that absolutely requiredfor the project at hand. But since the project is usually a brand newdesign, you’ll need to ensure that the hardware actually worksper seand then actually works with the software.

We recommend that you install some form of easy-to-get-at hardwaredebugging port, so that the software can output diagnostics as it’sbooting. Generally, something as simple as a latched output that can

256 Appendix: A � System Design Considerations November 3, 2006

Page 277: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

drive a single LED is sufficient, but an 8- or 16-bit port that drives anumber of 7-segment LEDs would be even better. Best of all is asimple serial port, because more meaningful diagnostics can bewritten by the software and easily captured.

This debug port can be left off for final assembly or a slightlymodified “final” version of the board can be created. The cost savingsin terms of software development time generally pay for the hardwaremodifications many times over.

Field upgrades

You can handle the issue of field upgrades in various ways, dependingon the nature of your particular target system:

� a JTAG port

� socketed Flash/EPROM devices

� a communications port.

You may need such a vehicle for your update software even duringyour initial software development effort. At this early phase, you’lleffectively be performing “field upgrades” as your software is beingdeveloped.

Other design considerationsThere are other design considerations that relate to both the hardwareand software development process. In this section, we’ll discuss someof the more common ones.

EPROM/Flash filesystem considerations

Solid-state mass storage can be located anywhere in the address space— it should be linearly mapped. In legacy designs (particularly x86),the mass storage device was often forced into a window of some size(typically from 8K to 64K), with additional hardware being requiredto map that window into the processor’s address space. Additionally,this window was traditionally located in the first 1M of memory.

November 3, 2006 Appendix: A � System Design Considerations 257

Page 278: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Introduction 2006, QNX Software Systems GmbH & Co. KG.

With a modern, 32-bit processor, the physical address space of theprocessor is usually sufficient to address the entire mass storagedevice. In fact, this makes the software easier by not having to worryabout how to address the window-mapping hardware.

The two driving factors to be considered in the hardware design ofsolid-state media are cost and compatibility. If the medium is to besoldered onto the board, then there’s little chance that it may need tobe compatible with other operating systems. Therefore, simply mapthe entire medium into the address space of the processor and don’tadd additional hardware to perform windowing or bank switching.

Adhering to standards (e.g. PCMCIA, FFS2, etc.) for solid-statememory is also unnecessary — our Flash filesystem drivers knowhow to address and use just a raw Flash device.

When the time comes to decide on the logical layout of the flashmemory chips, the tradeoff will be between the size of the erase blockand the speed of access. By taking four flash devices and organizingthem into a 32-bit wide bus, you gain speed. However, you alsoincrease the erase block size by a factor of four (e.g. 256K eraseblocks).

Note that we don’t recommend trying to XIP out of flash memorythat’s being used for a flash filesystem. This is because the flashfilesystem may need to erase a particular block of memory. While thiserase operation is in progress, depending on the particular type offlash memory device you have, theentire device may be unusable. Ifthis isalso the device containing the code that the processor isactively executing from, you’ll run into problems. Therefore, werecommend that you use at least two independent sets of flashdevices: one set for the filesystem and one set for the code.

IPL location

Under Neutrino, the only location requirement is that the ROM bootdevice that performs the IPL is addressable at theprocessor’s resetvector. No special hardware is required to be able to “move” thelocation of the boot ROM.

258 Appendix: A � System Design Considerations November 3, 2006

Page 279: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

Graphics cards

All the drivers under Neutrino can be programmed to deal withgraphics hardware at any address — there’s no requirement to mapthe VGA video aperture below 1M.

A20 gate

On the x86 platform, another vestige of the legacy 1M addresslimitation is usually found in something called anA20 gate. This is apiece of hardware that would force the A20 address line to zero,regardless of the actual setting of the A20 address line on theprocessor.

The justification for this was for legacy software that would dependon the ability to wrap past location0xFFFFF back to0x00000.Neutrino doesn’t have such a requirement. As a result, the OS doesn’tneed any A20 gate hardware to be installed. Note that someembedded x86 processors have the A20 gate hardware built right intothe processor chip itself — the IPL will disable the A20 gate as soonas possible after startup.

If your system requires a standard BIOS, there’s a small chance thatthe BIOS will make use of the A20 gate. To find out for certain,consult your BIOS supplier.

External ISA bus slots

Neutrino doesn’t require the external ISA bus to be mapped into theusual x860x00000-to-0xFFFFF address range. This simplifies thehardware design, eliminating issues such as shadow RAM and therequirement to move a portion of the RAM (usually0xA0000 through0xFFFFF) to some other location.

But if your hardware needs to run with a standard BIOS and tosupport BIOS extensions, then this optimization can’t beimplemented, because the BIOS expects extensions at0xA0000

through0xEFFFF (typically).

November 3, 2006 Appendix: A � System Design Considerations 259

Page 280: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Introduction 2006, QNX Software Systems GmbH & Co. KG.

PCI bus slots

In Neutrino, all PCI drivers interface to a PCI resource manager (e.g.pci-bios, pci-p5064, pci-raven), which handles the hardwareon behalf of the drivers.

For details, see thepci-* entry in theUtilities Reference.

External clocks

Neutrino can be driven with an external clock. In some systemsthere’s a “standard” clock source supplied as part of the system or ofthe highly integrated CPU chip itself. For convenience, the OS canoperate with an external clock source that’s not generated by thiscomponent. However, keep two things in mind:

� The timing resolution for software timers will be no better than thetiming resolution of the external clock.

� The hardware clock will be driving a software interrupt handler.

Therefore, keep the rates down to a reasonable number. Almost allmodern processors can handle clock interrupts at 1 kHz or lower —processors with higher CPU clock rates (e.g. Pentium-class, 300 MHzRISC processors, etc.) can handle faster clock interrupts.

Note that there’s no requirement to keep the clock frequency to some“round number.” If it’s convenient to derive the clock interrupt from abaud rate generator or other crystal, the OS will be able to accuratelyscale the incoming clock rate for use in its internal timers andtime-of-day clocks.

Interrupts & controllers

On an x86 design, the default startup supports two ProgrammableInterrupt Controllers (PICs). These must be 8259-compatible, withthe standard configuration of a secondary 8259 connected to the IRQ2line of the primary interrupt controller.

260 Appendix: A � System Design Considerations November 3, 2006

Page 281: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

Beware of hanging devices off IRQ7 and IRQ15 on an 8259 chip —these are generally known as the “glitch interrupts” and can beunreliable.

If your x86 hardware design differs, there’s no constraint about thePICs, but you must write the code to handle them.

On non-x86 designs, be aware that there may be only one interruptline going to the processor and that a number of hardware devicesmay be sharing that one line. This is generally accomplished in one oftwo ways:

� wire-OR

� PIC chip

In either case, the relevant design issue is to determine the orderingand priority of interrupts from hardware sources. You’ll want toarrange the hardware and software to give highest priority (and firstorder) to the interrupt source that has the most stringent latencyrequirements. (For more details, see the chapter on Writing anInterrupt Handler in theProgrammer’s Guide, along with theInterruptAttach() andInterruptAttachEvent() function calls in theLibrary Reference.)

Serial and parallel ports

Serial and parallel ports are certainly desirable — and highlyrecommended — but not required. The 16550 component with16-byte FIFOs is suitable for Neutrino. Our drivers can work withthese devices on a byte-aligned or doubleword-aligned manner.

If you’re going to support multiple serial ports on your device, youcan have the multiple devices share the same interrupt. It’s up to thesoftware to decide which device generated the interrupt and then tohandle that interrupt. The standard Neutrino serial port handlers areable to do this.

November 3, 2006 Appendix: A � System Design Considerations 261

Page 282: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

NMI 2006, QNX Software Systems GmbH & Co. KG.

Although the serial driver can be told to use a “nonstandard” clockrate when calculating its divisor values, this can cause the baud rate todeviate from the standard.

Try to run DTR, DSR, RTS, CTS if possible, because hardware flowcontrol will help on slower CPUs.

Parallel port considerations

Generally, the parallel port doesnot require an interrupt line — thisisn’t used by our standard parallel port drivers.

NMIAvoid theNon-Maskable Interrupt (NMI) in x86 designs. PPC,MIPS, ARM, and SH-4 don’t even support it.

An NMI is an interrupt which can’t be disabled by clearing the CPU’sinterrupt enable flag, unlike most normal interrupts. Non-Maskableinterrupts are typically used to signal events that require immediateaction, such as a parity error, a hardware failure, or imminent loss ofpower.

The problem with NMIs is that they can occur even when interruptshave been disabled. This is important because sometimes it’s assumedthat interrupts can be masked to avoid being interrupted. NMIsundermine this assumption and this can lead to unexpected behaviourif an NMI fires during a period in which that software expects to beoperating without interruption.

For this reason, NMIs are normally only used when the subsequentcondition of the machine is not a relevant consideration; for instance,when the machine is about to shut down, or when an unrecoverablehardware error has occurred.

Anytime an NMI is used, any software may experience unexpectedbehavior and there’s no good way to predict what the behavior maybe.

262 Appendix: A � System Design Considerations November 3, 2006

Page 283: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Design do’s and don’ts

Design do’s and don’tsBefore you commit to a design, take a look at the following tips —you may save yourself some grief. Although some of these pointsassume you’re relying on our Custom Engineering services, theprinciples behind all of them are sound.

Do:� Do design in more speed/memory than you think you need.

� Do try a proof of concept using off-the-shelf hardware, if possible.

� Do have a serial port/debug output device on the board; have itreasonably close to the CPU in hardware terms (i.e. don’t put it onthe other side of a PCI bridge).

� Do allow the ROM/flash devices holding the IPL code to besocketed.

� If using a MIPS processor, make sure any devices needed by theIPL/startup sequence are in the physical address range of0x00000000 to 0x20000000 — that makes it accessible from thekseg1 virtual address block.

� Do consider staggering a device’s ports by any power of 2, butdon’t mix up the address lines so that the I/O registers appear in astrange order.

� Do try to use a timer chip that allows free-running operation,rather than one that requires poking after every interrupt.

� Do put the timer on its own interrupt line so that the kernel doesn’thave to check that the interrupt actually came from the timer.

� Do follow the CPU’s interface for reporting a bus error — don’treport it as a hardware interrupt.

� If you have optional pieces, make sure you have some positivemethod of determining what pieces are present (something otherthan poking at it and seeing if it responds).

November 3, 2006 Appendix: A � System Design Considerations 263

Page 284: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Design do’s and don’ts 2006, QNX Software Systems GmbH & Co. KG.

� Do run your design by us, ideallybefore you build it.

� Do make a point of stating requirements you think are obvious.

� Do remember to point out any pitfalls you know about.

� Do send us as much documentation as you have available onchipsets, panels, etc.

Don’t:� Don’t use write-only registers.

� Don’t nest interrupt controller chips too deeply — one big wideinterrupt controller is better.

� Don’t use hardware that requires short delays between registeraccesses (e.g. Zilog SCC).

� Don’t put information from many different places into the sameI/O register location if the OS/drivers also have to do RMW cyclesto it.

� Don’t decide that no-BIOS is the way to go just because it soundscool.

� Don’t use a $2.00 chip instead of a $3.00 chip and expect theperformance of a $10.00 chip.

� Don’t build your first run of boards without leaving a way to debugthe system.

� Don’t build your first run of boards with only 1M of RAM onboard.

� Don’t send us anything without correct schematics that match whatyou send.

� Don’t program the flash and then solder it on, leaving us with nooption to reprogram it.

� Don’t build just one prototype that must be shipped back and forthseveral times.

264 Appendix: A � System Design Considerations November 3, 2006

Page 285: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Appendix B

Sample Buildfiles

In this appendix. . .Introduction 267Generic examples 267Processor-specific notes 278

November 3, 2006 Appendix: B � Sample Buildfiles 265

Page 286: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 287: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Introduction

IntroductionIn this appendix, we’ll look at some typical buildfiles you can usewith mkifs or import into the IDE’s System Builder to get yoursystem up and running. This appendix is divided into two main parts:

� a “generic” part that contains some incomplete cut-and-pastefragments illustrating common techniques, as well as completesamples for the x86 platform.

� processor-specific notes.

We finish with a section for each of the supported processorplatforms, showing you differences from the x86 samples and notingthings to look out for.

Note that you should read both the section for your particularprocessor as well as the section on generic samples, because thingslike shared objects (which are required by just about everything) aredocumented in the generic section.

Generic examplesIn this section, we’ll look at some common buildfile examples that areapplicable (perhaps with slight modifications, which we’ll note) to allplatforms. We’ll start with some fragments that illustrate varioustechniques, and then we’ll wrap up with a few complete buildfiles. Inthe “Processor-specific notes” section, we’ll look at what needs to bedifferent for the various processor families.

Shared librariesThe first thing you’ll need to do is to ensure that the shared objectsrequired by the various drivers you’ll be running are present.Alldrivers require at least the standard C library shared object(libc.so). Since the shared object search order looks in/proc/boot, you don’t have to do anything special, except includethe shared library into the image. This is done by simply specifyingthe name of the shared library on a line by itself, meaning “includethis file.”

November 3, 2006 Appendix: B � Sample Buildfiles 267

Page 288: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Generic examples 2006, QNX Software Systems GmbH & Co. KG.

The runtime linker is expected to be found in a file calledldqnx.so.2, but the runtime linker is currently contained within thelibc.so file, so we would make a process manager symbolic link toit.

The following buildfile snippet applies:

# include the C shared librarylibc.so# create a symlink called ldqnx.so.2 to it[type=link] /usr/lib/ldqnx.so.2=/proc/boot/libc.so

How do you determine which shared objects you need in the image?You can use theobjdump utility to display information about theexecutables you’re including in the image; look for the objectsmarked asNEEDED For example, suppose you’re includingping inyour image:

$ objdump -x �which ping� | grep NEEDEDobjdump: /usr/bin/ping: no symbolsNEEDED libsocket.so.2NEEDED libc.so.2

Theping executable needslibsocket.so.2 andlibc.so.2. Youneed to useobjdump recursively to see what these shared objectsneed:

$ objdump -x /lib/libsocket.so.2 | grep NEEDEDNEEDED libc.so.2

$ objdump -x /lib/libc.so.2 | grep NEEDED$

Thelibsocket.so.2 shared object needs onlylibc.so.2, which,in turn, needs nothing. So, if you’re includingping in your image,you also need to include these two shared objects.

268 Appendix: B � Sample Buildfiles November 3, 2006

Page 289: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Generic examples

Running executables more than onceIf you want to be able to run executables more than once, you’ll needto specify the[data=copy] attribute for those executables. If youwant it to apply toall executables, just put it on a line by itself beforethe executables. This causes the data segment to be copied before it’sused, preventing it from being overwritten by the first invocation ofthe program.

Multiple consolesFor systems that have multiple consoles or multiple serial ports, youmay wish to have the shell running on each of them. Here’s anexample showing you how that’s done:

[+script] .script = {# start any other drivers you need heredevc-con -e -n4 &reopen /dev/con1[+session] esh &reopen /dev/con2[+session] esh &...

As you can see, the trick is to:

1 Start the console driver with the-n option to ask for more thanone console (in this case, we asked for four virtual consoles).

2 Redirect standard input, output, and error to each of theconsoles in turn.

3 Start the shell on each console.

It’s important to run the shell in the background (via the ampersandcharacter “&”) — if you don’t, then the interpretation of the scriptwill suspenduntil the shell exits!

November 3, 2006 Appendix: B � Sample Buildfiles 269

Page 290: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Generic examples 2006, QNX Software Systems GmbH & Co. KG.

Starting other programs on consoles

Generally speaking, this method can be used to start various otherprograms on the consoles (that is to say, you don’t have to start theshell; it could beany program).

To do this for serial ports, start the appropriate serial driver (e.g.devc-ser8250), and redirect standard input, output, and error foreach port (e.g./dev/ser1, /dev/ser2). Then run the appropriateexecutable (in the background!) after the redirection.

The[+session] directive makes the program the session leader (asper POSIX) — this may not be necessary for arbitrary executables.

Redirection

You can do thereopen on any device as many times as you want.You would do this, for example, to start a program on/dev/con1,then start the shell on/dev/con2, and then start another program on/dev/con1 again:

[+script] .script = {...reopen /dev/con1prog1 &reopen /dev/con2[+session] esh &reopen /dev/con1prog2 &...

/tmp

To create the/tmp directory on a RAM-disk, you can use thefollowing in your buildfile:

[type=link] /tmp = /dev/shmem

This will establish/tmp as a symbolic link in the process manager’spathname table to the/dev/shmem directory. Since the/dev/shmemdirectory is really the place where shared memory objects are stored,

270 Appendix: B � Sample Buildfiles November 3, 2006

Page 291: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Generic examples

this effectively lets you create files on a RAM-disk — files createdare, in reality, shared memory objects living in RAM.

Note that the line containing the link attribute (the[type=link]line) should be placedoutside of the script file or boot file — after all,you’re tellingmkifs that it should create a file that just happens to bea link rather than a “real” file.

Complete example — minimal configurationThis configuration file does the bare minimum necessary to give you ashell prompt on the first serial port:

[virtual=ppcbe,srec] .bootstrap = {startup-rpx-lite -Dsmc1.115200.64000000.16PATH=/proc/boot procnto-800

}[+script] .script = {

devc-serppc800 -e -F -c64000000 -b115200 smc1 &reopen

[+session] PATH=/proc/boot esh &}

[type=link] /dev/console=/dev/ser1[type=link] /usr/lib/ldqnx.so.2=/proc/boot/libc.so

libc.so

[data=copy]devc-serppc800esh# specify executables that you want to be able# to run from the shell: echo, ls, pidin, etc...echolspidincatcp

November 3, 2006 Appendix: B � Sample Buildfiles 271

Page 292: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Generic examples 2006, QNX Software Systems GmbH & Co. KG.

Complete example — flash filesystemLet’s now examine a complete buildfile that starts up the flashfilesystem:

[virtual=x86,bios +compress] .bootstrap = {startup-biosPATH=/proc/boot:/bin procnto

}

[+script] .script = {devc-con -e -n5 &reopen /dev/con1devf-i365sl -r -b3 -m2 -u2 -t4 &waitfor /fs0p0[+session] TERM=qansi PATH=/proc/boot:/bin esh &

}

[type=link] /tmp=/dev/shmem[type=link] /bin=/fs0p0/bin[type=link] /etc=/fs0p0/etc

libc.so[type=link] /usr/lib/ldqnx.so.2=/proc/boot/libc.solibsocket.so

[data=copy]

devf-i365sldevc-conesh

The buildfile’s.bootstrap specifies the usualstartup-bios andprocnto (the startup program and the kernel). Notice how we set thePATH environment variable to point not only to/proc/boot, butalso to/bin — the/bin directory is a link (created with the[type=link]) to the flash filesystem’s/fs0p0/bin path.

In the.script file, we started up the console driver with fiveconsoles, reopened standard input, output, and error for/dev/con1,and started the flash filesystem driverdevf-i365sl. Let’s look atthe command-line options we gave it:

-r Enable fault recovery for dirty extents, dangling extents, andpartial reclaims.

272 Appendix: B � Sample Buildfiles November 3, 2006

Page 293: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Generic examples

-b3 Enable background reclaim at priority3.

-u2 Specify the highest update level (2) to update files anddirectories.

-t4 Specify the highest number of threads. Extra threads willincrease performance when background reclaim is enabled(with the-b option) and when multiple chips and/or spareblocks are available.

Thedevf-i365sl will automatically mount the flash partition as/fs0p0. Notice the process manager symbolic links we created at thebottom of the buildfile:

[type=link] /bin=/fs0p0/bin[type=link] /etc=/fs0p0/etc

These give us/bin and/etc from the flash filesystem.

Complete example — disk filesystemIn this example, we’ll look at a filesystem for rotating media. Noticethe shared libraries that need to be present:

[virtual=x86,bios +compress] .bootstrap = {startup-biosPATH=/proc/boot:/bin LD LIBRARY PATH=/proc/boot:/lib:/dll procnto

}

[+script] .script = {pci-bios &devc-con &reopen /dev/con1

# Disk driversdevb-eide blk cache=2m,automount=hd0t79:/,automount=cd0:/cd &

# Wait for a bin for the rest of the commandswaitfor /x86 10

# Some common serverspipe &mqueue &devc-pty &

November 3, 2006 Appendix: B � Sample Buildfiles 273

Page 294: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Generic examples 2006, QNX Software Systems GmbH & Co. KG.

# Start the main shell[+session] esh

}

# make /tmp point to the shared memory area[type=link] /tmp=/dev/shmem

# Redirect console messages# [type=link] /dev/console=/dev/ser1

# Programs require the runtime linker (ldqnx.so) to be at# a fixed location[type=link] /usr/lib/ldqnx.so.2=/proc/boot/libc.so

# Add for HD support[type=link] /usr/lib/libcam.so.2=/proc/boot/libcam.so

# add symbolic links for bin, dll, and lib# (files in /x86 with devb-eide)[type=link] /bin=/x86/bin[type=link] /dll=/x86/lib/dll[type=link] /lib=/x86/lib

# We use the C shared lib (which also contains the runtime linker)libc.so

# Just in case someone needs floating point and our CPU doesn’t# have a floating point unitfpemu.so.2

# Include the hard disk shared objects so we can access the disklibcam.soio-blk.so

# For the QNX 4 filesystemcam-disk.sofs-qnx4.so

# For the CD-ROM filesystem and the PCIcam-cdrom.sofs-cd.sopci-bios

# Copy code and data for all executables after this line[data=copy]

# Include a console driver, shell, etc.eshdevb-eide

274 Appendix: B � Sample Buildfiles November 3, 2006

Page 295: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Generic examples

devc-con

For this release of Neutrino, you can’t use the floating-point emulator(fpemu.so.2) in statically linked executables.

In this buildfile, we see the startup command line for thedevb-eide

command:

devb-eide blk cache=2m,automount=hd0t79:/automount=cd0:/cd &

This line indicates that thedevb-eide driver should start and thenpass the string beginning with thecache= through to the end (exceptfor the ampersand) to the block I/O file (io-blk.so). This willexamine the passed command line and then start up with a2-megabyte cache (thecache=2m part), automatically mount thepartition identified byhd0t79 (the first QNX filesystem partition) asthe pathname/hd, and automatically mount the CD-ROM as/cd.

Once this driver is started, we then need to wait for it to get access tothe disk and perform the mount operations. This line does that:

waitfor /ppcbe/bin

This waits for the pathname/ppcbe/bin to show up in the pathnamespace. (We’re assuming a formatted hard disk that contains a validQNX filesystem with${QNX TARGET} copied to the root.)

Now that we have a complete filesystem with all the shippedexecutables installed, we run a few common executables, like the Pipeserver.

Finally, the list of shared objects contains the.so files required forthe drivers and the filesystem.

Complete example — TCP/IP with network filesystemHere’s an example of a buildfile that starts up an Ethernet driver, theTCP/IP stack, and the network filesystem:

November 3, 2006 Appendix: B � Sample Buildfiles 275

Page 296: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Generic examples 2006, QNX Software Systems GmbH & Co. KG.

[virtual=mipsle,elf +compress] .bootstrap = {startup-p5064 -vvvPATH=/proc/boot procnto

}[+script] .script = {

devc-ser8250 -e -b9600 0x1d0003f8,0x23 &reopen

# Start the PCI serverpci-p5064 &waitfor /dev/pci

# Network drivers and filesystemsio-net -dtulip-p5064 -pttcpip if=ndi0:10.0.0.1 &waitfor /dev/socketfs-nfs2 10.0.0.2:/mipsle/ / 10.0.0.2:/etc /etc &

# Wait for a "bin" for the rest of the commandswaitfor /usr/bin

# Some common serverspipe &mqueue &devc-pty &

[+session] sh}

# make /tmp point to the shared memory area[type=link] /tmp=/dev/shmem

# Redirect console messages[type=link] /dev/console=/dev/ser1

# Programs require the runtime linker (ldqnx.so) to be at# a fixed location[type=link] /usr/lib/ldqnx.so.2=/proc/boot/libc.so# We use the C shared lib (which also contains the runtime linker)libc.so

# If some one needs floating point...fpemu.so.2

# Include the network files so we can access files across the netdevn-tulip-p5064.sonpm-ttcpip.so

# Include the socket librarylibsocket.so[data=copy]

276 Appendix: B � Sample Buildfiles November 3, 2006

Page 297: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Generic examples

# Include the network executables.devc-ser8250io-netfs-nfs2

For this release of Neutrino, you can’t use the floating-point emulator(fpemu.so.2) in statically linked executables.

This buildfile is very similar to the previous one shown for the disk.The major difference is that instead of startingdevb-eide to get adisk filesystem driver running, we startedio-net to get the networkdrivers running. The-p option toio-net specifies that it should loadthe protocolttcpip, which is the tiny TCP/IP stack. Theif=...specifies the IP address of this interface. Finally, the-d specifies thedriver that should be loaded, in this case the driver for a DEC 21x4x(Tulip)-compatible Ethernet controller.

Once the network manager is running, we need to synchronize thescript file interpretation to the availability of the drivers. That’s whatthewaitfor /dev/socket is for — it waits until the networkmanager has loaded the tiny TCP/IP stack and then waits for the stackto initialize itself.

The next thing started is the NFS filesystem module,fs-nfs2, withoptions telling it that it should mount the filesystem present on10.0.0.2 in two different places:${QNX TARGET} should bemounted in/, and/etc should be mounted as/etc.

Since it may take some time to go over the network and establish themounting, we see anotherwaitfor, this time ensuring that thefilesystem on the remote has been correctly mounted (here we assumethat the remote has a directory called${QNX TARGET}/mipsle/bin

— since we’ve mounted the remote’s${QNX TARGET} as/, thewaitfor is really waiting formipsle/bin under the remote’s${QNX TARGET} to show up).

November 3, 2006 Appendix: B � Sample Buildfiles 277

Page 298: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Processor-specific notes 2006, QNX Software Systems GmbH & Co. KG.

Processor-specific notesIn this section, we’ll look at what’s different from the generic fileslisted above for each processor family. Since almost everything that’sprocessor- and platform-specific in Neutrino is contained in the kerneland startup programs, there’s very little change required to go from anx86 with standard BIOS to, for example, a PowerPC 800 evaluationboard.

Specifying the processorThe first obvious difference is that you must specify the processor thatthe buildfile is for. This is actually a simple change — in the[virtual=...] line, substitute thex86 specification witharmle,mipsbe|le, ppcbe, orshle.

Examples

For this CPU: Use this attribute:

ARM (little-endian) [virtual=armle,binary]

MIPS (big-endian) [virtual=mipsbe,elf]

MIPS (little-endian) [virtual=mipsle,elf]

PPC (big-endian) [virtual=ppcbe,openbios]

SH-4 (little-endian) [virtual=shle,srec]

Specifying the startup programAnother difference is that the startup program is tailored not only forthe processor family, but also for the actual board the processor runson. If you’re not running an x86 with a standard BIOS, you shouldreplace thestartup-bios command with one of the manystartup-* programs we supply.

To find out what startup programs we currently provide, please referto the following sources:

278 Appendix: B � Sample Buildfiles November 3, 2006

Page 299: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Processor-specific notes

� theboards directory underbsp working dir/src/hardware/startup.

� QNX docs (BSP docs as well asstartup-* entries inUtilitiesReference).

� the Developer Support Center area of our website(www.qnx.com).

Specifying the serial deviceThe examples listed previously provide support for the 8250 family ofserial chips. Some non-x86 platforms support the 8250 family aswell, but others have their own serial port chips.

For details on our current serial drivers, see:

� devc-* entries in theUtilities Reference.

� the Developer Support Center area of our website(www.qnx.com).

November 3, 2006 Appendix: B � Sample Buildfiles 279

Page 300: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 301: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Glossary

November 3, 2006 Glossary 281

Page 302: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino
Page 303: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

A20 gate

On x86-based systems, a hardware component that forces the A20address line on the bus to zero, regardless of the actual setting of theA20 address line on the processor. This component is in place tosupport legacy systems, but the QNX Neutrino OS doesn’t requireany such hardware. Note that some processors, such as the 386EX,have the A20 gate hardware built right into the processor itself — ourIPL will disable the A20 gate as soon as possible after startup.

adaptive

Scheduling algorithm whereby a thread’s priority is decayed by 1. SeealsoFIFO, round robin, andsporadic.

adaptive partitioning

A method of dividing, in a flexible manner, CPU time, memory, fileresources, or kernel resources with some policy of minimumguaranteed usage.

asymmetric multiprocessing (AMP)

A multiprocessing system where a separate OS, or a separateinstantiation of the same OS, runs on each CPU.

atomic

Of or relating to atoms. :-)

In operating systems, this refers to the requirement that an operation,or sequence of operations, be consideredindivisible. For example, athread may need to move a file position to a given location and readdata. These operations must be performed in an atomic manner;otherwise, another thread could preempt the original thread and movethe file position to a different location, thus causing the original threadto read data from the second thread’s position.

November 3, 2006 Glossary 283

Page 304: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

attributes structure

Structure containing information used on a per-resource basis (asopposed to theOCB, which is used on a per-open basis).

This structure is also known as ahandle. The structure definition isfixed (iofunc attr t), but may be extended. See alsomountstructure.

bank-switched

A term indicating that a certain memory component (usually thedevice holding animage) isn’t entirely addressable by the processor.In this case, a hardware component manifests a small portion (or“window”) of the device onto the processor’s address bus. Specialcommands have to be issued to the hardware to move the window todifferent locations in the device. See alsolinearly mapped.

base layer calls

Convenient set of library calls for writing resource managers. Thesecalls all start withresmgr *(). Note that while some base layer callsare unavoidable (e.g.resmgr pathname attach()), we recommend thatyou use thePOSIX layer calls where possible.

BIOS/ROM Monitor extension signature

A certain sequence of bytes indicating to the BIOS or ROM Monitorthat the device is to be considered an “extension” to the BIOS orROM Monitor — control is to be transferred to the device by theBIOS or ROM Monitor, with the expectation that the device willperform additional initializations.

On the x86 architecture, the two bytes0x55and0xAA must be present(in that order) as the first two bytes in the device, with control beingtransferred to offset0x0003.

block-integral

The requirement that data be transferred such that individual structurecomponents are transferred in their entirety — no partial structurecomponent transfers are allowed.

284 Glossary November 3, 2006

Page 305: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

In a resource manager, directory data must be returned to a client asblock-integral data. This means that only completestruct dirent

structures can be returned — it’s inappropriate to return partialstructures, assuming that the nextIO READ request will “pick up”where the previous one left off.

bootable

An image can be either bootable ornonbootable. A bootable image isone that contains the startup code that the IPL can transfer control to.

bootfile

The part of an OS image that runs thestartup code and the Neutrinomicrokernel.

bound multiprocessing (BMP)

A multiprocessing system where a single instantiation of an OSmanages all CPUs simultaneously, but you can lock individualapplications or threads to a specific CPU.

budget

In sporadic scheduling, the amount of time a thread is permitted toexecute at its normal priority before being dropped to its low priority.

buildfile

A text file containing instructions formkifs specifying the contentsand other details of animage, or formkefs specifying the contentsand other details of an embedded filesystem image.

canonical mode

Also called edited mode or “cooked” mode. In this mode thecharacter device library performs line-editing operations on eachreceived character. Only when a line is “completely entered” —typically when a carriage return (CR) is received — will the line ofdata be made available to application processes. Contrastraw mode.

November 3, 2006 Glossary 285

Page 306: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

channel

A kernel object used with message passing.

In QNX Neutrino, message passing is directed towards aconnection(made to a channel); threads can receive messages from channels. Athread that wishes to receive messages creates a channel (usingChannelCreate()), and then receives messages from that channel(usingMsgReceive()). Another thread that wishes to send a messageto the first thread must make a connection to that channel by“attaching” to the channel (usingConnectAttach()) and then sendingdata (usingMsgSend()).

CIFS

Common Internet File System (aka SMB) — a protocol that allows aclient workstation to perform transparent file access over a network toa Windows 95/98/NT server. Client file access calls are converted toCIFS protocol requests and are sent to the server over the network.The server receives the request, performs the actual filesystemoperation, and sends a response back to the client.

CIS

Card Information Structure — a data block that maintains informationabout flash configuration. The CIS description includes the types ofmemory devices in the regions, the physical geometry of thesedevices, and the partitions located on the flash.

combine message

A resource manager message that consists of two or more messages.The messages are constructed as combine messages by the client’s Clibrary (e.g.stat(), readblock()), and then handled as individualmessages by the resource manager.

The purpose of combine messages is to conserve network bandwidthand/or to provide support for atomic operations. See alsoconnectmessage andI/O message.

286 Glossary November 3, 2006

Page 307: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

connect message

In a resource manager, a message issued by the client to perform anoperation based on a pathname (e.g. anio open message).Depending on the type of connect message sent, a context block (seeOCB) may be associated with the request and will be passed tosubsequent I/O messages. See alsocombine message andI/Omessage.

connection

A kernel object used with message passing.

Connections are created by client threads to “connect” to the channelsmade available by servers. Once connections are established, clientscanMsgSendv() messages over them. If a number of threads in aprocess all attach to the same channel, then the one connection isshared among all the threads. Channels and connections are identifiedwithin a process by a small integer.

The key thing to note is that connections and file descriptors (FD) areone and the same object. See alsochannel andFD.

context

Information retained between invocations of functionality.

When using a resource manager, the client sets up an association orcontext within the resource manager by issuing anopen() call andgetting back a file descriptor. The resource manager is responsible forstoring the information required by the context (seeOCB). When theclient issues further file-descriptor based messages, the resourcemanager uses the OCB to determine the context for interpretation ofthe client’s messages.

cooked mode

Seecanonical mode.

November 3, 2006 Glossary 287

Page 308: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

core dump

A file describing the state of a process that terminated abnormally.

critical section

A code passage thatmust be executed “serially” (i.e. by only onethread at a time). The simplest from of critical section enforcement isvia amutex.

deadlock

A condition in which one or more threads are unable to continue dueto resource contention. A common form of deadlock can occur whenone thread sends a message to another, while the other thread sends amessage to the first. Both threads are now waiting for each other toreply to the message. Deadlock can be avoided by good designpractices or massive kludges — we recommend the good designapproach.

device driver

A process that allows the OS and application programs to make use ofthe underlying hardware in a generic way (e.g. a disk drive, a networkinterface). Unlike OSs that require device drivers to be tightly boundinto the OS itself, device drivers for QNX Neutrino are standardprocesses that can be started and stopped dynamically. As a result,adding device drivers doesn’t affect any other part of the OS —drivers can be developed and debugged like any other application.Also, device drivers are in their own protected address space, so a bugin a device driver won’t cause the entire OS to shut down.

discrete (or traditional) multiprocessor system

A system that has separate physical processors hooked up inmultiprocessing mode over a board-level bus.

DNS

Domain Name Service — an Internet protocol used to convert ASCIIdomain names into IP addresses. In QNX native networking,dns isone ofQnet’s builtin resolvers.

288 Glossary November 3, 2006

Page 309: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

dynamic bootfile

An OS image built on the fly. Contraststatic bootfile.

dynamic linking

The process whereby you link your modules in such a way that theProcess Manager will link them to the library modules before yourprogram runs. The word “dynamic” here means that the associationbetween your program and the library modules that it uses is doneatload time, not at linktime. Contraststatic linking. See alsoruntimeloading.

edge-sensitive

One of two ways in which aPIC (Programmable Interrupt Controller)can be programmed to respond to interrupts. In edge-sensitive mode,the interrupt is “noticed” upon a transition to/from the rising/fallingedge of a pulse. Contrastlevel-sensitive.

edited mode

Seecanonical mode.

EOI

End Of Interrupt — a command that the OS sends to the PIC afterprocessing all Interrupt Service Routines (ISR) for that particularinterrupt source so that the PIC can reset the processor’s In ServiceRegister. See alsoPIC andISR.

EPROM

Erasable Programmable Read-Only Memory — a memorytechnology that allows the device to be programmed (typically withhigher-than-operating voltages, e.g. 12V), with the characteristic thatany bit (or bits) may be individually programmed from a1 state to a0state. To change a bit from a0 state into a1 state can only beaccomplished by erasing theentire device, settingall of the bits to a1state. Erasing is accomplished by shining an ultraviolet light throughthe erase window of the device for a fixed period of time (typically

November 3, 2006 Glossary 289

Page 310: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

10-20 minutes). The device is further characterized by having alimited number of erase cycles (typically 10e5 - 10e6). ContrastflashandRAM.

event

A notification scheme used to inform a thread that a particularcondition has occurred. Events can be signals or pulses in the generalcase; they can also be unblocking events or interrupt events in thecase of kernel timeouts and interrupt service routines. An event isdelivered by a thread, a timer, the kernel, or an interrupt serviceroutine when appropriate to the requestor of the event.

FD

File Descriptor — a client must open a file descriptor to a resourcemanager via theopen() function call. The file descriptor then servesas a handle for the client to use in subsequent messages. Note that afile descriptor is the exact same object as a connection ID (coid,returned byConnectAttach()).

FIFO

First In First Out — a scheduling algorithm whereby a thread is ableto consume CPU at its priority level without bounds. See alsoadaptive, round robin, andsporadic.

flash memory

A memory technology similar in characteristics toEPROM memory,with the exception that erasing is performed electrically instead of viaultraviolet light, and, depending upon the organization of the flashmemory device, erasing may be accomplished in blocks (typically64k bytes at a time) instead of the entire device. ContrastEPROMandRAM.

FQNN

Fully Qualified NodeName — a unique name that identifies a QNXNeutrino node on a network. The FQNN consists of the nodenameplus the node domain tacked together.

290 Glossary November 3, 2006

Page 311: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

garbage collection

Aka space reclamation, the process whereby a filesystem managerrecovers the space occupied by deleted files and directories.

HA

High Availability — in telecommunications and other industries, HAdescribes a system’s ability to remain up and running withoutinterruption for extended periods of time.

handle

A pointer that the resource manager base library binds to thepathname registered viaresmgr attach(). This handle is typically usedto associate some kind of per-device information. Note that if you usetheiofunc *() POSIX layer calls, you must use a particulartype ofhandle — in this case called anattributes structure.

hard thread affinity

A user-specified binding of a thread to a set of processors, done bymeans of arunmask. Contrastsoft thread affinity.

image

In the context of embedded QNX Neutrino systems, an “image” canmean either a structure that contains files (i.e. an OS image) or astructure that can be used in a read-only, read/write, orread/write/reclaim FFS-2-compatible filesystem (i.e. a flashfilesystem image).

inherit mask

A bitmask that specifies which processors a thread’s children can runon. Contrastrunmask.

interrupt

An event (usually caused by hardware) that interrupts whatever theprocessor was doing and asks it do something else. The hardware willgenerate an interrupt whenever it has reached some state wheresoftware intervention is required.

November 3, 2006 Glossary 291

Page 312: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

interrupt handler

SeeISR.

interrupt latency

The amount of elapsed time between the generation of a hardwareinterrupt and the first instruction executed by the relevant interruptservice routine. Also designated as “Til ”. Contrastschedulinglatency.

interrupt service routine

SeeISR.

interrupt service thread

A thread that is responsible for performing thread-level servicing ofan interrupt.

Since anISR can call only a very limited number of functions, andsince the amount of time spent in an ISR should be kept to aminimum, generally the bulk of the interrupt servicing work shouldbe done by a thread. The thread attaches the interrupt (viaInterruptAttach() or InterruptAttachEvent()) and then blocks (viaInterruptWait()), waiting for the ISR to tell it to do something (byreturning an event of typeSIGEV INTR). To aid in minimizingscheduling latency, the interrupt service thread should raise itspriority appropriately.

I/O message

A message that relies on an existing binding between the client andthe resource manager. For example, anIO READ message dependson the client’s having previously established an association (orcontext) with the resource manager by issuing anopen() and gettingback a file descriptor. See alsoconnect message, context, combinemessage, andmessage.

292 Glossary November 3, 2006

Page 313: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

I/O privileges

A particular right, that, if enabled for a given thread, allows the threadto perform I/O instructions (such as the x86 assemblerin andoutinstructions). By default, I/O privileges are disabled, because aprogram with it enabled can wreak havoc on a system. To enable I/Oprivileges, the thread must be running asroot, and callThreadCtl().

IPC

Interprocess Communication — the ability for two processes (orthreads) to communicate. QNX Neutrino offers several forms of IPC,most notably native messaging (synchronous, client/serverrelationship), POSIX message queues and pipes (asynchronous), aswell as signals.

IPL

Initial Program Loader — the software component that either takescontrol at the processor’s reset vector (e.g. location0xFFFFFFF0onthe x86), or is a BIOS extension. This component is responsible forsetting up the machine into a usable state, such that the startupprogram can then perform further initializations. The IPL is written inassembler and C. See alsoBIOS extension signature andstartupcode.

IRQ

Interrupt Request — a hardware request line asserted by a peripheralto indicate that it requires servicing by software. The IRQ is handledby thePIC, which then interrupts the processor, usually causing theprocessor to execute anInterrupt Service Routine (ISR).

ISR

Interrupt Service Routine — a routine responsible for servicinghardware (e.g. reading and/or writing some device ports), forupdating some data structures shared between the ISR and thethread(s) running in the application, and for signalling the thread thatsome kind of event has occurred.

November 3, 2006 Glossary 293

Page 314: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

kernel

Seemicrokernel.

level-sensitive

One of two ways in which aPIC (Programmable Interrupt Controller)can be programmed to respond to interrupts. If the PIC is operating inlevel-sensitive mode, the IRQ is considered active whenever thecorresponding hardware line is active. Contrastedge-sensitive.

linearly mapped

A term indicating that a certain memory component is entirelyaddressable by the processor. Contrastbank-switched.

message

A parcel of bytes passed from one process to another. The OSattaches no special meaning to the content of a message — the data ina message has meaning for the sender of the message and for itsreceiver, but for no one else.

Message passing not only allows processes to pass data to each other,but also provides a means of synchronizing the execution of severalprocesses. As they send, receive, and reply to messages, processesundergo various “changes of state” that affect when, and for howlong, they may run.

microkernel

A part of the operating system that provides the minimal servicesused by a team of optional cooperating processes, which in turnprovide the higher-level OS functionality. The microkernel itself lacksfilesystems and many other services normally expected of an OS;those services are provided by optional processes.

mount structure

An optional, well-defined data structure (of typeiofunc mount t)within aniofunc *() structure, which contains information used on a

294 Glossary November 3, 2006

Page 315: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

per-mountpoint basis (generally used only for filesystem resourcemanagers). See alsoattributes structure andOCB.

mountpoint

The location in the pathname space where a resource manager has“registered” itself. For example, the serial port resource managerregisters mountpoints for each serial device (/dev/ser1,/dev/ser2, etc.), and a CD-ROM filesystem may register a singlemountpoint of/cdrom.

multicore system

A chip that has one physical processor with multiple CPUsinterconnected over a chip-level bus.

mutex

Mutual exclusion lock, a simple synchronization service used toensure exclusive access to data shared between threads. It is typicallyacquired (pthread mutex lock()) and released(pthread mutex unlock()) around the code that accesses the shareddata (usually acritical section). See alsocritical section.

name resolution

In a QNX Neutrino network, the process by which theQnet networkmanager converts anFQNN to a list of destination addresses that thetransport layer knows how to get to.

name resolver

Program code that attempts to convert anFQNN to a destinationaddress.

NDP

Node Discovery Protocol — proprietary QNX Software Systemsprotocol for broadcasting name resolution requests on a QNXNeutrino LAN.

November 3, 2006 Glossary 295

Page 316: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

network directory

A directory in the pathname space that’s implemented by theQnetnetwork manager.

Neutrino

Name of an OS developed by QNX Software Systems.

NFS

Network FileSystem — a TCP/IP application that lets you graftremote filesystems (or portions of them) onto your local namespace.Directories on the remote systems appear as part of your localfilesystem and all the utilities you use for listing and managing files(e.g.ls, cp, mv) operate on the remote files exactly as they do onyour local files.

NMI

Nonmaskable Interrupt — an interrupt that can’t be masked by theprocessor. We don’t recommend using an NMI!

Node Discovery Protocol

SeeNDP.

node domain

A character string that theQnet network manager tacks onto thenodename to form anFQNN.

nodename

A unique name consisting of a character string that identifies a nodeon a network.

nonbootable

A nonbootable OS image is usually provided for larger embeddedsystems or for small embedded systems where a separate,configuration-dependent setup may be required. Think of it as asecond “filesystem” that has some additional files on it. Since it’s

296 Glossary November 3, 2006

Page 317: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

nonbootable, it typically won’t contain the OS, startup file, etc.Contrastbootable.

OCB

Open Control Block (or Open Context Block) — a block of dataestablished by a resource manager during its handling of the client’sopen() function. This context block is bound by the resource managerto this particular request, and is then automatically passed to allsubsequent I/O functions generated by the client on the file descriptorreturned by the client’sopen().

package filesystem

A virtual filesystem manager that presents a customized view of a setof files and directories to a client. The “real” files are present on somemedium; the package filesystem presents a virtual view of selectedfiles to the client.

partition

A division of CPU time, memory, file resources, or kernel resourceswith some policy of minimum guaranteed usage.

pathname prefix

Seemountpoint.

pathname space mapping

The process whereby the Process Manager maintains an associationbetween resource managers and entries in the pathname space.

persistent

When applied to storage media, the ability for the medium to retaininformation across a power-cycle. For example, a hard disk is apersistent storage medium, whereas a ramdisk is not, because the datais lost when power is lost.

November 3, 2006 Glossary 297

Page 318: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

Photon microGUI

The proprietary graphical user interface built by QNX SoftwareSystems.

PIC

Programmable Interrupt Controller — hardware component thathandles IRQs. See alsoedge-sensitive, level-sensitive, andISR.

PID

Process ID. Also oftenpid (e.g. as an argument in a function call).

POSIX

An IEEE/ISO standard. The term is an acronym (of sorts) for PortableOperating System Interface — the “X” alludes to “UNIX”, on whichthe interface is based.

POSIX layer calls

Convenient set of library calls for writing resource managers. ThePOSIX layer calls can handle even more of the common-casemessages and functions than thebase layer calls. These calls areidentified by theiofunc *() prefix. In order to use these (and westrongly recommend that you do), you must also use the well-definedPOSIX-layerattributes (iofunc attr t), OCB (iofunc ocb t),and (optionally)mount (iofunc mount t) structures.

preemption

The act of suspending the execution of one thread and starting (orresuming) another. The suspended thread is said to have been“preempted” by the new thread. Whenever a lower-priority thread isactively consuming the CPU, and a higher-priority thread becomesREADY, the lower-priority thread is immediately preempted by thehigher-priority thread.

298 Glossary November 3, 2006

Page 319: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

prefix tree

The internal representation used by the Process Manager to store thepathname table.

priority inheritance

The characteristic of a thread that causes its priority to be raised orlowered to that of the thread that sent it a message. Also used withmutexes. Priority inheritance is a method used to preventpriorityinversion.

priority inversion

A condition that can occur when a low-priority thread consumes CPUat a higher priority than it should. This can be caused by notsupporting priority inheritance, such that when the lower-prioritythread sends a message to a higher-priority thread, the higher-prioritythread consumes CPUon behalf of the lower-priority thread. This issolved by having the higher-priority thread inherit the priority of thethread on whose behalf it’s working.

process

A nonschedulable entity, which defines the address space and a fewdata areas. A process must have at least onethread running in it —this thread is then called the first thread.

process group

A collection of processes that permits the signalling of relatedprocesses. Each process in the system is a member of a process groupidentified by a process group ID. A newly created process joins theprocess group of its creator.

process group ID

The unique identifier representing a process group during its lifetime.A process group ID is a positive integer. The system may reuse aprocess group ID after the process group dies.

November 3, 2006 Glossary 299

Page 320: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

process group leader

A process whose ID is the same as its process group ID.

process ID (PID)

The unique identifier representing a process. A PID is a positiveinteger. The system may reuse a process ID after the process dies,provided no existing process group has the same ID. Only the ProcessManager can have a process ID of 1.

pty

Pseudo-TTY — a character-based device that has two “ends”: amaster end and a slave end. Data written to the master end shows upon the slave end, and vice versa. These devices are typically used tointerface between a program that expects a character device andanother program that wishes to use that device (e.g. the shell and thetelnet daemon process, used for logging in to a system over theInternet).

pulses

In addition to the synchronous Send/Receive/Reply services, QNXNeutrino also supports fixed-size, nonblocking messages known aspulses. These carry a small payload (four bytes of data plus a singlebyte code). A pulse is also one form ofevent that can be returnedfrom an ISR or a timer. SeeMsgDeliverEvent() for more information.

Qnet

The native network manager in QNX Neutrino.

QoS

Quality of Service — a policy (e.g.loadbalance) used to connectnodes in a network in order to ensure highly dependable transmission.QoS is an issue that often arises in high-availability (HA) networks aswell as realtime control systems.

300 Glossary November 3, 2006

Page 321: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

RAM

Random Access Memory — a memory technology characterized bythe ability to read and write any location in the device withoutlimitation. Contrastflash andEPROM.

raw mode

In raw input mode, the character device library performs no editing onreceived characters. This reduces the processing done on eachcharacter to a minimum and provides the highest performanceinterface for reading data. Also, raw mode is used with devices thattypically generate binary data — you don’t want any translations ofthe raw binary stream between the device and the application.Contrastcanonical mode.

replenishment

In sporadic scheduling, the period of time during which a thread isallowed to consume its executionbudget.

reset vector

The address at which the processor begins executing instructions afterthe processor’s reset line has been activated. On the x86, for example,this is the address0xFFFFFFF0.

resource manager

A user-level server program that accepts messages from otherprograms and, optionally, communicates with hardware. QNXNeutrino resource managers are responsible for presenting aninterface to various types of devices, whether actual (e.g. serial ports,parallel ports, network cards, disk drives) or virtual (e.g./dev/null,a network filesystem, and pseudo-ttys).

In other operating systems, this functionality is traditionallyassociated withdevice drivers. But unlike device drivers, QNXNeutrino resource managers don’t require any special arrangementswith the kernel. In fact, a resource manager looks just like any otheruser-level program. See alsodevice driver.

November 3, 2006 Glossary 301

Page 322: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

RMA

Rate Monotonic Analysis — a set of methods used to specify,analyze, and predict the timing behavior of realtime systems.

round robin

Scheduling algorithm whereby a thread is given a certain period oftime to run. Should the thread consume CPU for the entire period ofits timeslice, the thread will be placed at the end of the ready queuefor its priority, and the next available thread will be made READY. Ifa thread is the only thread READY at its priority level, it will be ableto consume CPU again immediately. See alsoadaptive, FIFO, andsporadic.

runmask

A bitmask that indicates which processors a thread can run on.Contrastinherit mask.

runtime loading

The process whereby a program decideswhile it’s actually runningthat it wishes to load a particular function from a library. Contraststatic linking.

scheduling latency

The amount of time that elapses between the point when one threadmakes another thread READY and when the other thread actually getssome CPU time. Note that this latency is almost always at the controlof the system designer.

Also designated as “Tsl”. Contrastinterrupt latency.

session

A collection of process groups established for job control purposes.Each process group is a member of a session. A process belongs tothe session that its process group belongs to. A newly created processjoins the session of its creator. A process can alter its session

302 Glossary November 3, 2006

Page 323: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

membership viasetsid(). A session can contain multiple processgroups.

session leader

A process whose death causes all processes within its process groupto receive a SIGHUP signal.

soft thread affinity

The scheme whereby the microkernel tries to dispatch a thread to theprocessor where it last ran, in an attempt to reduce thread migrationfrom one processor to another, which can affect cache performance.Contrasthard thread affinity.

software interrupts

Similar to a hardware interrupt (seeinterrupt), except that the sourceof the interrupt is software.

sporadic

Scheduling algorithm whereby a thread’s priority can oscillatedynamically between a “foreground” or normal priority and a“background” or low priority. A thread is given an executionbudgetof time to be consumed within a certainreplenishment period. Seealsoadaptive, FIFO, andround robin.

startup code

The software component that gains control after the IPL code hasperformed the minimum necessary amount of initialization. Aftergathering information about the system, the startup code transferscontrol to the OS.

static bootfile

An image created at one time and then transmitted whenever a nodeboots. Contrastdynamic bootfile.

November 3, 2006 Glossary 303

Page 324: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG.

static linking

The process whereby you combine your modules with the modulesfrom the library to form a single executable that’s entirelyself-contained. The word “static” implies that it’s not going to change— all the required modules are already combined into one.

symmetric multiprocessing (SMP)

A multiprocessor system where a single instantiation of an OSmanages all CPUs simultaneously, and applications can float to any ofthem.

system page area

An area in the kernel that is filled by the startup code and containsinformation about the system (number of bytes of memory, locationof serial ports, etc.) This is also called the SYSPAGE area.

thread

The schedulable entity under QNX Neutrino. A thread is a flow ofexecution; it exists within the context of aprocess.

timer

A kernel object used in conjunction with time-based functions. Atimer is created viatimer create() and armed viatimer settime(). Atimer can then deliver anevent, either periodically or on a one-shotbasis.

timeslice

A period of time assigned to around-robin or adaptive scheduledthread. This period of time is small (on the order of tens ofmilliseconds); the actual value shouldn’t be relied upon by anyprogram (it’s considered bad design).

304 Glossary November 3, 2006

Page 325: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Index

!

<startup.h> 149

A

A20 207, 259adaptive partitioning 59add cache() 180add callout() 180add callout array() 181add interrupt() 181add interrupt array() 164, 181,

196add ram() 181, 198add string() 164, 181add typed string() 164, 182alloc qtime() 182alloc ram() 182ARM 167, 174, 196–198, 204, 278as add() 182as add containing() 182AS ATTR CACHABLE 143AS ATTR CONTINUED 143

AS ATTR KIDS 143AS ATTR READABLE 143AS ATTR WRITABLE 143as default() 183as find() 183as find containing() 184as info2off() 184AS NULL OFF 143as off2info() 184AS PRIORITY DEFAULT 143as set checker() 184as set priority() 185avoid ram() 185

B

bank-switched See also imagedefined 93

BIOS 4, 5, 152, 208extension 98, 208if you don’t have one 278

block size buildfile attribute62, 63

boot header 107

November 3, 2006 Index 305

Page 326: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Index 2006, QNX Software Systems GmbH & Co. KG.

BOOTP 98, 104bootstrap file (.bootstrap) 50,

59bound multiprocessing (BMP) 58break detect() 177BSP binary components

command line 33IDE 34

BSP source codecommand line 30importing 32

buildfileattributes 50block size 62, 63combining 56compress 60, 109CPU 58data 269filter 63, 64gid 56keeplinked 88max size 62min size 62module 59newpath 54perms 56physical 59script 51search 53spare blocks 62, 64type 271uid 56virtual 50, 59, 108, 278

complete examples of 267including lots of files in 57simple example of 49specifying a processor in 278

syntax 50Bus item

(system page) 150

C

cache 153, 154, 156, 179cacheattr 156CACHE FLAG CTRL PHYS 157CACHE FLAG DATA 157CACHE FLAG INSTR 157CACHE FLAG NONCOHERENT 157CACHE FLAG NONISA 157CACHE FLAG SHARED 157CACHE FLAG SNOOPED 157CACHE FLAG SUBSET 157CACHE FLAG UNIFIED 157CACHE FLAG VIRTUAL 157CACHE FLAG WRITEBACK 157calc time t() 185calloc ram() 185callout area 163callout io map indirect() 186callout memory map indirect()

186callout register data() 186callouts 8, 176

writing your own 209chip access() 187chip done() 187chip read16() 188chip read32() 188chip read8() 187chip write16() 188chip write32() 188

306 Index November 3, 2006

Page 327: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Index

chip write8() 188CIFS 82clock

external 260ClockAdjust() 160, 161ClockCycles() 160ClockPeriod() 160ClockTime() 161cold-start IPL 4, 99compress buildfile attribute 60,

109compressing/decompressing 64compression

mountpoint (.cmp) 67rules 67

config callout 171config() 178confname() 164control() 179conventions, typographical xviicopy memory() 188CPU buildfile attribute 58CPU FLAG FPU 154CPU FLAG MMU 154cpuinfo 159custom engineering 256

D

data buildfile attribute 269debugging 83

hardware considerations 256versions of software 256

del typed string() 189design do’s and don’ts 263

Device item(system page) 151

display char() 177

E

Ethernet 277

F

f3s flash t 233f3s service t 232f3s close() 235f3s ident() 239f3s init() 233f3s open() 234, 237f3s page() 234f3s reset() 239f3s socket option() 236, 237f3s socket syspage() 238f3s start() 233f3s status() 234f3s sync() 243f3s v2erase() 241f3s v2islock() 244f3s v2lock() 245f3s v2read() 239f3s v2resume() 243f3s v2suspend() 242f3s v2unlock() 245f3s v2unlockall() 246f3s v2write() 240falcon init l2 cache() 189falcon init raminfo() 189

November 3, 2006 Index 307

Page 328: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Index 2006, QNX Software Systems GmbH & Co. KG.

falcon system clock() 189field upgrades 257files

.bootstrap 50, 59main.c 120

filesystemCIFS (Common Internet File

System)[fs-cifs] 80ISO-9660 CD-ROM

(fs-cd.so) 80Linux (fs-ext2.so) 80MS-DOS (fs-dos.so) 80NFS (Network File

System)[fs-nfs2] 80package (fs-pkg) 80QNX 4 (fs-qnx4.so) 80

filter buildfile attribute 63, 64find startup info() 189, 198find typed string() 190flags member 168flash 257

accessing compressed fileswithout decompressing64

logical layout of memorychips 258

transferring images to 73two independent sets of

devices 258Flash filesystem

partitions 40flashcmp 64flashctl 74floating point emulator 277fs-cd.so 80fs-cifs 80fs-dos.so 80

fs-ext2.so 80fs-nfs2 80fs-pkg 80fs-qnx4.so 80ftruncate() 69

G

gid buildfile attribute 56Group item

(system page) 150

H

handle common option() 190hardware

debuggers 83supported by Neutrino 11, 15,

16system design

considerations 255hwi add device() 191hwi add inputclk() 191hwi add irq() 192hwi add location() 192hwi add nicaddr() 192hwi add rtc() 192hwi alloc item() 147, 149, 193hwi alloc tag 193hwi alloc tag() 147, 149hwi find as() 193hwi find item() 148, 193hwi find tag() 194HWI NULL OFF 147–149

308 Index November 3, 2006

Page 329: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Index

hwi off2tag() 149, 194hwi tag2off() 148, 195HWI TAG INFO() 149, 150

I

imagebank-switched 93, 101

sources of 94bootable 47combining multiple files 72compressing 60defined 47determining which shared

libraries to include 268example of using an OS image

as a filesystem 48format 5, 72generating 36linearly mapped 93listing contents of 60more than one in system 48nonbootable 48transferring to flash 73

init asinfo() 195init cacheattr() 156, 195init cpuinfo() 153, 156, 195init hwinfo() 196Initial Program Loader See IPLinit intrinfo() 164, 196init mmu() 197init pminfo() 197init qtime() 160, 197init qtime sa1100() 197init raminfo() 182, 185, 198

init smp() 141, 172, 173, 198init syspage memory() 198init system private() 141, 191, 199Intel hex records 73InterruptAttach() 164, 171, 261InterruptAttachEvent() 171, 261InterruptMask() 170InterruptUnmask() 170intrinfo area 164io 152IPL 3, 37

cold-start 4, 99customizing the IPL 105debugging 83

debug symbolinformation 85

responsibilities of 93types of 4warm-start 4, 98

ISA bus slots, external 259

J

JTAGfield upgrades 257hardware debuggers 83

jtag reserve memory() 199

K

keeplinked buildfile attribute 88kprintf() 190, 199

November 3, 2006 Index 309

Page 330: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Index 2006, QNX Software Systems GmbH & Co. KG.

L

ldqnx.so.2 268linearly mapped 100.See also

imagedefined 93recommended 103sources of 94

linker, runtime 268Linux filesystem 80location tag 151lseek() 65lstat() 65

M

main() 138, 149, 226, 231mask() 178max size buildfile attribute 62memory 152memory

linearly addressable 5planning for target system 256

min size buildfile attribute 62MIPS 167, 174, 196–198, 204, 278mips41xx set clock freqs() 199MIPS CPU FLAG 128BIT 154MIPS CPU FLAG 64BIT 154MIPS CPU FLAG L2 PAGE CACHE OPS

154MIPS CPU FLAG MAX PGSIZEMASK

154MIPS CPU FLAG NO COUNT 154MIPS CPU FLAG NO WIRED 154MIPS CPU FLAG PFNTOPSHIFTMASK

154

MIPS CPU FLAGS MAX PGSIZESHIFT154

MIPS CPU FLAG SUPERVISOR 154mkefs 47, 62

buildfile 62mkifs 47, 49, 52, 267MKIFS PATH 52mkimage 72mkrec 72module buildfile attribute 59Moore’s Law 69Motorola S records 73mountpoints

filesystem 76raw

transferring images toflash 74

N

networkboot 103drivers 78, 80filesystems 78, 81, 275

newpath buildfile attribute 54NFS (Network Filesystem) 82, 277NMI 262

O

objdump 268openbios init raminfo() 200O TRUNC 69

310 Index November 3, 2006

Page 331: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Index

P

parallel portdoesn’t need an interrupt

line 262pathname delimiter in QNX

Momentics documentationxviii

pcnet reset() 200pdebug 83perms buildfile attribute 56Photon, in embedded systems xxphysical buildfile attribute 59PIC 260poll key() 177POSIX 51, 61, 65, 69, 82, 270pound sign, in buildfiles 50power() 180PPC 167, 196–198, 204, 278PPC/BE 167ppc400 pit init qtime() 200ppc405 set clock freqs() 200ppc600 set clock freqs() 201ppc700 init l2 cache() 201ppc800 pit init qtime() 201ppc800 set clock freqs() 202PPCCPU ALTIVEC 154PPCCPU DCBZ NONCOHERENT 154PPCCPU EAR 154PPCCPU FPREGS 154PPCCPU HW HT 154PPCCPU HW POW 154PPCCPU SW HT 154PPCCPU SW TLBSYNC 154PPCCPU TLB SHADOW 154PPCCPU XAEN 154ppc dec init qtime() 202

print char() 199printf() 199print syspage() 202procnto

memory pool, adding to 112,113

optional modules, binding 59starting 3, 6, 51version, verifying 219

Q

Qnet (QNX native networking) 15QNX Neutrino

running for the first time 41qtime 160

R

read() 65reboot() 179reclamation 64reopen 270reset vector 3ROM

devices 103monitor 5

rtc time() 203runtime linker 268

S

script buildfile attribute 51

November 3, 2006 Index 311

Page 332: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

Index 2006, QNX Software Systems GmbH & Co. KG.

script fileon the target 58

search buildfile attribute 53sendnto 37serial port 104

loader 104recommended on target

system 261support for multiple 261

SH 175, 196–198, 204SH-4 278shared libraries 267

which to include in animage 268

shellrunning in background 269

SMP 198software debuggers 83spare blocks buildfile attribute

62, 64startup 6

creating your own 138debugging 83

debug symbolinformation 87

library 180structure of 138transferring control to 105

startup header 114startup info box 114startup info mem 112startup info mem extended

113startup info skip 112startup info time 114startup info* structures 111startup io map() 205

startup io unmap() 205startup memory map() 206startup memory unmap() 206stat() 66, 82struct startup info disk

113SYSENTER/SYSEXIT 154syspage entry 139, 156, 160SYSPAGEARM 141SYSPAGEMIPS 141SYSPAGEPPC 141SYSPAGESH4 141SYSPAGEX86 141system page area 7, 135, 139

accessing data within 139fields in 140

T

TCP/IP 275timer load() 177timer reload() 177timer value() 177truncation 69tulip reset() 206type buildfile attribute 271typed strings area 164typographical conventions xvii

U

uid buildfile attribute 56uncompress() 206union 171

312 Index November 3, 2006

Page 333: QNX Neutrino Realtime Operating Systemsupport7.qnx.com/download/download/14702/neutrino...QNX Neutrino Realtime Operating System Building Embedded Systems For targets running QNX Neutrino

2006, QNX Software Systems GmbH & Co. KG. Index

unmask() 178

V

virtual buildfile attribute 50, 59,108, 278

W

warm-start IPL 4, 98

X

X86 CPU BSWAP 154X86 CPU CMOV 154X86 CPU CPUID 154X86 CPU FXSR 154x86 cpuid string() 207X86 CPU INVLPG 154X86 CPU MMX 154X86 CPU MTRR 154X86 CPU PAE 154X86 CPU PGE 154X86 CPU PSE 154X86 CPU RDTSC 154X86 CPU SEP 154X86 CPU SIMD 154x86 cputype() 207X86 CPU WP 154x86 enable a20() 207x86 fputype() 208x86 init pcbios() 208

x86 pcbios shadow rom() 208x86 scanmem() 198, 208, 209

November 3, 2006 Index 313