SlideShare a Scribd company logo
1 of 21
Download to read offline
Preparation
       for

MIT-OSE Lab4
       Ben
    2012/05/29
● Locking
● Scheduling
● Coordination and processes
● Locking
● Scheduling
● Coordination and processes
Abstract SMP architecture

● processors with one shared memory

● devices

● interrupts processed in parallel
Avoiding list race
                            Lock list_lock; // one per list
insert(int data){
  List *l = new List;       insert(int data){
  l->data = data;             List *l = new List;
                              l->data = data;

                                acquire(&list_lock);
    l->next = list ; // A
    list = l;    // B           l->next = list ; // A   critical section, or
                                list = l;    // B       atomic section



}                               release(&list_lock);
                            }

    ● multiple processes adding to the disk queue
Race Condition

                                                           Time
             A                           B
CPU1




                 l->next                     list
Memory
                           l->next                  list




CPU2
         A                           B
Implementing lock and release

● use atomic instructions (e.g., xchg)
For example, the x86 <tt>xchg %eax, addr</tt> instruction
does the following:

freeze other CPUs' memory activity for address addr
temp := *addr
*addr := %eax
%eax = temp
un-freeze other memory activity
x86 asm to implement a spinlock
lock:              ; The lock variable. 1 = locked, 0 = unlocked.
   dd    0

spin_lock:
   mov eax, 1
   xchg eax, [lock] ; Atomically swap EAX register with lock variable.
   test    eax, eax
   jnz     spin_lock
   ret

spin_unlock:
   mov eax, 0        ; Set the EAX register to 0.
   xchg eax, [lock] ; Atomically swap EAX register with lock variable.
   ret                ; The lock has been released.
Design Issues - locks and interrupts
● ide disk generates interrupt when disk
  operation completes
● interrupt causes ideintr to run
● ideintr acquires lock?
    deadlock?
    give interrupt handler lock? (recursive
  locks)
● xv6: critical sections have no interrupts
  turned on
Design Issues - locks and modularity
move(l1, l2) { move(l1, l2) {       move(l1, l2) {
                  acquire(l1.lock);   acquire(l1.lock);
                  acquire(l2.lock);   e = del(l1)
                  e = del(l1)         release(l1.lock)
  e = del(l1)
                  insert(l2, e)       acquire(l2.lock);
  insert(l2, e)
                  release(l1.lock)    insert(l2, e)
                  release(l2.lock)    release(l2.lock)
}                                   }
                }
     original                      recursive                         Modified

● recursive locks are a bad idea
  ideintr should certainly not use that instead of disabling interrupts!
● Locking
● Scheduling
● Coordination and processes
Goals for solution

● Switching transparent to user threads
● User thread cannot hog a processor
Code - Concurrency

 - plock held across switch; why?
   yield: p is set runnable, p must complete
switch before another scheduler chooses p

- hard to reason about; coroutine style helps

 - can two schedulers select the same runnable
process?
 - why does scheduler release after loop, and
re-acquire it immediately? (run with interrupts!)
Code - Thread clean up

● let's look at kill: can we clean up killed
  process? (no: it might be running,
    holding locks etc.) before returning to user
  space: process kills itself by calling exit

● let's look at exit; can thread delete its stack?
  (no: it has to switch off it!)

●   wait() does the cleanup
● Locking
● Scheduling
● Coordination and processes
Required reading: remainder of proc.c, sys_wait, sys_exit, and sys_kill.
Coordination and more processes
Big picture

Multiple threads executing in the kernel and
sharing memory, devices and various data
structures.
● Allow more than one process to be
   executing to take advantage of multiple
   CPUs
● Allow system calls that block waiting for I/O.
producer consumer queue
struct pcq {
                                     Need lock for pcq->ptr if multiple
    void *ptr;
                                     processors
};

void*
pcqread(struct pcq *q){

    while((p=q->ptr)==0);
    q->ptr = 0;
    return p;
}
                                   Waste CPU Time. Instead of polling,
pcqwrite(struct pcq *q, void *p)   Use event-based (sleep and wakeup)
{
    while(q->ptr != 0);
    q->ptr = p;
}
Sleep & wakeup
sleep(chan):                    sleep(void *chan, struct spinlock *lk)
                                {
  curproc->chan = chan
                                   struct proc *p = curproc[cpu()];
  curproc->state = SLEEPING
  sched()                           p->chan = chan;
                                    p->state = SLEEPING;
                                    release(lk);
                                    sched();
                                    acquire(lk);
                                }

                                wakeup(void *chan)
wakeup(chan):                   {
  foreach p in proc[]:            for(each proc p) {
    if p->chan == chan               if(p->state == SLEEPING
      and p->state==SLEEPING:            && p->chan == chan)
                                        p->state = RUNNABLE;
      p->state = RUNNABLE         }
                                }
producer consumer queue (cont.)
struct pcq {                        struct pcq {
    void *ptr;                          void *ptr;
};                                      struct spinlock lock; };

void*                               void* pcqread(struct pcq *q) {
pcqread(struct pcq *q){                 acquire(&q->lock);
                                        while(q->ptr == 0)sleep(q, &q->lock);
    while((p=q->ptr)==0);               p = q->ptr;
    q->ptr = 0;                         q->ptr = 0;
    return p;                           wakeup(q); /* wake pcqwrite */
}                                       release(&q->lock);
                                        return p;
                                    }
pcqwrite(struct pcq *q, void *p){   pcqwrite(struct pcq *q, void *p) {
    while(q->ptr != 0);                 acquire(&q->lock);
    q->ptr = p;                         while(q->ptr != 0) sleep(q, &q->lock);
}                                       q->ptr = p;
                                        wakeup(q); /* wake pcqread */
                                        release(&q->lock);
                                        return p;
                                    }
Q&A

                    Schduling
      Locking


                ?
                Threads

More Related Content

What's hot

Facts about multithreading that'll keep you up at night - Guy Bar on, Vonage
Facts about multithreading that'll keep you up at night - Guy Bar on, VonageFacts about multithreading that'll keep you up at night - Guy Bar on, Vonage
Facts about multithreading that'll keep you up at night - Guy Bar on, VonageCodemotion Tel Aviv
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18nyifi2009
 
Make A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkMake A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkYodalee
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu WorksZhen Wei
 
C10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, AkamaiC10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, AkamaiCodemotion Tel Aviv
 
Introduction to nand2 tetris
Introduction to nand2 tetrisIntroduction to nand2 tetris
Introduction to nand2 tetrisYodalee
 
LMAX Disruptor as real-life example
LMAX Disruptor as real-life exampleLMAX Disruptor as real-life example
LMAX Disruptor as real-life exampleGuy Nir
 
W8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational ProcessorW8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational ProcessorDaniel Roggen
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageablecorehard_by
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingDavid Evans
 
Fast HTTP string processing algorithms
Fast HTTP string processing algorithmsFast HTTP string processing algorithms
Fast HTTP string processing algorithmsAlexander Krizhanovsky
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)David Evans
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by exampleYunWon Jeong
 
LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)Wang Hsiangkai
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Intro2 Cuda Moayad
Intro2 Cuda MoayadIntro2 Cuda Moayad
Intro2 Cuda MoayadMoayadhn
 

What's hot (20)

Advanced locking
Advanced lockingAdvanced locking
Advanced locking
 
Facts about multithreading that'll keep you up at night - Guy Bar on, Vonage
Facts about multithreading that'll keep you up at night - Guy Bar on, VonageFacts about multithreading that'll keep you up at night - Guy Bar on, Vonage
Facts about multithreading that'll keep you up at night - Guy Bar on, Vonage
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18n
 
Make A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkMake A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst Framework
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
 
C10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, AkamaiC10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, Akamai
 
Introduction to nand2 tetris
Introduction to nand2 tetrisIntroduction to nand2 tetris
Introduction to nand2 tetris
 
LMAX Disruptor as real-life example
LMAX Disruptor as real-life exampleLMAX Disruptor as real-life example
LMAX Disruptor as real-life example
 
W8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational ProcessorW8_2: Inside the UoS Educational Processor
W8_2: Inside the UoS Educational Processor
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and Scheduling
 
Fast HTTP string processing algorithms
Fast HTTP string processing algorithmsFast HTTP string processing algorithms
Fast HTTP string processing algorithms
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by example
 
LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
System Calls
System CallsSystem Calls
System Calls
 
Intro2 Cuda Moayad
Intro2 Cuda MoayadIntro2 Cuda Moayad
Intro2 Cuda Moayad
 
Kommons
KommonsKommons
Kommons
 

Viewers also liked

SMP implementation for OpenBSD/sgi
SMP implementation for OpenBSD/sgiSMP implementation for OpenBSD/sgi
SMP implementation for OpenBSD/sgiTakuya ASADA
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemJohn Efstathiades
 
Area Under Curves Basic Concepts - JEE Main 2015
Area Under Curves Basic Concepts - JEE Main 2015 Area Under Curves Basic Concepts - JEE Main 2015
Area Under Curves Basic Concepts - JEE Main 2015 Ednexa
 
Android발표자료 홍종진
Android발표자료 홍종진Android발표자료 홍종진
Android발표자료 홍종진Jong Jin Hong
 
Smart dsp os_user_guide
Smart dsp os_user_guideSmart dsp os_user_guide
Smart dsp os_user_guideeng_basemm
 
Veeam webinar - Deduplication best practices
Veeam webinar - Deduplication best practicesVeeam webinar - Deduplication best practices
Veeam webinar - Deduplication best practicesJoep Piscaer
 
Graph Image Segmentation
Graph Image SegmentationGraph Image Segmentation
Graph Image SegmentationManohar Kuse
 
Deployment Best Practices
Deployment Best PracticesDeployment Best Practices
Deployment Best PracticesMongoDB
 
Wait queue
Wait queueWait queue
Wait queueRoy Lee
 
Jpeg image compression using discrete cosine transform a survey
Jpeg image compression using discrete cosine transform   a surveyJpeg image compression using discrete cosine transform   a survey
Jpeg image compression using discrete cosine transform a surveyIJCSES Journal
 
안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기
안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기
안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기OnGameServer
 
Discrete Cosine Transform Stegonagraphy
Discrete Cosine Transform StegonagraphyDiscrete Cosine Transform Stegonagraphy
Discrete Cosine Transform StegonagraphyKaushik Chakraborty
 

Viewers also liked (20)

SMP implementation for OpenBSD/sgi
SMP implementation for OpenBSD/sgiSMP implementation for OpenBSD/sgi
SMP implementation for OpenBSD/sgi
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded System
 
Area Under Curves Basic Concepts - JEE Main 2015
Area Under Curves Basic Concepts - JEE Main 2015 Area Under Curves Basic Concepts - JEE Main 2015
Area Under Curves Basic Concepts - JEE Main 2015
 
Overview Of Msil
Overview Of MsilOverview Of Msil
Overview Of Msil
 
Android발표자료 홍종진
Android발표자료 홍종진Android발표자료 홍종진
Android발표자료 홍종진
 
Understand
UnderstandUnderstand
Understand
 
Smart dsp os_user_guide
Smart dsp os_user_guideSmart dsp os_user_guide
Smart dsp os_user_guide
 
Lpc1768
Lpc1768Lpc1768
Lpc1768
 
Compression Ii
Compression IiCompression Ii
Compression Ii
 
Veeam webinar - Deduplication best practices
Veeam webinar - Deduplication best practicesVeeam webinar - Deduplication best practices
Veeam webinar - Deduplication best practices
 
Graph Image Segmentation
Graph Image SegmentationGraph Image Segmentation
Graph Image Segmentation
 
Deployment Best Practices
Deployment Best PracticesDeployment Best Practices
Deployment Best Practices
 
Memory Pools for C and C++
Memory Pools for C and C++Memory Pools for C and C++
Memory Pools for C and C++
 
Wait queue
Wait queueWait queue
Wait queue
 
Image Compression Techniques: A Survey
Image Compression Techniques: A SurveyImage Compression Techniques: A Survey
Image Compression Techniques: A Survey
 
Jpeg image compression using discrete cosine transform a survey
Jpeg image compression using discrete cosine transform   a surveyJpeg image compression using discrete cosine transform   a survey
Jpeg image compression using discrete cosine transform a survey
 
DVBSimulcrypt2
DVBSimulcrypt2DVBSimulcrypt2
DVBSimulcrypt2
 
안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기
안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기
안준석님 - 안드로이드 프로세스들의 통신 메커니즘 : 바인더 이야기
 
Discrete Cosine Transform Stegonagraphy
Discrete Cosine Transform StegonagraphyDiscrete Cosine Transform Stegonagraphy
Discrete Cosine Transform Stegonagraphy
 
Oslib rm
Oslib rmOslib rm
Oslib rm
 

Similar to Preparation for mit ose lab4

rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfYodalee
 
Kernel Recipes 2019 - RCU in 2019 - Joel Fernandes
Kernel Recipes 2019 - RCU in 2019 - Joel FernandesKernel Recipes 2019 - RCU in 2019 - Joel Fernandes
Kernel Recipes 2019 - RCU in 2019 - Joel FernandesAnne Nicolas
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptablesKernel TLV
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)Sri Prasanna
 
When the OS gets in the way
When the OS gets in the wayWhen the OS gets in the way
When the OS gets in the wayMark Price
 
Xdp and ebpf_maps
Xdp and ebpf_mapsXdp and ebpf_maps
Xdp and ebpf_mapslcplcp1
 
HSA Kernel Code (KFD v0.6)
HSA Kernel Code (KFD v0.6)HSA Kernel Code (KFD v0.6)
HSA Kernel Code (KFD v0.6)Hann Yu-Ju Huang
 
Much Ado About Blocking: Wait/Wakke in the Linux Kernel
Much Ado About Blocking: Wait/Wakke in the Linux KernelMuch Ado About Blocking: Wait/Wakke in the Linux Kernel
Much Ado About Blocking: Wait/Wakke in the Linux KernelDavidlohr Bueso
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from insidejulien pauli
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 
A whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerA whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerNikita Popov
 
Kernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power ManagementKernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power ManagementAnne Nicolas
 
Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016Atin Mukherjee
 
Adding replication protocol support for psycopg2
Adding replication protocol support for psycopg2Adding replication protocol support for psycopg2
Adding replication protocol support for psycopg2Alexander Shulgin
 

Similar to Preparation for mit ose lab4 (20)

FPGA Tutorial - LCD Interface
FPGA Tutorial - LCD InterfaceFPGA Tutorial - LCD Interface
FPGA Tutorial - LCD Interface
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
 
Plpgsql internals
Plpgsql internalsPlpgsql internals
Plpgsql internals
 
Kernel Recipes 2019 - RCU in 2019 - Joel Fernandes
Kernel Recipes 2019 - RCU in 2019 - Joel FernandesKernel Recipes 2019 - RCU in 2019 - Joel Fernandes
Kernel Recipes 2019 - RCU in 2019 - Joel Fernandes
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptables
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
 
When the OS gets in the way
When the OS gets in the wayWhen the OS gets in the way
When the OS gets in the way
 
DHow2 - L6 VHDL
DHow2 - L6 VHDLDHow2 - L6 VHDL
DHow2 - L6 VHDL
 
Xdp and ebpf_maps
Xdp and ebpf_mapsXdp and ebpf_maps
Xdp and ebpf_maps
 
HSA Kernel Code (KFD v0.6)
HSA Kernel Code (KFD v0.6)HSA Kernel Code (KFD v0.6)
HSA Kernel Code (KFD v0.6)
 
Much Ado About Blocking: Wait/Wakke in the Linux Kernel
Much Ado About Blocking: Wait/Wakke in the Linux KernelMuch Ado About Blocking: Wait/Wakke in the Linux Kernel
Much Ado About Blocking: Wait/Wakke in the Linux Kernel
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
Sysprog 14
Sysprog 14Sysprog 14
Sysprog 14
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
A whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerA whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizer
 
Kernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power ManagementKernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power Management
 
Pycon Sec
Pycon SecPycon Sec
Pycon Sec
 
Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016
 
Verilog_Examples (1).pdf
Verilog_Examples (1).pdfVerilog_Examples (1).pdf
Verilog_Examples (1).pdf
 
Adding replication protocol support for psycopg2
Adding replication protocol support for psycopg2Adding replication protocol support for psycopg2
Adding replication protocol support for psycopg2
 

More from Benux Wei

F9 microkernel app development part 2 gpio meets led
F9 microkernel app development part 2 gpio meets ledF9 microkernel app development part 2 gpio meets led
F9 microkernel app development part 2 gpio meets ledBenux Wei
 
F9 microkernel app development part 1
F9 microkernel app development part 1F9 microkernel app development part 1
F9 microkernel app development part 1Benux Wei
 
F9 microkernel code reading part 4 memory management
F9 microkernel code reading part 4 memory managementF9 microkernel code reading part 4 memory management
F9 microkernel code reading part 4 memory managementBenux Wei
 
F9 Microkernel code reading part 2 scheduling
F9 Microkernel code reading part 2 schedulingF9 Microkernel code reading part 2 scheduling
F9 Microkernel code reading part 2 schedulingBenux Wei
 
While software engineer meets 3d printer
While software engineer meets 3d printerWhile software engineer meets 3d printer
While software engineer meets 3d printerBenux Wei
 
F9 Microkernel code reading - part 1
F9 Microkernel code reading - part 1F9 Microkernel code reading - part 1
F9 Microkernel code reading - part 1Benux Wei
 
Real practice of Networking design on specialized for ARM Cortex-M
Real practice of Networking design on specialized for ARM Cortex-MReal practice of Networking design on specialized for ARM Cortex-M
Real practice of Networking design on specialized for ARM Cortex-MBenux Wei
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded cBenux Wei
 
Stm32 f4 first touch
Stm32 f4 first touchStm32 f4 first touch
Stm32 f4 first touchBenux Wei
 

More from Benux Wei (9)

F9 microkernel app development part 2 gpio meets led
F9 microkernel app development part 2 gpio meets ledF9 microkernel app development part 2 gpio meets led
F9 microkernel app development part 2 gpio meets led
 
F9 microkernel app development part 1
F9 microkernel app development part 1F9 microkernel app development part 1
F9 microkernel app development part 1
 
F9 microkernel code reading part 4 memory management
F9 microkernel code reading part 4 memory managementF9 microkernel code reading part 4 memory management
F9 microkernel code reading part 4 memory management
 
F9 Microkernel code reading part 2 scheduling
F9 Microkernel code reading part 2 schedulingF9 Microkernel code reading part 2 scheduling
F9 Microkernel code reading part 2 scheduling
 
While software engineer meets 3d printer
While software engineer meets 3d printerWhile software engineer meets 3d printer
While software engineer meets 3d printer
 
F9 Microkernel code reading - part 1
F9 Microkernel code reading - part 1F9 Microkernel code reading - part 1
F9 Microkernel code reading - part 1
 
Real practice of Networking design on specialized for ARM Cortex-M
Real practice of Networking design on specialized for ARM Cortex-MReal practice of Networking design on specialized for ARM Cortex-M
Real practice of Networking design on specialized for ARM Cortex-M
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
 
Stm32 f4 first touch
Stm32 f4 first touchStm32 f4 first touch
Stm32 f4 first touch
 

Recently uploaded

MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?Olivia Kresic
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Riya Pathan
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… AbridgedLean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… AbridgedKaiNexus
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchirictsugar
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailAriel592675
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024christinemoorman
 
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadIslamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadAyesha Khan
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...lizamodels9
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionMintel Group
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis UsageNeil Kimberley
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxMarkAnthonyAurellano
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Kirill Klimov
 

Recently uploaded (20)

MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… AbridgedLean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchir
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detail
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024
 
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadIslamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted Version
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024
 

Preparation for mit ose lab4

  • 1. Preparation for MIT-OSE Lab4 Ben 2012/05/29
  • 2. ● Locking ● Scheduling ● Coordination and processes
  • 3. ● Locking ● Scheduling ● Coordination and processes
  • 4. Abstract SMP architecture ● processors with one shared memory ● devices ● interrupts processed in parallel
  • 5. Avoiding list race Lock list_lock; // one per list insert(int data){ List *l = new List; insert(int data){ l->data = data; List *l = new List; l->data = data; acquire(&list_lock); l->next = list ; // A list = l; // B l->next = list ; // A critical section, or list = l; // B atomic section } release(&list_lock); } ● multiple processes adding to the disk queue
  • 6. Race Condition Time A B CPU1 l->next list Memory l->next list CPU2 A B
  • 7. Implementing lock and release ● use atomic instructions (e.g., xchg) For example, the x86 <tt>xchg %eax, addr</tt> instruction does the following: freeze other CPUs' memory activity for address addr temp := *addr *addr := %eax %eax = temp un-freeze other memory activity
  • 8. x86 asm to implement a spinlock lock: ; The lock variable. 1 = locked, 0 = unlocked. dd 0 spin_lock: mov eax, 1 xchg eax, [lock] ; Atomically swap EAX register with lock variable. test eax, eax jnz spin_lock ret spin_unlock: mov eax, 0 ; Set the EAX register to 0. xchg eax, [lock] ; Atomically swap EAX register with lock variable. ret ; The lock has been released.
  • 9. Design Issues - locks and interrupts ● ide disk generates interrupt when disk operation completes ● interrupt causes ideintr to run ● ideintr acquires lock? deadlock? give interrupt handler lock? (recursive locks) ● xv6: critical sections have no interrupts turned on
  • 10. Design Issues - locks and modularity move(l1, l2) { move(l1, l2) { move(l1, l2) { acquire(l1.lock); acquire(l1.lock); acquire(l2.lock); e = del(l1) e = del(l1) release(l1.lock) e = del(l1) insert(l2, e) acquire(l2.lock); insert(l2, e) release(l1.lock) insert(l2, e) release(l2.lock) release(l2.lock) } } } original recursive Modified ● recursive locks are a bad idea ideintr should certainly not use that instead of disabling interrupts!
  • 11. ● Locking ● Scheduling ● Coordination and processes
  • 12. Goals for solution ● Switching transparent to user threads ● User thread cannot hog a processor
  • 13. Code - Concurrency - plock held across switch; why? yield: p is set runnable, p must complete switch before another scheduler chooses p - hard to reason about; coroutine style helps - can two schedulers select the same runnable process? - why does scheduler release after loop, and re-acquire it immediately? (run with interrupts!)
  • 14. Code - Thread clean up ● let's look at kill: can we clean up killed process? (no: it might be running, holding locks etc.) before returning to user space: process kills itself by calling exit ● let's look at exit; can thread delete its stack? (no: it has to switch off it!) ● wait() does the cleanup
  • 15. ● Locking ● Scheduling ● Coordination and processes Required reading: remainder of proc.c, sys_wait, sys_exit, and sys_kill.
  • 17. Big picture Multiple threads executing in the kernel and sharing memory, devices and various data structures. ● Allow more than one process to be executing to take advantage of multiple CPUs ● Allow system calls that block waiting for I/O.
  • 18. producer consumer queue struct pcq { Need lock for pcq->ptr if multiple void *ptr; processors }; void* pcqread(struct pcq *q){ while((p=q->ptr)==0); q->ptr = 0; return p; } Waste CPU Time. Instead of polling, pcqwrite(struct pcq *q, void *p) Use event-based (sleep and wakeup) { while(q->ptr != 0); q->ptr = p; }
  • 19. Sleep & wakeup sleep(chan): sleep(void *chan, struct spinlock *lk) { curproc->chan = chan struct proc *p = curproc[cpu()]; curproc->state = SLEEPING sched() p->chan = chan; p->state = SLEEPING; release(lk); sched(); acquire(lk); } wakeup(void *chan) wakeup(chan): { foreach p in proc[]: for(each proc p) { if p->chan == chan if(p->state == SLEEPING and p->state==SLEEPING: && p->chan == chan) p->state = RUNNABLE; p->state = RUNNABLE } }
  • 20. producer consumer queue (cont.) struct pcq { struct pcq { void *ptr; void *ptr; }; struct spinlock lock; }; void* void* pcqread(struct pcq *q) { pcqread(struct pcq *q){ acquire(&q->lock); while(q->ptr == 0)sleep(q, &q->lock); while((p=q->ptr)==0); p = q->ptr; q->ptr = 0; q->ptr = 0; return p; wakeup(q); /* wake pcqwrite */ } release(&q->lock); return p; } pcqwrite(struct pcq *q, void *p){ pcqwrite(struct pcq *q, void *p) { while(q->ptr != 0); acquire(&q->lock); q->ptr = p; while(q->ptr != 0) sleep(q, &q->lock); } q->ptr = p; wakeup(q); /* wake pcqread */ release(&q->lock); return p; }
  • 21. Q&A Schduling Locking ? Threads