Chapter 2 PDF
Chapter 2 PDF
Chapter-2 -Time
Real-Time
System Concepts
Dr. Li-Pin Chang
Real-Time and Embedded System Lab.
National Taiwan University
Objectives
• To know essential topics on the
design of:
– Embedded operating systems
– Real-time systems
Foreground/Background
Systems
• The system consists of an infinite loop which calls
modules to perform jobs. (a super loop)
– The background (or, task) level.
ISR
Time
ISR
ISR
Code execution
Critical Sections
• A portion of code must be treated
indivisibly.
– To protect shared resources from
corrupting due to race conditions.
– Could be implemented by using interrupt
enable/disable, semaphores, events,
mailboxes, etc.
Resources
• An entity used by a task.
– Memory objects
• Such as tables, global variables …
– I/O devices.
• Such as disks, communication transceivers.
MEMORY
CPU
CPU Registers
SP
Context
Task
• A task is basically an infinite loop for
a real-time system.
OSMBoxPost() OSMBoxPend()
OSQPost() OSQPend()
OSQPostFront()
OSTaskDel() OSSemPost() OSSemPend()
OSTaskResume() OSTaskSuspend()
OSTimeDlyResume() OSTimeDly()
OSTimeTick() OSTimeDlyHMSM()
OSTaskCreate()
OSTaskCreateExt() OSStart()
OSIntExit() Interrupt
OS_TASK_SW()
DORMANT READY RUNNING ISR
OSIntExit()
OSTaskDel()
Task is Preempted
OSTaskDel()
Context Switch
• It occurs when the scheduler decides to run a different
task.
(3) The ISR handles the event and makes a higher priority
task ready-to-run.
(7) The new higher priority task then executes to handle the
event signaled by the ISR.
Preemptive Kernels
• The benefit of a preemptive kernel is the system
is more responsive.
– uC/OS-2 (and most RTOS) is preemptive.
– The execution of a task is deterministic.
• A high-priority task gain control of the CPU instantly when
it is ready (if no resource-locking is done).
(6)
(7)
(1) A task is executing but interrupted.
(2) If interrupts are enabled, the CPU vectors (jumps) to the ISR.
(3) The ISR handles the event and makes a higher priority task
ready to run. Upon completion of the ISR, a service provided by
the kernel is invoked. (i.e., a function that the kernel provides is
called).
(4)
(5) This function knows that a more important task has been made
ready to run, and thus, instead of returning to the interrupted
task, the kernel performs a context switch and executes the
code of the more important task. When the more important task
is done, another function that the kernel provides is called to
put the task to sleep waiting for the event (i.e., the ISR) to
occur.
(6)
(7) The kernel then sees that a lower priority task needs to
execute, and another context switch is done to resume
execution of the interrupted task.
Reentrant Functions
• Reentrant functions can be invoked
simultaneously without corrupting any data.
– Reentrant functions use either local variables
(on stacks) or synchronization mechanisms
(such as semaphores).
Temp == 1
while (1) { OSIntExit() while (1) {
x = 1; z = 3;
y = 2; (2) t = 4;
ISR O.S.
(3)
swap(&x, &y);
{
(1) swap(&z, &t);
{
Temp = *x; Temp = *z;
*z = *t;
(5) *t = Temp;
*x = *y; O.S. }
*y = Temp; (4) .
} .
. OSTimeDly(1);
. Temp == 3! .
OSTimeDly(1); .
} }
Temp == 3
(1) When swap() is interrupted, TEMP contains 1.
(2)
(3) The ISR makes the higher priority task ready to run, so
at the completion of the ISR, the kernel is invoked to
switch to this task. The high priority task sets TEMP to 3
and swaps the contents of its variables correctly. (i.e.,
z=4 and t=3).
(5) The lower priority task is thus resumed. Note that at this
point, TEMP is still set to 3! When the low priority task
resumes execution, the task sets y to 3 instead of 1.
Non-Reentrant Functions
• There are several ways to make the
code reentrant:
– Declare TEMP as a local variable.
– Disable interrupts and then enable
interrupts.
– Use a semaphore.
Round-Robin Scheduling
• Adopted when no “priority” is adopted or tasks have the
same priority.
– Most traditional operating systems utilize RR scheduling.
(4) (12)
Task 1 (H)
(8)
Task 2 (M)
(5) (9)
Task 1 (H)
(11)
Task 2 (M)
real-time system . .
if(flag == 1)
Locking is failed.
flag remains 1.
else
Locking is success.
flag is set as 1 after the swapping.
... critical section ...
Mutual Exclusion
• Disabling/Enabling Scheduling:
– No preemptions could happen while the scheduler is
disabled.
– However, interrupts still happen.
• ISR’s could still corrupt shared data.
• Once an ISR is done, the interrupted task is always
resumed even there are high priority tasks ready.
– Rescheduling might happen right after the scheduler is
re-enabled.
– Higher overheads and weaker effects than
enabling/disabling interrupts.
void Function (void)
{
OSSchedLock();
. /* You can access shared data
. in here (interrupts are recognized) */
OSSchedUnlock();
}
Mutual Exclusion
• Semaphores:
– Provided by the kernel.
– Semaphores are used to:
• Control access to a shared resource.
• Signal the occurrence of an event.
• Allow tasks to synchronize their activities.
– Higher priority tasks which does not interested in the
protected resources can still be scheduled to run.
OS_EVENT *SharedDataSem;
void Function (void)
{
INT8U err;
OSSemPend(SharedDataSem, 0, &err);
. /* You can access shared data
. in here (interrupts are recognized) */
OSSemPost(SharedDataSem);
}
Mutual Exclusion
• Semaphores:
– OSSemPend() / OSSemPost()
– OSSemPend:
• Counter--;
• If the value of the semaphore <0, the task is blocked and moved to
the wait list immediately.
• A time-out value can be specified .
– OSSemPost:
• Counter++;
• If the value of the semaphore >= 0, a task in the wait list is
removed from the wait list.
– Reschedule if needed.
Mutual Exclusion
• Semaphores:
– Three kinds of semaphores:
• Counting semaphore (init >1)
• Binary semaphore (init = 1)
• Rendezvous semaphore (init = 0)
– On event posting, a waiting task is released
from the waiting queue.
• The highest-priority task.
• FIFO (not supported by uC/OS-2)
– Interrupts and scheduling are still enabled
under the use of semaphores.
"I am task #1!"
TASK 1
Acquire Semaphore
SEMAPHORE PRINTER
Acquire Semaphore
TASK 2
"I am task #2!"
Mutual Exclusion
• Example: use a semaphore to protect a RS-232
communication portÆ
DRIVER RS-232C
TASK2 CommSendCmd()
Semaphore
Mutual Exclusion
• Using a counting semaphore to synchronize
the use of a buffer.
BUF *BufReq(void) void BufRel(BUF *ptr)
{ {
BUF *ptr; Disable interrupts;
ptr->BufNext = BufFreeList;
Acquire a semaphore; BufFreeList = ptr;
Disable interrupts; Enable interrupts;
ptr = BufFreeList; Release semaphore;
BufFreeList = ptr->BufNext; }
Enable interrupts;
return (ptr); **Red statements can be replaced
} by a binary semaphore. Here we
disable/enable interrupts for the
consideration of efficientcy.
BufFreeList
Next Next Next 0
10
BufReq() BufRel()
Buffer Manager
Task1 Task2
Mutual Exclusion
• Summary:
τ1
τ2
τ3 τ1
τ1
τ4
Synchronization
• Different from mutual exclusion, it is
much like waiting for an event.
• If a semaphore is used, it must be
initialized to 0.
– It is called unilateral rendezvous.
– TaskÅÆTask, ISRÆTask
• Note that an ISR never cause itself blocked.
POST PEND
ISR TASK
POST PEND
TASK TASK
Synchronization
• Two semaphores could be used to
rendezvous two tasks.
– It can not be used to synchronize
between ISR’s and tasks.
– For example, a kernel-mode thread
could synchronize with a user-mode
worker thread which performs
complicated jobs.
Synchronization
Task1()
{
for (;;) { POST PEND
Perform operation;
Signal task #2; (1) TASK TASK
Wait for signal from task #2; (2)
Continue operation; PEND POST
}
}
Task2()
** Semaphores are {
both initialized to 0 for (;;) {
Perform operation;
Signal task #1; (3)
Wait for signal from task #1; (4)
Continue operation;
}
}
Event Flags
• Event flags are used when a task needs to synchronize with
the occurrence of one or more events.
OR POST PEND
TASK
ISR
DISJUNCTIVE SYNCHRONIZATION
TASK
Events Semaphore
ISR
CONJUNCTIVE SYNCHRONIZATION
TASK ISR
Events
(8, 16 or 32 bits)
Semaphore
Events
POST PEND
OR TASK
Semaphore
Events
POST PEND
AND TASK
Intertask communication
• A task/ISR might want to exchange data
with another task/ISR.
– Mutual exclusion is needed for shared variable.
• OSMboxPend():
– The message in the mailbox is retrieved.
– If the mailbox is empty, the task is immediately blocked and moved to
the wait-list.
– A time-out value can be specified.
• OSMboxPost():
– A message is posted in the mailbox.
– If there is already a message in the mailbox, an error is returned
(not overwritten).
– If tasks waiting for a message from the mailbox, the task with the
highest priority is removed from the wait-list and scheduled to run.
• OSMboxAccept():
– If there is no message, return immediately instead of being blocked.
Mailbox
POST PEND
TASK TASK
10
Message Queues
• A message queue consists an array of elements and a wait-list.
• The CPU saves the context of the current running task and jumps
to the corresponding service routine (ISR).
• The ISR processes the event, and upon completion of the ISR, the
program returns to
– The background for a foreground/background system
– The interrupted task for a non-preemptive kernel
– The highest priority task ready to run for a preemptive kernel
TIME
TASK
ISR #1
ISR #2
ISR #3
Interrupt #1
Interrupt #2
Interrupt #3
Interrupt Latency
• Real-time systems disable interrupts to
manipulate critical sections of code and enable
interrupts when critical section has executed.
interrupt latency =
max. amount of interrupts are disabled +
Time to start executing the first instruction in the ISR
Interrupt Response
• Interrupt response: the time between the reception of the
interrupt and the start of the user code that handles the
interrupt – accounts for all the overhead involved in
handling an interrupt
Interrupt Request
BACKGROUND BACKGROUND
ISR
CPU context
User ISR Code restored
Interrupt Latency
Interrupt Recovery
Interrupt Response
Interrupt latency, response,
and recovery
(Non-preemptive kernel)
TIME
Interrupt Request
TASK TASK
ISR
CPU context
User ISR Code restored
Interrupt Latency
Interrupt Recovery
Interrupt Response
Interrupt latency, response,
and recovery
(Preemptive kernel)
TIME
Interrupt Request
Interrupt Recovery
TASK TASK
Interrupt Response
Exit function restored
B
TASK
Interrupt Recovery
Non-Maskable
Interrupts
• NMI’s can not be disabled.
– They are generally reserved for drastic events, such as
the power-source is almost exhausted.
Interrupt response
= Interrupt latency
+ Time to save the CPU’s context
Interrupt recovery
= Time to restore the CPU’s context
+ Time to execute the return from interrupt instruction
Tick ISR
Delayed Task
t1 t3
(19 mS) t2 (27 mS)
(17 mS)
Tick ISR
Delayed Task
t3
t1 t2 (27 mS)
(6 mS) (19 mS)
Tick ISR
Delayed Task
t2
t1 (26 mS)
(40 mS)