






















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!























In this project, you will explore user-level processes. You will create a single process, running in its own address space. When this user-level process executes, the CPU will be in “user mode.”
The user-level process will make system calls to the kernel, which will cause the CPU to switch into “system mode.” Upon completion, the CPU will switch back to user mode before resuming execution of the user-level process.
The user-level process will execute in its own “logical address space.” Its address space will be broken into a number of “pages” and each page will be stored in a frame in memory. The pages will be resident (i.e., stored in frames in physical memory) at all times and will not be swapped out to disk in this project. (Contrast this with “virtual” memory, in which some pages may not be resident in memory.)
The kernel will be entirely protected from the user-level program; nothing the user-level program does can crash the kernel.
Please keep your old files from previous projects separate and don’t modify them once you submit them. This is a good rule for all programming projects in all classes. If there is ever any question about whether code was completed on time, we can always go back and look at the Unix “file modification date” information.
Set up a new directory for this project called cs333/p5 and download all the files from
~walpole/public_html/class/cs333/fall2005/spank/p
You should get the following files:
Switch.s Runtime.s System.h System.c List.h List.c BitMap.h BitMap.c
makefile FileStuff.h FileStuff.c Main.h Main.c DISK
UserRuntime.s UserSystem.h UserSystem.c MyProgram.h MyProgram.c TestProgram1.h TestProgram1.c TestProgram2.h TestProgram2.c
The following files are unchanged from the last project and you should not modify them:
Switch.s Runtime.s System.h System.c List.h List.c BitMap.h BitMap.c
The following files are not provided; instead you will modify what you created in the last project. Copy these files to your p5 directory, so that you still have the p4 version in your p4 directory.
Kernel.h Kernel.c
Change --diskDriver: DiskDriver --fileManager: FileManager to: diskDriver: DiskDriver fileManager: FileManager
Add a function prototype for the function InitFirstProcess. You can add it after the other function prototypes:
Change ProcessFinish (exitStatus: int) to: ProcessFinish (exitStatus: int) InitFirstProcess ()
Please make the following changes to your copy of Kernel.c:
Change the DiskInterruptHandler function from: FatalError ("DISK INTERRUPTS NOT EXPECTED IN PROJECT 4") to: currentInterruptStatus = DISABLED -- print ("DiskInterruptHandler invoked!\n") if diskDriver.semToSignalOnCompletion diskDriver.semToSignalOnCompletion.Signal() endIf
Your first task is to load and execute the user-level program called MyProgram. Since the user-level program must be read from a file on the SPANK disk, you’ll first need to understand how the SPANK disk works, how files are stored on the disk, and how the FileManager code works.
MyProgram invokes the SystemShutdown syscall, which you’ll need to implement.
Modify all the syscall handlers so they print the arguments that are passed to them. In the case of integer arguments, this should be straightforward, but the following syscalls take a pointer to an array of char as one of their arguments.
Exec Create Open
This pointer is in the user-program’s logical address space. You must first move the string from user- space to a buffer in kernel space. Only then can it be safely printed.
Also, some of the syscalls return a result. You must modify the handlers for these syscalls so that the following syscalls return these values. (These are just arbitrary values, to make sure you can return something.)
Fork 1000 Join 2000 Exec 3000 Create 4000 Open 5000 Read 6000 Write 7000 Seek 8000
For this task, you should modify only the handler methods (e.g., Handle_Sys_Fork, Handle_Sys_Join, etc.) You should not modify SyscallTrapHandler or the wrapper functions in UserSystem.
Implement the Exec syscall. The Exec syscall will read a new executable program from disk and copy it into the address space of the process which invoked the Exec. It will then begin execution of the new program. Unless there are errors, there will not be a return from the Exec syscall.
First, let’s look at our operating system from the users’ point of view. User-level programs will be able to invoke the following kernel routines:
Exit Shutdown Yield Fork Join Exec Create Open Read Write Seek Close
(This is the grand plan for our OS; these system calls will not be implemented in this project.)
enum SYSCALL_EXIT = 1, SYSCALL_SHUTDOWN, SYSCALL_YIELD, SYSCALL_FORK, SYSCALL_JOIN, SYSCALL_EXEC, SYSCALL_CREATE, SYSCALL_OPEN, SYSCALL_READ, SYSCALL_WRITE, SYSCALL_SEEK, SYSCALL_CLOSE
These codes numbers are used both by the user-level program and by the kernel. Consequently, there is an identical copy of this enum in both Kernel.h and UserSystem.h. (You should not change the system call interface, but if one were to need to change these code numbers, it would be critical that both enums were changed identically.)
As an example, here is the code for the wrapper function for “Read.” It simply invokes DoSyscall and returns whatever DoSyscall returns.
function Sys_Read (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int return DoSyscall (SYSCALL_READ, fileDesc, buffer asInteger, sizeInBytes,
endFunction
Here is the function prototype for DoSyscall:
external DoSyscall (funCode, arg1, arg2, arg3, arg4: int) returns int
The DoSyscall routine is set up to deal with up to 4 arguments. Since the Read syscall only needs 3 arguments, the wrapper function must supply an extra zero for the fourth argument.
DoSyscall treats all of its arguments as untyped words (i.e., as int), so the wrapper functions must coerce the types of the arguments if they are not int. Whatever DoSyscall returns, the wrapper function will return.
DoSyscall is in UserRuntime.s, which will be linked with all user programs. The code is given next.
It moves each of the 4 arguments into registers r1, r2, r3, and r4. It then moves the function code into register r5 and executes the syscall instruction. It assumes the kernel will place the result (if any) in r1, so after the syscall instruction, it moves the return value from r1 to the stack, so that the wrapper function can retrieve it.
DoSyscall: load [r15+8],r1! Move arg1 into r load [r15+12],r2! Move arg2 into r load [r15+16],r3! Move arg3 into r
load [r15+20],r4! Move arg4 into r load [r15+4],r5! Move funcCode into r syscall r5! Do the syscall store r1,[r15+4]! Move result from r1 onto stack ret! Return
Some of the kernel routines require no arguments and/or return no result. As an example, consider the wrapper function for Yield. The compiler knows that DoSyscall returns a result, so it insists that we do something with this value. The wrapper function simply moves it into a variable and ignores it.
function Sys_Yield () var ignore: int ignore = DoSyscall (SYSCALL_YIELD, 0, 0, 0, 0) endFunction
Here is a list of all the wrapper functions, including their arguments and return types.
Sys_Exit (returnStatus: int) Sys_Shutdown () Sys_Yield () Sys_Fork () returns int Sys_Join (processID: int) returns int Sys_Exec (filename: String) returns int Sys_Create (filename: String) returns int Sys_Open (filename: String) returns int Sys_Read (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int Sys_Write (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int Sys_Seek (fileDesc: int, newCurrentPos: int) returns int Sys_Close (fileDesc: int)
In addition to the wrapper functions, the UserSystem package contains a few other routines that support the Spankish language. These are more-or-less duplicates of the same routines in the System package. Likewise, some of the material from Runtime.s is duplicated in UserRuntime.s. This duplication is necessary because user-level programs cannot invoke any of the routines that are part of the kernel.
For example the functions print, printInt, nl, etc. have been duplicated at the user level so the user- level program has the ability to print.
[Note that, at this point, all printing is done by cheating, using a “trapdoor” in the emulator. Normally, a user-level program would need to invoke syscalls (such as Sys_Write) to perform any output, since user-level programs can’t access the I/O devices directly. However, since we are not yet ready to address questions about output to the serial device, we are including these cheater print functions, which rely on a trapdoor in the emulator.]
Every user-level program needs to “use” the UserSystem package and be linked with the UserRuntime.s code. For example:
In our OS, each process will have exactly one thread. A process may also have several open files and can do I/O via the Read and Write syscalls. The I/O will go to the SPANK disk. For now, there is no serial (i.e., terminal) device.
Next we describe each syscall in more detail.
function Sys_Exit (returnStatus: int)
This function causes the current process and its thread to terminate. The returnStatus will be saved so that it can be passed to a Sys_Join executed by the parent process. This function never returns.
function Sys_Shutdown ()
This function will cause an immediate shutdown of the kernel. It will not return.
function Sys_Yield ()
This function yields the CPU to another process on the ready list. Once this process is scheduled again, this function will return. From the caller's perspective, this routine is similar to a “nop.”
function Sys_Fork () returns int
This function creates a new process which is a copy of the current process. The new process will have a copy of the virtual memory space and all files open in the original process will also be open in the new process. Both processes will then return from this function. In the parent process, the pid of the child will be returned; in the child, zero will be returned.
function Sys_Join (processID: int) returns int
This function causes the caller to wait until the process with the given pid has terminated, by executing a call to Sys_Exit. The returnStatus passed by that process to Sys_Exit will be returned from this function. If the other process invokes Sys_Exit first, this returnStatus will be saved until either its parent executes a Sys_Join naming that process’s pid or until its parent terminates.
function Sys_Exec (filename: String) returns int
This function is passed the name of a file. That file is assumed to be an executable file. It is read in to memory, overwriting the entire address space of the current process. Then the OS will begin executing the new process. Any open files in the current process will remain open and unchanged in the new process. Normally, this function will not return. If there are problems, this function will return -1.
function Sys_Create (filename: String) returns int
This function creates a new file on the disk. If all is okay, it returns 0, otherwise it returns a non- zero error code. This function does not open the file; so the caller must use Sys_Open before attempting any I/O.
function Sys_Open (filename: String) returns int
This function opens a file. The file must exist already exist. If all is OK, this function returns a file descriptor, which is a small, non-negative integer. It errors occur, this function returns -1.
function Sys_Read (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int
This function is passed the fileDescriptor of a file, which is assumed to have been successfully opened, a pointer to an area of memory, and a count of the number of bytes to transfer. This function reads that many bytes from the current position in the file and places them in memory. If there are not enough bytes between the current position and the end of the file, then a lesser number of bytes are transferred. The current file position will be advanced by the number of bytes transferred.
If the input is coming from the serial device (the terminal), this function will wait for at least one character to be typed before returning, and then will return as many characters as have been typed and buffered since the previous call to this function.
This function will return the number of characters moved. If there are errors, it will return -1.
function Sys_Write (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int
This function is passed the fileDescriptor of a file, which is assumed to have been successfully opened, a pointer to an area of memory, and a count of the number of bytes to transfer. This function writes that many bytes from the memory to the current position in the file.
If the end of the file is reached, the file’s size will be increased.
The current file position will be advanced by the number of bytes transferred, so that future writes will follow the data transferred in this invocation.
The output may also be directed to the serial output, i.e., to the terminal.
This function will return the number of characters moved. If there are errors, it will return -1.
function Sys_Seek (fileDesc: int, newCurrentPosition: int) returns int
When an runtime error is detected by the CPU, the CPU performs exception processing, which is similar to the way it processes an interrupt. Here are the sorts of runtime errors that can occur in the SPANK architecture:
Illegal Instruction Arithmetic Exception Address Exception Page Invalid Exception Page Read-only Exception Privileged Instruction Alignment Exception
As an example, consider what happens when an Alignment Exception occurs. (The others are handled the same way.)
The CPU will consult the interrupt vector in low memory (see Runtime.s) and will jump to an assembly language routine called AlignmentExceptionHandler. The assembly routine first checks to see if the interrupted code was executing in system mode or not. If it was in system mode, then the assumption is that there is a bug in the kernel, so the assembly routine prints a message and halts execution.
However, if the CPU was in user mode, the assumption is that the user-level program has a bug. The OS will need to handle that bug without itself stopping. So the assembly AlignmentExceptionHandler routine makes an upcall to a Spankish routine with the same name.
The high-level AlignmentExceptionHandler routine simply prints a message and terminates the process. Process termination is performed in a routine called ProcessFinish, which is not yet written. (For now, we’ll assume that user-level programs do not have any bugs.)
When ProcessFinish is implemented in a later project, it will need to return the ProcessControlBlock (PCB) to the free pool. It will also need to free any additional resources held by the process, such as OpenFile objects. Of course, any open files will need to be closed first. Finally, ProcessFinish will call ThreadFinish and will not return.
(Note that a Thread object cannot be added back to the free thread pool by the thread that is running. Instead, in ThreadFinish the thread is added to a list called threadsTobeDestroyed. Later, after another thread begins executing (in Run) the first thing it will do is add any threads on that list back to the free pool by calling threadManager.FreeThread.)
When a user-level thread executes a syscall instruction, the assembly routine SyscallTrapHandler in Runtime.s will be invoked. The assembly routine will then call a Spankish routine with the same name.
The assembly routine does not need to save registers because the interrupted code was executing in user mode and the handler will be executed in system mode.
Recall that just before the syscall, the DoSyscall routine placed the arguments in the (user) registers r1, r2, r3, and r4, with an integer indicating which kernel function is wanted in register r5. The SyscallTrapHandler assembly routine takes the values from the user registers. Since it is running in system mode, it must use a special instruction called “readu” to get values from the user registers. It pushes them on to the system stack so that the high-level routine can access them. Then it calls the high- level SyscallTrapHandler routine. When the high-level routine returns, it takes the returned value from the stack and moves it into user register r1, using an instruction called “writeu,” and then executes a “reti” instruction to return to the interrupted user-level process. Execution will resume back in DoSyscall directly after the “syscall” instruction.
The high-level routine called SyscallTrapHandler simply takes a look at the function code and calls the appropriate routine to finish the work. For every kind of syscall, there is a corresponding “handler routine” in the OS.
System call Handler function in the kernel Exit Handle_Sys_Exit Shutdown Handle_Sys_Shutdown Yield Handle_Sys_Yield Fork Handle_Sys_Fork Join Handle_Sys_Join Exec Handle_Sys_Exec Create Handle_Sys_Create Open Handle_Sys_Open Read Handle_Sys_Read Write Handle_Sys_Write Seek Handle_Sys_Seek Close Handle_Sys_Close
It is these routines that you will need to implement, in this and other projects.
Note that interrupts will be disabled when the SyscallTrapHandler routine begins. The first thing the high-level routine does is set the global variable currentInterruptStatus to DISABLED so that it is accurate. In fact, all the interrupt and exception handlers begin by setting currentInterruptStatus to DISABLED for this reason.
Also note that after the handler routines return to the interrupted routine, interrupts will be re-enabled. Why? Because the Status Register in the CPU will be restored as part of the operation of the reti instruction, restoring the interrupt (and paging and system mode) status bits to what they were when the
DiskInterrupt occurs. So to perform asynchronous I/O, the caller will invoke StartReadSector (or StartWriteSector) giving it a Semaphore. Then the caller can either do other stuff, or wait on the Semaphore.
Since it may be a little tricky to manage asynchronous I/O correctly, the DiskDriver class also provides a couple of methods to make it easy to do I/O synchronously.
When you call SynchReadSector or SynchWriteSector, the caller will be suspended and will be returned to only after a successful completion of the I/O. These routines will deal with transient errors by retrying the operation until it works. Other errors (such as a bad sectorAddr or bad memoryAddr) will be dealt with by a call to FatalError.
In order to implement these methods, the DiskDriver contains a mutex called diskBusy and a semaphore called SemUsedInSynchMethods. Each synch method makes sure the disk is not busy with I/O from some other thread and, if so, waits until it is completed. This is the purpose of the diskBusy mutex. After acquiring the lock, each synch method will call StartReadSector (or StartWriteSector) supplying the semaphore. The synch method will then wait until the disk operation is complete. The calling thread will remain blocked for the duration.
In a later project, we may have time to implement a full file system, like the one used by Unix systems. For now, you are supplied with a very minimal file system, called the “stub” file system. In Unix, directories are structured in a tree shape and there are lots of complexities concerning how files are stored on the disk.
In the stub file system, the disk will contain only one directory, and several files. The directory is limited in size to one sector and is kept in sector 0 of the disk. The exact number of files that can be accommodated depends on how long the file names are.
Each file has a name and a file length (in bytes). Each file is stored on disk in a sequence of consecutive sectors. Once a file is placed on the disk, and more files are added after it, it is impossible to increase the size of the file. Each file is allocated an integral number of sectors. (Since the last sector in each file may be only partially full, it would be possible to increase the size of a file up to the next sector boundary. However, it is not worth the effort. Instead, the solution is to design a better file system!)
For now, the directory is read-only, so files may not be created and the size of files may not be changed.
The classes FileManager, FileControlBlock, and OpenFile are provided for you, to make using the file system from within the kernel easier.
The SPANK tool called diskUtil can be used to create a file system on the SPANK disk, to add files to the disk, to remove files, and to print out the directory.
The SPANK DISK is organized as follows. The disk contains a single directory and this is kept in sector
(1) The starting sector (2) The file length, in bytes (possibly zero) (3) The number of characters in the file name (4) The file name
The directory begins with three numbers:
(1) Magic Number (0x73747562 = “stub”) (2) Number of files (possibly zero) (3) Number of the next free sector
These are followed by the entries for each file.
Once created, a SPANK file may not have its size increased. When a file is removed, the free sectors become unusable; there is no compaction or any attempt to reclaim the lost space.
Each time the diskUtil program is run, it performs one of the following functions:
Initialize set up a new file system on the SPANK disk List list the directory on the SPANK disk Create create a new file of a given size Remove remove a file Add copy a file from Unix to SPANK Extract copy a file from SPANK to Unix Write write sectors from a Unix file to the SPANK disk
The following command line options tell which function is to be performed by diskUtil:
-h Print help info.
-d DiskFileName The file used to emulate the SPANK disk. If missing, “DISK” will be used.
-i Initialize the file system on the SPANK “DISK” file. This will effectively remove all files on the SPANK disk and reclaim all available space.
% diskUtil -a MyProgram MyProgram % diskUtil –l StartingSector SizeInSectors SizeInBytes FileName ============== ============= =========== ===================== 0 1 8192 < directory > 1 1 8192 MyFileA 2 3 17000 MyFileB 5 8 60264 MyProgram
There is only one FileManager object; it is created and initialized at startup time.
I am supplying several methods to help you access files on the “stub” file system; these methods are located in this class. You’ll need to know how to access files in order to create the first user-level process. You’ll need to open the executable file, read the bytes from disk, then close the file. You’ll also need to use the fileManager when you implement the Exec syscall.
Some of the following material pertains more to the next project than this project. Read it all now to get familiar with the framework. You may want to review it again during the next project.
Associated with the FileManager class, there are two other classes called FileControlBlock and OpenFile. These two classes contain fields, but do not contain many methods of their own (besides Init() and Print() methods). Instead, most of the work associated with the file system is done by the FileManager methods.
The FileControlBlock (FCB) objects and the OpenFile objects are limited resources. The FileManager maintains a free list for each of these, as well as code to allocate new FCB objects and new OpenFile objects and maintain the free lists.
The FileManager also deals with opening files. This involves finding the file in the file system, that is, determining the file’s location on disk. In the “stub” file system this is pretty simple since there is only one directory and it fits into a single sector. The FileManager—as programmed now—reads the directory sector (sector 0) into a frame as part of the FileManager.Init method. Subsequent attempts to open a file require no disk accesses. (Of course, for a “real” file system, things won’t be so simple!)
The semantics of files in the kernel you are building will be similar to the semantics of files in Unix.
Consider the case where one process has opened a file and does a kernel call to read, say, 10 bytes. The kernel must read the appropriate sector, extract the 10 bytes out of that sector, and finally copy those 10 bytes into the process’s virtual memory space. This requires the kernel to maintain a frame of memory to use as a buffer; the sector will be read into this buffer by the OS.
If the 10 bytes happen to span the boundary between sectors, the kernel must read both sectors in order to complete the Read syscall. And of course, during the I/O operations other threads should be allowed to run.
Now consider when the process wants to write, say, 20 bytes to a file. The kernel will need to bring in the appropriate sector and copy the 20 bytes from the process’s virtual address space to the buffer. Should the kernel write the buffer back to disk immediately? No; it is likely that the process will want to write some more bytes to that very same sector, so it is more efficient to leave the sector in memory.
When should the kernel write the sector back to disk? When the process closes the file, the kernel should write it back. Also, other I/O operations on the file may need different sectors, so the kernel should write the sector back to disk when the buffer is needed for another sector. However, if the buffer has not been modified, then there is no need to write it back to the disk. Therefore, we associate a Boolean called bufferIsDirty with each buffer frame. When a buffer is first read in from disk, it is considered to be “clean,” but after any operation modifies the buffer, it should be marked “dirty.”
Next consider the case in which two processes have both opened the same file. (Let’s call them processes “A” and “B.”) Any update by process A must be immediately be visible to process B. If process A writes to a file and B reads from that same file, even before A has closed the file, then B should see the new data. Since the kernel may not actually write to the disk for a long time after process A does the write, it means that processes A and B must share the buffer.
Also, when one process finally closes a file, the buffer must be written back to the disk. The guarantee the kernel makes is that once we return from a call to Sys_Close, the disk has been updated. The program can stop worrying about failures, etc., and can tell the user that it has completed its task. Any changes the program has made—even if the system crashes in the next instance—will be permanent and will not be lost. After a Sys_Close, the kernel must not return to the user-level program until the buffer (or all buffers, if there is more than one) is written to the disk successfully.
The purpose of a FileControlBlock (FCB) is to record all the data associated with a single file. This includes the buffer and the bufferIsDirty bit. Here is the definition of FCB:
class FileControlBlock superclass Listable fields numberOfUsers: int -- count of OpenFiles pointing here startingSectorOfFile: int -- or -1 if FCB not in use sizeOfFileInBytes: int bufferPtr: int -- addr of a page frame relativeSectorInBuffer: int -- or -1 if none bufferIsDirty: bool -- Set to true when buffer is modified methods Init () Print () endClass
A small number FCBs are preallocated and kept in a table called fcbTable, which is maintained by the FileManager. The FileManager is responsible for allocating new FileControlBlock objects and for returning unused FileControlBlock objects to a free pool called fcbFreeList.