2025 Final

This final was used in 2025’s version of CS 61. It is provided for your interest.

Show all solutions

Rules

The exam is open book, open note, limited open computer. You may access the textbook and your own notes. You may also use computers or electronic devices to access your own class materials and public class materials. Specifically:

However:

Any violations of this policy are breaches of academic honesty and will be treated accordingly. Please appreciate our flexibility and behave honestly and honorably.

Additionally, students are taking the exam at different times. Do not post publicly about the exam until given permission to do so by course staff. This includes general comments about exam difficulty.

Questions

If you have questions during the exam, write us email at cs61-staff@g.harvard.edu. Don’t use the Edboard. We may not notice Edboard posts, and you aren’t supposed to access the Edboard anyway.

Completing your exam

You have 180 minutes to complete the exam starting from the time you press Start. Different students may have different exams. Enter your answers directly in this form. A green checkmark appears when an answer is saved.

Students with extra time accommodations: If your extra time is not reflected next to the start button, contact course staff and wait for confirmation before pressing it.

You should not need to attach a drawing or other longer notes, but you may do so by adding them to a final subdirectory in your cs61-f25-psets repository. Make sure you push your changes to GitHub before time is up, and explain in this form where we should look at your notes.

There is no need to explicitly “submit” the exam. Your changes are automatically saved with timestamps. We’ll grade the latest version saved within your exam window.

Notes

Assume a Linux operating system running on the x86-64 architecture unless otherwise stated. If you get stuck, move on to the next question. If you’re confused, explain your thinking briefly for potential partial credit.

Some figures and code samples can be pinned to your browser so you can keep them visible as you scroll through the test. Push 📌 and then drag and resize the pinned figure.

1. Let’s economize (14 points)

In each of the following questions, you are asked to choose the economy option: the choice that results in fewer bytes, fewer system calls, fewer processes, etc., depending on the question. You should assume that both options start from the same machine and process state, and that there are no unusual failures (e.g., memory exhaustion, file descriptor exhaustion). If the options are about the same or there’s not enough information to tell, select “same/it depends” and explain briefly.

QUESTION 1A. In a completed pset 1, which of these m61_malloc calls would result in fewer bytes of memory being allocated for the user?

  1. m61_malloc(10)
  2. m61_malloc(15)
  3. Same/it depends (explain briefly)

QUESTION 1B. In a completed pset 1, which of these m61_malloc calls would result in fewer bytes of memory becoming unavailable for use in other allocations?

  1. m61_malloc(10)
  2. m61_malloc(15)
  3. Same/it depends (explain briefly)

QUESTION 1C. In a completed pset 1, which of these m61_calloc calls will result in fewer bytes of memory being allocated for the user?

  1. m61_calloc(20, 20)
  2. m61_calloc(100, 1)
  3. Same/it depends (explain briefly)

QUESTION 1D. In a completed pset 1, which of these m61_calloc calls will result in fewer bytes of memory being allocated for the user?

  1. m61_calloc(20, 20)
  2. m61_calloc(-1, -10000)
  3. Same/it depends (explain briefly)

QUESTION 1E. Which of these structs will have the smaller size?

  1. struct A {
        int x;
        char c;
    };
    
  2. struct B {
        char c1;
        char c2;
        int x;
    };
    
  3. Same/it depends (explain briefly)

QUESTION 1F. Here’s the assembly for a C++ function f:

_Z1fl:
   movq %rdi, %rax
   cmpq $61, %rdi
   je .L2
.L3:
   cmpq $16, %rax
   jle .L2
   movq %rax, %rdx
   sarq $1, %rdx
   subq %rdx, %rax
   jmp .L3
.L2:
   ret

Which argument to f would result in fewer instructions being executed before the function returns?

  1. 60
  2. 61
  3. Same/it depends (explain briefly)

QUESTION 1G. For the same assembly function, which argument to f would result in a smaller return value?

  1. 64
  2. 65
  3. Same/it depends (explain briefly)

QUESTION 1H. Which of these C++ functions has the shorter mangled name post-compilation?

  1. long add(long a, long b)
  2. long foo(long a, long b, long c, long d)
  3. Same/it depends (explain briefly)

QUESTION 1I. Which of these WeensyOS implementations will use fewer page table entries when running a p-fork test?

  1. An implementation that does not share read-only pages between parent and child processes (before phase 8 of pset 3)
  2. An implementation that shares read-only pages between parent and child processes (after phase 8 of pset 3)
  3. Same/it depends (explain briefly)

QUESTION 1J. Which of these file access patterns, when implemented using the default stdio library, will result in in fewer system calls?

  1. Sequential reads (as in pset 4’s cat61)
  2. Reverse sequential reads (as in reverse61)
  3. Same/it depends (explain briefly)

QUESTION 1K. Which of these file access patterns will involve fewer caches?

  1. Sequential reads using the default stdio library
  2. Sequential reads using system calls
  3. Same/it depends (explain briefly)

QUESTION 1L. Which of these command lines, when run on a pset 5-style shell, will create fewer processes?

  1. /bin/echo cs61 && /bin/echo is | grep i && /bin/echo good
  2. /bin/echo cs61 && /bin/echo is | grep i & /bin/echo good
  3. Same/it depends (explain briefly)

QUESTION 1M. Which of these command lines, when run on a pset 5-style shell, will execute fewer dup2 system calls?

  1. cat file1.txt | grep foo
  2. cat file1.txt > file2.txt
  3. Same/it depends (explain briefly)

QUESTION 1N. Which of these situations in pset 6 should result in fewer blocked threads? Assume that both threads are accessing the same file f.

  1. Thread 1 calls io61_try_lock(f, 25, 40) while Thread 2 calls io61_try_lock(f, 30, 50)
  2. Thread 1 calls io61_lock(f, 25, 40) while Thread 2 calls io61_lock(f, 25, 40)
  3. Same/it depends (explain briefly)

2. Nodes of mystery (10 points)

Consider the following x86-64 assembly function:

_Z7mysteryPKP4Nodemi:
        testq   %rsi, %rsi
        je      .L6
        movl    $0, %ecx
.L5:
        movq    (%rdi,%rcx,8), %rax
        testq   %rax, %rax
        je      .L3
.L4:
        cmpl    %edx, (%rax)
        je      .L7
        movq    8(%rax), %rax
        testq   %rax, %rax
        jne     .L4
.L3:
        addq    $1, %rcx
        cmpq    %rcx, %rsi
        ja      .L5
        movl    $0, %eax
        ret
.L6:
        movl    $0, %eax
        ret
.L7:
        movl    $1, %eax
        ret

QUESTION 2A. Which of these corresponds to the data structure being accessed in lines 10–14 of the assembly? List the best answer.

  1. struct Node { int value[20]; }
  2. struct Node { Node* prev; Node* next; }
  3. struct Node { int value; Node* next; }
  4. struct Node { long value; Node* next; }
  5. struct Node { Node* next; int value; }
  6. None of these

QUESTION 2B. What is the purpose of line 13, testq %rax, %rax? List the best answer.

  1. A null pointer check
  2. Testing whether an integer counter has reached 0
  3. Testing whether a system call returned an error
  4. An integer overflow check
  5. None of these

QUESTION 2C. How many parameters does the function take, and what registers are they passed in?

QUESTION 2D. Which of these parameters corresponds to a value being searched for in the data structure?

QUESTION 2E. Which of these parameters most likely has unsigned integer type?

QUESTION 2F. What overall data structure does this function traverse? List the best answer.

  1. A linked list
  2. An array of linked lists
  3. A binary tree
  4. An array of integers
  5. A 2D matrix of integers, implemented as an array of int* pointers
  6. None of these

3. Kernel pipe sharing (13 points)

Mario Mario wants to implement pipes on WeensyOS using memory pages that are shared among processes. To write data into a “pipe,” a process writes bytes into the pipe page; to read data from a “pipe,” a process copies bytes out of that page and updates metadata to signal that the data was consumed. Supporting shared memory requires changing the kernel. Let’s-a go!

QUESTION 3A. Mario begins by implementing sys_shpage_alloc, which should allocate a shared-memory page. This system call resembles sys_page_alloc and has the same arguments and return values. Mario’s initial code is:

int syscall_shpage_alloc(uintptr_t addr) {
    if (addr < PROC_START_ADDR || addr >= MEMSIZE_VIRTUAL || (addr % PAGESIZE) != 0) {
        return -1;
    }
    vmiter it(current->pagetable, addr);
    if (it.present()) {
        return -1;
    }
    void* ptr = kalloc(PAGESIZE);
    if (!ptr || it.try_map(ptr, PTE_PWU) < 0) {
        kfree(ptr);
        return -1;
    }
    memset(ptr, 0, PAGESIZE);
    return 0;
}

What is the purpose of the addr < PROC_START_ADDR check on line A2? Explain briefly.

QUESTION 3B. What is the purpose of the it.present() check on line A6? Select the best answer.

  1. It prevents segmentation faults
  2. It prevents memory leaks
  3. It prevents replacing kernel data
  4. It prevents replacing memory previously allocated to the process
  5. It prevents data races
  6. None of these apply

QUESTION 3C. A page allocated by syscall_shpage_alloc should be mapped with an additional permission flag, PTE_OS1, as well as the usual flags. Change Mario’s syscall_shpage_alloc to add this flag. Refer to specific line numbers.

QUESTION 3D. We now turn to Mario’s sys_fork implementation. (We’ll see the fork_pt helper in the next question.)

int syscall_fork() {
    pid_t child_pid = /* find available PID; return 0 if none available */;
    x86_64_pagetable* child_pt = kalloc_pagetable();
    if (child <= 0 || !child_pt || !fork_pt(current->pagetable, child_pt)) {
        ... free all allocated memory ...
        return -1;
    }

    ptable[child_pid].pagetable = child_pt;
    ptable[child_pid].regs = current->regs;
    ptable[child_pid].regs.reg_rax = 0;
    ptable[child_pid].state = P_RUNNABLE;
    return child;
}

What is the purpose of ptable[child_pid].regs.reg_rax = 0 on line F11? Explain briefly.

QUESTION 3E. The fork_pt helper copies memory and memory mappings from pagetable src to pagetable dst. It should copy writable process memory, but share other kinds of memory. Mario’s implementation is:

bool fork_pt(x86_64_pagetable* src, x64_64_pagetable* dst) {
    for (vmiter it(src, 0); it.va() < MEMSIZE_VIRTUAL; it += PAGESIZE) {
        uintptr_t pa = it.pa();
        void* newpage = nullptr;
        // copy page if necessary
        if (it.va() >= PROC_START_ADDR && (it.perm() & PTE_PWU) == PTE_PWU) {
            newpage = kalloc(PAGESIZE);
            if (!newpage) {
                return false;
            }
            memcpy(newpage, reinterpret_cast<void*>(pa), PAGESIZE);
            pa = reinterpret_cast<uintptr_t>(newpage);
        }
        // map page
        if (vmiter(dst, it.va()).try_map(pa, it.perm() & PTE_PWU) < 0) {
            kfree(newpage);
            return false;
        }
        // increment reference count for shared process pages
        if (it.va() >= PROC_START_ADDR && (it.perm() & PTE_U) != 0 && pa == it.pa()) {
            ++physpages[pa / PAGESIZE].refcount;
        }
    }
    return true;
}

Line P11, which runs for writable process pages, copies the contents of a source page into a newly-allocated page for the child. This line does not use the current process’s virtual address for the source page, which is it.va(); it passes reinterpret_cast<void*>(pa) instead. Why? List all that apply.

  1. Virtual memory is not active when the processor is running in kernel mode.
  2. The page table installed in the processor when the kernel is running is not the same as the current process’s page table.
  3. The kernel uses an identity-mapped page table, so the byte of memory with physical address pa is accessible at virtual address pa.
  4. The kernel must verify all virtual addresses provided as system call parameters.
  5. None of these apply.

QUESTION 3F. Change fork_pt so that writable process pages mapped with the PTE_OS1 bit are directly shared, rather than copied. Refer to specific lines of code.

4. Stdio pipe sharing (12 points)

Part 3 and Part 4 are independent, but they have the same background: Mario Mario is implementing a pipe using WeensyOS shared memory.

For Part 4, assume that two or more WeensyOS processes have read/write access to a shared memory page (at PIPE_ADDR) that implements a pipe. The following code gives the shpipe structure, and shows the parent process code that initializes that structure. (We assume that Mario has implemented std::mutex for his WeensyOS.)

struct shpipe {
    constexpr size_t size = 2048;
    std::mutex lock;
    size_t head;      // index of oldest byte in pipe buffer; 0 <= head < 2048
    size_t len;       // number of bytes in pipe buffer; 0 <= len <= 2048
    unsigned char buf[size]; // pipe buffer contents

    // return index of first byte of available space in pipe buffer;
    // 0 <= tail() < 2048
    size_t tail() const {
        return (this->head + this->len) % this->size;
    }
};

assert(sys_shpage_alloc(PIPE_ADDR) == 0);
shpipe* shp = reinterpret_cast<shpipe*>(PIPE_ADDR);
... initialize shp->lock ...
shp->head = 0;
shp->len = 0;

The questions will use shpipe* shp to refer to this page. Note that changes to *shp made by one process are immediately visible to other processes sharing that page.

QUESTION 4A. Mario’s shpipe_writec function writes a byte into the pipe. It returns 1 if the byte was written, and -1 if there was no room.

ssize_t shpipe_writec(shpipe* shp, unsigned char ch) {
    std::unique_lock guard(shp->lock);
    if (shp->len >= shp->size) {
        return -1;
    }
    shp->buf[shp->tail()] = ch;
    ++shp->len;
    return 1;
}

Write the corresponding int shpipe_readc(shpipe* shp) function, which should consume and return the oldest byte in the pipe, or return -1 if there were no bytes in the pipe.

QUESTION 4B. Mario’s shpipe_write function calls shpipe_writec (somewhat like how in the pset 4 handout code, io61_write calls io61_writec).

ssize_t shpipe_write(shpipe* shp, const char* buf, size_t sz) {
    size_t w = 0;
    while (w < sz && shpipe_writec(shp, buf[w]) == 1) {
        ++w;
    }
    if (w == 0 && sz > 0) {
        return -1;
    }
    return w;
}

What does this function return if it is asked to write bytes to a completely full pipe?

QUESTION 4C. Assume two Linux processes have access to the write end of an initially-empty pipe. They concurrently call write(write_end_fd, "Mario", 5). What are the contents of the resulting pipe buffer?

QUESTION 4D. Assume two WeensyOS processes with access to the same initially-empty shpipe* shp concurrently call shpipe_write(shp, "Mario", 5). Give an example of possible pipe buffer contents that would be impossible in the previous question.

QUESTION 4E. Sketch how to change Mario’s shpipe_write so that WeensyOS pipes and Linux pipes have the same semantics for multi-byte writes. (Just a sentence or two.)

QUESTION 4F. Mario’s first shpipe_write function has high per-request cost, because it makes a separate function call to write each byte. It would be faster to call memcpy to move bytes in chunks. Here’s Mario’s optimized attempt:

ssize_t shpipe_write(shpipe* shp, const char* buf, size_t sz) {
    std::unique_lock guard(shp->lock);
    size_t w = 0;
    while (w < sz && shp->len < shp->size) {
        size_t c = std::min(sz - w, shp->size - shp->len);  // number of bytes to copy
        memcpy(&shp->buf[shp->tail()], &buf[w], c);
        shp->len += c;
        w += c;
    }
    if (w == 0 && sz > 0) {
        return -1;
    }
    return w;
}

On line X5, what does sz - w represent? List the best answer.

  1. The number of data bytes currently in the pipe buffer
  2. The number of bytes of available space in the pipe buffer
  3. The number of contiguous bytes in the pipe buffer starting at shp->tail()
  4. The number of bytes the caller asked to write
  5. The number of caller bytes written so far
  6. The number of caller bytes remaining to write
  7. None of these apply

QUESTION 4G. On line X5, what does shp->size - shp->len represent? List the best answer.

  1. The number of data bytes currently in the pipe buffer
  2. The number of bytes of available space in the pipe buffer
  3. The number of contiguous bytes in the pipe buffer starting at shp->tail()
  4. The number of bytes the caller asked to write
  5. The number of caller bytes written so far
  6. The number of caller bytes remaining to write
  7. None of these apply

QUESTION 4H. Unfortunately, Mario observes some serious problems with his optimized shpipe_write. Bytes are corrupted—shpipe_readc sometimes returns garbage rather than the written bytes—and more awfully, there’s undefined behavior: wild writes into the pipe page and even into adjacent memory.

Describe how to fix shpipe_write, or briefly describe the problem.

QUESTION 4I. How does shpipe_write differ from a Linux write? List all that apply.

  1. shpipe_write never blocks to wait for space. Code that writes to a pipe must implement polling rather than blocking.
  2. shpipe_write cannot detect that all “read ends” of the pipe are closed, so it will never return EPIPE or receive a SIGPIPE signal.
  3. shpipe_write does not make any system calls; it is implemented entirely at user level. write, in contrast, is a system call.
  4. shpipe_write, unlike write, never returns a short write.
  5. None of these apply.

5. Wipes (13 points)

The writer Eileen Chang finds pipes unaesthetic—two file descriptors for one object! So she implements a new type of kernel abstraction, the wipe. The wipe() system call returns a new wipe file descriptor that supports both reading and writing. Data written to the wipe via write(wipefd) can be read from the wipe via read(wipefd). Reads and writes behave similarly to pipes; for instance, reads from an empty wipe block, as do writes to a full wipe.

QUESTION 5A. Eileen runs this test program under strace:

int main() {
    char buf[BUFSIZ];
    int w = wipe();
    write(w, "Hello, ", 7);
    read(w, buf, BUFSIZ);
    write(w, "world\n", 6);
    read(w, buf, BUFSIZ);
}

Fill in blanks B1–B5 in this resulting strace output. (Run strace or refer to storage exercises for examples of full strace output.)

1992 wipe()                        = 3
1992 write(3, ____B1____, 7)       = 7
1992 read(3, ____B2____, 4096)     = ____B3____
1992 write(3, "world\n", 6)        = 6
1992 read(3, ____B4____, 4096)     = ____B5____

QUESTION 5B. Eileen then runs this test program:

int main() {
    int w = wipe();
    if (fork() == 0) {
        write(w, "AAAA", 4);
        write(w, "BBBB", 4);
        _exit(0);
    }
    char buf[BUFSIZ];
    read(w, buf, BUFSIZ);
}

List all possible results of the read system call in the parent, including both bytes read and system call return values.

QUESTION 5C. In the following test program, Eileen expects the read to return 0, indicating end-of-file, but it does not. (“Fundamental truth is unyielding, like a mountain.”) Explain briefly what happens and why.

int main() {
    int w = wipe();
    if (fork() == 0) {
        ssize_t r = write(w, "", 0);
        assert(r == 0);
        _exit(0); // close wipe for writing
    }
    char buf[BUFSIZ];
    ssize_t r = read(w, buf, BUFSIZ);
    assert(r == 0);
}

QUESTION 5D. Eileen proposes to address this problem with a new shutdown system call.

int shutdown(int w, int how)

Shut down the wipe file descriptor w for reading or writing. If how is SHUT_RD, then w can no longer be used for reading (future reads will return errors). If how is SHUT_WR, then w can no longer be used for writing.

shutdown(w, how) does not affect other file descriptors for the same wipe, such as copies in other processes or copies previously created by dup2. However, shutdown status is inherited across fork and by newly created dup2 copies.

Once all of a wipe’s file descriptors are shut down for writing, future reads from the wipe will return end-of-file. Similarly, once all of a wipe’s file descriptors are shut down for reading, future writes to the wipe will return EPIPE (and may cause a SIGPIPE signal).

Note that shutdown is not a substitute for close.

Add a shutdown call to Eileen’s test program from the previous question so that its read returns end-of-file as she expected.

QUESTION 5E. Fill in blanks B1–B5 in the following function so that it properly initializes a two-process pipeline foo | bar and waits for bar to terminate.

void make_pipeline() {
    B1: // your code here
    pid_t p1 = fork();
    assert(p1 >= 0);
    if (p1 == 0) {
        B2: // your code here
        execlp("foo", "foo", nullptr);
    }
    B3: // your code here
    pid_t p2 = fork();
    assert(p2 >= 0);
    if (p2 == 0) {
        B4: // your code here
        execlp("bar", "bar", nullptr);
    }
    B5: // your code here
}

Use normal pipes, not wipes. You will use at least pipe, dup2, close, and waitpid, and you may assume system calls do not fail.

QUESTION 5F. Repeat the previous question but using wipes instead of pipes. You will use at least wipe, shutdown, dup2, close, and waitpid, and again, you may assume system calls do not fail.

6. Exhaustion (12 points)

QUESTION 6A. If a shell never reaped zombie processes, the operating system kernel could eventually run out of some resource. What kind of resource? List the best answer; explain briefly if unsure.

  1. Disk space
  2. File descriptors
  3. Memory
  4. Process IDs
  5. Thread stack space

QUESTION 6B. Which operation is used to reap zombie processes? List the best answer.

  1. close
  2. exit
  3. free/delete
  4. kill
  5. munmap
  6. unlink
  7. waitpid
  8. Something else

QUESTION 6C. What issues might the shell observe if zombie processes caused resource exhaustion? List all that apply.

  1. dup2 returns -1
  2. fork returns -1
  3. malloc returns nullptr
  4. open returns -1
  5. pipe returns -1
  6. Process segmentation fault or other unexpected termination
  7. None of these

QUESTION 6D. If a shell did not properly implement pipe hygiene, the shell process could eventually run out of some resource. What kind of resource? List the best answer.

  1. Disk space
  2. File descriptors
  3. Memory
  4. Process IDs
  5. Thread stack space

QUESTION 6E. What operation is used to implement pipe hygiene? List the best answer.

  1. close
  2. exit
  3. free/delete
  4. kill
  5. munmap
  6. unlink
  7. waitpid
  8. Something else

QUESTION 6F. What issues might the shell observe if a pipe hygiene issue caused resource exhaustion? List all that apply.

  1. dup2 returns -1
  2. fork returns -1
  3. malloc returns nullptr
  4. open returns -1
  5. pipe returns -1
  6. Process segmentation fault or other unexpected termination
  7. None of these

QUESTION 6G. If a shell did not properly deallocate command structures after executing the corresponding commands, the shell process could eventually run out of some resource. What kind of resource? List the best answer.

  1. Disk space
  2. File descriptors
  3. Memory
  4. Process IDs
  5. Thread stack space

QUESTION 6H. What operation is used to deallocate command structures? List the best answer.

  1. close
  2. exit
  3. free/delete
  4. kill
  5. munmap
  6. unlink
  7. waitpid
  8. Something else

QUESTION 6I. What issues might the shell observe if it did not properly deallocate command structures? List all that apply.

  1. dup2 returns -1
  2. fork returns -1
  3. malloc returns nullptr
  4. open returns -1
  5. pipe returns -1
  6. Process segmentation fault or other unexpected termination
  7. None of these

7. Office hours (10 points)

Alvin Ye is developing a simulator for CS 61 office hours. He represents students as threads accessing a shared office_hours object. TFs are represented by name.

struct office_hours {
    std::mutex lock;
    std::list<std::string> tf_pool;  // names of available TFs
};

void student_thread(office_hours* oh, std::string student) {
    while (true) {
        std::string tf = get_tf(oh);
        sleep(1000); // `tf` helps `student` for 1000 seconds
        put_tf(oh, tf);
    }
}

The get_tf function waits for an available TF, then removes that TF from the pool and returns their name. put_tf adds a TF back to the pool.

QUESTION 7A. Implement put_tf. Use oh->tf_pool.push_back(tf_name) to add the TF to the pool, and make sure to include proper synchronization.

void put_tf(office_hours* oh, std::string tf_name) {
    // Your code here

QUESTION 7B. Here is an implementation of get_tf.

std::string get_tf(office_hours* oh) {
    std::unique_lock<std::mutex> guard(oh->lock);
    // wait for a TF to become available
    while (oh->tf_pool.empty()) {
    }
    // remove them from the pool and return them
    std::string my_tf = oh->tf_pool.front();
    oh->tf_pool.pop_front();
    return my_tf;
}

List all that apply.

  1. get_tf can cause data races.
  2. get_tf uses the polling strategy to wait for a TF.
  3. get_tf works correctly when a TF is initially available.
  4. get_tf works correctly when no TF is initially available.
  5. get_tf can cause deadlock.
  6. None of the above.

QUESTION 7C. Fix any get_tf correctness problems you identified in the prior question, or explain briefly why get_tf is correct as is.

QUESTION 7D. Tell Alvin how to add a condition variable so that students can wait for a TF without wasting CPU time. You will add code to the office_hours structure, to get_tf, and to put_tf.

QUESTION 7E. Should the simulated students be happy about the fairness of their access to TFs? Explain briefly.

8. Synchronizing malloc (16 points)

In pset 1, Chase Infiniti developed and tested a debugging memory allocator. She now wants that allocator to work when there are multiple threads.

The handout code for m61_malloc and m61_free is as follows (shortened, and without file and line arguments):

struct m61_memory_buffer {
    char* buffer = /* initialized by constructor */;
    size_t pos = 0;
    size_t size = 8 << 20; ...
};
m61_memory_buffer default_buffer;

void* m61_malloc(size_t sz) {
    if (default_buffer.pos + sz > default_buffer.size) {
        return nullptr;
    }
    void* ptr = &default_buffer.buffer[default_buffer.pos];
    default_buffer.pos += sz;
    return ptr;
}

void m61_free(void* ptr) {
}

QUESTION 8A. Say that two threads, T1 and T2, execute the following thread function concurrently, using the handout code:

void threadfunc() {
    char* buf = reinterpret_cast<char*>(m61_malloc(16));
    memset(buf, 0, 16);
    m61_free(buf);
}

Which of lines M9, M10, M11, M12, M13, and (in threadfunc) F3 and F4 might be involved in a data race? List all that apply or say “none.”

QUESTION 8B. Line M14, return ptr;, is never involved in a data race. Why not? Explain briefly.

QUESTION 8C. Could this code ever execute undefined behavior that is not related to a data race? Explain briefly.

QUESTION 8D. Chase decides to avoid data races by making m61_memory_buffer::pos an atomic integer, std::atomic<size_t> instead of size_t. After this change, which of lines M9, M10, M11, M12, M13, F3, and F4 might be involved in a data race? List all that apply or say “none.”

QUESTION 8E. Making pos atomic solved some data races, but other synchronization problems remained, so Chase worked on. Her version of m61_malloc now begins with:

void* m61_malloc(size_t sz) {
    if (sz == 0 || sz > default_buffer.size) {
        return nullptr;
    }
    size_t new_pos = (default_buffer.pos += sz);
    ... // Your code here
}

(Recall that default_buffer.pos += sz, used as an expression, returns the incremented value of default_buffer.pos.)

Complete this m61_malloc so that it is correct for multithreaded use. Every concurrent call to m61_malloc should return either nullptr or a new allocation disjoint from all others, and m61_malloc should not cause data races.

QUESTION 8F. Enough atomics. How could Chase use std::mutex to make the handout code safe for multithreaded use? A full-credit answer adds two new lines to the initial handout code, and makes no other changes.

QUESTION 8G. Chase uses this mutex to complete the pset, including free coalescing. She then stress-tests her implementation by running many concurrent stress_threads:

void stress_thread(size_t sz) {
    for (size_t n = 0; n != 1'000'000'000; ++n) {
        void* ptr = m61_malloc(sz);
        memset(ptr, 0, sz);
        m61_free(ptr);
    }
}

But she observes that the threads don’t execute in parallel: rather, at most times during the test, all threads but one are waiting to acquire a mutex (though the thread holding the mutex frequently changes). What is the best name for this phenomenon?

  1. Deadlock
  2. Undefined behavior
  3. Coarse-grained synchronization
  4. Blocking
  5. Race condition
  6. None of the above

QUESTION 8H. Chase decides to optimize her implementation for the stress_thread workload. She adds three new global variables to m61.cc:

static thread_local void* recent_ptr = nullptr;
static thread_local size_t recent_size = 0;
static thread_local bool recent_allocated = false;

These variables are thread-local, meaning each thread has its own private version. Thread T1’s recent_ptr is a different variable than thread T2’s.

Describe how to use these variables in m61_malloc and m61_free so that the stress_threads almost never need to acquire a mutex, but Chase’s library is still correct and safe for any multithreaded use. Your code can fit within the OPT1–OPT4 sections of Chase’s base implementation:

void* m61_malloc(size_t sz) {
    OPT1: /* Your code here if needed */
    ... lock mutex ...
    ... find space, `return nullptr` if no space ...
    ... set `ptr` to address of new allocation ...
    OPT2: /* Your code here if needed */
    ... unlock mutex ...
    return ptr;
}

void* m61_free(void* ptr) {
    OPT3: /* Your code here if needed */
    ... lock mutex ...
    ... validate `ptr` ...
    ... free `ptr`; coalesce free space ...
    OPT4: /* Your code here if needed */
    ... unlock mutex ...
}

Your code may leak memory when a thread exits, and don’t worry about statistics.

9. The end (5 points)

QUESTION 9A. Which unit needs the most changes in future iterations of the class? Any answer but no answer will receive full credit.