PennFAT
This assignment is Part 1 of the PennOS project sequence. In this part you will implement PennFAT, a FAT16-like file system that lives inside a single host OS file, and a standalone shell program for interacting with it.
In Part 2 (PennOS), we will mount this exact file system and expose it through PennOS system calls. The scaffolding in this writeup is designed so your Part 1 code drops cleanly into Part 2 with minimal refactoring.
Table of contents
- PennFAT
Collaboration
This is a group project. You must work in your assigned groups.
You may reuse code from earlier projects only if you wrote it. You may not reuse code from the internet or from previous semesters.
One last note: this is a long and complex project that will take you many, many hours to complete. This document can only provide you with a primer of the innumerable challenges you will face; read it carefully, but be sure to use other resources as well. In particular, read the manual pages, and ask questions of your friendly TAs. Likely, this will be the largest program you have yet written as a student. Devise a game plan, map out functions together, design how the various routines of PennOS will interact, and assign each other tasks thoughtfully so the pieces fit together at the end.
Remember, a lot of small, easy programs equal one large, complex program. Don’t try to conquer the entire project in one go: it is organized such that splitting up tasks into discrete components and writing modular code are strategies that will be rewarded.
Overview
You will implement:
- A file system format called PennFAT, stored in a single host OS file (the “disk image”). This is one binary file.
- A standalone program called
pennfatthat provides a prompt, parses commands, and calls your PennFAT routines. - A kernel-style API for the file system (
k_*functions) that you will later reuse for PennOS.
Creating the Perfect Scaffolding
By the end of this assignment, your codebase should already have a clean separation between:
- Standalone shell layer (command parsing, user interaction)
- File system kernel layer (
k_*functions: open/read/write/close/unlink/lseek/ls…etc) - File system on-disk layout helpers (directory traversal, FAT traversal, block allocation)
Error handling (file system-specific error codes, set globally, readable by later PennOS code)
- A global open file table (kernel-level system-wide table of open files) that:
- Tracks per-open-file metadata needed for correct executions of
k_read/k_write/k_lseek - Enforces “only one writer” rules for
F_WRITEandF_APPEND
- Tracks per-open-file metadata needed for correct executions of
In Part 2, PennOS will add per-process FD tables and will implement s_* calls by delegating most of the work to these k_* routines. If your k_* layer is clean, Part 2 becomes integration instead of an entire rewrite.
Background
Your operating system will mount its own file system, PennFAT, based on FAT16. (For references, see Chapter 4.3.2 in Tanenbaum 4th edition, pages 285-286.) You are only required to implement the root directory of PennFAT.
A PennFAT file system has two regions:
- FAT region, an array of 2-byte entries (
uint16_t fat[]) - Data region, fixed-size blocks that store files and the root directory file
Conceptually, you can think of a file as a sequence of fixed-size blocks and a file system as a way to find the right blocks for a file in the right order. A FAT provides a simple way to do this by storing links between physical blocks of a file. Placed at the beginning of the file system before any block, the FAT has a predetermined size and can be easily mapped into memory. This is also its greatest disadvantage: being of fixed size, the FAT also limits the size of the file system.
Block numbering
- The data region begins at block number 1
fat[0]does not correspond to a data block, it stores formatting informationfat[1]corresponds to data block 1 (the root directory file starts here)
FAT entry meaning
0means free block0xFFFFmeans end-of-file chain- Otherwise,
fat[i] = jmeans “the block that comes after blockiin the file is blockj”
Formatting info in fat[0]
The FAT of PennFAT consists of a predetermined number of entries specified by the two metadata values in fat[0].
The least significant byte (LSB) of the first entry of the FAT determines the size of a block. The following LSB mappings are valid:
| LSB | Size (bytes) |
|---|---|
| 0 | 256 |
| 1 | 512 |
| 2 | 1024 |
| 3 | 2048 |
| 4 | 4096 |
The most significant byte (MSB) of the first entry of the FAT determines the number of blocks in the FAT. The MSB can range from 1-32 (numbers outside of this range will be considered an error).
Then we can make the following calculations:
fat_size_bytes = block_size_bytes * fat_blocksfat_entries = fat_size_bytes / 2data_region_size_bytes = block_size_bytes * (fat_entries - 1)
Importantly, the number of block numbers we can reference is limited. With 0xFFFF symbolizing the end of a file, 0xFFFE is the largest valid index we possible could have into the FAT.
Root directory entries
The Root directory is a file stored in the data region. It contains fixed-size 64-byte entries:
struct pennos_dirent {
char name[32];
uint32_t size;
uint16_t firstBlock;
uint8_t type;
uint8_t perm;
time_t mtime;
// remaining 16 bytes reserved (e.g. for extensions)
}
char name[32]: 32-byte null-terminated file name.name[0]also serves as a special byte marker with the following numerical values.- 0: end of directory
- 1: deleted entry; the file is also deleted
- 2: deleted entry; the file is still being used
uint32_t size: number of bytes in fileuint16_t firstBlock: number indicating the first block number of the file (undefined if size is zero)uint8_t type: number for the type of the file, which will be one of the following:- 0: unknown
- 1: a regular file
- 2: a directory file
- 4: a symbolic link
NoteRead more about symbolic links here. This could be a possible extension.
uint8_t perm: file permissions, which will be one of the following:- 0: none
- 2: write only
- 4: read only
- 5: read and executable (shell scripts)
- 6: read and write
- 7: read, write, and executable
time_t mtime: creation/modification time as returned bytime(2)in Linux
By iterating over the directory entries, all files in the file system can be enumerated. To find a block in the file system using a FAT entry, you will use lseek(2). For example, given a FAT entry with the value 5 (thus referring to the 5th data block in the data section of the file system), you can sek to the beginning of the corresponding data block in the file containing your PennFAT by the following call to lseek:
lseek(fs_fd, fat_size + block_size * 4, SEEK_SET)
where fat_size is the size of the FAT in bytes and block_size is the size of a block in bytes.
The PennFAT Assignment
Your file system itself will exist as a single binary file on the host OS. A simple shell starter code (prompt, read input, execute command) will be provided for you to fully implement in order to build your standalone PennFAT, with its appropriate function calls. This will allow for interaction with your file system without an operating system implementation. Note this is only the pseudocode, you should be filling this in with your code and also be implementing the PennFAT routines. The information about routines can be found in here.
You will provide a single standalone program, separate from the final PennOS executable, called pennfat, which doesn’t have any arguments.
Just like the previous shells you’ve made so far, your Standalone PennFAT should ignore SIGINT and SIGTSTP, and only exit on Ctrl+D.
For a makefile guide, take a look at the makefile section.
File Descriptors and Global Open File Table
Classically, an operating system will store a struct continaing metadat for each open file in the operating system. This structure will save information such as the mode of file and offset pointers that indicate where subsequent reads or writes should take place. During a system call to modify the file, a reference to that file must be provided. This “reference” is a file descriptor (an integer) that is usually just the index that the structure shows up in the system-wide open file table.
In our stand-alone penn-fat shell users will invoke commands that cause the shell to directly invoke these k_ functions, but in pennos the user will call a s_ level system call which uses a process-level file descriptor table to then call the k_ level funtions you write in this assignment.
Note that the file system-related system calls are abstraction layers and so code that calls these funcions should not care about the format of the underlying file system. That is, consider what must occur when an operating system has mounted multiple file systems of different types. When there is a call to read(2) for a particular file descriptor, the operating system will determine on which file system variant the file lives (e.g., FAT32, ext3, etc.) and then call the appropriate file system dependent function to perform the read operation (which usually is provided by module) and the caller doesn’t have to consider all of these details.
Within your standalone PennFAT, you should devise some representation of File Descriptors and the kernel-level system-wide open file table. You must design each structure so that a file is addressable with its integer file descriptor, and its information is saved in a structure in a way that is indexable by the file descriptor.
You must also reserve the standard file descriptors that relate to STDIN/STDOUT/STDERR as to not complicate later integrations. These will receive descriptors 0/1/2. These file descriptors should be connected to the controlling terminal and can be passed to the k_* functions described below to read from and write to it. There is no associated FAT entry for these terminal connections.
A recommended starting point for this is some one dimensional array or list of type void*. You should pass a file descriptor into most of the k_ functions that you should implement for PennFAT.
To be clear: you are not implementing the per-process level file desciptor table in this assignment. The file descriptors here are descriptors into the global kernel level file table. You will implement the process-level file descriptor tables (and process level file descriptors) in PennOS.
PennFAT Kernel Level Functions
Your standalone FAT will provide at least the following functions for file manipulation.
k_open(const char *fname, int mode)open a file namefnamewith the modemodeand return a file descriptor. The allowed modes are as follows:F_WRITE- open the file for reading and writing, truncates if the file exists, or creates it if it does not exist. Only one instance of a file can be opened inF_WRITEmode; error if attempting to open a file for writing more than onceF_READ- open the file for reading only; error if the file does not existF_APPEND- open the file for reading and writing but does not truncate the file if exists. Additionally, the file pointer references the end of the file; error if attempting to open a file for writing more than once
NoteIt may be useful to define some additional helper functions, such as one which will traverse the root directory block by block and check each block for the filename given. It may also be useful to define a helper function that will need to find the next available empty index within the FAT and then update the root accordingly.k_openreturns a file descriptor on success and a negative value on error. What characters are allowed in filenames? You may follow the POSIX standard, linked herek_read(int fd, char *buf, int n)
Readnbytes from the file referenced byfdintobufand increment the file pointer byn. On return,k_readreturns the number of bytes read,0if EOF is reached, or a negative number on error.NoteThis function requires some thought, and will need to get the first block number of the file, navigate to it using lseek(2), and read the appropriate number of bytes, possibly traversing multiple blocks.k_write(int fd, const char *buf, int n)
Writenbytes of the data referenced bybufto the filefdand increment the file pointer byn. On return,k_writereturns the number of bytes written, or a negative value on error. Note that this writes bytes not chars, these can be anything, even'\0'.NoteNote that it is possible that a new block will be needed, in which case a fresh block allocation will have to occur and an update to the FAT will be necessary.k_close(int fd)
Close the filefdand return 0 on success, or a negative value on failure.k_unlink(const char *fname)
Remove the file. Be careful how you implement this! Like Linux, you should not be able to delete a file that is in use by another process. Furthermore, consider where updates will be necessary. You do not necessarily need to clear the previous data in the data region, but should at least note this area as ‘nullified’ or fresh and ready to write to, elsewhere.k_lseek(int fd, int offset, int whence)
Reposition the file pointer forfdto theoffsetrelative to the directivewhence. You must also implement the constantsF_SEEK_SET,F_SEEK_CUR, andF_SEEK_END, which should behave as their similarly named counterparts inlseek(2). Note that this could require updates to the metadata of the file, for example, if the new position of n exceeds the files previous file size!k_ls(const char *filename)
returns a list of the filefilenamein the current directory. If filename isNULL, list all files in the current directory. This should act as very similar to posix, displaying the first block number of the file, its permissions (you can leave this for the time being, chmod will be required to be implemented later), size, latest modification timestamp and filename.
Standalone PennFAT Commands
With the above kernel-level functions, you will implement the following routines for the Standalone PennFAT program.
Key:
CAPITAL: Capitalized words are file names (or constants in the case of themkfscommand)...: This means that we can optionally have multiple of the preceding element[ ]: This means that what comes in brackets are optional arguments (the brackets are not included when running the command itself)
Standalone PennFAT Routines:
The first three routines are special routines to make your file system binary, mount the binary to memory, and unmount it from memory. These functions can be implemented with UNIX’s standard system calls. These functions should print error messages and reprompt if any underlying C system calls fail.
mkfs FS_NAME BLOCKS_IN_FAT BLOCK_SIZE_CONFIG
Creates a PennFAT file system in the file namedfs_name. The number of blocks in the FAT region isblocks_in_fat(ranging from 1 through 32), and the block size is 256, 512, 1024, 2048, or 4096 bytes corresponding to the value (0 through 4) ofblock_size_config. Can ONLY be called if there is no currently mounted file system. Prints “unexpected command” error if file system is currently mounted.mount FS_NAME
Mounts the file system namedfs_nameby loading its FAT into memory. Prints “unexpected command” error if file system is currently mounted. Check this section to see how to load your binary file system to memory.umount
Unmounts the currently mounted file system. Prints “unexpected command” error if no file system is mounted
The following set of routines can ONLY be executed if a file system is currently mounted in memory. Also, you may only use your implemented kernel-level system calls (k_functions) to implement these unless specified below.
touch FILE ...
Creates the files if they do not exist, or updates their timestamp to the current system time.mv SOURCE DEST
RenamesSOURCEtoDEST.rm FILE ...
Removes the files.cat FILE ... [ -w OUTPUT_FILE ]
Concatenates the files and prints them to stdout by default, or overwritesOUTPUT_FILE. IfOUTPUT_FILEdoes not exist, it will be created. (Same forOUTPUT_FILEin the commands below.)cat FILE ... [ -a OUTPUT_FILE ]
Concatenates the files and prints them to stdout by default, or appends toOUTPUT_FILE.cat -w OUTPUT_FILE
Reads from the terminal and overwritesOUTPUT_FILE.cat -a OUTPUT_FILE
Reads from the terminal and appends toOUTPUT_FILE.cp [ -h ] SOURCE DEST
CopiesSOURCEtoDEST. With-h,SOURCEis from the host OS.cp SOURCE -h DEST
CopiesSOURCEfrom the file system toDESTin the host OS.chmod
Similar tochmod(1)in the VM.ls
List all files in the directory, similar tols -ilin bash. For example:
2 -rw 30000 Nov 7 01:00 up-to-thirty-one-byte-file-name
120 -r- 1000 Oct 31 21:59 Posix-file_name.2
The columns above are first block number, permissions, size, month, day, time, and name.
Note that you should be using k_functions to implement each command’s functionality, unless you are interacting with the host OS files. This means that if you are using C system calls such as open(2), read(2), write(2) in your implementation of cat, you are doing something wrong. You should be using k_open, k_read, and k_write instead. The functionality you implement for k_functions should make the implementations of command simple.
The ONLY case you may use the C system calls is when you are interacting with the host OS. For example, the cp SOURCE -h DEST command, when specified with the -h flag, you will have to read the contents of a file from the PennFAT file system, and write to a file in the host OS. You must use k_read to read from the PennFAT file system, but may use write(2) to write to a file in the host OS.
Hint This means that even ls can simply be a wrapper around k_ls, a function you already implemented.
Loading the FAT into Memory
There are two options you can do for loading the FAT into mamory.
malloc and manually sync-ing
The simplest way to load your FAT into memory is to just allocate an array big enough and then read the FAT from the file into the array like so (minus error checking):
#include <stdint.h>
#include <stdlib.h>
...
uint16_t* fat = malloc(fat_size);
int fs_fd = open(fs_name, O_RDWR);
ssize_t res = read(fs_fd, fat, fat_size);
Everytime you modify the fat you would need to store it back to the file to make sure the updates to the fat aren’t lost if the program crashes:
lseek(fs_fd, 0, SEEK_SET);
write(fs_fd, fat, fat_size);
mmap
When mounting your PennFAT file system, you may find it useful to mmap(2) the FAT region directly into memory. This way you will have copy-on-write for free (meaning that when you modify the values in the FAT array, it will also automatically sync that data with the file system). Here is a code snippet (minus error checking) to get you started on this process:
When people have used mmap() before it has sometimes caused issues where writing to other parts of the file that aren’t in the mapped array will report a success without the data actually being stored back into the file. For this reason I generally recommend using the malloc method above.
#include <stdint.h>
#include <sys/mman.h>
...
int fs_fd = open(fs_name, O_RDWR);
uint16_t *fat = mmap(NULL, fat_size, PROT_READ | PROT_WRITE, MAP_SHARED, fs_fd, 0);
Now, fat references an array.
Do not mmap the entire PennFAT file system. Remember, only the FAT should be in memory. Everything else is on disk.
Error Handling in Standalone PennFAT
Within a header file, you should define some error macros for generic error handling within PennFat. Again, this implementation will be useful for other error handling within the wider PennOS system. As a starting point, FS_NOT_MOUNTED and FILE_NOT_FOUND may be useful. You should set these errors and return values such that errors can later be propagated up the call stack.
Getting Started
Task 0: Disk image layout and mkfs
This is not an exhaustive list but is here to give you some ideas.
Implement mkfs to:
- Create and format the disk image file
- Initialize FAT: s
fat[0]encodes formattingfat[1]is the root directory block and should be allocated (end-of-chain)- Other entries are free
- Initialize the root directory file with an end-of-directory entry marker
Task 1: Mount and Unmount
- Mount by mmapping FAT only
- Unmount by flushing/unmapping FAT and closing the disk image
Task 2: Directory traversal helpers
Write helpers to:
- Find a file by name
- Find a free directory slot
- Iterate directory for
ls - Update metadata (size, firstBlock, perm, mtime)
Task 3: FAT traversal and block allocation
Write helpers to:
- Traverse block chains
- Find free blocks
- Allocate and link blocks
- Free a chain
Task 4: Global open file table
Implement:
- FD allocation (skipping 0/1/2)
- Per-open metadata including offset
- Enforce single-writer rules for
F_WRITEandF_APPEND - Correct cleanup on
k_close
Task 5: Implement k_* API
Keep each k_* function modular, using helpers.
Task 6: Implement standalone commands as wrappers
Shell command implementations should be thin wrappers around k_*.
Error Handling (required)
Define file system errors in a header. At minimum, include errors like:
FS_NOT_MOUNTEDFILE_NOT_FOUND
Set your error state and return negative values so errors can be propagated up the call stack.
Advice and Hints
- Keep file system logic out of your shell.
- Implement helpers (directory scan, block traversal, allocation).
- Derive FAT size and block size from
fat[0]at mount time. - Test with files that cross block boundaries. (Always think about what could break your system!)
Developing Your Code
We highly recommend you use the course-standardized Docker Container given by course staff because all grading will be done on the course Docker Container. Please do not develop on OSX directly as there are significant enough differences between OSX and Unix variants such as Ubuntu Linux. If you decide to develop in a different container/machine anyway, you must compile and test your PennOS on the course-standardized Docker Container to ensure your PennOS runs as you expect.
Repository Creation
The repo creation gradescope assignment for penn-fat is live, please submit a text file named account.txt and have it be in the form:
<email 1>
<github account 1>
<email 2>
<github account 2>
Only one member of the group needs to do this. Make sure you are distributed into Canvas groups correctly before doing this.
Here is the link to the PennFat repo creation assignment.
Makefile
As described above, you will need to have a Makefile to compile your code. We have provided a sample makefile for you here: Makefile This makefile should work if you follow the repository structure below. The only thing you need to specify in it are the programs that have a main in it. There are some comments in the makefile for what you will need to edit.
Feel free to make modifications to it as you need it.
Submission and Grading
Milestone
For the milestone your group will be assigned a TA that you will meet with. You can see the assigned TA for your group by ckecking the pinned post on the Ed Discussion board. Reach out to the TA(s) and try to schedule a time where you can all meet. You should meet with your TA by the end of Friday October 16th at the latest. Try to meet before the end of Wednesday October 14th if possible.
In this meeting your group will be collectively asked the following two questions and then two more questions from a pool of questions (that we are not disclosing) that should be of similar difficulty to the two questions we are sharing publicly. These questions are designed so that we can check that you have read the specification and have at least seriously thought out some of your implementation. It is ok if you haven’t written code for the assignment yet, but should have at least planned some things out. The reason some of the questions are not shared before hand is not to “trick” you, but to make sure you have thought about the assignment. We encourage you to vocalize your thoughts and ask questions to your TA if you are stuck.
The meeting will also be a good time to ask your TA for help clarifying anything about the assignment. Please come with questions if you have any!
Public Milestone Questions:
- Walk through the steps that will happen when you call
k_open(char* fname, int mode);. Be somewhat specific in which steps need to be done (exact code is not neeeded). - A real file system will operate on the block level when writing to storage, meaning that when data is read/written to the device, we read/write a full block at a time. Will you be doing that? Why or why not?
Grading
Each group will receive 3 grade entries for this project: A pass/fail grade for the milestone and 2 grades (one for documentation, and one functionality score).
Each team will receive a group grade for the development; however, individual grades may differ. This can occur due to lack of individual effort, or other group dynamics. Below is an approximate grading guideline to give you some ideas on breakdown on code complexity:
- 5% Documentation & Milestone
- 95% File System Functionality
Repository Structure
This project will be submitted on Gradescope via GitHub. To submit, place all relevant code and documents in your groups git repo on the master branch. You must organize your code into directories from the top-level as follows:
./bin/: all compiled binaries (executables) should be placed here
./doc/: all documentation should be placed here
./src/: all source code should be placed here (e.g. pennfat.c)
./test/: any optional tests you have can be placed here
Your code should compile from the top level directory (./) by issuing the make command. Then, you should go to the Gradescope submission and submit your GitHub repo name link. Finally: make sure that you add all of your project partners to the same submission.
For reference, below is a sample, truncated example of a project structure. This is not a complete example, but it should give you a good idea of how to organize your project.
.
|-- Makefile
|-- bin
| `-- pennfat
|-- doc
| `-- README.md
|-- src
| |-- pennfat_shell.c # prompt + parse + command dispatch
| |-- pennfat_shell.h
| |-- pennfat_kfs.c # k_* API implementation
| |-- pennfat_kfs.h
| |-- pennfat_structs.h # dirent struct, constants, types
| |-- pennfat_disk.c # on-disk helpers: FAT traversal, alloc/free, dir scan
| |-- pennfat_disk.h
| |-- pennfat_errors.c # error code strings
| |-- pennfat_errors.h
| `-- util/
| `-- (optional helpers)
`-- test
`-- (optional)
You can combine files differently, but you must preserve the conceptual separation: shell vs k_* vs disk helpers vs errors.
Deliverables
You must submit:
- Your file system implementation (
k_*layer and helpers) - A README describing:
- How to build
- How to run
- Design overview of your global open file table
- Any extra helper commands you added (optional)
- A short design note section in README describing:
- How you represent directory entries in memory
- How you traverse FAT chains
- How you allocate and free blocks
- How you enforce “only one writer”
- A description of what tools you used (Generative AI / Textbooks / References / etc.). A deep description is not needed, but you should describe how you used the tool and what was completed using the tool. If you did not use any tools, please state so.
(Your Part 2 companion document will be a separate deliverable later. For Part 1, keep design notes concise.)
What we will run
We will compile with make and run:
./bin/pennfat
We will test:
mkfs,mount,umount- command correctness for all required commands
- multi-block reads/writes
- writer exclusivity rules
- correct
lsformatting shape - correct mmap behavior (FAT only)
Grading emphasis (Part 1)
- On-disk correctness and mounting
- FAT chain correctness (alloc/free/traverse)
k_*correctness and clean layering- standalone command behavior
- error handling consistency
What to keep for Part 2
Do not throw away Part 1.
In Part 2 (PennOS), you will:
- Mount the same disk image from
./pennos fatfs [log] - Implement
s_open/s_read/...by callingk_open/k_read/... - Add per-process FD tables on top of your global open file table
So the goal is: your Part 1 k_* layer becomes the file system backend for PennOS.
Attribution
This is a large and complex project using arcane and compactly documented APIs. We do not expect you to be able to complete it without relying on some outside references. That said, we do expect you to struggle a lot, which is how you will learn about systems programming, by doing things yourself.
The primary rule to keep you safe from plagiarism/cheating in this project is to attribute in your documentation any outside sources you use. This includes both resources used to help you understand the concepts, and resources containing sample code you incorporated in your OS. The course text need only be cited in the latter case.