Compare commits

..
2 Commits
4 changed files with 328 additions and 20 deletions

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
# Assignment 1
## Objectives
- Understand the OS/161 thread subsystem and existing synchronization primitives: spinlocks and semaphores.
- Have implemented working locks, condition variables, and reader-writer locks that you can use it later assignments.
- Be able to properly address different synchronization problems by choosing and applying the correct synchronization primitive.
## Tasks
- [ ] Implement sleeping lock
- [ ] Learn from Linux's implementation of [`rt_mutex`](https://elixir.bootlin.com/linux/v6.16.9/source/include/linux/rtmutex.h#L23)
- [ ] Notice how we need 2 things: the details of the cpu task and the wait channel we need to sleep on. Do more research on this.
- [ ] Implement condition variables
- [ ] Implement reader-writer locks
- [ ] Solve synchronization problems
- `kern/synchprobs/*`: these files are where you will implement your solutions to the synchronization problems.
- `kern/test/synchprobs.c`: this file contains driver code we will use to test your solutions. You can and should change this file to stress test your code.
## Code Reading Questions
- Thread questions
- What happens to a thread when it calls thread_exit? What about when it sleeps?
- What function—or functions—handle(s) a context switch?
- What does it mean for a thread to be in each of the possible thread states?
- What does it mean to turn interrupts off? How is this accomplished? Why is it important to turn off interrupts in the thread subsystem code?
- What happens when a thread wakes up another thread? How does a sleeping thread get to run again?
- Scheduling questions
- What function (or functions) choose the next thread to run?
- How is the next thread to run chosen?
- What role does the hardware timer play in scheduling?
- What hardware independent function is called on a timer interrupt?
- Synchronization questions
- Describe how wchan_sleep and wchan_wakeone are used to implement semaphores.
- Why does the lock API in OS/161 provide lock_do_i_hold, but not lock_get_holder?
## Notes
Finally, to successfully run the ASST1 tests you will need to configure your kernel to use a large amount of memory. We suggest the maximum of 16 MB. This is because your kernel currently leaks memory allocations that are larger than a page, and that includes all 4K thread stacks. So you will find that even if you correctly allocate and deallocate memory in your synchronization primitives and problems, your kernel will only run a certain number of tests before it runs out of memory and `panic`s. This is normal. However, you should make sure that your kernel does not leak smaller amounts of memory. Your kernel includes tools to help you measure this.
- `curthread` is a globally (actually per-CPU) available pointer to "the currently running thread,"
+47 -20
View File
@@ -1,32 +1,59 @@
# OS161 Learning # OS/161 Learning
My work on the [ops-class.org](https://ops-class.org/) OS/161 assignments (OS/161 2.0.3).
- Upstream: `https://github.com/ops-class/os161` (remote `upstream`)
- My repo: <https://git.minhtrannhat.com/minhtrannhat/os161> (remote `origin`)
## Progress
| Assignment | Topic | Status |
| --- | --- | --- |
| ASST0 | Introduction, tools, code reading | Done (tag `asst0`) |
| ASST1 | Locks, condition variables, reader-writer locks, synchronization problems | Not started |
| ASST2 | System calls and processes | Not started |
| ASST3 | Virtual memory | Not started |
## Setup ## Setup
- Follow instructions from UBC University: <https://people.ece.ubc.ca/~os161/os161-site/install-docker.html> The toolchain runs natively on Arch Linux. It does not use Docker.
- Get their docker image and build the container
- Go here to get the OS161 base source tarball <http://www.os161.org/download/>
- Do your magic (gunzip, tar -xvf) and make sure the folder is named `src`
- Next your need a config file, a sample config file (provided by UBC) can be obtained by <https://people.ece.ubc.ca/~os161/os161-site/install.html>
- Then we run the kernel with the help of the `sys161` simulator:
cd ~/os161/root 1. Install these AUR packages: `mips-harvard-os161-binutils`, `mips-harvard-os161-gcc48`, `mips-harvard-os161-gdb`, `sys161` and `guile2.0`.
2. If a package does not build, read [os161-build-fixes.md](./os161-build-fixes.md). It has the fixes for GCC 14 and Python 3.12+.
## Build
Run the script from the repo root:
./recompile.sh # builds the ASST1 kernel config
./recompile.sh DUMBVM # builds a different kernel config
The script does these steps:
- It builds and installs userland.
- It configures, builds and installs the kernel into `root/`.
- It writes `compile_commands.json` for clangd.
## Run
cd root
sys161 kernel sys161 kernel
## The pieces `root/sys161.conf` gives the machine 16 MB of RAM and 8 CPUs. The ASST1 tests need the large RAM size, because the kernel leaks the memory of thread stacks.
- OS/161 Kernel source tree ## Source tree
- The kernel sources for OS/161 is in the `kern` subdirectory, which has its own configuration script.
- The `conf.kern` file determines what source files get included in our kernel build so we might have to modify the file later on.
- Debugging - `kern/`: the kernel. `kern/conf/conf.kern` sets which source files go into the kernel build.
- Follow the steps at <https://people.ece.ubc.ca/~os161/os161-site/gdb-attach.html> - `kern/thread/synch.c`: the synchronization primitives (ASST1).
- `kern/synchprobs/`: the synchronization problems (ASST1).
- `userland/`: the user programs and test programs.
- `test161/`: the test161 targets and tests.
## Assignments ## Debugging
### Assignments 0 Follow the steps at <https://people.ece.ubc.ca/~os161/os161-site/gdb-attach.html>.
- [Assignment 0 Answers](./Assignment0.md) ## Assignment answers
### Assignments 1 - [Assignment 0](./Assignment0.md)
- [Assignment 1](./Assignment1.md)
- [Assignment 1 Answers](./Assignment1.md)
+167
View File
@@ -0,0 +1,167 @@
# OS161 Toolchain Build Fixes on Arch Linux (2026)
This document summarizes the issues encountered and fixes applied when building the
OS161 cross-compiler toolchain on a modern Arch Linux system.
## Environment
- **OS:** Arch Linux (kernel 6.19.9)
- **GCC:** 14.x (host compiler)
- **Python:** 3.14
- **AUR packages:** `mips-harvard-os161-binutils`, `mips-harvard-os161-gcc48`, `mips-harvard-os161-gdb`, `sys161`, `guile2.0`
---
## Issue 1: `guile2.0` — Expired GPG Key
**Package:** `guile2.0-2.0.14-6`
**Error:**
```
-> FF478FB264DE32EC296725A3DDC0F5358812F8F2, required by: guile2.0
:: Importing keys with gpg...
gpg: key DDC0F5358812F8F2: no public key - can't apply revocation certificate
-> problem importing keys
```
**Cause:** The PGP signing key for Andy Wingo (guile maintainer) has expired and is no
longer available on public keyservers. The PKGBUILD requires verification of a `.sig`
file that cannot be validated.
**Fix:** Edit `~/.cache/yay/guile2.0/PKGBUILD` to remove the `.sig` source and
`validpgpkeys` array, then build manually with `makepkg --skippgpcheck`:
```diff
-source=(https://ftp.gnu.org/pub/gnu/$_pkgname/$_pkgname-$pkgver.tar.gz{,.sig})
-validpgpkeys=('3CE464558A84FDC69DB40CFB090B11993D9AEBB5' # Ludovic Courtès <[email protected]>
- 'FF478FB264DE32EC296725A3DDC0F5358812F8F2') # Andy Wingo
-md5sums=('333b6eec83e779935a45c818f712484e'
- 'SKIP')
+source=(https://ftp.gnu.org/pub/gnu/$_pkgname/$_pkgname-$pkgver.tar.gz)
+md5sums=('333b6eec83e779935a45c818f712484e')
```
```bash
cd ~/.cache/yay/guile2.0
makepkg -si --noconfirm --skippgpcheck
```
---
## Issue 2: `binutils` / `gcc48` — `static_assert` Keyword Conflict
**Packages:** `mips-harvard-os161-binutils-2.24`, `mips-harvard-os161-gcc48-4.8.3`
**Error:**
```
opcodes/mips-formats.h:83:7: error: expected identifier or '(' before 'static_assert'
83 | static_assert[(1 << (SIZE)) == ARRAY_SIZE (MAP)]; \
| ^~~~~~~~~~~~~
```
**Cause:** This old code uses `static_assert[condition]` as a compile-time assertion
trick — declaring a zero-length array to force a compile error if the condition is
false. This was common before C11. In C11, `_Static_assert` became a language keyword,
and GCC 14 defines `static_assert` as a built-in macro expanding to it, even without
including `<assert.h>`. The result: what was a valid identifier is now a reserved word.
**Fix:** Force the C99 standard (where `static_assert` is not a keyword) via CFLAGS
in each PKGBUILD:
For `mips-harvard-os161-binutils` (`~/.cache/yay/mips-harvard-os161-binutils/PKGBUILD`):
```diff
- make tooldir=/usr
+ make tooldir=/usr CFLAGS="${CFLAGS} -std=gnu99"
```
For `mips-harvard-os161-gcc48` (`~/.cache/yay/mips-harvard-os161-gcc48/PKGBUILD`):
```diff
- export CFLAGS="-O2"
- export CXXFLAGS="-O2"
+ export CFLAGS="-O2 -std=gnu99"
+ export CXXFLAGS="-O2 -std=gnu++98"
```
---
## Issue 3: `gdb` — Multiple Compatibility Failures
**Package:** `mips-harvard-os161-gdb-7.8`
This package required three separate fixes.
### 3a. `static_assert` Keyword Conflict (same as Issue 2)
Same root cause as above. However, `-std=gnu99` alone was not sufficient here because
of the next issue.
### 3b. `implicit declaration of 'strcmp'` — GCC 14 Hard Error
**Error:**
```
sim/common/gentmap.c:119:7: error: implicit declaration of function 'strcmp'
119 | if (strcmp (argv[1], "-h") == 0)
note: include '<string.h>' or provide a declaration of 'strcmp'
```
**Cause:** `sim/common/gentmap.c` calls `strcmp` without including `<string.h>`.
In C89/C99, this used to produce only a warning. **GCC 14 changed this to a hard
error** regardless of the C standard mode. The flag `-Wno-implicit-function-declaration`
does not suppress it because the sub-Makefile adds `-Wall` after CFLAGS, which
re-enables the diagnostic as an error.
**Fix:** Patch the source in the PKGBUILD's `prepare()` function (so it survives
re-extraction), and use `-std=gnu89` (which avoids `static_assert` issues while
being the appropriate standard for this K&R-era code):
```diff
prepare() {
cd gdb-${_pkgver}
sed -i "/ac_cpp=/s/\$CPPFLAGS/\$CPPFLAGS -O2/" libiberty/configure
patch -p1 -i ${srcdir}/gdb.patch
+ # GCC 14 made implicit function declarations hard errors; add missing include
+ sed -i '/#include <stdlib.h>/a #include <string.h>' sim/common/gentmap.c
mkdir ${srcdir}/gdb-build
}
```
```diff
- export CFLAGS="-O2"
- export CXXFLAGS="-O2"
+ export CFLAGS="-O2 -std=gnu89"
+ export CXXFLAGS="-O2 -std=gnu++98"
```
### 3c. `_PyOS_ReadlineTState` Removed in Python 3.12+
**Error:**
```
gdb/python/py-gdb-readline.c:57:29: error: '_PyOS_ReadlineTState' undeclared
57 | PyEval_RestoreThread (_PyOS_ReadlineTState);
```
**Cause:** `_PyOS_ReadlineTState` is a private CPython API that was removed in
Python 3.12. The system runs Python 3.14, making this integration code
completely incompatible.
**Fix:** Disable Python support in the gdb configure step. Python scripting is not
needed for OS161 kernel debugging:
```diff
--disable-nls --nfp \
--disable-shared --disable-threads \
- --disable-werror
+ --disable-werror \
+ --with-python=no
```
---
## Summary Table
| Package | Error | Root Cause | Fix |
|---|---|---|---|
| `guile2.0` | GPG key import failure | Maintainer key expired, not on keyservers | Remove `validpgpkeys` + `.sig` from PKGBUILD; build with `--skippgpcheck` |
| `mips-harvard-os161-binutils` | `static_assert` keyword conflict | GCC 14 predefines `static_assert` as a C11 macro | Add `-std=gnu99` to `make` call |
| `mips-harvard-os161-gcc48` | `static_assert` keyword conflict | Same as above | Set `CFLAGS="-O2 -std=gnu99"` in PKGBUILD |
| `mips-harvard-os161-gdb` | `static_assert` + implicit `strcmp` + Python API removed | GCC 14 strictness + Python 3.14 incompatibility | Use `-std=gnu89`; patch `gentmap.c`; add `--with-python=no` |
Executable
+63
View File
@@ -0,0 +1,63 @@
#!/bin/bash
set -e
SRCDIR="$(cd "$(dirname "$0")" && pwd)"
CONFIG="${1:-ASST1}"
# Configure the build.
cd "$SRCDIR"
./configure --ostree="$SRCDIR/root"
# Clean userland objects so bear captures a full build. Without this,
# an incremental build only regenerates .depend files, and bear records
# -M commands instead of real compiles. clean also removes build/install;
# the "includes" stage of bmake reinstalls the headers before compiling.
bmake clean
# Build userland (and capture compile commands for clangd).
bear --output "$SRCDIR/compile_commands.json" -- bmake -j 10
bmake install
# Configure a kernel.
cd "$SRCDIR/kern/conf"
./config "$CONFIG"
# Clean stale objects so bear captures a full build.
# cleandir also removes includelinks, so run config again to restore them.
cd "$SRCDIR/kern/compile/$CONFIG"
bmake cleandir
cd "$SRCDIR/kern/conf"
./config "$CONFIG"
# Generate dependency files — outside bear, these are -M commands not -c.
cd "$SRCDIR/kern/compile/$CONFIG"
bmake depend -j 10
# Compile and install the kernel (append kernel compile commands).
cd "$SRCDIR"
bear --output "$SRCDIR/compile_commands.json" --append -- \
sh -c "cd kern/compile/$CONFIG && bmake -j 10"
cd "$SRCDIR/kern/compile/$CONFIG"
bmake install
# Keep only real compile commands. bear also captures -M/-MM dependency
# generation from "bmake depend"; clangd cannot use those, and a dep-gen
# entry can shadow the real compile entry for the same file.
python3 - "$SRCDIR/compile_commands.json" <<'EOF'
import json, sys
path = sys.argv[1]
with open(path) as f:
db = json.load(f)
dep_flags = {"-M", "-MM", "-MD", "-MMD", "-MG", "-MP"}
kept = [e for e in db if not dep_flags.intersection(e.get("arguments", []))]
with open(path, "w") as f:
json.dump(kept, f, indent=2)
print(f"compile_commands.json: kept {len(kept)} of {len(db)} entries")
EOF
echo "Kernel + Userland baked fresh ! :)"