← All writing

Operating Systems: Three Easy Pieces (1)

Scheduling and Memory Management

Parts: 1 · 2 · 3

7.CPU Scheduling

7.1 Workload Assumptions

7.2 Scheduling Metrics

turnaround time : The turnaround time of a job is defined as the time at which the job completes minus the time at which the job arrived in the system.

This conundrum shows us that life isn’t always perfect.

7.3 First In, First Out (FIFO)

7.4 Shortest Job First (SJF)

In fact, given our assumptions about jobs all arriving at the same time, we could prove that SJF is indeed an optimal scheduling algorithm. (This is difference from other bad textbooks).

7.5 Shortest Time-to-Completion First (STCF)

Add preemption to SJF, known as the Shortest Time-to-Completion First (STCF) or Preemptive Shortest Job First (PSJF) scheduler.

Any time a new job enters the system, the STCF scheduler determines which of the remaining jobs (including the new job) has the least time left, and schedules that one.

And as before, given our new assumptions (jobs can be switched when running), STCF is provably optimal; given that SJF is optimal if all jobs arrive at the same time, you should probably be able to see the intuition behind the optimality of STCF.

Thus, if we knew job lengths, and that jobs only used the CPU, and our only metric was turnaround time, STCF would be a great policy.

7.6 A New Metric: Response Time

In fact, for a number of early batch computing systems, these types of scheduling algorithms made some sense. However, the introduction of time-shared machines changed all that. Now users would sit at a terminal and demand interactive performance from the system as well. And thus, a new metric was born: response time.

We define response time as the time from when the job arrives in a system to the first time it is scheduled.

7.7 Round Robin

The basic idea is simple: instead of running jobs to completion, RR runs a job for a time slice (sometimes called a scheduling quantum) and then switches to the next job in the run queue.

Note that the cost of context switching does not arise solely from the OS actions of saving and restoring a few registers. When programs run, they build up a great deal of state in CPU caches, TLBs, branch predictors, and other on-chip hardware.

Indeed, this is an inherent trade-off: if you are willing to be unfair, you can run shorter jobs to completion, but at the cost of response time; if you instead value fairness, esponse time is lowered, but at the cost of turnaround time.

7.8 Incorporating I/O

A scheduler clearly has a decision to make when a job initiates an I/O request, because the currently-running job won’t be using the CPU during the I/O; it is blocked waiting for I/O completion.

8.Scheduling: The Multi-Level Feedback Queue

The Multi-level Feedback Queue (MLFQ) scheduler was first described by Corbato et al. in 1962 [C+62] in a system known as the Compatible Time-Sharing System (CTSS), and this work, along with later work on Multics, led the ACM to award Corbato its highest honor, the Turing Award.

TIP: SCHEDULING MUST BE SECURE FROM ATTACK

Second, a smart user could rewrite their program to game the scheduler. Gaming the scheduler generally refers to the idea of doing something sneaky to trick the scheduler into giving you more than your fair share of the resource.

8.6 MLFQ: Summary

The refined set of MLFQ rules, spread throughout the chapter, are reproduced here for your viewing pleasure:

• Rule 1: If Priority(A) > Priority(B), A runs (B doesn’t).

• Rule 2: If Priority(A) = Priority(B), A & B run in round-robin fashion using the time slice (quantum length) of the given queue.

• Rule 3: When a job enters the system, it is placed at the highest priority (the topmost queue).

• Rule 4: Once a job uses up its time allotment at a given level (regardless of how many times it has given up the CPU), its priority is reduced (i.e., it moves down one queue).

• Rule 5: After some time period S, move all the jobs in the system to the topmost queue.

MLFQ is interesting for the following reason: instead of demanding a priori knowledge of the nature of a job, it observes the execution of a job and prioritizes it accordingly. In this way, it manages to achieve the best of both worlds: it can deliver excellent overall performance (similar to SJF/STCF) for short-running interactive jobs, and is fair and makes progress for long-running CPU-intensive workloads. For this reason, many systems, including BSD UNIX derivatives [LM+89, B86], Solaris [M06], and Windows NT and subsequent Windows operating systems [CS97] use a form of MLFQ as their base scheduler.

9.Scheduling: Proportional Share

In this chapter, we’ll examine a different type of scheduler known as a proportional-share scheduler, also sometimes referred to as a fair-share scheduler.

9.1 Basic Concept: Tickets Represent Your Share

TIP: USE RANDOMNESS

One of the most beautiful aspects of lottery scheduling is its use of randomness. When you have to make a decision, using such a randomized approach is often a robust and simple way of doing so.

Lottery scheduler.

9.6 Stride Scheduling

For this reason, Waldspurger invented stride scheduling, a deterministic fair-share scheduler [W95].

9.7 The Linux Completely Fair Scheduler (CFS)

Despite these earlier works in fair-share scheduling, the current Linux approach achieves similar goals in an alternate manner. The scheduler, entitled the Completely Fair Scheduler (or CFS) [J09], implements fairshare scheduling, but does so in a highly efficient and scalable manner.

Recent studies have shown that scheduler efficiency is surprisingly important; specifically, in a study of Google datacenters, Kanev et al. show that even after aggressive optimization, scheduling uses about 5% of overall datacenter CPU time [K+15].

13.The Abstraction: Address Spaces

13.3 The Address Space

The address space of a process contains all of the memory state of the running program.

For example, the code of the program (the instructions) have to live in memory somewhere, and thus they are in the address space. The program, while it is running, uses a stack to keep track of where it is in the function call chain as well as to allocate local variables and pass parameters and return values to and from routines. Finally, the heap is used for dynamically-allocated, user-managed memory, such as that you might receive from a call to malloc() in C or new in an objectoriented language such as C++ or Java. Of course, there are other things in there too (e.g., statically-initialized variables), but for now let us just assume those three components: code, stack, and heap.

The program code lives at the top of the address space. Next, we have the two regions of the address space that may grow (and shrink) while the program runs. Those are the heap (at the top) and the stack (at the bottom).

However, this placement of stack and heap is just a convention; you could arrange the address space in a different way if you’d like (as we’ll see later, when multiple threads co-exist in an address space, no nice way to divide the address space like this works anymore, alas).

13.4 Goals

One major goal of a virtual memory (VM) system is transparency. Thus, the program shouldn’t be aware of the fact that memory is virtualized; rather, the program behaves as if it has its own private physical memory.

Another goal of VM is efficiency (time and space).

Finally, a third VM goal is protection.

ASIDE: EVERY ADDRESS YOU SEE IS VIRTUAL

Ever write a C program that prints out a pointer? The value you see (some large number, often printed in hexadecimal), is a virtual address.

In fact, any address you can see as a programmer of a user-level program is a virtual address.

It’s only the OS (and the hardware), through its tricky techniques of virtualizing memory, that knows where in the physical memory of the machine these instructions and data values lie.

c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) 
{
    int x = 3;
    printf("location of code : %p\n", main);
    printf("location of heap : %p\n", malloc(100e6));
    printf("location of stack: %p\n", &x);
    return x;
}

However the result of this code is different from book which verifies that placement of stack and heap is just a convention.

Output in my PC (Windows):

Code
location of code : 00007ff6f7be1584
location of heap : 000002d680006040
location of stack: 000000e25f1ff68c

Output in book:

Code
location of code : 0x1095afe50
location of heap : 0x1096008c0
location of stack: 0x7fff691aea64

Since book uses Mac system, thus has a different memory manager.

14.Interlude: Memory API

Malloc()

free()

15.Address Translation

15.3 Dynamic (Hardware-based) Relocation

Use two registers to implement. The hardware must also provide the base and bounds registers themselves.Namely, a base register is used to transform virtual addresses (generated by the program) into physical addresses. A bounds (or limit) register ensures that such addresses are within the confines of the address space.

Code
physical address = virtual address + base

16.Segmentation

16.1 Segmentation: Generalized Base/Bounds

To solve this problem, an idea was born, and it is called segmentation.

A segment is just a contiguous portion of the address space of a particular length, and in our canonical address space, we have three logically-different segments: code, stack, and heap.

What segmentation allows the OS to do is to place each one of those segments in different parts of physical memory, and thus avoid filling physical memory with unused virtual address space

The hardware structure in our MMU required to support segmentation is just what you’d expect: in this case, a set of three base and bounds register pairs.

What if we tried to refer to an illegal address (i.e., a virtual address of 7KB or greater), which is beyond the end of the heap? You can imagine what will happen: the hardware detects that the address is out of bounds, traps into the OS, likely leading to the termination of the offending process. And now you know the origin of the famous term that all C programmers learn to dread: the segmentation violation or segmentation fault.

16.2 Which Segment Are We Referring To?

One common approach, sometimes referred to as an explicit approach, is to chop up the address space into segments based on the top few bits of the virtual address. (Like first two bits represent segments).

There are other ways for the hardware to determine which segment a particular address is in. In the implicit approach, the hardware determines the segment by noticing how the address was formed. If, for example, the address was generated from the program counter (i.e., it was an instruction fetch), then the address is within the code segment; if the address is based off of the stack or base pointer, it must be in the stack segment; any other address must be in the heap.

Instead of just base and bounds values, the hardware also needs to know which way the segment grows (a bit, for example, that is set to 1 when the segment grows in the positive direction, and 0 for negative).

16.4 Support for Sharing

Specifically, to save memory, sometimes it is useful to share certain memory segments between address spaces. In particular, code sharing is common and still in use in systems today.

To support sharing, we need a little extra support from the hardware, in the form of protection bits.

Basic support adds a few bits per segment, indicating whether or not a program can read or write a segment, or perhaps execute code that lies within the segment.

By setting a code segment to read-only, the same code can be shared across multiple processes, without worry of harming isolation

16.5 Fine-grained vs. Coarse-grained Segmentation

Most of our examples thus far have focused on systems with just a few segments (i.e., code, stack, heap); we can think of this segmentation as coarse-grained, as it chops up the address space into relatively large, coarse chunks. However, some early systems (e.g., Multics [CV65,DD68]) were more flexible and allowed for address spaces to consist of a large number of smaller segments, referred to as fine-grained segmentation.

Supporting many segments requires even further hardware support, with a segment table of some kind stored in memory.

The general problem that arises is that physical memory quickly becomes full of little holes of free space, making it difficult to allocate new segments, or to grow existing ones. We call this problem external fragmentation [R69].

Unfortunately, though, no matter how smart the algorithm, external fragmentation will still exist; a good algorithm attempts to minimize it.

17.Free-Space Management


Next →

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.