RTOS Real-Time Operating Systems Conteúdo Conceitos Complexidade de uma aplicação...
-
Upload
joao-vitor-nicholas-ramalho-estrela -
Category
Documents
-
view
218 -
download
2
Transcript of RTOS Real-Time Operating Systems Conteúdo Conceitos Complexidade de uma aplicação...
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
Sistema Controlado
ambiente
• computador• pessoas
• chão de fábrica
• sensores
Composição
hardware
S.O.
Aplicação
•botões•sensores
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
Assíncrono:
evento
Síncrono:
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
ativa tarefa fim tarefa
T
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íticoEx. controle de temperatura de uma usina nuclear
Soft: • pode sobreviver após um deadlineEx. 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)
Tempo de execução
Período
DeadlineInicio
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 Prioridade10 1 (maior)12 215 320 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
P2 misses first deadline
Would have met the deadline if p2 = (10,30,30), utilization reduced 83%
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
12
Process 2 begins runningProcess 2 acquires lock on resource
Process 1 preempts Process 2Process 1 tries to acquire lock for resource
Outras Características Desempenho
• Tempo de reposta Pooled Loop
TR= S + F + PS=sinalização do hardware (ns)F=verificação do flag (s)P=processamento (ms)
InterrupçãoTR = L + C + S + PL=tempo de interrupçãoC=tempo de troca de contextoS=tempo de escalonamentoP=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óriaPercentual de memória utilizada analisador lógico
ComunicaçãoTransferê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:
concorrência de processos (baseada em prioridade)TemporizaçãoSincronizaçãoExclusão mútua
Escalonamento: 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(500s 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 Time Computing, University of 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.
Copyright © 2001 Stephen A. Edwards All rights reserved
CSE 537s
TinyOS source code and programming
Most slides are modified from Berkeley TinyOS introduction
Xiaorui Wang
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
CommunicationActuating Sensing Communication
Application (User Components)
Main (includes Scheduler)
Hardware AbstractionsModified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
TinyOS component model
• Component has:– Frame (storage)– Tasks: computation– Interface:
• Command • Event
• Frame: static storage model - compile time memory allocation (efficiency)
• Command and events are function calls (efficiency)
Messaging Component
Internal StateInternal Tasks
Commands Events
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
How TinyOS works : SchedulingTwo-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
TOS_EVENT(name)(args) {...return status;}
Real implementation:#define TOS_COMMAND(command_name) TOS_CALL_COMMAND(command_name)#define TOS_EVENT(event_name) TOS_SIGNAL_EVENT(event_name)
TOS_TASK(name)(args) {...return status;}
{... TOS_POST_TASK(name)(args)}
FIFO Queue Fun. Pointer
{... status = TOS_SIGNAL_EVENT(name)(args)...}
Function call
TOS_COMMAND(name)(args) {...return status;}
{... status = TOS_CALL_COMMAND(name)(args)...}
Function Call
One byte message type used todirect packet to handlersReal implementation:if(msg.type == 0) val = Handler0(data);
if(msg.type == 1) val = Handler1(data);….….if(msg.type == 255) val = Handler255(data);
User need to redefine handler name #define Handler1 XXXX #define Handler5 NULL_FUNC
30 Byte Fix length PacketCRC check 16 bit CRC check, Drops packet if failsRedundancy transmit transmitted 3 times
How TinyOS works : Communication
Application Component
RFM
Radio byte
Messaging
bit
byte
packet Radio Packet
AM Dispatcher
Application
messaging
H1 H2 H3
Simplex transceiverWe can Set Operation Mode (TX/RX) Set Sampling Rate Receive one Bit Transmit one Bit Notify TX/RX is finished Shut down RFM (1/10th)
A simple profiling:
If we want to send 60 Byte data,
we need to invoke:
Messaging layer 1 times
Packet layer >2 times
byte layer > 60 times
RFM > 480 times
• Bit EncodingManchester encoding (1b 2b)DC balancing (4b 6b)SEC_DED forward error correction(8b 17b)• Error detection & correction SEC_DED Correct 1b Detect 2b• Signal strength
Each time a 1 bit is read in, the ADC samples the value of the BBOUT pin.
• CSMADetect whether current channel is free to transmit, otherwise waitfor random of clock ticks [12,75]
clock rate (10kHZ) LFSR
PackagingDividing/Combine
Routing Echo ; Base_station Relay;….Special address 0xff = Broadcast Address 0x7E = UART interface
Content-based routingConsensus algorithmLocation ServiceTrackingSensor data processing…………
Modified from Tian He et. Al., TinyOS source code and programming, U of Virginia
What is a typical TinyOS applicationA 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
Component interface (.comp)• Commands that it accepts(implemented)• Commands that it uses• Events that it signals• Events that it handles (implemented)
Component implementation (.c)• Functions that implement interface• Frame: internal state• Tasks: internal concurrency• Uses only internal namespace
Internal Tasks
Messaging Component
Internal State
Commands Events
A typical TinyOS component
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
Programming the Mote (3)
Relations Component dependence (.desc)
• Glue the components• Denote the dependence among component.• Mapping the interface between the component.
MAIN
COUNTER
CLOCK LEDS
An example: output the counter number to LEDs
Composing applications from components Simple counter program
main_sub_init
counter_init
CLOCK INT_TO_LEDS
MAIN
COUNTER
main_sub_start
counter_start
counter_sub_clock_init
clock_init
clock_event
clock_fire_event
counter_sub_output_init
int_to_leds_init
counter_output
int_to_leds_output
generic init interface
clock interface
output interface
.c file implementthe interface
.desc file describethe relationships
betweenthe component
Interfacesare defined
through.COMP File
Files for this simple applicationSeven 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.descinclude modules{
MAIN;COUNTER;INT_TO_LEDS;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_LEDS:INT_TO_LEDS_INIT
COUNTER:COUNTER_OUTPUT INT_TO_LEDS:INT_TO_LEDS_OUTPUT
apps/cnt_to_led.desc
MAIN
COUNTER
main_sub_init
counter_init
.comp component interface file
TOS_MODULE COUNTER;
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
To be implemented in .c file
Declare and access variable TOS_FRAME_BEGIN, TOS_FRAME_END to declare a component frame
example
VAR(foo) to access a variable (foo) in the frame
TOS_FRAME_BEGIN(COUNTER_frame) {
char state;
}TOS_FRAME_END(COUNTER_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_frameTOS_FRAME_BEGIN(COUNTER_frame) {
char state;
}TOS_FRAME_END(COUNTER_frame);
COUNTER.c
//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 - 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 RFMAll 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
CLOCK
MAIN
COUNTER
hardware.h
hardware.h
AM
PACKETOBJ
SEC_DED_RADIO_BYTE
RFM
INT_TO_RFM
Main.c sched.c
Counter.c Counter.comp
Clock.c Clock.comp
INT_TO_RFM.c INT_TO_RFM.comp
am.c am.comp
PACKETOBJ.c PACKETOBJ.comp
SEC_DED_RADIO_BYTE.c ...comp
RFM.c ...comp
Relationship description Cnt_to_rfm.desc
More complicated example: cnt_to_rfm
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
Message Storage
Component that originates message provides buffer TOS_Msg type provides header and trailer wrapper, so copies
are avoided Application data referenced as msg.data
TOS_FRAME_BEGIN(INT_TO_RFM_frame) {
char pending;
TOS_Msg msg;
}
TOS_FRAME_END(INT_TO_RFM_frame);
typedef struct{
char val;
} int_to_led_msg;
INT_TO_RFM.c
Inside MSG.h
struct MSG_VALS{
short addr;
char type;
unsigned char group;
char data[DATA_LENGTH];
short crc;
short strength;
short time;
short tone_time;
};
#define DATA_LENGTH 30
#define TOS_Msg struct MSG_VALS
data is a character pointer pointing to the beginning of the message's payload. The payload is currently standardized to be 30 bytes long
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; }}return 0;
}
msg buffer
access application msg buffer
cast to defined format
Set protection for the buffer
avoid re-entering to protect buffer, not to wait the radio
build msgrequest transmission
destination identifier
set handler identifier
Modified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
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
Generic_Com : Com_Send_Msg
AM_Standard : AM_Send_Msg
AM -> TOS_POST_TASK(AM_Send_Task)
AM : TOS_TASK(AM_Send_Task)
PacketObj : Packet_TX_Packet
AM : AM_Sub_TX_Packet
PacketObj : Packet_TX_Bytes
SEC_DED_Radio_Byte : Radio_Byte_TX_Bytes
SEC_DED_Radio_Byte : Radio_Sub_TX_BIT
RFM : RFM_TX_BITINT_TO_RFM : INT_TO_RFM_SUB_SEND_MSG
Scheduler
How sending message works?
AM
Application
Component 1
Pending
Data buffer
State
Buffer is provided by the application component.
The lower level will not copy the buffer. They just use pointer of the buffer.
System Scheduler
Lower level
Application
Component 2
Pending
Data buffer
State = 1State = 0
1
0
Completion Event
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.
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;
}
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?
How to send the message to LEDs display?
RFM_TO_LEDS:INT_READING is wired to GENERIC_COMM:GENERIC_COMM_MSG_HANDLER_4
RFM_TO_LEDS:RFM_TO_LEDS_LED_OUTPUT is wired to INT_TO_LEDS:INT_TO_LEDS_OUTPUT
The Active Message layer decodes the handler type and dispatches it.
All GENERIC_COMM handlers have the following interface that application handler for incoming messages:
TOS_MsgPtr GENERIC_COMM_HANDLER_X(TOS_MsgPtr data);
Same handler Number here.
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_EVENTSENS_OUTPUT:SENS_OUTPUT_SUB_CLOCK_INIT CLOCK:CLOCK_INIT
SENS_OUTPUT:SENS_OUTPUT_SUB_OUTPUT_INIT INT_TO_LEDS:INT_TO_LEDS_INITSENS_OUTPUT:SENS_OUTPUT_OUTPUT_COMPLETE INT_TO_LEDS:INT_TO_LEDS_DONESENS_OUTPUT:SENS_OUTPUT_OUTPUT INT_TO_LEDS:INT_TO_LEDS_OUTPUT
SENS_OUTPUT:SENS_DATA_INIT PHOTO:PHOTO_INITSENS_OUTPUT:SENS_GET_DATA PHOTO:PHOTO_GET_DATASENS_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);};
system/PHOTO.descModified from D. Culler et. Al., TinyOS boot camp presentation, Feb 2001
Event Driven Sensor Data
clock event handler initiates data collection sensor signals data ready event data event handler calls output command common pattern
char TOS_EVENT(SENSE_OUTPUT_CLOCK_EVENT)(){
return TOS_CALL_COMMAND(SENSE_GET_DATA)();
}
char TOS_EVENT(SENSE_DATA_READY)(int data){
TOS_CALL_COMMAND(SENS_OUTPUT_OUTPUT)((data >> 2) &0x7);
return 1;
}
SENS_OUTPUT.c
void display(char val)
{
if (val & 1) TOS_CALL_COMMAND(SENSE_LEDy_on)();
……......
}
SENSE_GET_DATA is wired to PHOTO_GET_DATA which is wired to ADC:ADC_GET_DATA. ADC_GET_DATA implement depends on platform
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 PCto 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
0
3
9
8
7
6
2
5
4
1
Injected routing beacon
Programming Environment
Platform: cygwin on top of Windows 2000 Software: perl, gcc, java, atmel tools ,cygwin
Program Code
Mote-PC communication
Mote-to-mote 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
CPU
ROM
RAM
ASIC
ASIC
RTOSa.out
Applicationsoftware
simulator
compilerapplicationsourcecode
debugger
USER
Embedded Microprocessor Evolution
19891989 19931993 19951995 19991999
> 500k transistors1 - 0.8 33 mHz
2+M transistors0.8 - 0.5
75 - 100 mHz
5+M transistors0.5 - 0.35
133 - 167 mHz
22+M transistors0.25 - 0.18
500 - 600 mHz
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 CrisisCheaper, more powerfulCheaper, more powerful
MicroprocessorsMicroprocessors
MoreMoreApplicationsApplications
IncreasingIncreasingTime-to-marketTime-to-market
pressurepressure
Bigger, More Complex Bigger, More Complex ApplicationsApplications
EmbeddedEmbeddedSoftwareSoftware
CrisisCrisis
J. Fiddler - WRS
J. Fiddler - WRS
SW: Embedded Software Tools
CPU
ROM
RAM
ASIC
ASIC
RTOSa.out
Applicationsoftware
simulator
compilerapplicationsourcecode
debugger
USER
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
CPU
ROM
RAM
ASIC
ASIC
RTOSa.out
Applicationsoftware
simulator
compilerapplicationsourcecode
debugger
USER
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
CPU
ROM
RAM
ASIC
ASIC
RTOSa.out
Applicationsoftware
simulator
compilerapplicationsourcecode
debugger
USER
Embedded Microprocessor Evolution
19891989 19931993 19951995 19991999
> 500k transistors1 - 0.8 33 mHz
2+M transistors0.8 - 0.5
75 - 100 mHz
5+M transistors0.5 - 0.35
133 - 167 mHz
22+M transistors0.25 - 0.18
500 - 600 mHz
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
CPU
ROM
RAM
ASIC
ASIC
RTOSa.out
Applicationsoftware
simulator
compilerapplicationsourcecode
debugger
USER
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
CPU
ROM
RAM
ASIC
ASIC
RTOSa.out
Applicationsoftware
simulator
compilerapplicationsourcecode
debugger
USER
Embedded Microprocessor Evolution
19891989 19931993 19951995 19991999
> 500k transistors1 - 0.8 33 mHz
2+M transistors0.8 - 0.5
75 - 100 mHz
5+M transistors0.5 - 0.35
133 - 167 mHz
22+M transistors0.25 - 0.18
500 - 600 mHz
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
CPU
ROM
RAM
ASIC
ASIC
RTOSa.out
Applicationsoftware
simulator
compilerapplicationsourcecode
debugger
USER
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
Multiprocessing supportGraphics Internet support
POSIX LibraryJava support File system
WindNet Networking
Core OS
Wind Microkernel
Real-Time Embedded Applications
VxWorks 5.4 Scalable Run-Time System
Supported Processors
PowerPC 68K, CPU 32 ColdFire MCORE 80x86 and Pentium i960 ARM and Strong ARM MIPS SH
SPARC NEC V8xx M32 R/D RAD6000 ST 20 TriCore
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
BSP
Device dependent codeHardware
independent code
Processor dependent
code
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
pSOS+ Kernel
Memory Management
POSIX LibraryBSPsI/O system
Loader Debug C/C++ File System
pSOS 2.5
Supported processors
PowerPC 68K ColdFire MIPS ARM and Strong
ARM X86 and Pentium i960 SH
M32/R m.core NEC v8xx ST20 SPARClite
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
Internal Kernel API
Kernel
pluggable schedulers, mem alloc, synchronization, timers, interrupts,
threads
HAL
Dev
ice
D
rive
rs
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, multi-
level 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
VxWorks pSOS eCosTask Y Y Only Thread
Scheduler Preemptive, static Preemptive PreemptiveSynchronization mechanism No condition variable Y Y
POSIX support Y Y Linux
Scalable Y Y Y
Custom hw support BSP BSP HAL, I/Opackage
Kernel size - 16KB -
Multiprocessor support VxMP/ VxFusion(accessories)
PSOS+mkernel
None
Recall the ``Board Support Package’’
BSP = Initializing code for hardware device + device driver for peripherals
BSP Developer’s Kit
BSP
Device dependent codeHardware
independent code
Processor dependent
code
Introduction to Device Drivers
What are device drivers?• Make the attached device work.• Insulate the complexities involved in I/O handling.
Application
Device driver
Hardware
RTOS
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