CS 61 Makeup Test

1. Racing form (9 points)

Every question in this section uses these global variables:

int n = 1;
int x = 100;
std::atomic<int> a = 1;
std::mutex m;

In each question, the main thread starts two concurrent threads, T1 and T2, then joins them. Mark whether the corresponding code has a data race, and if it does not, list all possible final values of the named variable. (Each question starts fresh from the initial values above.)

QUESTION 1A.

QUESTION 1B.

QUESTION 1C.

QUESTION 1D.

QUESTION 1E.

QUESTION 1F.

QUESTION 1G.

Reminder: a.exchange(v) sets a to v and returns the previous value of a, all in one atomic step.


2. Cyberlocks (15 points)

You’re at an internship at a famous company, FaceXSINeuraBoring, helping to develop a new operating system for cyberintelligent systems. This OS has atomics and std::condition_variable_any, but no std::mutex. You decide to build your own mutex. You start with a spinlock:

struct spinlock61 {
    std::atomic<int> v = 0;         // 0 means unlocked, 1 means locked
    void lock() {
        while (v.exchange(1) == 1) { /* do nothing */ }
    }
    void unlock() {
        v = 0;
    }
};

A spinlock provides mutual exclusion, but a thread waiting for it polls. You want a mutex whose waiting threads block. Here’s your design; three pieces are missing.

struct mutex61 {
    spinlock61 s;
    bool locked = false;    // true iff some thread holds the mutex
    std::condition_variable_any cv;

    void lock() {
        s.lock();
        while (____(a)____) {
            ____(b)____;
        }
        locked = true;
        s.unlock();
    }
    void unlock() {
        s.lock();
        locked = false;
        ____(c)____;
        s.unlock();
    }
};

Reminders: v.exchange(x) sets v to x and returns the previous value of v, all in one atomic step. And cv.wait(lk) works with any object lk that has lock() and unlock() functions, including a spinlock61: it atomically calls lk.unlock() and blocks, and calls lk.lock() again before returning.

QUESTION 2A. Fill in the three blanks.

QUESTION 2B. Which of these statements about the completed mutex61 are true? Select all that apply.

  1. The spinlock s is never locked while the mutex is locked.
  2. A thread that holds the mutex (it has returned from mutex61::lock() and has not yet called mutex61::unlock()) also holds the spinlock s.
  3. A thread that is blocked in cv.wait(s) does not hold the spinlock s.
  4. A thread calling mutex61::lock() might poll, but only while some other thread is executing the few instructions between s.lock() and s.unlock() in one of mutex61’s functions.
  5. cv.wait(s) changes the spinlock so that s.lock() blocks instead of polling.
  6. None of the above

QUESTION 2C. Your boss, Smelin Husk, now tells you to get rid of std::condition_variable_any too. You must replace it with your own class, cv61, built from two new system calls that Smelin has added to the kernel:

Here’s your first attempt. You change mutex61 to use it (so its cv member has type cv61), and make no other changes.

struct cv61 {
    void wait(spinlock61& lk) {
        lk.unlock();
        pb_block();
        lk.lock();
    }
    void notify_all() {
        pb_unblock();
    }
};

Thread T1 holds a mutex61, and thread T2 calls mutex61::lock() on the same mutex. Put the following four events in an order that leaves T2 blocked forever, even though the mutex ends up unlocked and no other thread ever uses it.

  1. T2, in cv61::wait, executes lk.unlock() (line 3).
  2. T2, in cv61::wait, calls pb_block() (line 4).
  3. T1, in mutex61::unlock, locks s and sets locked = false.
  4. T1, in cv61::notify_all, calls pb_unblock() (line 8).

Order:

QUESTION 2D. How would you describe this bug? Select all that apply.

  1. Data race
  2. Race condition
  3. Sleep–wakeup race
  4. Lost wakeup
  5. Deadlock
  6. Undefined behavior
  7. None of the above

QUESTION 2E. You eventually convince Smelin that a correct condition variable is impossible with his interface as it is, and he offers you a choice of four new interfaces. Choose one and use it to write a correct cv61. You may add members to cv61, and you may use spinlock61, atomics, and standard containers such as std::vector.

  1. Clear and block. In one atomic step, pb_block(std::atomic<int>* x) both sets *x = 0 and blocks the calling thread. pb_unblock() is unchanged: it wakes up every thread currently blocked in pb_block.
  2. Persistent wakeups. int pb_gettid() returns the calling thread’s ID. pb_block() blocks the calling thread. pb_unblock(int tid) wakes up thread tid if it is blocked in pb_block; if thread tid is not blocked, then its next call to pb_block() returns immediately instead of blocking.
  3. Numbered wakeups. pb_block(int n) blocks the calling thread. pb_unblock(int n) wakes up every thread currently blocked in a call to pb_block with the same argument n; threads blocked with a different argument stay blocked. If no thread is blocked with argument n, it does nothing.
  4. Block if unchanged. pb_block(std::atomic<int>* x, int expected) performs the following in one atomic step: if *x == expected, it blocks the calling thread; otherwise it returns immediately. pb_unblock() is unchanged: it wakes up every thread currently blocked in pb_block.

Note: When a system call performs several actions “in one atomic step,” nothing any other thread does can happen between those actions. Every other thread’s operations, including its system calls, take effect either entirely before the step or entirely after it.

Write your cv61 here, including any members you add and both wait(spinlock61& lk) and notify_all(). You may assume that every caller of wait calls it in a loop that rechecks its condition.


3. Single slot silliness (16 points)

Here is a correct, simple implementation of part of the IO61 library from problem set 5. It uses a single-slot cache with the representation from section.

struct io61_file {
    int fd;
    int mode;                               // O_RDONLY or O_WRONLY
    static constexpr off_t bufsize = 4096;
    unsigned char cbuf[bufsize];
    off_t tag = 0;       // file offset of first byte in `cbuf`
    off_t pos_tag = 0;   // file offset of next byte to read or write
    off_t end_tag = 0;   // file offset 1 past last valid `cbuf` byte
};

void io61_fill(io61_file* f) {              // read caches only
    f->tag = f->pos_tag = f->end_tag;
    ssize_t n = read(f->fd, f->cbuf, f->bufsize);
    if (n > 0) {
        f->end_tag = f->tag + n;
    }
}

int io61_readc(io61_file* f) {
    if (f->pos_tag == f->end_tag) {
        io61_fill(f);
        if (f->pos_tag == f->end_tag) {
            return -1;                      // end of file
        }
    }
    unsigned char ch = f->cbuf[f->pos_tag - f->tag];
    ++f->pos_tag;
    return ch;
}

void io61_flush(io61_file* f) {             // write caches only
    ssize_t n = write(f->fd, f->cbuf, f->end_tag - f->tag);
    assert(n == f->end_tag - f->tag);
    f->tag = f->end_tag;
}

int io61_writec(io61_file* f, int c) {
    if (f->end_tag == f->tag + f->bufsize) {
        io61_flush(f);
    }
    f->cbuf[f->end_tag - f->tag] = c;
    ++f->pos_tag;
    ++f->end_tag;
    return 0;
}
 
int io61_seek(io61_file* f, off_t off) {
    if (f->mode == O_WRONLY) {
        io61_flush(f);
    }
    if (lseek(f->fd, off, SEEK_SET) == -1) {
        return -1;
    }
    f->tag = f->pos_tag = f->end_tag = off;
    return 0;
}

int io61_close(io61_file* f) {
    if (f->mode == O_WRONLY) {
        io61_flush(f);
    }
    int r = close(f->fd);
    delete f;
    return r;
}

QUESTION 3A. Recall that the cat61 and reverse61 test programs each read a single input file and generate a single output file, reading and writing a character at a time using io61_readc and io61_writec. However, reverse61 reads the input file backwards by calling io61_seek before each character. (cat61 never calls io61_seek.)

The code above produces correct answers for reverse61 tests, but runs much slower than stdio. Why? Explain briefly.

QUESTION 3B. You need to grade six students’ turnins for this problem set. Their code is the same as the correct version above, except that each of them made one change. Match each student’s change to the behavior it causes. Write one behavior number per student; a behavior may be used more than once or not at all.

Reminder: The detachable reference page at the end of the exam has a full copy of the io61 code for your reference.

QUESTION 3C. Another student, Greg, deletes lines 59–61, so that io61_close never calls io61_flush, and then runs cat61 on an input file whose size is 40,980 = 10 × 4096 + 20 bytes. What is the size of the resulting output file? (You may write your answer as an expression, such as “10 × 4096 + 20”.)


4. Reference check (20 points)

This question concerns the following reference string, which contains ten accesses to five different blocks.

1  2  3  1  5  2  1  4  2  4

All caches in this question are fully associative and start out empty.

QUESTION 4A. Complete this diagram to show how a three-slot LRU cache processes the reference string. As in lecture, each column shows the cache’s contents after the corresponding access. Circle each block when it is loaded into the cache (a miss).

Refstr→ 1 2 3 1 5 2 1 4 2 4
Slot A ① 1 1
B ② 2
C ③

QUESTION 4B. How many hits does the three-slot LRU cache observe?

Hits:

QUESTION 4C. How many hits does a three-slot FIFO cache observe on this reference string? (You may use the diagram for scratch work, but only your number will be graded.)

Refstr→ 1 2 3 1 5 2 1 4 2 4
Slot A
B
C

Hits:

QUESTION 4D. Which of these statements are true for every reference string? Select all that apply.

  1. A four-slot FIFO cache observes at least as many hits as a three-slot FIFO cache.
  2. A four-slot LRU cache observes at least as many hits as a three-slot LRU cache.
  3. A three-slot cache using Bélády’s optimal algorithm observes at least as many hits as a three-slot LRU cache.
  4. A three-slot LRU cache observes at least as many hits as a three-slot FIFO cache.
  5. None of the above

QUESTION 4E. The remaining questions concern implementations of a 3-slot, fully-associative cache. Here’s a sketch of the implementation framework:

struct slot {
    int address;        // address of this block (e.g., 1–5); 0 = empty
    unsigned long info; // used to choose a slot to evict

    void load();        // called after a miss that used this slot
    void hit();         // called after a hit that used this slot
};

slot cache[3];
unsigned long now = 1;  // current time; incremented by 1 on each step

Does struct slot contain any padding, and if so, where?

QUESTION 4F. Assuming cache is located at address 0x601040, compute the following numeric values. You may use hexadecimal.

QUESTION 4G. Write the bodies of slot::load() and slot::hit() so that the cache implements the FIFO eviction policy. Your code may use now; if a body should be empty, write “empty”. Note that when the cache needs to evict a block, it always evicts the slot with the smallest info.

QUESTION 4H. The cache you implemented in the previous question starts out empty, with now == 1, and then processes a reference string. Each access is one step. Afterward, a debugger shows these bytes of memory starting at the address of cache. (Each row shows 16 bytes in increasing address order.)

0x601040:   04 00 00 00  00 00 00 00  05 00 00 00  00 00 00 00
0x601050:   05 00 00 00  00 00 00 00  06 00 00 00  00 00 00 00
0x601060:   01 00 00 00  00 00 00 00  03 00 00 00  00 00 00 00
0x601070:   02 FF FF FF  BA BA BA BA  BA BA BA BA  00 00 00 00

Finish the following reference string so that processing your reference string could have created this dump.

Reference string: 2 3 1

QUESTION 4I. Here are three versions of slot::hit(), compiled to x86-64 assembly. (Recall that a member function’s this pointer is passed like a first argument.) One implements LRU, one implements FIFO, and one implements LFU (least frequently used), in which the block evicted is the one that has been accessed the fewest number of times. Which is which?

QUESTION 4J. When the cache needs to evict a slot, it calls a function victim whose arguments and return type you don’t know. Here is its assembly.

victim:
        movslq  %esi, %rsi
        movq    %rdi, %rax
        movq    %rdi, %rdx
        salq    $4, %rsi
        addq    %rdi, %rsi
.L2:
        cmpq    %rsi, %rdx
        je      .L4
        movq    8(%rax), %rcx
        cmpq    %rcx, 8(%rdx)
        jnb     .L3
        movq    %rdx, %rax
.L3:
        addq    $16, %rdx
        jmp     .L2
.L4:
        ret

Which of these statements are true based on this assembly? Select all that apply.

  1. This function accepts at least two arguments.
  2. This function’s first argument is a pointer.
  3. This function’s second argument is a pointer.
  4. This function returns a pointer.
  5. This function contains a loop.
  6. This function can modify memory.
  7. This function calls another function.
  8. None of the above