cs205 project nachos

46
CS205 Operating Systems Project Development of NachOS

Upload: hassan-tariq

Post on 07-Apr-2015

541 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: CS205 Project NachOS

CS‐205Operating Systems Project

Development of NachOS

Page 2: CS205 Project NachOS

Project PhasesProject Phases

• Project is comprises of 3 PhasesProject is comprises of 3 Phases– Phase 1 – Process Management ( Due on Oct 20)

– Phase 2 – Process Coordination ( Due on Nov 8)

– Phase 3 – Multiprogramming ( Due On Nov 26)

Page 3: CS205 Project NachOS

NachOS Installation GuideNachOS Installation Guide

• You can directly download NachOS on yourYou can directly download NachOS on your machine from anywhere you like or you can use the following linkuse the following link

• http://mll.csie.ntu.edu.tw/course/os_f08/217.htmhtm

• NachOS official Web site

• http://www.cs.washington.edu/homes/tom/nachos/

Page 4: CS205 Project NachOS

Phase 1Phase 1

Process Management Module

Page 5: CS205 Project NachOS

TasksTasks

• Implement Thread SchedulingImplement Thread Scheduling– Default is FCFS

Priority scheduling + Round Robin– Priority scheduling + Round Robin

Page 6: CS205 Project NachOS

NACHOS ThreadsNACHOS Threads• Ready queue

b l f d h d b– A List object: a list of ready thread objects• Thread state

– READY• The thread will be kept in readyList.The thread will be kept in readyList.

– RUNNING• The global variable currentThread always points the currently running thread.

– BLOCKED• The thread is blocked to wait for some event until the event takes place• The thread is blocked to wait for some event until the event takes place.• A blocked thread is not in readyList. Instead, it would be put in other queues.

– JUST_CREATED• The thread is just created, but not ready to be put in readyList (not ready to run).

Page 7: CS205 Project NachOS

Thread Life CycleThread Life Cycle

N

JUST_CREATED

Note:Thread::Yield() invoks Scheduler::FindNextToRun() to select next thread to run.

Thread::Fork()

Call Scheduler::E t ll

READY(use a readyList)

ReadyToRun() Event occurs, call Scheduler::ReadyToRun()(Move thread back to the ready queue)

(use a readyList)

RUNNING

BLOCKEDCall Thread::Yield()

Call Thread::Sleep()7

RUNNING Call Thread::Sleep()(Put thread to waiting queue)

Page 8: CS205 Project NachOS

Thread ObjectsThread Objects• Thread()

h h d– Constructor: sets the thread as JUST_CREATED status• Fork()

– Allocate stack, initialize registers.– Call Scheduler::ReadyToRun() to put the thread into readyList and set itsCall Scheduler::ReadyToRun() to put the thread into readyList, and set its 

status as READY. • Yield()

– Suspend the calling thread and put it into readyList.C ll S h d l Fi dN tT R () t l t th th d f d Li t– Call Scheduler::FindNextToRun() to select another thread from readyList.

– Execute selected thread by Scheduler::Run(), which sets its status as RUNNING and call SWITCH() (in code/threads/switch.s) to exchange the running thread.

• Sleep()– Suspend the current thread and find other thread to run– Change its state to BLOCKED.

Page 9: CS205 Project NachOS

Example : Create ThreadsExample : Create Threads

• void SelfTest()()– Test whether thread implementation works.– Fork a new thread and yield current one to execute it

• static void SimpleThread(int which)– A procedure where execution is to begin when the thread starts executingstarts executing

• Command line: nachos ‐K• In this project, you can trace the above two functions p j , yas the starting point.

Page 10: CS205 Project NachOS

The Flow to Invoke SelfTest()The Flow to Invoke SelfTest()

In main.cc– if (strcmp(argv[i], "‐K") == 0)

threadTestFlag = TRUE; >./nachos ‐Kg ;– if (threadTestFlag) 

kernel‐>ThreadSelfTest();// test threads and synchronization• In Kernel::ThreadSelfTest()

kernel‐>ThreadSelfTest()

In Kernel::ThreadSelfTest()currentThread‐>SelfTest();// test thread switching

– In Thread::SelfTest()Thread *t = new Thread("forked thread");

Thread::SelfTest()

Fork(SimpleThread,1)( );t‐>Fork((VoidFunctionPtr) SimpleThread, (void *) 1);kernel‐>currentThread‐>Yield();SimpleThread(0);

( p , )

10

Page 11: CS205 Project NachOS

Timesharing in NachosTimesharing in Nachos

• Alarm objectj– code/threads/alarm.cc and alarm.h– Nachos create a Timer object which interrupts every “TimerTicks” ticksTimerTicks  ticks

• code/machine/timer.cc and timer.h• When Timer interrupts, nachos calls its interrupt handler Timer::CallBack(), which resets the timer and call Alarm::CallBack()

– Alarm::CallBack()• Call interrupt‐>YieldOnReturn(), which would yield current thread in Interrupt::OneTick() after all interrupts are handled

“Ti Ti k ” i d fi d i d / hi / t t h d f lt i– “TimerTicks” is defined in code/machine/stats.h, default is 100

Page 12: CS205 Project NachOS

Timesharing in Nachos (Cont.)Timesharing in Nachos (Cont.)

• Nachos initialize a Alarm object inNachos initialize a Alarm object in Kernel::Initialize()

• Alarm generates interrupts every 100 ticksAlarm generates interrupts every 100 ticks (default)

• Nachos yields current thread in AlarmNachos yields current thread in Alarm interrupt handler

• In effect, no thread could run longer than 100In effect, no thread could run longer than 100 ticks (unless there is no other threads)

Page 13: CS205 Project NachOS

Tasks to doneTasks to done

• We have following tasks to be completed:g p– Implement a priority scheduling to replace default FCFS– Round‐Robin mechanism is already built by Alarm object, b t h it ti libut we can change its time slice

Page 14: CS205 Project NachOS

Reading Schedule FileReading Schedule File

• We do actual works in a new function in class Thread (Modify code/threads/thread cc and thread h)(Modify code/threads/thread.cc and thread.h)

void Thread::SchedulingTest(char *ParameterFile) {<Parse the parameter file to put thread’s name, remaining execution ticks, and priority to ThreadName[], RemainingExecutionTicks[], and ThreadPriorityp[], respectively.>…Thread *t;for(i=0;i<NumberOfThreadsDefinedInParemeterFile;i++){

t = new Thread(ThreadName[i]);t = new Thread(ThreadName[i]); t‐>setPriority(ThreadPriority[i]);

t‐>Fork((voidFunctionPtr) threadBody, (void *) RemainingExecutionTicks[i]);

}

14

}kernel‐>currentThread‐>Yield(); // Give up CPU in order to run new threads

}

Page 15: CS205 Project NachOS

Reading Schedule FileReading Schedule File

• Sample schedule file:p4A 2 7B 1 3C 3 5D 2 4

– 4 threads: A,B,C,D– Thread name, priority, remaining ticks

P i it 1 10 1 i th hi h t i it– Priority = 1~10, 1 is the highest priority– Thread name is 10 characters (including NULL) or less, NOTE THAT you 

should provide a newly allocated space for name strings to Thread constructor because it only stores pointer. DON’T give it local y p gvariables.

Page 16: CS205 Project NachOS

Reading Schedule FileReading Schedule File

• Implement thread body:– We run a while loop, which loops tick_to_exec times.

This parameter is supplied by Fork( (void*) RemainingExecutionTicks[i])Fork(…, (void*) RemainingExecutionTicks[i])

– Call kernel‐>interrupt‐>OneTick() to increase system execution ticks

– Print thread info, including its name and remaining ticks, g g

void threadBody (int tick_to_exec) {while(tick_to_exec > 0) {tick_to_exec‐‐;kernel >interrupt >OneTick();kernel‐>interrupt‐>OneTick();printf("%s: remaining = %d\n", 

kernel‐>currentThread‐>getName(), tick_to_exec);}

}

16

}

Page 17: CS205 Project NachOS

Priority SchedulingPriority Scheduling

• Add required member variables and methods to Thread class(code/threads/thread.cc and thread.h)– void Thread::setPriority(int p)

• Set new priority p to this threadint Thread::getPriority()– int Thread::getPriority()

• Retrieve current priority– int priority

• A thread’s priority (private variable)p y (p )

• Modify constructor to give default priority to new threads– Thread::Thread()

• In this project, we set default priority to 10 in order to avoid these threads’ p j p yeffects when doing our scheduling

Page 18: CS205 Project NachOS

Priority SchedulingPriority Scheduling

• Modify Scheduler classModify Scheduler class– code/threads/scheduler.cc and scheduler.h

– How to do? Please figure it out yourself

– You may need to use SortedList class

– If two threads have the same priority, the first thread in h h d l fil fi ( )the schedule file runs first (FCFS)

Page 19: CS205 Project NachOS

Round‐RobinRound Robin

• Alarm class generates interrupts everyAlarm class generates interrupts every TimerTicks ticks (default = 100)

• TimerTicks is defined in code/machine/stats h• TimerTicks is defined in code/machine/stats.h

• You can change it, and watch the differences

Page 20: CS205 Project NachOS

Sample scheduling resultSample scheduling result

B: remaining = 2

• Time slice = 100 ticks

B: remaining = 2B: remaining = 1B: remaining = 0D: remaining = 3D: remaining = 2• Schedule file:

4A 2 7

D: remaining = 2D: remaining = 1D: remaining = 0A: remaining = 6A: remaining = 5

B 1 3C 3 5D 2 4

A: remaining = 5A: remaining = 4C: remaining = 4C: remaining = 3C: remaining = 2D 2 4

• Why thread D run before A?

C: remaining = 2C: remaining = 1C: remaining = 0A: remaining = 3A: remaining = 2

20– Timer interrupts

A: remaining = 2A: remaining = 1A: remaining = 0Machine halting!

Page 21: CS205 Project NachOS

RequirementRequirement

• Implement priority scheduling• Write a 2‐page report

– Don’t just paste your code, I’ll read it myself– Change time slice to 50 ticks, run nachos on test schedule we supply 

d l i h land explain the results– You may need to use “‐d +” to trace the execution

• You need to update the threads.cc, threads.h, scheduler.cc and p , ,scheduler.h

• If your Project could not run at the time of evaluation, it will be considered as FAILURE

Page 22: CS205 Project NachOS

Test filesTest files

• We supply a test schedule file “testThreads txt”We supply a test schedule file  testThreads.txt  at OS Folder – Your implementation should have the same– Your implementation should have the same results as the sample scheduling when time slice = 100

– We will use other schedules to test, so don’t cheat

Page 23: CS205 Project NachOS

DeadlinesDeadlines

• Due on Oct 20Due on Oct 20

• Late submission will cause a deduction on 20% per dayper day

• Do not copy the code & protect your code well

Page 24: CS205 Project NachOS

Phase 2Phase 2

Process Coordination Module

Page 25: CS205 Project NachOS

SynchronizationSynchronization

• Practice thread synchronizationPractice thread synchronization– Producer‐consumer problem

Dining philosophers problem– Dining philosophers problem

– Implement these problems with Nachos thread and synchronization routinesand synchronization routines

Page 26: CS205 Project NachOS

Synchronization ProblemsSynchronization Problems

• Producer‐consumer problem– A fixed‐size buffer– Producer generates data and put it into bufferProducer generates data and put it into buffer– Consumer retrieves data from buffer– They work simultaneously– The objective is to make sure thatThe objective is to make sure that

• producer won’t put data into buffer when it’s full• consumer won’t remove data from en empty buffer• the state of buffer is consistent after each action

BufferProducer Consumer

Page 27: CS205 Project NachOS

Producer‐consumer problemProducer consumer problem

• When it comes to Nachos …– A buffer may be a global variable, e.g. a global array– The consumer and the producer would be threads

• Where the problem lies• Where the problem lies …– Threads may be yielded at any point– When both threads access the same data, we must make 

h h d ’ i h h i kisure that a thread won’t access it when another is working on it.

– Or, the data may be corrupted

Page 28: CS205 Project NachOS

Synchronization Problems (cont.)Synchronization Problems (cont.)

• Dining philosophers problem• Dining philosophers problem– 5 philosophers, with 5 chopsticks– A philosopher can either think or 

eateat– When she/he want to eat, she/he 

must take both chopsticks on her/his left and rightg

– If all philosophers hold one chopstick, we have a deadlock(philosophers are strange, aren’t th ?)they?)

28http://en.wikipedia.org/wiki/Image:Dining_philosophers.png

Page 29: CS205 Project NachOS

Dining philosophers problemDining philosophers problem

• Now we deal with 5 threads apparentlyNow we deal with 5 threads, apparently

• Figure out a method to prevent deadlockA l ti i t k th t– An easy solution is to make sure that a philosopher need to pick up both chopsticks at the same timethe same time

Page 30: CS205 Project NachOS

Tasks to be doneTasks to be done 

• Implements producer‐consumer problem withImplements producer consumer problem with semaphores and locks (built by Nachos)

• Implements dining philosopher problem with• Implements dining philosopher problem with a monitor‐style class (built by you)

Page 31: CS205 Project NachOS

Producer Consumer ProblemProducer Consumer Problem

• Produce and consume 30 items: 0~29• Produce and consume 30 items: 0~29

• The buffer size is 5

• Print the item number you produced or consumed, and the l b f i i h h d b ffcurrent total number of items in the shared buffer

// Thread body for producervoid Producer(int arg) {

int i;f (i 0 i 30 i ){for(i=0;i<30;i++){

// Produce item i here (maybe stores it in a global array)printf("Produced item %d, Total %d item(s)\n“, ...);

}}}

// Thread body for consumervoid Consumer(int arg) {

int i;for(i=0;i<30;i++){

31

for(i=0;i<30;i++){// Consume item i here (maybe retrieve it from a global array)printf(“Consumed item %d, Total %d item(s)\n“, ...);

}}

Page 32: CS205 Project NachOS

Producer‐Consumer problem (cont.)Producer Consumer problem (cont.)

Produced item 0 Total 1 item(s)

• Sample output:

Produced item 0, Total 1 item(s)Produced item 1, Total 2 item(s)Consumed item 0, Total 1 item(s)Consumed item 1, Total 0 item(s)Produced item 2, Total 1 item(s)Produced item 3, Total 2 item(s)Produced item 4, Total 3 item(s)Consumed item 2, Total 2 item(s)Consumed item 2, Total 2 item(s)Produced item 5, Total 3 item(s)Consumed item 3, Total 2 item(s)Consumed item 4, Total 1 item(s)

6 2Produced item 6, Total 2 item(s)Consumed item 5, Total 1 item(s)Produced item 7, Total 2 item(s)Produced item 8, Total 3 item(s)

32

, ( )Produced item 9, Total 4 item(s)Consumed item 6, Total 3 item(s)...

Page 33: CS205 Project NachOS

Dining Philosopher problemDining Philosopher problem

• Following skeleton is an example, you canFollowing skeleton is an example, you can design by yourself

• A monitor‐style class DiningTable:A monitor style class DiningTable:• We have 5 philosophers (0~4), which means 5 threadsthreads

• Each philosopher starts at thinking, then eating, then thinking … for 10 timeseating, then thinking … for 10 times

• Print what a philosopher is doing when she/he starts to do thatstarts to do that

Page 34: CS205 Project NachOS

Dining Philosopher Problem (cont)Dining Philosopher Problem (cont)

0: Philosopher 0 is eating

• Sample output:

0: Philosopher 0 is eating0: Philosopher 0 is thinking1: Philosopher 0 is eating0: Philosopher 3 is eating0: Philosopher 3 is thinking0: Philosopher 2 is eating1: Philosopher 0 is thinking0: Philosopher 2 is thinking0: Philosopher 2 is thinking0: Philosopher 1 is eating0: Philosopher 1 is thinking1: Philosopher 1 is eating1 11: Philosopher 1 is thinking0: Philosopher 4 is eating0: Philosopher 4 is thinking2: Philosopher 0 is eating

34

p g1: Philosopher 3 is eating...

Page 35: CS205 Project NachOS

Some TipsSome Tips

• Just like Thread, Semaphore, Lock, and Condition all phave a name argument in constructor: please DO NOT provide a local string to them 

• You should make sure that main thread (the onlyYou should make sure that main thread (the only thread which builds other threads) “waits” until other threads finish

H t d ? Thi i l h i ti bl (– How to do? This is also a synchronization problem (an easy one)

Page 36: CS205 Project NachOS

RequirementsRequirements

• Implement 2 synchronization problems– Make sure that no deadlock would occur

h h ld b bl– The output should be reasonable• E.g. in first problem, following output is wrong

Produced item 0, Total 1 item(s)P d d it 1 T t l 1 it ( ) # T t l h ld b 2

• E.g. in second problem, following output is wrong

Produced item 1, Total 1 item(s) # Total should be 2Consumed item 2, Total 1 item(s) # Item 2 is not generated yet

0: Philosopher 0 is eating0: Philosopher 1 is eating # Ph. 1 cannot eat because Ph. 0

is eating and holding the h ti k h 1 d

36

chopstick Ph. 1 needs

Page 37: CS205 Project NachOS

DocumentationDocumentation

• Write a 2‐page report– Don’t just paste your code, I’ll read it myself– Explain why your implementations would generate correct output, 

and why there is no deadlock

• If your Project could not run at the time of evaluation, it will be considered as FAILURE,

• The files you need to update are threads.cc, threads.h, and main.cc

Page 38: CS205 Project NachOS

DeadlinesDeadlines

• Due on Nov 8Due on Nov 8

• Late submission will cause a deduction on 20% per dayper day

• Do not copy the code & protect your code well

Page 39: CS205 Project NachOS

Phase 3Phase 3

Multiprogramming

Page 40: CS205 Project NachOS

ProblemProblem

• Design and implement appropriate supportDesign and implement appropriate support for multiprogramming

• Extend the system calls to handle process• Extend the system calls to handle process management and inter‐process communication primitivescommunication primitives

Page 41: CS205 Project NachOS

Goal 1Goal 1

• Alter your exceptions to finish the threadAlter your exceptions to finish the thread instead of halting the system. 

• This will be important as a run time exception• This will be important, as a run time exception should not cause the operating system to shut downdown.

• Modify exception.cc

Page 42: CS205 Project NachOS

Goal 2Goal 2

• Implement multiprogramming. – The Nachos code is restricted to running one user program at a 

time. • In order to convert the system from uni‐programming to 

multiprogramming. • Modify addrspace.h, addrspace.cc, and  machine.h• You will need to:You will need to:

– Come up with a way of allocating physical memory frames so that multiple programs can be loaded into memory at once.

– Properly handling freeing address space when a user program p y g g p p gfinishes.

– It is very important to alter the user program loader algorithm such that it handles frames of information.

Page 43: CS205 Project NachOS

Goal 2 (cont)Goal 2 (cont)

Modify NumPhysPages (default 128) variable in machine.h

• You are not required to deal with limited memory space

• Currently memory space allocation assumes thatCurrently, memory space allocation assumes that a process is loaded into a contiguous section of memory. 

l ll• Once multiprogramming is active, memory will no longer appear contiguous in nature. 

• If you do not correct the routine it is most likely• If you do not correct the routine, it is most likely that loading another user program will corrupt the operating system

Page 44: CS205 Project NachOS

DocumentationDocumentation

• Write a 2‐page report ( NOT more than 2 )– Don’t just paste your code, I’ll read it myself– Explain why your implementations would generate correct output– Describe meaningful problems you encountered and how you solved.g p y y

• You need to send us whole NACHOS directory

• If your code could not run at evaluation time• If your code could not run at evaluation time, it will be considered as a failure

Page 45: CS205 Project NachOS

DeadlinesDeadlines

• Due on Nov 26Due on Nov 26

• Late submission will cause a deduction on 20% per dayper day

• Do not copy the code & protect your code well

Page 46: CS205 Project NachOS

Good LuckGood Luck