Real-Time Operating Systems

Download Report

Transcript Real-Time Operating Systems

RTOS
Real-Time Operating
Systems
Conteúdo
• Conceitos
• Complexidade de uma aplicação
• Características do Kernel
• Comunicação e sincronização
• Desempenho
• Tolerância à falhas
• Exemplos
Conceitos
 São sistemas que satisfazem à fortes condições de tempo
de resposta  correção lógica + temporal
 Precisão e desempenho estão fortemente ligados
 Estão preparados para o tratamento de entradas
assíncronas
 Previsíbilidade no pior caso de carga e falhas
Aplicações
 Controle de um processo de fabricação
 Controle de tráfego aéreo
 Treinamento militar
 ...
Composição
Sistema
Controlador
• computador
• pessoas
• sensores
Sistema
Controlado
• chão de fábrica
Composição
Aplicação
hardware
•botões
•sensores
S.O.
primitivas para gerenciamento
de tarefas, comunicação e
sincronização entre processos
Conceitos básicos
• Interrupção: é um sinal de hardware que
gera um evento
•
Evento: ocorrência que faz o programa ter
um comportamento não seqüencial
Síncrono:
Assíncrono:
evento
Conceitos Básicos
• Falha: um sistema falha quando não atende aos
requisitos pré-estabelecidos
• Tempo de resposta: tempo decorrente entre a
entrada de um conjunto de dados e a saída de
todas as respostas associadas.
• Sincronização: condição para que uma tarefa
atinja uma condição específica
• Deadline : tempo limite para execução de uma
tarefa
Características
 Vínculos temporais
•
periódico
 x vezes num período T
 de t em t
 Mais freqüente
•
não periódico
 deadline para início e/ou fim
 Mais complexo
 Implementação
•
reativo: interação com ambiente
•
especialista: hardware próprio
Dimensionamento
• Granularidade do deadline
T
ativa tarefa
fim tarefa
quanto menor T ou quanto menor
deadline-T (tight deadline) menor a
granularidade
Dimensionamento
• Rigor do deadline
Hard:
• não adianta executar após um deadline;
• crítico
Ex. controle de temperatura de uma usina nuclear
Soft:
• pode sobreviver após um deadline
Ex. robô em uma fábrica; monitoramento periódico
de uma aeronave
Dimensionamento
• Confiabilidade
Deadline garantido através de pré alocação de
recursos
Problema: O que realmente é crítico?
• Tamanho do sistema
totalmente carregado na memória
fases carregadas antes da execução
Dimensionamento
• Ambiente determinístico:
• controlado;
• estático.
ex. linha de montagem
• Ambiente não determinístico:
• dinâmico.
ex. robô em marte
Sistema Operacional
 Princípios
•
O fator tempo deve fazer parte dos
fundamentos do sistema
•
Balanceamento entre flexibilidade e
previsibilidade
•
Disponibilidade dos recursos necessários
Sistema Operacional
 Exigências
•
Ser rápido;
•
Ser previsível;
•
Ser confiável;
•
Ser adaptável;
•
Ser tolerante a falhas.
Sistema Operacional
 Otimizações
•
•
•
Troca de contexto rápida
Tamanho reduzido
Resposta rápida à interrupções
 Tratamento temporal
•
•
•
Relógio de tempo real
Escalonamento por prioridade
Primitivas para administração temporal
(pausa/retorno/atraso)
Sistema Operacional
 Concorrência
 Modelo de tarefas  (tempo de execução,
período,deadline)
Inicio
Tempo de
execução
Período
Deadline
Sistema Operacional
 Primitivas Kernel
•
Criação de tarefas
•
Eliminação de tarefas
•
Suspensão de tarefas
•
Reativação de tarefas
•
Mudança de prioridade
•
Retardo
Sistema Operacional
 Implementações
 Pooled Loop
 mais simples;
 teste contínuo de um flag para
verificar a ocorrência de um evento. ;
 Não há escalonamento (uma única
tarefa) nem mecanismos de
sincronização.
Sistema Operacional
 Interrupções
 há troca de contexto
 podem ser periódicas ou não periódicas
 prioridade mais alta interrompe mais baixa
Ex. usina nuclear
 Problema: starvation
nada é mais
importante que
o controle de
temperatura
Sistema Operacional

Escalonamento
O que fazer com multiplos processos de mesma
prioridade?
1. Impedir que isso aconteça (simples); cada
processo tem uma prioridade
2. Time slice
3. Processos com a mesma prioridade não
interrompem outros
Sistema Operacional
 Escalonamento Rate-Monotonic
Processos mais freqüêntes tem
maior prioridade
Periodo
10
12
15
20
Prioridade
1
(maior)
2
3
4
(menor)
Sistema Operacional

Características
•
•
•
•
•
•
produz escalas em tempo de execução
deadline = período
tempo de computação é conhecido e constante
tempo de troca de contexto ~ 0
tarefas periódicas e independentes
escalonabilidade ( calculo de utilização na fase de projeto)
U =  Ci / Pi <= n ( 21/n – 1)
RMS Missing a Deadline
 p1 = (10,20,20) p2 = (15,30,30) utilization is 100%
1
2
Would have met the
deadline if p2 = (10,30,30),
utilization reduced 83%
P2 misses first deadline
Sistema Operacional
 Escalonamento EDF (earliest deadline first)
Processos com deadline mais próximo
recebem maior prioridade
•
•
Assume as mesmas premissas do RM
Reordenação da fila a cada nova execução
EDF Meeting a Deadline
 p1 = (10,20,20) p2 = (15,30,30) utilization is 100%
1
2
P2 takes priority because its
deadline is sooner
Sistema Operacional
 Comparação RM x EDF
Sistema Operacional
 RM garante até 69% de utilização e EDF garante
100%
 EDF é mais complexo e pode gerar um overhead
inaceitável
 RM e EDF assumem que não há interação entre os
processos, que é uma simplificação muito forte.
Sistema Operacional
 Problemas com concorrência:
•
Inversão de prioridade
 Solução
•
Aumento temporário de prioridade do processo
quando obtem um recurso
1
2
Process 1 tries to acquire lock for resource
Process 1 preempts Process 2
Process 2 acquires lock on resource
Process 2 begins running
Outras Características
 Desempenho
•
Tempo de reposta
 Pooled Loop
TR= S + F + P
S=sinalização do hardware (ns)
F=verificação do flag (s)
P=processamento (ms)
 Interrupção
TR = L + C + S + P
L=tempo de interrupção
C=tempo de troca de contexto
S=tempo de escalonamento
P=processamento
Outras Características
 Tempo de carga
•
analisador lógico
 Caminho crítico
 Software pronto e hardware disponível
•
contagem de instruções
 Quando ainda é cedo para o analisador lógico
 Aproximadamente o código final
 Simulador para determinar o tempo de cada
instrução.
Outras Características
 Carga de memória
Percentual de memória utilizada analisador lógico
 Comunicação
Transferência de informações entre tarefas
•
•
Área Comum De Memória
Troca De Mensagem
Tolerância a Falhas
Habilidade de continuar executando
após falha de hardware ou software
 Espacial:
redundância de hardware+software
Temporal:
algoritmo
(checkpoint, logs, replicação)
Estudo de caso: STRAD


Baseado em processador 8088/8086
Primitivas:

Escalonamento:
 concorrência de processos (baseada em
prioridade)
Temporização
Sincronização
Exclusão mútua
processo corrente é o que está pronto com
mais alta prioridade

Comunicação entre processos:
troca de mensagem
Estudo de Caso: QNX
 kernel (8KB)
 Multitarefa
 Escalonamento preemptivo baseado em prioridades
 Rápida troca de contexto
 Comunicação através de troca de mensagens
Estudo de Caso: QNX

kernel
•
Comunicação entre processos
 Mensagem: comunicação bloqueante

Proxies: comunicação não
bloqueante(utilizada quando não há
necessidade de resposta ou emissor não
quer ficar bloqueado

Sinais: comunicação assíncrona
Estudo de Caso: QNX
•
Comunicação de baixo nível via rede
 Um circuito virtual é estabelecido quando um
processo deseja enviar uma mensagem através
da chamada ao sistema qnx_vc_attach().
 Esta função cria uma identificação virtual (VID)
para cada ponta do circuito, isto é, uma para o
transmissor e uma para o receptor, porém a
identificação criada na máquina transmissora
equivale à receptora e vice-versa
Estudo de Caso: QNX
•
Escalonamento de processos



•
FIFO
Round Robin
Adaptativo (default)
– Reduz a prioridade de 1 quando consome a fatia de tempo.
– Aumenta a prioridade de 1 quando o processo que teve sua
prioridade reduzida permanece na fila de prontos por mais de
um minuto.
– Se um processo é bloqueado, a prioridade original é
restaurada.
Tratamento de interrupções
Estudo de Caso: QNX

Processos adicionais
•
•
•
•
Gerenciador de processos
Gerenciador do sistema de arquivos
Gerenciador de dispositivos
Gerenciador de rede
Estudo de Caso: QNX

Primitivas de Tempo
•
Criação de timer



•
•
•
Sleep until completion
Notify with proxy
Notify with signal
Alarme absoluto / relativo
Remoção de timer
Precisão(500s até 50 ms)
Estudo de Caso: QNX

Funções comuns
•
•
•
Sistema de arquivos
Segurança
Rotinas de tratamento de interrupções
Inicialização do QNX em um microcontrolador
Élan SC400
Referências

D. Ripps, Guia de Implementação para programação em Tempo
Real, Cap. I e II, Editora Campus, 1993.

P. Laplante, Real Time Systems Design and Analysis - an
engineer’s handbook, Cap. I, III, VI, VII, VIII, IX, XI, IEEE Press,
1992.

A. Freedman, and R. Lees, Real Time Computer Systems, Cap. I,
Crane Russak & Company, 1977.

J.
Stankovic,
Real
Massachusetts, 1992.

Yodaiken, The RT-Linux approach to hard real-time,
Departament of Computer Science, New Mexico Institute of
Technology

J.ª Stankovic et al, Strategic Directions in real-time and
embedded systems, ACM Computing Surveys, vol28, n 4,
December, 1996.

Romulo de Oliveira, Jean-Marie Farines, Jonidas S Fraga,
Sistemas de Tempo Real, Escola de Computação 2000.
Time
Computing,
University
of
CSE 537s
TinyOS source code
and programming
Xiaorui Wang
Most slides are modified from Berkeley TinyOS introduction
Copyright © 2001 Stephen A. Edwards All rights reserved
Roadmap
 TinyOS Overview
 A simple Counter program
 Sending and receiving message through sensor
network
 Event driven Sensor data
 Posting a task
 TOSSIM: Simulator on PC
 Programming Environment
TinyOS Overview
• Application = scheduler + graph of components
– Compiled into one executable
• Event-driven architecture
• Single shared stack
• No kernel/user space differentiation
Main (includes Scheduler)
Application (User Components)
Actuating
Communication
Sensing
Communication
Hardware Abstractions
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
TinyOS component model
• Component has:
– Frame (storage)
– Tasks: computation
– Interface:
• Command
• Event
Messaging Component
Internal Tasks
Commands
Internal State
Events
• Frame: static storage model - compile time
memory allocation (efficiency)
• Command and events are function calls (efficiency)
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
How TinyOS works : Scheduling
Two-level scheduling ( Event and Task )
– Single shared stack ( used by both interrupt and function call)
– Scheduler is simple FIFO with bounded number of pending task.
– Task can NOT preempt each other.
– Event has high priority than Task. Event can preempt task
– Event can preempt each other, once enabled
– When idle , scheduler shut down node except for clock
Modified from Tian He et. Al., TinyOS source code and programming, U of Virginia
Event implementation
Event is independent of FIFO scheduler.
 Lowest level events are supported directly by Hardware
interrupt
 Software events propagate from lower level to upper level
through function call.
INTERRUPT(_output_compare2_){ // Hardware Timer Event Handler
…
TOS_SIGNAL_EVENT(CLOCK_FIRE_EVENT)( ); //Software Event
…
}
TinyOS Commands,Events and
Tasks
{
...
status = TOS_CALL_COMMAND(name)(args)
...
}
TOS_EVENT(name)(args) {
...
return status;
}
Function call
Function Call
TOS_COMMAND(name)(args) {
...
return status;
}
TOS_TASK(name)(args) {
...
return status;
}
{
...
status = TOS_SIGNAL_EVENT(name)(args)
...
}
{
...
TOS_POST_TASK(name)(args)
}
Fun. Pointer
FIFO Queue
Real implementation:
#define TOS_COMMAND(command_name) TOS_CALL_COMMAND(command_name)
#define TOS_EVENT(event_name)
TOS_SIGNAL_EVENT(event_name)
How TinyOS works : Communication
Application
Application
Component
H1
H2
H3
AM Dispatcher
messaging
Messaging
packet
byte
bit
Radio Packet
Radio byte
RFM
• Bit Encoding
One
byte message
type
to
Manchester
encoding
(1bused
2b)
A simple profiling:
DC
balancing
 6b)
direct
packet to(4b
handlers
If we want toforward
send 60error
Byte data,
SEC_DED
correction
Real
implementation:
we
need
to==
invoke:
(8b
17b)
30
Byte
Fix
if(msg.type
0)length
val =Packet
Handler0(data);
Packaging
Content-based
routing
• Messaging
Error
CRCdetection
check
layer & correction
1 times
Dividing/Combine
Consensus
algorithm
SEC_DED
Correct
1b
Detect
16
bit
CRC
check,
if(msg.type
==
1) val
= >2
Handler1(data);
Packet
layer
times 2b
Routing
Location
Service
• Signal
strength
Drops
packet if fails
….
byte
layer; Base_station
> 60
times
Echo
Relay;….
Tracking
Each
time
a
1
bit
is
read
in,
Simplex
transceiver
Redundancy
transmit> 480 times
….Special
address
RFM
Sensor
data processing
the
ADC
samples
the value
We
can
transmitted
3
times
if(msg.type
==
255)
val
=
Handler255(data)
0xff
= BBOUT
Broadcast
Address
……
ofOperation
the
pin.
Set
Mode
(TX/RX)
0x7E
= UART
interface
……
• CSMA
Set
Sampling
Rate
UserReceive
need
toone
redefine
handler
name
Detect
whether
channel
Bit current
#define
Handler1
is free
to
transmit,
otherwise wait
Transmit
one
BitXXXX
#define
NULL_FUNC
forHandler5
random
ticks [12,75]
Notify
TX/RXofisclock
finished
Shut down RFM (1/10th)
clock rate (10kHZ) LFSR
Modified from Tian He et. Al., TinyOS source code and programming, U of Virginia
What is a typical TinyOS
application
A typical TinyOS application consists of
 a main
 a scheduler (sched.o)
 an AM dispatcher
 a list of component objects
 relationship between components.
Simplified Main Loop for TinyOS
application: FIFO scheduler
int main() {
TOS_CALL_COMMAND(MAIN_SUB_INIT)(); // initialize the subcomponents
TOS_CALL_COMMAND(MAIN_SUB_START)(); //start the subcomponents
while(1){
while(!TOS_schedule_task()) { }; //Run until no task in the FIFO Queue
asm volatile ("sleep" ::); // save power
}
}
Programming the Mote (1)
Program = graph of components + FIFO scheduler.
Graph of components = individual components + relations
Individual components = command/event interface + behavior
Behavior = Event + Command + Internal Tasks
Programming the Mote (2)
Individual component
A typical TinyOS component

Component interface (.comp)
• Commands that it accepts(implemented)
• Commands that it uses
• Events that it signals
Messaging Component
• Events that it handles (implemented)
Internal Tasks

Component implementation (.c)
• Functions that implement interface
• Frame: internal state
• Tasks: internal concurrency
• Uses only internal namespace
Commands
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
Internal State
Events
Programming the Mote (3)
Relations

Component dependence (.desc)
• Glue the components
• Denote the dependence among component.
• Mapping the interface between the component.
MAIN
An example: output
the counter number
to LEDs
COUNTER
CLOCK
LEDS
components
Simple counter
program
.descInterfaces
file describe
the
relationships
areimplement
defined
.c file
between
through
the
interface
the.COMP
component
File
generic init interface
MAIN
clock interface
main_sub_start
main_sub_init
counter_init
output interface
counter_start
COUNTER
counter_sub_clock_init
clock_init
clock_event
counter_sub_output_init
clock_fire_event
CLOCK
int_to_leds_init
counter_output
int_to_leds_output
INT_TO_LEDS
Files for this simple application
Seven Files
 Describe the relation between compoents:
•
cnt_to_led.desc
 Describe three components ( two files each)
•
•
•
Counter.c
Counter.comp
Clock.c
Clock.comp
INT_TO_LED.c INT_TO_LED.comp
Composing applications from components
Example:
apps/cnt_to_led.desc
include modules{
MAIN;
MAIN
COUNTER;
INT_TO_LEDS;
main_sub_init
CLOCK;
};
counter_init
MAIN:MAIN_SUB_INIT COUNTER:COUNTER_INIT
COUNTER
MAIN:MAIN_SUB_START COUNTER:COUNTER_START
COUNTER:COUNTER_CLOCK_EVENT CLOCK:CLOCK_FIRE_EVENT
COUNTER:COUNTER_SUB_CLOCK_INIT CLOCK:CLOCK_INIT
COUNTER:COUNTER_SUB_OUTPUT_INIT INT_TO_LEDS:INT_TO_LEDS_INIT
COUNTER:COUNTER_OUTPUT INT_TO_LEDS:INT_TO_LEDS_OUTPUT
apps/cnt_to_led.desc
.comp component interface file
TOS_MODULE COUNTER;
To be implemented in .c file
ACCEPTS{
char COUNTER_START(void);
char COUNTER_INIT(void);
};
HANDLES{
void COUNTER_CLOCK_EVENT(void);
};
USES{
//need following service provide by other component
char COUNTER_SUB_CLOCK_INIT(char interval, char scale);
char COUNTER_SUB_OUTPUT_INIT();
char COUNTER_OUTPUT(int value);
};
SIGNALS{ // no signal it will generate
};
COUNTER.comp
Declare and access variable

TOS_FRAME_BEGIN, TOS_FRAME_END to declare a component frame
example
TOS_FRAME_BEGIN(COUNTER_frame) {
char state;
}
TOS_FRAME_END(COUNTER_frame);

VAR(foo)
to access a variable (foo) in the frame
Real implementation:
#define TOS_FRAME_BEGIN(frame_type)
typedef struct
#define TOS_FRAME_END(frame_type)
frame_type;
static frame_type
TOS_MY_Frame;
#define VAR(x)
TOS_MY_Frame.x
Implemention: COUNTER.c
#include "tos.h"
#include "COUNTER.h"
//Frame Declaration
#define TOS_FRAME_TYPE COUNTER_frame
TOS_FRAME_BEGIN(COUNTER_frame) {
char state;
}
TOS_FRAME_END(COUNTER_frame);
//Events handled
/* Clock Event Handler: */
void TOS_EVENT(COUNTER_CLOCK_EVENT)(){
VAR(state) ++;
TOS_CALL_COMMAND(COUNTER_OUTPUT)(VAR(state)); /* update LED state */
}
COUNTER.c
COUNTER.c - rudimentary event
processing
//Commands accepted
char TOS_COMMAND(COUNTER_INIT)(){
VAR(state) = 0;
/* initialize output component */
return TOS_CALL_COMMAND(COUNTER_SUB_OUTPUT_INIT)();
}
char TOS_COMMAND(COUNTER_START)(){
/* initialize clock component and start event processing */
return TOS_CALL_COMMAND(COUNTER_SUB_CLOCK_INIT)(tick2ps);
}
Roadmap
 TinyOS Overview
 A simple Counter program
 Sending and receiving message through sensor
network
 Event driven Sensor data
 Posting a task
 TOSSIM: Simulator on PC
 Programming Environment
More complicated example: cnt_to_rfm
Changing counter output from LEDs to RFM
All you have to do is just changing the wiring
between the components
To demonstrate:
 1. Asynchronous command completion events
 2. Use of a generic communication stack
 3. Sending an Active Message to a named handler
 4. Active Message Handlers (partially)
 5. Buffer management discipline for messages
cnt_to_rfm.desc
include modules{
MAIN;
COUNTER;
INT_TO_RFM;
CLOCK;
};
MAIN:MAIN_SUB_INIT COUNTER:COUNTER_INIT
MAIN:MAIN_SUB_START COUNTER:COUNTER_START
COUNTER:COUNTER_CLOCK_EVENT CLOCK:CLOCK_FIRE_EVENT
COUNTER:COUNTER_SUB_CLOCK_INIT CLOCK:CLOCK_INIT
COUNTER:COUNTER_SUB_OUTPUT_INIT INT_TO_RFM:INT_TO_RFM_INIT
COUNTER:COUNTER_OUTPUT_COMPLETE INT_TO_RFM:INT_TO_RFM_COMPLETE
COUNTER:COUNTER_OUTPUT INT_TO_RFM:INT_TO_RFM_OUTPUT
More complicated example: cnt_to_rfm
MAIN
Main.c sched.c
Counter.c Counter.comp
COUNTER
CLOCK
Clock.c
Clock.comp
Relationship description
Cnt_to_rfm.desc
INT_TO_RFM
INT_TO_RFM.c INT_TO_RFM.comp
hardware.h
AM
am.c am.comp
PACKETOBJ
PACKETOBJ.c PACKETOBJ.comp
SEC_DED_RADIO_BYTE
SEC_DED_RADIO_BYTE.c ...comp
RFM
RFM.c ...comp
hardware.h
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
Message Storage
TOS_FRAME_BEGIN(INT_TO_RFM_frame) {
char pending;
struct MSG_VALS{
TOS_Msg msg;
short addr;
}
data is a character pointer pointing
to the beginning of the message's
TOS_FRAME_END(INT_TO_RFM_frame);
payload. The payload is currently
standardized to be 30 bytes long
typedef struct{
char val;
} int_to_led_msg;

Inside MSG.h
char type;
unsigned char group;
char data[DATA_LENGTH];
short crc;
short strength;
short time;
tone_time;
Component that originates messageshort
provides
buffer
};

TOS_Msg type provides header and #define
trailerDATA_LENGTH
wrapper, so
30 copies
are avoided
#define TOS_Msg struct MSG_VALS

Application data referenced as msg.data
INT_TO_RFM.c
Send Message
char TOS_COMMAND(INT_TO_RFM_OUTPUT)(int val){
int_to_led_msg* message = (int_to_led_msg*)VAR(msg).data;
if (!VAR(pending)) {
message->val = val;
if (TOS_COMMAND(INT_TO_RFM_SUB_SEND_MSG)(TOS_MSG_BCAST,
AM_MSG(INT_READING), &VAR(msg))) {
VAR(pending) = 1;
return 1;
}
access application msg buffer
}
cast to defined format
return 0;
avoid re-entering to protect buffer,
not to wait the radio
build msg
request transmission
}
destination identifier
set handler identifier
msg buffer
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
Set protection for the buffer
Send Message

INT_TO_RFM_SUB_SEND_MSG directly links to
COMM_SEND_MSG(short addr, char type, TOS_Msg* data) in
GENERIC_COMM

INT_TO_RFM:INT_READING message handler
is wired to GENERIC_COMM : GENERIC_COMM_MSG_HANDLER_4

GENERIC_COMM provides the mapping from handler name to
handler identifier (here 4). Totally 256 handlers, meaning you can
handle 256 different types of message at same time.

GENERIC_COMM:COMM_SEND_MSG is wired to
AM_STANDARD:AM_SEND_MSG
More detailed call sequences
INT_TO_RFM : INT_TO_RFM_SUB_SEND_MSG
RFM : RFM_TX_BIT
Generic_Com : Com_Send_Msg
SEC_DED_Radio_Byte : Radio_Sub_TX_BIT
AM_Standard : AM_Send_Msg
SEC_DED_Radio_Byte : Radio_Byte_TX_Bytes
AM -> TOS_POST_TASK(AM_Send_Task)
Scheduler
AM : TOS_TASK(AM_Send_Task)
PacketObj : Packet_TX_Bytes
PacketObj : Packet_TX_Packet
AM : AM_Sub_TX_Packet
How sending message works?
Application
Pending
Component 1
Application
Component 2
Data buffer
Pending
1
Data buffer
0
AM
Buffer is provided by the
application component.
The lower level will not
copy the buffer. They just
use pointer of the buffer.
State
State
=0
1
System
Scheduler
Lower level
Completion Event
char TOS_EVENT(INT_TO_RFM_SUB_MSG_SEND_DONE)(TOS_MsgPtr sentBuffer){
if (VAR(pending) && sentBuffer == &VAR(data)) {
VAR(pending) = 0;
TOS_SIGNAL_EVENT(INT_TO_RFM_COMPLETE)(1);
return 1;
}
return 0;
}
 When transmission of a message is completed,
GENERIC_COMM will signal a COMM_SEND_DONE event to
all components that are registered with the Active Message
component. A pointer to the buffer sent is provided as an
argument to the event.
Registered means
those component
which are wired to
Generic_Send_Done
event in .desc file
How to receive?
RFM_to_LEDs : receive message from CNT_TO_RFM
How can receiving side know how to handle the
incoming message?
Same handler
Number here.
RFM_TO_LEDS:INT_READING is wired to
GENERIC_COMM:GENERIC_COMM_MSG_HANDLER_4
The Active Message layer decodes the handler type
and dispatches it.
How to send the message to LEDs display?
RFM_TO_LEDS:RFM_TO_LEDS_LED_OUTPUT is wired to
INT_TO_LEDS:INT_TO_LEDS_OUTPUT
All GENERIC_COMM handlers have the following interface
that application handler for incoming messages:
TOS_MsgPtr GENERIC_COMM_HANDLER_X(TOS_MsgPtr data);
Roadmap
 TinyOS Overview
 A simple Counter program
 Sending and receiving message through sensor
network
 Event driven Sensor data
 Posting a task
 TOSSIM: Simulator on PC
 Programming Environment
Event-driven Sensor Data
include modules{
MAIN;
SENS_OUTPUT;
INT_TO_LEDS;
CLOCK;
PHOTO;
};
MAIN:MAIN_SUB_INIT SENS_OUTPUT:SENS_OUTPUT_INIT
MAIN:MAIN_SUB_START SENS_OUTPUT:SENS_OUTPUT_START
SENS_OUTPUT:SENS_OUTPUT_CLOCK_EVENT CLOCK:CLOCK_FIRE_EVENT
SENS_OUTPUT:SENS_OUTPUT_SUB_CLOCK_INIT CLOCK:CLOCK_INIT
SENS_OUTPUT:SENS_OUTPUT_SUB_OUTPUT_INIT INT_TO_LEDS:INT_TO_LEDS_INIT
SENS_OUTPUT:SENS_OUTPUT_OUTPUT_COMPLETE INT_TO_LEDS:INT_TO_LEDS_DONE
SENS_OUTPUT:SENS_OUTPUT_OUTPUT INT_TO_LEDS:INT_TO_LEDS_OUTPUT
SENS_OUTPUT:SENS_DATA_INIT PHOTO:PHOTO_INIT
SENS_OUTPUT:SENS_GET_DATA PHOTO:PHOTO_GET_DATA
SENS_OUTPUT:SENS_DATA_READY PHOTO:PHOTO_DATA_READY
apps/sens_to_leds.desc
Asynchronous Sensor Interface
TOS_MODULE PHOTO;
JOINTLY IMPLEMENTED_BY PHOTO;
ACCEPTS{
char PHOTO_INIT(void);
char PHOTO_GET_DATA(void);
char PHOTO_PWR(char mode);
};
SIGNALS{
char PHOTO_DATA_READY(int data);
};
USES{
char SUB_ADC_INIT(void);
char SUB_ADC_GET_DATA(char port);
};
HANDLES{
char PHOTO_ADC_DONE(int data);
};
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
system/PHOTO.desc
Event Driven Sensor Data
char TOS_EVENT(SENSE_OUTPUT_CLOCK_EVENT)(){
return TOS_CALL_COMMAND(SENSE_GET_DATA)();
}
SENSE_GET_DATA is wired to
PHOTO_GET_DATA which is
char TOS_EVENT(SENSE_DATA_READY)(int data){
wired to ADC:ADC_GET_DATA.
TOS_CALL_COMMAND(SENS_OUTPUT_OUTPUT)((data >> ADC_GET_DATA
2) &0x7);
implement
depends on platform
return 1;
}
void display(char val)
{
 clock event handler initiates
data collection
if (val & 1)
 sensor signals data ready
event
TOS_CALL_COMMAND(SENSE_LEDy_on)();
 data event handler calls……......
output command
 common pattern
}
SENS_OUTPUT.c
Post Tasks for Application Data
Processing
 Sense 2 application at nest/apps/sense2
Posting Task
char TOS_EVENT(SENSE_DATA_READY)(short data){
putdata(data);
TOS_POST_TASK(processData);
return 1;
}
Handling Task
TOS_TASK(processData){
int i, sum = 0;
TOS_CALL_COMMAND(SENSE_LEDg_toggle)();
for (i=0; i<maxdata; i++)
sum = sum + (VAR(data[i]) >> 7);
display(sum >> shiftdata);
}
Roadmap
 TinyOS Overview
 A simple Counter program
 Sending and receiving message through sensor
network
 Event driven Sensor data
 Posting a task
 TOSSIM: Simulator on PC
 Programming Environment
TOSSIM : simulator on PC
to debug apps/router/router application
 What TOSSIM can do?
•
•
•
•
•
•
simulated running on PC
packet injection
packet sniffing
using dbg to output debugging information
static parameters setting
more …
 TOSSIM is compiled by typing make pc and run by
typing ./binpc/main
 Set DBG option to see desired debugging info
•
Export DBG=sim,am,usr1
TOSSIM: Injecting Packets into the
Network

Port 10579 for "dynamic packet injection.“

Use packets injecting to create an initial seed routing beacon
in the network in this application

What does the Injecting packets tool look like?
Visualizing Network Traffic
Use visualizing to display what the sensors send in the network
1
2
3
4
Injected routing beacon
5
0
6
7
8
9
Programming Environment
 Platform:
cygwin on top of Windows 2000
 Software:
perl, gcc, java, atmel tools ,cygwin
Mote-to-mote communication
Program Code
Mote-PC
communication
Steps
 Write Component ( .c and .comp file )
 Write Relation
( .desc file )
Run on Mote
•
Modify makefile
 Set GROUP_ID
 redefine Macro: DESC = XXXXX.desc
•
Build
 Make clean ; make
•
Upload the image into Mote and run
 Make install_windows
Run on PC
•
•
•
Modify makefilePC
Build: make clean ; make pc
Run: main < node_ID >
Programming & debug Tools
 Makefile
•
Create super.h from DESC and COMP file, then link all
component into one single image that is executable by
ATMEL AVR AT90S2343 processor.
 Make pc
•
It’s for debug purpose and run on the PC
 gdb main <nod_ID>
 Serial Port listener -- monitor traffic between mote
and PC.
SW: Embedded Software Tools
U
S
E
R
application
source
compiler
Application
code
software
a.out
debugger
simulator
C
P
U
A
S
I
C
RTOS
ROM
A
S
I
C
RAM
Embedded Microprocessor
Evolution
> 500k transistors
1 - 0.8 
33 mHz
1989
2+M transistors
0.8 - 0.5 
75 - 100 mHz
1993
5+M transistors
0.5 - 0.35 
133 - 167 mHz
1995
22+M transistors
0.25 - 0.18 
500 - 600 mHz
1999
 Embedded CPU cores are getting smaller; ~ 2mm2 for up to 400
mHz
• Less than 5% of CPU size
 Higher Performance by:
• Faster clock, deeper pipelines, branch prediction, ...
 Trend is towards higher integration of processors with:
• Devices that were on the board now on chip: “system on a
chip”
• Adding more compute power by add-on DSPs, ...
• Much larger L1 / L2 caches on silicon
J. Fiddler - WRS
Embedded Software Crisis
J. Fiddler - WRS
Cheaper, more powerful
Microprocessors
Increasing
Time-to-market
pressure
Embedded
Software
Crisis
J. Fiddler - WRS
Bigger, More Complex
Applications
More
Applications
SW: Embedded Software Tools
U
S
E
R
application
source
compiler
Application
code
software
a.out
debugger
simulator
C
P
U
A
S
I
C
RTOS
ROM
A
S
I
C
RAM
Outline on RTOS
 Introduction
 VxWorks
•
General description
 System
 Supported processors
•
Details




Kernel
Custom hardware support
Closely coupled multiprocessor support
Loosely coupled multiprocessor support
 pSOS
 eCos
 Conclusion
Embedded Development:
Generation 0
 Development: Sneaker-net
 Attributes:
•
•
•
No OS
Painful!
Simple software only
Embedded Development:
Generation 1
 Hardware: SBC, minicomputer
 Development: Native
 Attributes:
•
Full-function OS
 Non-Scalable
 Non-Portable
•
•
Turnkey
Very primitive
SW: Embedded Software Tools
U
S
E
R
application
source
compiler
Application
code
software
a.out
debugger
simulator
C
P
U
A
S
I
C
RTOS
ROM
A
S
I
C
RAM
Outline on RTOS
 Introduction
 VxWorks
•
General description
 System
 Supported processors
•
Details




Kernel
Custom hardware support
Closely coupled multiprocessor support
Loosely coupled multiprocessor support
 pSOS
 eCos
 Conclusion
Embedded Development:
Generation 0
 Development: Sneaker-net
 Attributes:
•
•
•
No OS
Painful!
Simple software only
Embedded Development:
Generation 1
 Hardware: SBC, minicomputer
 Development: Native
 Attributes:
•
Full-function OS
 Non-Scalable
 Non-Portable
•
•
Turnkey
Very primitive
Embedded Development:
Generation 2
 Hardware: Embedded
 Development: Cross, serial line
 Attributes
•
•
•
•
•
Kernel
Originally no file sys, I/O, etc.
No development environment
No network
Non-portable, in assembly
Embedded Development:
Generation 2
 Hardware: Embedded
 Development: Cross, serial line
 Attributes
•
•
•
•
•
Kernel
Originally no file sys, I/O, etc.
No development environment
No network
Non-portable, in assembly
SW: Embedded Software Tools
U
S
E
R
application
source
compiler
Application
code
software
a.out
debugger
simulator
C
P
U
A
S
I
C
RTOS
ROM
A
S
I
C
RAM
Embedded Microprocessor
Evolution
> 500k transistors
1 - 0.8 
33 mHz
1989
2+M transistors
0.8 - 0.5 
75 - 100 mHz
1993
5+M transistors
0.5 - 0.35 
133 - 167 mHz
1995
22+M transistors
0.25 - 0.18 
500 - 600 mHz
1999
 Embedded CPU cores are getting smaller; ~ 2mm2 for up to 400
mHz
• Less than 5% of CPU size
 Higher Performance by:
• Faster clock, deeper pipelines, branch prediction, ...
 Trend is towards higher integration of processors with:
• Devices that were on the board now on chip: “system on a
chip”
• Adding more compute power by add-on DSPs, ...
• Much larger L1 / L2 caches on silicon
J. Fiddler - WRS
SW: Embedded Software Tools
U
S
E
R
application
source
compiler
Application
code
software
a.out
debugger
simulator
C
P
U
A
S
I
C
RTOS
ROM
A
S
I
C
RAM
Embedded Development:
Generation 2
 Hardware: Embedded
 Development: Cross, serial line
 Attributes
•
•
•
•
•
Kernel
Originally no file sys, I/O, etc.
No development environment
No network
Non-portable, in assembly
SW: Embedded Software Tools
U
S
E
R
application
source
compiler
Application
code
software
a.out
debugger
simulator
C
P
U
A
S
I
C
RTOS
ROM
A
S
I
C
RAM
Embedded Microprocessor
Evolution
> 500k transistors
1 - 0.8 
33 mHz
1989
2+M transistors
0.8 - 0.5 
75 - 100 mHz
1993
5+M transistors
0.5 - 0.35 
133 - 167 mHz
1995
22+M transistors
0.25 - 0.18 
500 - 600 mHz
1999
 Embedded CPU cores are getting smaller; ~ 2mm2 for up to 400
mHz
• Less than 5% of CPU size
 Higher Performance by:
• Faster clock, deeper pipelines, branch prediction, ...
 Trend is towards higher integration of processors with:
• Devices that were on the board now on chip: “system on a
chip”
• Adding more compute power by add-on DSPs, ...
• Much larger L1 / L2 caches on silicon
J. Fiddler - WRS
SW: Embedded Software Tools
U
S
E
R
application
source
compiler
Application
code
software
a.out
debugger
simulator
C
P
U
A
S
I
C
RTOS
ROM
A
S
I
C
RAM
Outline on RTOS
 Introduction
 VxWorks
•
General description
 System
 Supported processors
•
Details




Kernel
Custom hardware support
Closely coupled multiprocessor support
Loosely coupled multiprocessor support
 pSOS
 eCos
 Conclusion
Embedded Development:
Generation 0
 Development: Sneaker-net
 Attributes:
•
•
•
No OS
Painful!
Simple software only
Embedded Development:
Generation 1
 Hardware: SBC, minicomputer
 Development: Native
 Attributes:
•
Full-function OS
 Non-Scalable
 Non-Portable
•
•
Turnkey
Very primitive
Embedded Development:
Generation 2
 Hardware: Embedded
 Development: Cross, serial line
 Attributes
•
•
•
•
•
Kernel
Originally no file sys, I/O, etc.
No development environment
No network
Non-portable, in assembly
Embedded Development:
Generation 3
 Hardware: SBC, embedded
 Development: Cross, Ethernet
•
Integrated, text-based, Unix
 Attributes
•
Scalable, portable OS
 Includes network, file & I/O sys, etc.
•
Tools on target
 Network required
 Heavy target required for development
•
Closed development environment
Embedded Development:
Generation 4
 Hardware: Embedded, SBC
 Development: Cross
•
Any tool - Any connection - Any target
•
Integrated GUI, Unix & PC
 Attributes
•
Tools on host
 No target resources required
 Far More Powerful Tools (WindView, CodeTest, …)
•
Open dev. environment, published API
•
Internet is part of dev. environment
 Support, updates, manuals, etc.
VxWorks
Real-Time Embedded Applications
Graphics
Multiprocessing support
Internet support
Java support
POSIX Library
File system
WindNet Networking
Core OS
Wind Microkernel
VxWorks 5.4 Scalable Run-Time System
Supported Processors
 PowerPC
 68K, CPU 32
 ColdFire
 SPARC
 NEC V8xx
 MCORE
 M32 R/D
 80x86 and Pentium
 RAD6000
 i960
 ARM and Strong ARM
 ST 20
 MIPS
 TriCore
 SH
Wind microkernel
 Task management
•
•
•
•
multitasking, unlimited number of tasks
preemptive scheduling and round-robin
scheduling(static scheduling)
fast, deterministic context switch
256 priority levels
Wind microkernel
 Fast, flexible inter-task communication
•
•
•
•
•
binary, counting and mutual exclusion semaphores
with priority inheritance
message queue
POSIX pipes, counting semaphores, message queues,
signals and scheduling
control sockets
shared memory
Wind microkernel
 High scalability
 Incremental linking and loading of
components
 Fast, efficient interrupt and exception
handling
 Optimized floating-point support
 Dynamic memory management
 System clock and timing facilities
``Board Support Package’’
 BSP = Initializing code for hardware device + device
driver for peripherals
 BSP Developer’s Kit
Hardware
independent
code
Processor
dependent
code
Device dependent code
BSP
VxMP
 A closely coupled multiprocessor support accessory
for VxWorks.
 Capabilities:
•
•
•
•
•
•
•
•
Support up to 20 CPUs
Binary and counting semaphores
FIFO message queues
Shared memory pools and partitions
VxMP data structure is located in a shared memory area
accessible to all CPUs
Name service (translate symbol name to object ID)
User-configurable shared memory pool size
Support heterogeneous mix of CPU
VxMP
 Hardware requirements:
•
•
•
•
Shared memory
Individual hardware read-write-modify mechanism
across the shared memory bus
CPU interrupt capability for best performance
Supported architectures:






680x0 and 683xx
SPARC
SPARClite
PPC6xx
MIPS
i960
VxFusion
 VxWorks accessory for loosely coupled configurations and
standard IP networking;
 An extension of VxWorks message queue, distributed
message queue.
 Features:
• Media independent design;
• Group multicast/unicast messaging;
• Fault tolerant, locale-transparent
operations;
•
Heterogeneous environment.
 Supported targets:
• Motorola: 68K, CPU32, PowerPC
• Intel x86, Pentium, Pentium Pro
App1
App2
VxFusion
Adapter Layer
Transport
pSOS
Loader
I/O system
Debug
C/C++
File System
BSPs
Memory
Management
POSIX
Library
pSOS+ Kernel
pSOS 2.5
Supported processors
 PowerPC
 M32/R
 68K
 m.core
 ColdFire
 NEC v8xx
 MIPS
 ST20
 ARM and Strong
ARM
 SPARClite
 X86 and Pentium
 i960
 SH
pSOS+ kernel
 Small Real Time multi-tasking kernel;
 Preemptive scheduling;
 Support memory region for different tasks;
 Mutex semaphores and condition variables
(priority ceiling)
 No interrupt handling is included
Board Support Package
 BSP = skeleton device driver code + code for
low-level system functions each particular
devices requires
pSOS+m kernel
 Tightly coupled or distributed processors;
 pSOS API + communication and coordination
functions;
 Fully heterogeneous;
 Connection can be any one of shared memory, serial
or parallel links, Ethernet implementations;
 Dynamic create/modify/delete OS object;
 Completely device independent
eCos
ISO C Library Native Kernel C API
ITRON 3.0 API
Drivers
Kernel
Device
Internal Kernel API
pluggable schedulers, mem alloc,
synchronization, timers, interrupts,
threads
HAL
Supported processors

Advanced RISC Machines ARM7

Fujitsu SPARClite

Matsushita MN10300

Motorola PowerPC

Toshiba TX39

Hitachi SH3

NEC VR4300

MB8683x series

Intel strong ARM
Kernel
 No definition of task, support multi-thread
 Interrupt and exception handling
 Preemptive scheduling: time-slice scheduler, multilevel queue scheduler, bitmap scheduler and priority
inheritance scheduling
 Counters and clocks
 Mutex, semaphores, condition variable, message box
Hardware Abstraction Layer
 Architecture HAL abstracts basic CPU, including:
•
•
•
interrupt delivery
context switching
CPU startup and etc.
 Platform HAL abstracts current platform, including
•
•
•
•
platform startup
timer devices
I/O register access
interrupt control
 Implementation HAL abstracts properties that lie between
the above,
•
•
architecture variants
on-chip devices
 The boundaries among them blurs.
Summary on RTOS
Task
VxWorks
pSOS
eCos
Y
Y
Only Thread
Preemptive, static
Preemptive
Scheduler
Y
Synchronization mechanism No condition variable
Preemptive
Y
POSIX support
Y
Y
Linux
Scalable
Y
Y
Y
BSP
BSP
-
16KB
HAL, I/O
package
-
VxMP/ VxFusion
(accessories)
PSOS+m
kernel
Custom hw support
Kernel size
Multiprocessor support
None
Recall the ``Board Support Package’’
 BSP = Initializing code for hardware device + device
driver for peripherals
 BSP Developer’s Kit
Hardware
independent
code
Processor
dependent
code
Device dependent code
BSP
Introduction to Device Drivers
 What are device drivers?
•
•
Make the attached device work.
Insulate the complexities involved in I/O handling.
Application
RTOS
Device driver
Hardware
Proliferation of Interfaces
 New Connections
•
•
•
•
USB
1394
IrDA
Wireless
 New Models
•
•
•
•
JetSend
Jini
HTTP / HTML / XML / ???
Distributed Objects (DCOM, CORBA)
Leads to Proliferation of Device
Drivers
Courtesy - Synopsys
Device Driver Characterization
 Device Drivers’ Functionalities
•
•
•
•
initialization
data access
data assignment
interrupt handling
Device Characterization

Block devices
• fixed data block sizes devices

Character devices
• byte-stream devices

Network device
• manage local area network and wide area network
interconnections