PowerPoint Presentation

Similar documents
Here is a "PLDWorld.com"... // EXCALIBUR... // Additional Resources // µc/os-ii... Page 1 of 23 Additional Resources: µc/os-ii Author: Source: HiTEL D

untitled

Microsoft PowerPoint - ARM9_uCOS-II_2004_10_14_for_print1.ppt

ESP1ºÎ-04

6주차.key

Microsoft PowerPoint - ARM 개발 환경.ppt

DE1-SoC Board

강의10

라는 점이다. ARM7TDMI 같은 ARM7에서는 페치(fetch), 디코드 (decode) 그리고 실행(execute)의 3단계로 구성된 파이프라인을 적 V4 PF1 ARMv I-캐시 액세 + 다이내믹

ARM 프로세서 입문

ARM01

MAX+plus II Getting Started - 무작정따라하기

Microsoft PowerPoint - 05-ARM-Instruction-Set.ppt

Microsoft PowerPoint - LN_1_ARM_CPU_0.ppt [호환 모드]

슬라이드 1

T100MD+

Microsoft Word - 1. ARM Assembly 실습_xp2.doc

10주차.key

SRC PLUS 제어기 MANUAL

PCServerMgmt7

APOGEE Insight_KR_Base_3P11

ARM Reverse Engineering

CD-RW_Advanced.PDF

hwp

Copyright 2012, Oracle and/or its affiliates. All rights reserved.,.,,,,,,,,,,,,.,...,. U.S. GOVERNMENT END USERS. Oracle programs, including any oper

Chap06(Interprocess Communication).PDF

<4D F736F F F696E74202D20BBB7BBB7C7D15F FBEDFB0A3B1B3C0B05FC1A638C0CFC2F72E BC8A3C8AF20B8F0B5E55D>

Remote UI Guide

<4D F736F F F696E74202D20322DBDC7BDC3B0A320BFEEBFB5C3BCC1A6>

hlogin2

untitled

Mango220 Android How to compile and Transfer image to Target

PowerChute Personal Edition v3.1.0 에이전트 사용 설명서

인켈(국문)pdf.pdf

2. GCC Assembler와 AVR Assembler의차이 A. GCC Assembler 를사용하는경우 i. Assembly Language Program은.S Extension 을갖는다. ii. C Language Program은.c Extension 을갖는다.

1217 WebTrafMon II

(Asynchronous Mode) ( 1, 5~8, 1~2) & (Parity) 1 ; * S erial Port (BIOS INT 14H) - 1 -

Microsoft PowerPoint - Introduction.pptx

untitled

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

PRO1_04E [읽기 전용]

INTRO Basic architecture of modern computers Basic and most used assembly instructions on x86 Installing an assembly compiler and RE tools Practice co

Microsoft PowerPoint - o8.pptx

임베디드 시스템 구조


API 매뉴얼

Microsoft PowerPoint APUE(Intro).ppt

KEY 디바이스 드라이버

슬라이드 제목 없음

Microsoft PowerPoint - 15-SMT_cho.ppt

CPX-E-SYS_BES_C_ _ k1

Something that can be seen, touched or otherwise sensed

CANTUS Evaluation Board Ap. Note

PRO1_09E [읽기 전용]

MPLAB C18 C

Deok9_PE Structure

FMX M JPG 15MB 320x240 30fps, 160Kbps 11MB View operation,, seek seek Random Access Average Read Sequential Read 12 FMX () 2

PowerPoint 프레젠테이션

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for

목차 1. 제품 소개 특징 개요 Function table 기능 소개 Copy Compare Copy & Compare Erase

목차 BUG offline replicator 에서유효하지않은로그를읽을경우비정상종료할수있다... 3 BUG 각 partition 이서로다른 tablespace 를가지고, column type 이 CLOB 이며, 해당 table 을 truncate

초보자를 위한 C++


ORANGE FOR ORACLE V4.0 INSTALLATION GUIDE (Online Upgrade) ORANGE CONFIGURATION ADMIN O

PowerPoint 프레젠테이션

Microsoft PowerPoint - ch07.ppt

Microsoft Word - FunctionCall

<31325FB1E8B0E6BCBA2E687770>

Microsoft PowerPoint - 30.ppt [호환 모드]

임베디드시스템설계강의자료 6 system call 1/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과

Deok9_Exploit Technique

Embedded System

Microsoft PowerPoint - polling.pptx

K7VT2_QIG_v3


휠세미나3 ver0.4

solution map_....

untitled

임베디드시스템설계강의자료 6 system call 2/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과

Sena Technologies, Inc. HelloDevice Super 1.1.0

untitled

기술 이력서 2.0

歯15-ROMPLD.PDF

<4D F736F F F696E74202D C61645FB3EDB8AEC7D5BCBA20B9D720C5F8BBE7BFEBB9FD2E BC8A3C8AF20B8F0B5E55D>

The Self-Managing Database : Automatic Health Monitoring and Alerting


KDTÁ¾ÇÕ-1-07/03

No Slide Title

R50_51_kor_ch1

GNU/Linux 1, GNU/Linux MS-DOS LOADLIN DOS-MBR LILO DOS-MBR LILO... 6

H3050(aap)

슬라이드 1

Solaris Express Developer Edition

PRO1_16E [읽기 전용]

BSC Discussion 1

Microsoft Word - ExecutionStack

Microsoft PowerPoint - ch03ysk2012.ppt [호환 모드]

김기남_ATDC2016_160620_[키노트].key

MS-SQL SERVER 대비 기능

Transcription:

ARM & ucos Ajou University Chang-yeon, Cho. <iprinceps@gmail.com> Copyright c 2006 by iprinceps No parts of this document may be reproduced in any form, in an electronic e retrieval system or otherwise, without the prior written permission of the publisher. 1

ARM Architecture 2

ARM Architecture About Company 1985. Acorn Computer Group develops the world s first commercial RISC processor 1990. 12 ARM pins out of Acorn and Apple 1991. the first embeddable RISC core ARM6 1993. TI, Cirrus, Samsung license ARM, ARM7 core 1995. Thumb architecture, StrongARM 1996. ARM9TDMI family announced 1998. ARM10 family announced 2002. ARM11 The industry's leading provider of 32-bit embedded RISC microprocessors with almost 75% of the market 3

ARM Architecture About ARM MPU ARM (Advanced RISC Machine) Architecture It s RISC (Reduced Instruction Set Computer) Large uniform register file Load/store architecture Simple addressing mode Uniform and fixed-length instruction field In addition, Shift + ALU data processing Auto increment/decrement addressing Load and store multiple Conditional execution Characteristic Small die size Low power Thumb instruction High code density High Performance, Lower Cost, Less Power 4

ARM Architecture Progression V6 V5TEJ ARM7TDMI ARM926EJ ARM1020E ARM9E SecureCore ARM920T StrongARM V5TE V4T V4 T: Thumb extension D: Debug extension M: Hardware multiplier I: Embedded ICE extension E: DSP Enhanced J: Java extension V6: Media extension ARM7 5

ARM Architecture Embedded Products 6

ARM Architecture ARM7 ALE A[31:0] ABE ALU Bus Address Register Add Inc Register Bank(31x32 + 6 CPSR/SPSR) A Bus 32x8 MPY Barrel Shifter 32-bit ALU Write Data Register Increment Bus B Bus Scan Control Instruction Decoder & Control Logic Read Data Register/IR & Decoder DBGRQI BREAKPTI DBGACK ECLK nexec ISYNC BL[3:0] APE MCLK nwait MAS[1:0] nirq nfiq nreset ABORT ntrans nmreq nopc SEQ LOCK ncpi CPA CPB nm[4:0] TBE TBIT HIGHZ nenout DBE nenin D[31:0] 7

ARM Architecture Pipeline ARM7 Pipeline (3 stage) FETCH DECODE EXECUTE FETCH DECODE EXECUTE FETCH DECODE EXECUTE Fetch : instruction 을읽어옴 Decode : 읽어온 instruction 을분석 Execution : 분석한 instruction 을실행 8

ARM Architecture Pipeline ARM9 Pipeline (5 stage) Fetch : instruction 을읽어옴 Decode : 읽어온 instruction을분석 Execution : 분석한 instruction 을실행 Memory : 메모리영역을억세스 Write : 처리결과를레지스터에저장 9

ARM Architecture ARM Core Comparison Cache (I/D) MMU AHB Bus Thumb DSP Jazelle Clock ARM7TDMI x x o o x x 133 ARM720T 8K Unified o o o x x 100 ARM920 16K/16K o o o x x 250 ARM940 4K/4K MPU o o x x 180 ARM926EJ Various o Dual o o o 220-250 ARM1020E 32K/32K o Dual o o x 325 ARM1020EJ Various MMU+ MPU Dual o o o 266-325 StrongARM 16K/16K o NA x x x 206 Xscale 32K/32K o NA o o x 400 10

ARM Programmer s s Model 11

ARM Programmer s s Model Data Types Supported Data Types Byte 8 bits Halfword 16 bits (aligned to 2-byte boundaries) Word 32 bits (aligned to 4-byte boundaries) Notes Unsigned: 0 ~ 2 N 1 Signed: -2 N-1 ~ +2 N-1 1 All data operations are performed on word quantities Load/Store transfer B, HW, W with zero-extending and sign-extending ARM instruction are exactly 1 word Thumb instruction are exactly 1 halfword 12

ARM Programmer s s Model Processor Modes Mode Description ID Comments User Normal program execution mode usr restriction System Privileged mode for operating system sys OS task FIQ When a fast interrupt fiq High-speed ch. IRQ When a normal interrupt irq Supervisor Exception mode for operating system svc SWI Abort When data or instruction prefetch abort abt Vir. Mem, MPro Undef When an undefined instruction und HW Emulation User and System mode share one bank of registers Exception mode: their own registers FIQ mode has private R8 ~ R14 the other modes have private R13 ~ R14 13

ARM Programmer s s Model ARM Registers User & System FIQ IRQ R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13 R14 R0 R1 R2 R3 R4 R5 R6 R7 R8_fiq R9_fiq R10_fiq R11_fiq R12_fiq R13_fiq R14_fiq R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13_irq R14_irq Supervisor Abort Undef R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13_svc R14_svc R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13_abt R14_abt R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13_und R14_und PC(R15) PC(R15) Program Counter PC(R15) PC(R15) PC(R15) PC(R15) Program Status Register CPSR CPSR CPSR CPSR CPSR SPSR_fiq SPSR_irq SPSR_svc SPSR_abt CPSR SPSR_fiq 14

ARM Programmer s s Model ARM Registers User & System FIQ IRQ R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13 R14 Program Counter PC(R15) R8_fiq R9_fiq R10_fiq R11_fiq R12_fiq R13_fiq R14_fiq Supervisor Abort Undef Totally 37 Registers = 31 GPR + 1 PC + 6 PSRs R13_irq R14_irq R13_svc R14_svc R13_abt R14_abt R13_und R14_und Program Status Register CPSR SPSR_fiq SPSR_irq SPSR_svc SPSR_abt SPSR_und 15

ARM Programmer s s Model ARM Registers Unbanked Registers: R0 ~ R7 Same to all modes Banked Registers: R8 ~ R14 R8 ~ R12 If simple interrupts -> FIQ can be very fast using only R8 ~ R14 R13 ~ R14 R13 Usually used for Stack Pointer (SP) R14 Usually used for Link Register (LR) When subroutine call (BL, BLX), receives PC value When exception, set to exception return address R15: Program Counter The value is the address of the instruction + 8 or 12 16

ARM Programmer s s Model ARM Registers Program Status Register (PSR) 31 30 29 28 27 8 7 6 5 4 0 N Z C V Reserved I F T M Flag field Status field Extension field Control field N Z C V I F T Condition Code Flags Negative result from ALU Zero result from ALU ALU operation caused Carry ALU operation overflowed Control bits 1: disables IRQ 1: disables FIQ 1: Thumb, 0: ARM Mode bits M[4:0] Mode 0b10000 User 0b11111 System 0b10001 FIQ 0b10010 IRQ 0b10011 Supervisor 0b10111 Abort 0b11011 Undefined CPSR (Current PSR): Hold the current status information SPSR (Saved PSR): Reserve the CPSR during exceptions 17

ARM Programmer s s Model ARM Registers 31 30 29 28 27 8 7 6 5 4 0 N Z C V Reserved I F T M Flag field Status field Extension field Control field N (Negative/Less Than Flag) 연산결과가음수 1, 양수 0 Z (Zero Flag) 연산결과가 0 1, 0 이아니면 0 C (Carry/Borrow/Extend Flag) 자리올림이나내림이발생한경우, Shift 연산등에서사용 Carry 가발생할경우 C = 1 Borrow 가발생할경우 C = 0 V (Overflow Flag) 연산의결과 ( 덧셈, 뺄셈 ) 가오버플로우되었을경우 1 Status flags are updated only if a data processing instruction has the S bit set (ex. SUBS) 18

ARM Programmer s s Model Exceptions Exception Type Priority Mode Vector High Vector Reset 1 Supervisor 0x00000000 0xFFFF0000 Undefined Instruction 6 Undefined 0x00000004 0xFFFF0004 SWI 6 Supervisor 0x00000008 0xFFFF0008 Prefetch Abort 5 Abort 0x0000000C 0xFFFF000C Data Abort 2 Abort 0x00000010 0xFFFF0010 Reserved 0x00000014 0xFFFF0014 IRQ 4 IRQ 0x00000018 0xFFFF0018 FIQ 3 FIQ 0x0000001C 0xFFFF001C When an exception occurs R14_<mode> = return address SPSR_<mode> = CPSR CPSR[4:0] = exception mode number CPSR[5] = 0 // in ARM state If <mode> == reset or FIQ CPSR[6] = 1 // disable FIQ CPSR[7] = 1 // disable IRQ PC = vector address 19 To return from exception CPSR = SPSR_<mode> PC = R14_<mode> By MOVS SUBS PC, XX or LDM with Restore CPSR

ARM Programmer s s Model Vectors Exception handlers are entered via hardware vectors Located in the bottom 8 words of memory 0x00 0x04 0x08 0x0c 0x10 0x14 0x18 0x1c Branch to Handler Branch to Handler Branch to Handler Branch to Handler Branch to Handler Branch to Handler Branch to Handler FIQ Handler Reset Undefined Instruction Software Interrupt Prefetch Memory Abort Data Memory Abort Reserved Normal Interrupt Fast Interrupt Interrupt Handler Most vectors contain a branch instruction to jump to their handler The FIQ handler is in-line for maximum speed 20

ARM Programmer s s Model - Endian Big Endian Processor : (Motorola, SPARC) High-order-byte-first, human-friendly type Little Endian Processor: ( DEX VAX, Intel X86) Low-order-byte-first, computer-friendly type RISC Microprocessors support Dual-Endian since its simple instruction and operand type. Store 4Bytes Word to Memory at N N N+1 N+2 N+3 B0 B1 B2 B3 MSB B3 B2 B1 LSB B0 B3 B2 B1 B0 N N+1 N+2 N+3 Little Endian Big Endian 21

Basic Startup Code 22

Startup Code Exception Handler Entry Exception Handler Entry 23

Startup Code Initialization Code Initializing any critical devices Disable Watch-dog Timer first. Disable Interrupt, or may cause spurious interrupt when enabled. Initializing the memory system Before Interrupts are enabled Before any code is called that access the RAM (e.g. Stack) ResetHandler ldr r0,=btcon ; Disable Watch-Dog Timer ldr r1,=0xa507 strh r1,[r0] ldr r0,=intmask ; All interrupt disable ldr r1,=0x0 str r1,[r0] LDR r4, =FMACON ; 2 clk, CPU holding LDR r3, =0x82 STRB r3, [r4] ldr r0,=smrdata ldmia r0,{r1-r3} ldr r0,=memcon0 ; BWSCON Address stmia r0,{r1-r3} 24

Startup Code Initialization Code Initializing the stack pointers sp_svc always be initialized. sp_irq, sp_fiq Must be initialized if it s used. sp_abt, sp_und Must be initialized if it s used. Not used in simple system. Initialized for debugging purposes. sp_usr Set up stack pointer when change to user mode to start Apps. InitStacks mrs r0,cpsr bic r0,r0,#modemask orr r1,r0,#undefmode NOINT msr cpsr_cxsf,r1 ldr sp,=undefstack orr r1,r0,#abortmode NOINT msr cpsr_cxsf,r1 ldr sp,=abortstack orr r1,r0,#irqmode NOINT msr cpsr_cxsf,r1 ldr sp,=irqstack orr r1,r0,#fiqmode NOINT msr cpsr_cxsf,r1 ldr sp,=fiqstack bic r0,r0,#modemask NOINT orr r1,r0,#svcmode msr cpsr_cxsf,r1 ldr sp,=svcstack ; NOINT 0xc0 ; UndefMode ; AbortMode ; IRQMode ; FIQMode ; SVCMode ; USER mode is not initialized. mov pc,lr ^ 0x80A000 UserStack # _SVC_STKSIZE SVCStack # _UND_STKSIZE UndefStack # _ABT_STKSIZE AbortStack # _IRQ_STKSIZE IRQStack # _FIQ_STKSIZE FIQStack # 0 25

Startup Code Initializing C environment C environment.code section (RO) : Code and constant data..data section (RW) : Read and writable data..bss section (ZI) : Zero-out data. #include <stdio.h> Zero-out this area. Copy Initialized RW Data..bss section (ZI section).data section (RW secion) SDRAM int a; int b = 1234; int c = 0; int main() { printf(" a = %d\n", a); printf(" b = %d\n", b); printf(" c = %d\n", c); } Load Image. Initialized RW Data.code section Flash ROM a = 0 b = 1234 c = 0 0x0000_0000 26

Startup Code Initializing C environment Section-related symbols Image$${Section}$${Base/Limit} {Section} : RO, RW, ZI {Base/Limit} : Base or limit pointer.bss section (ZI section).data section (RW secion) Initialized RW Data.code section Image$$ZI$$Limit Image$$ZI$$Base Image$$RW$$Limit Image$$RW$$Base Image$$RO$$Limit Image$$RO$$Base 0 1 2 IMPORT Image$$RO$$Limit IMPORT Image$$RW$$Base IMPORT Image$$ZI$$Base IMPORT Image$$ZI$$Limit IMPORT Main ; End of ROM code (=start of ROM data) ; Base of RAM to initialize ; Base and limit of area ; to zero initialize LDR r0, = Image$$RO$$Limit ; Get pointer to ROM data LDR r1, = Image$$RW$$Base ; and RAM copy LDR r3, = Image$$ZI$$Base ; Zero init base => top of initialised data CMP r0, r1 ; Check that they are different BEQ %F1 CMP r1, r3 ; Copy init data LDRCC r2, [r0], #4 STRCC r2, [r1], #4 BCC %B0 LDR r1, = Image$$ZI$$Limit ; Top of zero init segment MOV r2, #0 CMP r3, r1 ; Zero init STRCC r2, [r3], #4 BCC %B2 27

Startup Code Initializing C environment Need not initializing the C environment.bss section (ZI section).data section (RW secion).code section Image$$ZI$$Limit Image$$ZI$$Base Image$$RW$$Limit Image$$RW$$Base Image$$RO$$Limit Image$$RO$$Base Boot Code copy the application Image from Flash ROM. Application Image Boot Code 28

OS 29

OS OS 란? Operating System 의약자 사전적의미 : 효율적조작을목적으로하는제어프로그램 일반응용프로그램들이각자의작업을수행하기위해시스템자원을요구할때서로간의충돌없이효율적으로사용할수있도록자원을관리하고프로그램들의작업명령을받아서처리하는시스템소프트웨어 Ex) DOS, Windows 98/NT, Mac OS, UNIX, Linux, OS/2 30

OS RTOS 란? Real-Time Operating System 의약자 Real-Time Concepts 상대적인관점임 (vs. 일반적인 OS 처리 ) 극히짧은시간내에제공되어야하는서비스는 DSP나 ASIC 등으로특화되어 H/W Real-Time으로분류 일반적의미 : 주어진제약시간안에할당된일을처리할수있는 S/W Real-Time 을의미 Cf) Hard real-time, Soft real-time RT Systems : 제어시스템에서, 요구하는시간내에결과를출력하는시스템 31

OS RTOS 의구조 Application (Task) Application (Task) S/W OS Memory Management Comm. Management Task Management Time Management Scheduler Kernel Device Driver H/W 32

OS RTOS 의적용분야 RTOS는여러시스템에적용되나특히임베디드시스템에많이사용됨 일반 OS 시스템설계보다디자인이더어려움 시간제약이있는시스템에사용 영상, 의료, 음향기계등의시간의존적시스템 흐름제어, 엔진제어, 로봇등의자동화시스템 복합기능의가전기기등 네트워크접속, 고성능전화설비등통신시스템 33

OS 프로그래밍방식분류 순차적단순프로그래밍 간단한제어시스템에유리 Ex) Foreground/Background 방식 OS 를기반으로한프로그래밍 일반적으로큰프로그램에유리 프로그램의모듈화가용이함 Scheduler 를이용한 Multi-Task 가가능함 메모리 /IO 등의자원관리가쉬움 OS 에필요한 overhead( 메모리, CPU 등 ) 존재 Ex) Dos, WinCE, psos, VxWorks, Embedded Linux, Nucleus, Xinu, IOS, uc/os, ecos 등 34

OS Fourground/Background Background : Function 을이용하여원하는기능을불러프로그램을무한수행하는것 Foreground : 인터럽트에의해 ISR(Interrupt Service Routine) 을수행하는것 35

OS OS Based Programming 일반 Embedded OS 기반 PC와같이시간적으로처리지연이발생해도문제가없으며, 다양한 App. S/W가지원되는경우유리 WinCE : 친숙한개발환경, License, Guarantee Embedded Linux : Free, 개발환경구축필요 Real-Time OS 기반 정확한처리시간이필요한임베디드시스템에적합 VxWorks : License, Guarantee RTLinux : 일반리눅스커널의 Scheduler를변경 In-house RTOS ( 자체개발한 OS) : RTOS 시장의 50% 이상으로유료 or 무료 36

OS OS 의기본개념 Task, Resource, Event Critical Section, Mutual Exclusion, Deadlock Multi-Tasking, Context Switching Kernel, Scheduler Non-Preemptive, Preemptive Priority, CPU Utilization Synchronization Inter-task Communication Reentrancy Interrupts, Clock Tick 37

OS Task, Resource, Event Task = Thread 하나의간단한프로그램으로 CPU를사용하는작업 각각의우선순위, 스택영역을가짐 Resource 태스크가사용하는 Entity( 프로세서, I/O, 메모리등 ) Shared Resource 여러 Task에의해공용되는자원 Event Task에게작업을시작하도록지시할수있는상황 신호나메시지를주고받음 38

OS Critical Section, Mutual Exclusion Critical Section 여러 Task 들이공유자원에접근하는코드부분 Mutual Exclusion 오류방지를위해배타적으로공유자원을사용함 방법 : Test & Set, Scheduler 정지, Semaphore 등 Deadlock 공유자원문제로 Task들이서로끝없이기다리게되는상태를말함 주로대규모 Multi-Task Kernel에서일어남 해결책 : 사전자원점유, 자원해제순위, Semaphore 등의사용 39

OS Multi-Tasking Scheduling을통하여 Task를전환하여여러작업들이동시에수행되는것처럼보이게하는것 모듈구조의 Application을제공 실시간 Application에서의복잡성을줄여줌 CPU의활용도를극대화 한순간에한개의 Task 만이수행될수있으므로다른 Task는대기준비모드 40

OS Context Switching Multi-task가가능하도록 Task를바꾸기위한교환과정 다른 Task를수행하기위해현재수행중인 Task의 Context를스택에저장 새로운태스크의 Context를불러들임 실제작업을위한시간이아니므로 Overhead * Context : CPU Register, Stack 등의자원 41

OS Kernel OS 핵심기능의집합체 Task 간의 Communication, Task 관리를위한 Multi-tasking 시스템관리자 Context Switching 과같은기본적인서비스를제공 CPU 사용률향상을위해필수적으로필요한세마포어, 메일박스, 메시지큐, Time Delay등의통신방식제공 선점, 비선점커널 42

OS Scheduler 다음수행할작업을결정하는커널의한부분 대부분의실시간커널은우선순위에기반 배타적우선순위방식 동일우선순위허용방식 Kernel이어떠한 Scheduling 방식을채택했는가에따라분류 Non-Preemptive Kernel Preemptive Kernel Ex) Time Slice, Round-Robin, FIFO, EDF... 43

OS Non-Preemptive Kernel 현재진행중인프로세스가 CPU 사용을포기하기전까지는다른프로세스가진입할수없는구조 장점 : 짧은 Interrupt Latency 단점 : 나쁜 Task-Level Response 44

OS Preemptive Kernel 높은우선순위의 Task가언제라도 CPU의제어권을넘겨받을수있도록대기 거의모든 Real-time 시스템의체제가선점커널을사용 장점 : Deterministic 단점 : 자원관리에복잡한알고리즘이필요 45

OS Priority Task 처리의우선순위를뜻함 Static Priorities : 컴파일시에결정되어프로그램수행중에바꿀수없는우선순위방식 Dynamic Priorities : 프로그램수행중에우선순위가바뀔수있음 Priority Inversion Problem : Real-Time Kernel 에서많이발생되는문제 우선순위역전 TASK1(H) (4) (12) TASK2(M) TASK3(L) (1) (6) (8) (10) Task 3 Gets Semaphore (2) (3) Task 1 Preempts Task 3 (5) Task 1 tries to get semaphore (7) Task 2 Preempts Task 3 (9) Task 3 Resumes (11) Task 3 Releases the Semaphore 46

OS CPU Utilization 일반적으로높은우선순위의작업이작업실행횟수가더많음 47

OS Reentrancy 코드의재진입가능여부를나타냄 1 개이상의 Task 가동작할때공유자원을오류없이사용할수있는함수 48

OS Synchronization Synchronization : Event 발생을생성하거나기다리게하여작업의시작을맞추거나알려주는것 Semaphore등으로신호를전달할수있음 49

OS Event Flags 여러 Event 가발생하였을때 Task 의동기화를위한장치 Disjunctive Sync. : Task 가어떠한 Event 에도반응하여동기화되는것 Conjunctive Sync. : 모든 Event가다발생해야지동기화되는것 50

OS Inter-Task Communication = IPC(Inter Process Communication) Task 혹은 ISR이다른 Task 들과정보교환을목적으로통신하는것 보통전역데이터나메시지전달방식을사용 전역변수사용시접근의배타성확보필요 통신방법 Semaphore, Mutual Exclusion (MUTEX) Mailbox, Message Queue Event Flags 51

OS Interrupts 하드웨어메커니즘 불특정한시간에발생하는 Event에대해 ISR을만들어이를처리할수있게 CPU 할당을해주는서비스 실시간시스템에서는가능한한 Interrupt Disable Time이적도록해야함 Interrupt Nesting Interrupt Latency, Response, Recovery NMI(Non-maskable Interrupts) 52

OS Clock Ticks OS 의모든일은 Tick 단위로처리됨 주기적인특별한인터럽트로시스템의심장 간격은 10~200ms사이 주기가짧을수록시스템에부하를많이줌 53

uc/os /OS-II 54

ucos uc/os 란? Jean J. Labrosse 의저서인 The Real-Time Kernel 에속한부록 Code가몇개의파일로되어있는가장간단한구조의 RTOS임 도서와같이제공되어 RTOS의학습에적합 최근 License를부여하고있으나학습용에는필요없음 55

ucos ucos 의특징 코드의대부분이이식이가능한 C 로구성 임베디드시스템을위해 OS 의 ROM 화가능 옵션설정으로메모리 (ROM, RAM 등 ) 의크기조정가능 선점형실시간커널로서동작하므로높은우선순위태스크의응답시간이빠름 64개까지의 Multitasking 가능 (8개는시스템이사용 ) 기능이나서비스의실행시간예측가능 Task의 Stack 크기를각기다르게설정가능 Stack 체크기능이있음 IPC(Event Flag, Mailbox, Message Queue, Semaphore, Mutex) 제공 Fixed-sized memory partition Time-related function 255레벨의 Nesting Interrupts 가능 파일시스템, Network에대한기본적인지원이되지않음 3 rd Party지원 or 유료구현가능 56

ucos ucos-ii 의개요 Kernel Structure Task, 스케줄링, 인터럽트, 시스템초기화등 Task Management Task 의생성, 우선순위변경등 Time Management Task 의 Tick 카운터관리등 Intertask Communication ISR, 공유자원간의내부적통신 (IPC) 등 Memory Management 동적메모리할당, 고정메모리블록등 Porting 57

ucos Kernel Structure Critical Section Tasks, Task State, Task Control Block Ready List Task Scheduling Locking and Unlocking the Scheduler Interrupt under uc/os-ii Idle Task, Statistics Task, Clock Tick uc/os-ii Initialization Starting uc/os-ii 58

ucos Kernel Structure Critical Section uc/os-Ⅱ에서는코드의 critical sections에접근할때 disable/enable inter rupts 방법을사용하여보호 disable/enable interrupt를위해 2개의 macros 지원 OS_ENTER_CRITICAL( ) OS_EXIT_CRITICAL( ) 상기의 Macro는 processor specific하므로 OS_CPU.H 에서포팅필요 59

ucos Kernel Structure Critical Section:examples x86 에서의인터럽트 Enable/Disable 의예 Method 1 #define OS_ENTER_CRITICAL( ) asm #define OS_EXIT_CRITICAL( ) asm a total of 4 cycles Method 2 #define OS_ENTER_CRITICAL( ) asm #define OS_EXIT_CRITICAL( ) asm OS_ENTER_CRITICAL : 12 clock cycles OS_EXIT_CRITICAL : 8 clock cycles CLI STI PUSHF;CLI POPF 60

ucos Kernel Structure Task States (1) OSTaskDel() WAITING DORMANT OSTaskDel() OSTaskCreate() OSTaskCreateExt() OSMBoxPost() OSQPost() OSPostFront() OSSemPost() OSTaskRusume() OSTaskDlyResume() OSTimeTick() READY Preempted OSMBoxPend() OSQPend() OSSemPend() OSTaskSuspend() OSTimeDly() OSTimeDlyHMSM() OSStart() OSIntExit() OS_TASK_SW() RUNNING ISR Interrupt OSIntExit() 61

ucos Kernel Structure Task States (2) DORMANT Task가 ROM 또는 RAM에있지만 OS에등록이되지않은상태 스스로 or 다른 Task에의해 Delete된상태 READY 수행되어야할 Task들이등록된상태 언제라도수행될준비가되어있는상태 mulitasking은 OSStart() 에의해시작 OSStart() 에의해높은우선순위 Task가실행되기위해스케쥴링 RUNNING 하나의 task 만이 RUN 상태 WAITING Task가 delay되면 WAITING 상태 Timer가 expire 될수도있고, Ready 상태로갈수도있다. ISR RUNNING 상태의 Task는인터럽트가능 62

ucos Kernel Structure Task State : After OSInit() OSTCBPrioTbl[] [0] [1] [2] [3] 0 0 0 0 0 0....... 0 0 0 [61] 0 OSTCBList OS_TCB OSTCBStkptr OSRCBStkBottom OSTCBNext OSTCBPrev [62] * [63] * OS_TaskStat() 0 Task Stack 63 Task Stack OS_TCB OSTCBStkptr OSRCBStkBottom OSTCBNext OSTCBPrev OS_TaskIdle() 0

ucos Kernel Structure OS_TCB Free List OS_MAX_TASKS OS_TCB OS_TCB OS_TCB OSTCBFreeList 0 64

ucos Kernel Structure Ready List (1) 각 Task 는실행되기위에 OSRdyGrp and OSRdyTbl[] 에등록됨 OSRdyTbl[] Table of tasks which are ready to run. INT8U OSRdyTbl[OS_LOWEST_PRIO/8 + 1] OSRdyGrp Each bit represents a group INT8U OSRdyGrp 그룹당 8개의 task를가지고있고, OSRdyTbl[ ] 의각 bit들은 task들에대응 Ex. ) Bit i in OSRdyGrp is 1 when any bit in SRdyTbl[i] is 1. 65

ucos Kernel Structure Ready List (2) 66

ucos Kernel Structure Scheduling uc/os_ii 항상가장높은우선순위의 Task를실행 scheduler: 가장높은우선순위의Task를선정작업 OSSched(): Task-level scheduling OSIntExit(): ISR-level scheduling 67

ucos Kernel Structure Locking and Unlocking OSSchedLock() 이상의 scheduling 을방지함 호출된이후에는현재 Task 를 suspend 시킬수없음 Ex: OSMboxPend(), OSTimeDly() OSSchedLock() 과 OSSchedUnLock() 은항상 pair 로사용 OSLockNesting OSSchedLock() 이불린회수를표시 OSLockNesting = 0 이면 scheduling 이가능한상태임 68

ucos Kernel Structure Step of OSSched() Step1 : OSSched() 가 ISR (i.e.,osintnesting > 0) 이나 scheduling disable d (i.e., OSLockNesting > 0) 상태인지체크하여맞다면, OSSched() 빠져나감 OSIntNesting is incremented in OSIntEnter(). OSLockNesting is incremented when your application called OSSchedLock() at least once. Step2 : 아니면, Ready List 중가장높은우선순위의 Task 를실행준비함 Step3 : 가장높은우선순위 Task 가 RUN 상태인지체크 Step4 : 아니면, OS_TASK_SW() 를호출하여 context switching 시작 69

ucos Kernel Structure Idle Task μc/os-Ⅱ는항상하나의 Task는수행중이어야하므로실제일을하지않는 Task를하나수행함 OS_LOWEST_PRIO : 이 Idle Task의우선순위는가장낮음 OSIdleCtr : Idle Task가수행되면계속이값을증가시키고프로그램의 CPU 사용률측정에사용 void OSTaskIdle (void *pdata) { pdata = pdata; for (;;) { OS_ENTER_CRITICAL(); OSIdleCtr++; OS_EXIT_CRITICAL(); } } 70

ucos Kernel Structure Statistic Task OSTaskStat( ) OS_TASK_STAT_EN = 1 로설정하면사용가능 매초마다값을계산함 OSCPUUsage signed 8-bit integer 값으로실제값 프로그램에서사용한 CPU Time 을 % 로표시 OSIdleCtrMax : 지금까지중최대사용값표시 OSStatInit( ) 위의 statistic task 를사용하기위해서는이함수를초기에호출하여설정하여야함 OSCPUUsage (%) = 100(1 OSIdleCtr OSIdleCtrMax ) 71

ucos Kernel Structure Servicing an INT Interrupt Request TASK Vectoring Saving Context Notify kernel Task Response Interrupt disabled No New HPT Or OSLockNesting>0 User ISR code Interrupt Recovery TASK Return from interrupt Restore Context Notify kernel Interrupt Response ISR signals a task Task Response New HPT Interrupt Recovery Notify kernel Restore Context Return from interrupt TASK 72

ucos Kernel Structure OSIntEnter() OS 에게인터럽트에진입함을알려주기위하여 OSIntEnter() 함수를호출함 전역변수인 OSIntNesting 를증가하여 interrupt nesting 을표현 void OSIntEnter (void) { OS_ENTER_CRITICAL(); OSIntNesting++; OS_EXIT_CRITICAL(); } 73

ucos Kernel Structure OSIntExit() ISR 이끝나면 OSIntExit() 를호출하여 interrupt nesting counter 값을감소시킴 nesting counter = 0이면인터럽트가끝났으므로OS는 Highest Priority Task를실행시키기위해 scheduling을함 Highest Priority Task가실행준비가되면인터럽트에서실행할 Task로진입 74

ucos Kernel Structure OSIntCtxSw() Why not using OS_TASK_SW()? 인터럽트수행시이미 CPU register 등을저장하였으므로일의양을줄일수있음 OSIntCtxSw() 는단순히 processor의 stack pointer(sp) 만조정하면됨 75

ucos Kernel Structure Clock Tick 시스템의심장인 Clock Tick은특별한주기 Timer Interrupt로서사용 전형적으로 10 ~ 200ms를주기로사용함 (PC의경우 default tick rate = 18.20648Hz) A tick source: A hardware timer AC power line(50/60hz) signal Ticker interrupts 는 multitasking 이시작된이후에 Enable 해야함 (crash 방지 ) 76

ucos Kernel Structure Delayed Tick Tick Interrupt 20ms Tick ISR All Higher Priority Tasks Delayed Task 19ms 17ms 27ms 높은우선순위의 Task 나 ISR 을실행시키기위해 1Tick Delay 가필요할수있음 77

uc/os /OS-II 78

ucos Task Management 최대 64 개의 TASK 를관리 최상위, 최하위우선순위의 TASK 4 개씩 : 시스템용 각각의 Task 는 Return Type 과 Argument 를가지고있지만 Return 값을전달하지않음 void yourtask(void *pdata) { for(;;){ /* User Code */ Osxxxx(); /* User Code */ } } 무한반복형 Task void yourtask(void *pdata) { for(;;){ /* User Code */ OSTaskDel(OS_PRIO_SELF); } } 1 회수행형 Task 79

ucos Task Management Task Creation Task Deletion Change a Task s Priority Suspend and Resume a Task Obtain Information about a Task 80

ucos Task Management Task Creation TASK 들은 Multitasking 의시작전이나다른 TASK 에의해생성 스택도같이생성이되며, 스택영역은 C 컴파일의 malloc() 과같은기능의함수로동적할당가능 ISR(Interrupt Service Routine) 에서는 TASK를생성할수없음 Two functions for creating a task : OSTaskCreate() OSTaskCreateExt() 81

ucos Task Management Task Stacks Task 함수의외부에서정의되어야할자료 정적으로정의할경우 static OS_STK MyTaskStack[stack_size]; OS_STK MyTaskStack[stack_size]; 동적으로정의할경우 malloc() OS_STK *pstk* pstk; pstk = (OS_STK *)malloc(stack_size malloc(stack_size); if pstk!=(os_stk*)0){ /*Make sure malloc() has enough space*/ Create the task; } 82

ucos Task Management Task Stacks Stack grows From low to high memory. OS_STK_GROWTH is set to 0 in OS_CPU.H OS_STK TaskStack[TASK_STACK_SIZE]; OSTaskCreate(task, pdata,, &TaskStack[0], prio); From high to low memory. OS_STK_GROWTH is set to 1 in OS_CPU.H OS_STK TaskStack[TASK_STACK_SIZE]; OSTaskCreate(task, pdata,, &TaskStack[TASK_STACK_SIZE-1], prio); 83

ucos Task Management Functions OSTaskDel() - Deleting a Task Task를삭제할수있는함수 Task 스스로도호출가능 해당 Task는 DORMANT 상태로진입 OSTaskDelReq()- Requesting to Delete a Task 해당 Task 가스스로삭제되도록요청 현재수행중인 Task 가삭제되기를요청하면삭제될수있음 OSTaskChangePrio() Changing a Task s Priority Task 생성시에우선순위가결정되어있음 그러나이함수를사용하여변경가능 우선순위역전현상을해결가능 84

ucos Task Management Functions OSTaskSuspend() Suspending a Task Suspend 된 task 는 OSTaskResume() 에의해다시동작가능한상태로변경됨 스스로혹은다른 Task 를 Suspend 할수있음 주의사항 : event (e.g., a message, a semaphore) 를기다리고있는 Task 의경우에는신호전달에문제발생주의 OSTaskResume() Resuming a Task OSTaskResume() 을호출하면다시동작가능한상태로될수있음 OSTaskQuery() Getting Info. about a Task Tasks 그자체나다른 Task에대한기타정보를획득 (OS_CFG.H에정의한 Task 정보를바탕 ) 원하는 Task의 OS_TCB의정보를갖고있음 85

ucos Time Management Clock time을이용 시간과관련된함수를제공 OSTimeDly() OSTimeDlyHMSM() OSTimeDlyResume() OSTimeGet() OSTimeSet() 86

ucos Intertask Communication & Sync. 공유데이터를보호하고 TASK 간의통신을위한여러가지방법들 여러 TASK 들이사용하고있는데이터들이임의로변경되지않도록함 한 TASK가만들어낸정보를다른 TASK가이용하기위하여전달할수있는채널 synchronization과 coordination을구현하기위한방법 semaphore IPC를구현하는방법 mailbox, message queue 기타 : Mutex., Event Flags 87

ucos Intertask Communication & Sync. Semaphore Mailbox Message Queue Event Flags Mutex 88

ucos IPC & Sync - Semaphore Semaphore를사용하기전에이자원에대한생성이필요 Semaphore 사용법 (initial value 설정 ) shared resource n identical resources 5가지 semaphore service OSSemCreate() OSSemPend(), OSSemPost() OSSemAccept(), OSSemQuery() 89

ucos IPC & Sync Relationships (Tasks, ISRs) OSSemCreate() Task OSSemPost() N OR OSSempend() OSSemAccept() OSSemQuery() Task ISR OsSemPost() OSSemAccept() N 90

ucos IPC & Sync Message MailBox Task가독립적으로움직이지만이들사이의데이터교환을위한통로가필요 MailBox : Task간에직접 data(message) 를주고받는데에사용 하나의 message (mailbox is full) 만전달가능 구성 message를포함한데이터구조체를가리키는 Pointer 대기중인 TASK의리스트 단순히 post와 pend 여부만을검사하여 binary semaphore처럼도사용가능 91

ucos IPC & Sync Message MailBox Mailbox는 OS_MBOX_EN = 1로하여야사용가능 사용하기전에이자원에대한생성이필요 5가지의 Mailbox service OSMboxCreate() OSMboxPost() OSMboxPend() OSMboxAccept() OSMboxQuery() 기능과사용법은 Semaphore와동일 92

ucos IPC & Sync Relationships OSMboxCreate() Task ISR OSMboxPost() OSMboxPost() OSMboxAccept() ECB OSEventType *OSEventPtr OSEventTbl OSEventGrp Ⅱ Mailbox OSMboxPend() OSMboxAccept() OSMboxQuery() Message Task 93

ucos IPC & Sync Message Queue Message mailbox의 array와같음 OS_Q_EN = 1로하여야사용가능 사용되기전에생성되어야함 FIFO와 LIFO queue 모두사용가능 Resource의개수만큼 message 포함가능 Counting semaphore로사용가능 94

ucos IPC & Sync Message Queue Task OSQPost() OSQPostFront() OSQFlush() Message Queue Message* Message* Message* Message* Message* Message* Message* Task OSQPend() OSQAccept() OSQQuery() ISR OSQPost() OSQPostFront() OSQFlush() Size = N OSQCreate() ISR * OSQPend() OSQAccept() OSQQuery() 95

ARM Development Environment 96

ARM Development ARM Major Components Code Generation Tools ARM and Thumb ANSI C Compilers Embedded C++ Compilers Assemblers, Linker C and C++ runtime libraries CodeWarrior IDE Project manager Integrated build facilities Integrated editor GUI tool configuration Debuggers GUI (AXD) Command-line Debug Targets ARMulator, Instruction Set Simulator Angel debug monitor Multi-ICE JTAG ARM Firmware Suite Angel debug monitor MicroHAL ARM Applications Library Documentation Online hypertext based Hardcopy On-line help 97

ARM Development Development Environment Serial Port Cable Debug Host ICE Parallel Port Cable or USB/Ethernet Cable Target Board JTAG Cable 98

ARM Development About Code Warrior for the ADS Metrowerks CodeWarior IDE version 4.0 ARM-specific configuration panels that enable you to Configure the ARM development tools Project Manager *.c source armcc C Compiler *.o armlink Linker *.axf Image Code run *.s armasm Assembler *.o *.b armlib Librarian 99

ARM Development Software Development Process C 소스파일 어셈블리소스파일 컴파일러 어셈블러 라이브러리처리기 오브젝트파일 오브젝트파일 라이브러리 링커 형식변환기 실행파일 HEX 파일 매스크공정 에뮬레이터 시뮬레이터 다운로더 ROM Writer 시스템메모리 EPROM, 프로세서 ROM, 프로세서 100 하드웨어에뮬레이션 소프트웨어에뮬레이션

ARM Development Project New Project Executable Image, Object Library, Makefile Importer Wizard Add Files to Project Current Build Target Release Debug DebugRel 101

ARM Development Build Target Setting Target Settings ARM C Compiler Architecture or Processor Byte order Optimization Level Preprocessor ARM Linker LinkType RO base(0x0c100000) RW base ARM from ELF Output format 102