###### tags: `NTHU 111 Fall` `OS` `M`
# MP1: System Call Report
Team member:
1. 姓名:黃子軍,學號:110062143。
工作內容:報告內容撰寫與梳理、寫test program驗證correctness、補齊程式碼漏洞。
2. 姓名:徐菀吟,學號:110071510
工作內容:撰寫初版報告內容、撰寫程式碼。
---
## I. Trace code
---
### 1(a). SC_Halt (halt.c): Functions purposes and details:
---
#### (1) Machine::Run():
This function is called by kernel and starts program in thread which running user programs. It is the outermost function for executing user-level programs, called at the moment when an user-level program is launched.
(1). Initiate the instruction variable **instr**.
(2). Going into UserMode.
(3). Entering infinite loop, continuously execute the program by calling **OneInstruction(instr)**.
(4). call kernel->interrupt->**OneTick()**.
(5). It can be called multiple times (multithread).
#### (2) Machine::OneInstruction():
When this function return, it will return to **Machine::Run()**, otherwise, it will call **raiseException()** when encounter some exceptions.
(1). Fetch instruction.
(2). Retrieve the register.
(3). Compute next program counter.
(4). Execute the instruction (Also check if there's any exception).
(5). Increment program counters.
#### (3) Machine::RaiseException():
When an exception or a system call occurs, this function is called to take the control back to the kernel
(1). Store the address that cause the error in a specific register(virtual).
(2). Going into kernel mode(SystemMode).
(3). Handle the exception by calling **ExceptionHandler()**, arg is the type of the exception.
(4). Finally, go back to user mode(UserMode).
#### (4) ExceptionHandler():
Determine the cause of the exception. It might be Syscall, error in user program, or arithmetic exception, etc. If it is caused by Syscall , simply handle it by syscall's type, otherwise, output an error message.
#### (5) SysHalt():
This function is called by kernel to invoke halt, listed in **ksyscall.h**, which is a kernel interface for system call, simply put, is the bridge between kernel and user program.
(1). Call **interrupt->Halt()**.
#### (6) Interrupt::Halt():
The actual function to shut down the OS.
(1). Print out the performance statistics by calling **Statistics::Print()**.
(2). delete **kernel**.
---
### 1(b). The function flow
---
1. The user program is **compiled** along with system call header, and becomes binary file that contains MIPS instructions.
2. The function **Halt()** is compiled to be an instruction: **OP_SYSCALL**.
3. The machine start running (**Machine::Run()**).
4. Execute the instructions (**Machine::OneInstruction()**), in this example, it will encounter an instruction called **OP_SYSCALL**.
5. Raise exception (**Machine::RaiseException()**).
6. Now going into the SystemMode, and call **ExceptionHandler()**.
7. The type of system call is read from prespecified register, in this case **SC_Halt**. (This is the entry point from user program to kernel)
8. Call **SysHalt()**.
9. Call **Interrupt::Halt()**.
10. Finish system call operation.
---
### 2(a). SC_Create (createFile.c): Functions purposes and details:
---
#### (1) ExceptionHandler():
same as above.
#### (2) SysCreate():
Same as **SysHalt()**, listed in **ksycall.h** for kernel to call corresponding function.
(1). call **fileSystem->Create()**.
#### (3) FileSystem::Create():
<!-- **filesys.h** is data structures to represent the Nachos file system, stored on disk, organized into directories. There is two version: **STUB**, **real**. The former is running the Nachos simulation, the later builts on top of a disk simulator. -->
Create a file using filename.
(1). Get directory.
(2). Check if anything wrong happen, like the filename is already in directory, no sector to hold the file header, etc.
(3). Free up the temporary variables(hdr, freeMap).
(4). Return 1 if success else 0.
---
### 2(b). The function flow
---
First **6** steps are almost the same as **SC_Halt**, except that function **Create** takes one input, which is stored in **r4**.
1. The user program is **compiled** along with system call header, and becomes binary file that contains MIPS instructions.
2. The function **Create()** is compiled to be an instruction: **OP_SYSCALL**.
3. The machine start running (**Machine::Run()**).
4. Execute the instructions (**Machine::OneInstruction()**), in this example, it will encounter an instruction called **OP_SYSCALL**.
5. Raise exception (**Machine::RaiseException()**).
6. Now going into the SystemMode, and call **ExceptionHandler()**.
7. The type of system call is read from prespecified register, in this case **SC_Create**. (This is the entry point from user program to kernel)
8. Get the filename from **r4** and Call **SysCreate()**.
9. Call **FileSystem::Create()**.
10. Finish system call operation.
---
### 3(a). SC_PrintInt: Functions purposes and details:
---
#### (1) ExceptionHandler()
same as above.
#### (2) SysPrintInt()
Same as **SysHalt()**, listed in **ksycall.h** for kernel to call corresponding function.
(1). Call **synchConsoleOut->PutInt()**.
#### (3) SysnchConsoleOutput::PutInt()
Put a integer onto the console.
(1). Lock the console.
(2). Put one digit at a time, and wait if needed.
(3). Release the console.
<!-- Providing synchronized access to the keyboard and write a character to the console display, waiting if necessary. -->
<!-- (1). Check Busy or free. If the lock is free, can go on, else, set it busy and wait.(**lock->Acquire()**)
(2). The semaphore value of 0: busy, and semaphore value of 1: free.(**Semaphore::P()**) Besides, it need to disable interrupts before checking the value.
(3). Entering finite loop. Might be called multiple time, between **consoleOutput->PutChar()** and waitFor->**P()**.
(4). Call **lock->Release()** to set lock to be free.
(5). Because with **P()** is re-enable interrupts to do the loop, we need call **V()** to disable interrupts after calling **Scheduler::ReadyToRun()**
-->
#### (4) SysnchConsoleOutput::PutChar()
Similar to **SysnchConsoleOutput::PutInt()**, but no need to do loop. Just do **consoleOutput->PutChar()** once, and wait if needed.
#### (5) ConsoleOutput::PutChar()
Write a character to the simulated display, and call the interrupt handler to schedule the interrupt.
<!-- (1). If succussfully open a file, write characters. -->
#### (6) Interrupt::Schedule()
Arrange a time for the interrupt to occur, and insert the interrupt into pending queue.
(1). Initialize a pending interrupt object **toOccur**.
(2). Use **pending->Insert(toOccur)** to insert the interrput.
#### (7) Machine::Run()
same as above
#### (8) Machine::OneTick()
This function is called in two scenarios: interrupts are re-enabled, or a user instruction is executed
(1). Advance simulated time
(2). Turn off interrputs, so that interrput handler can run.
(3). Check for pending interrupts.
(4). re-enable interrputs.
(5). Check if a context switch is asked.
#### (9) Interrupt::CheckIfDue()
Check if there's any interrupt in the pending queue and if it's time to execute it, if so, pop and call the interrupt handler to handle it.
(1). Check if pending queue is empty, if not, return 0.
(2). Check if the scheduled time for the front interrupt is reached.
(3). Pop front and go to (2) again.
(4). If we fired of any interrupt handler, set inHander to false, and return true.
<!-- (1). If arg2 is TRUE that means there is nothing in the ready queue
(2). Use **IsEmpty()** to check if there is pending interrupts or not.
(3). Do loop to fired off intrrupt handler by pulling interrupt off list that means remove item from the front of the list
(3). If we fired off any intrrupt handler, set inHandler = FALSE, return true. -->
#### 10. ConsoleOutput::CallBack()
This function is called when the next character can be output to the display.
(1). Set **putBusy** to false, which is a variable telling if a print operation is in progress.
#### 11. SynchConsoleOutput::CallBack()
When it's safe to send the next character can be sent to the display, interrupt handler call this function to re-enable putchar operation.
---
### 3(b). The function flow
---
First **6** steps are the same as **SC_Create**.
<!-- 1. The user program is **compiled** along with system call header, and becomes binary file that contains MIPS instructions.
2. The function **Create()** is compiled to be an instruction: **OP_SYSCALL**.
3. The machine start running (**Machine::Run()**).
4. Execute the instructions (**Machine::OneInstruction()**), in this example, it will encounter an instruction called **OP_SYSCALL**.
5. Raise exception (**Machine::RaiseException()**). -->
...
6. Now going into the SystemMode, and call **ExceptionHandler()**.
7. The type of system call is read from prespecified register, in this case **SC_PrintInt**.
8. Get the value from **r4** and Call **SC_PrintInt()**. (This is the entry point from user program to kernel)
9. Call **SysPrintInt()**
10. Call **synchConsoleOut->PutInt()**
11. Call **consoleOutput->PutChar()**
12. Write the char onto the console, and call **interrupt->Schedule()**
13. The machine proceed to run and tick
14. Scheduled interrupt is due.
15. **CallBack()** to enable next print event, if there are any.
<!-- ---
## 4. Makefile
--- -->
---
## II: Implementation
### OpenFileId Open(char *name);
1. **test/start.s**
Because we don't use functions in C library, we need to define every keyword for a user program here. Otherwise, the file won't be compiled into "nachos-runnable" binary file.
<!-- Because we don't include C library, we need define what we need for a user program here. This is language assist for user programs running on top of Nachos.
It places the code for the system call into register r2, and arg1 is in r4, arg2 is in r5, arg3 is in r6, arg4 is in r7. The return value is in r2. This follows the standard C calling convention on the MIPS. -->
```asm=
.globl Open
.ent Open
Open:
addiu $2,$0,SC_Open
syscall
j $31
.end Open
```
2. **userprog/syscall.h**
We define system call codes here, so that the exception handler can recognize **SC_Open** as a system call.
<!-- Nachos system call interface. It is called by the "syscall" interustion that can be invoked from user programs. -->
<!-- We define system call codes here to tell the kernel which system call is being asked for, in other words, define the number corresponding to the type(system call). -->
```C++=
#define SC_Open 6
```
3. **userprog/exception.cc**
Imitate the implementation of **SC_Create**, add **SC_Open** into case list.
<!-- Entry point into the Nachos kernel from user programs via "syscall" or "exceptions". The former only supports "Halt" function, and the latter does something that the CPU can't handle. -->
```C++=
void ExceptionHandler(ExceptionType which)
...
case SC_Open:
DEBUG(dbgSys, "Open a file, initiated by user program.\n");
val = kernel->machine->ReadRegister(4);
{
// acquire the filename from main memory
char *filename = &(kernel->machine->mainMemory[val]);
// cout << filename << endl;
status = SysOpen (filename);
kernel->machine->WriteRegister(2, (int) status);
}
// Set Program Counter
kernel->machine->WriteRegister(PrevPCReg, kernel->machine->ReadRegister(PCReg));
kernel->machine->WriteRegister(PCReg, kernel->machine->ReadRegister(PCReg) + 4);
kernel->machine->WriteRegister(NextPCReg, kernel->machine->ReadRegister(PCReg)+4);
return;
ASSERTNOTREACHED();
break;
...
```
4. **userprog/ksyscall.h**
Add a function, enabling kernel to call to run the tasks of the system call.
```c++=
OpenFileId SysOpen(char *name)
{
return kernel->fileSystem->OpenAFile(name);
}
```
5. **filesys/filesys.h**
Initialize the tables. Note that OpenFileName[**fid**]->***filename**.
<!-- Given a textual file name to creating or opening or deleting files that are to be found in the **OpenFile** class **(openfile.h)**. -->
```C++=
FileSystem() {
for (int i = 0; i < 20; i++) {
OpenFileTable[i] = NULL;
OpenFileName[i] = NULL;
}
...
char* OpenFileName[20];
}
```
Given a filename, open a file only when ^(1)^exist available space, ^(2)^not exceeding 20 opened files, ^(3)^OpenFile is correctly construct.
```c++=
OpenFileId OpenAFile(char *name) {
int sector = OpenForReadWrite(name, FALSE);
if(sector == -1) return -1;
int file_idx = this->search_empty_idx();
if (file_idx == -1) {
return -1;
}
OpenFile* of = new OpenFile(sector);
if(of == NULL){
return -1;
}
OpenFileTable[file_idx] = of;
OpenFileName[file_idx] = name;
return file_idx;
}
int search_empty_idx() {
// return the empty index which is OpenFileId
for (int idx = 0; idx < 20; idx++) {
if (OpenFileTable[idx] == NULL) {
return idx;
}
}
return -1;
}
```
---
### int Write(char *buffer, int size, OpenFileId id);
1. **test/start.s**
```asm=
.globl Write
.ent Write
Write:
addiu $2,$0,SC_Write
syscall
j $31
.end Write
```
2. **userprog/syscall.h**
```c++=
#define SC_Write 8
```
3. **userprog/exception.cc**
Similar to **SC_Open**, but take two more args, **size**, **id**.
```c++=
void ExceptionHandler(ExceptionType which)
...
case SC_Write:
DEBUG(dbgSys, "Write a file, initiated by user program.\n");
numChar = kernel->machine->ReadRegister(4);
{
// acquire the char let this char write into the file
char *buffer = &(kernel->machine->mainMemory[numChar]);
// cout << buffer << endl;
// return the number of characters actually written to the file
status = SysWrite(buffer, (int)kernel->machine->ReadRegister(5), (int)kernel->machine->ReadRegister(6));
kernel->machine->WriteRegister(2, (int) status);
}
// check if successfully Write a file
if (status != -1) {
DEBUG(dbgSys, "Successfully Write a file, initiated by user program.\n");
} else {
DEBUG(dbgSys, "Fail to write a file, initiated by user program.\n");
}
// Set Program Counter
kernel->machine->WriteRegister(PrevPCReg, kernel->machine->ReadRegister(PCReg));
kernel->machine->WriteRegister(PCReg, kernel->machine->ReadRegister(PCReg) + 4);
kernel->machine->WriteRegister(NextPCReg, kernel->machine->ReadRegister(PCReg)+4);
return;
ASSERTNOTREACHED();
break;
...
```
4. **userprog/ksyscall.h**
Similar to **SysOpen**.
```c++=
int SysWrite(char *buffer, int size, int id){
return kernel->fileSystem->WriteFile(buffer, size, id);
}
```
5. **filesys/filesys.h**
Check if the id exist, and it is in the range [0,20), if good, call the pre-written function in **OpenFile** class to write a file.
```c++=
int WriteFile(char *buffer, int size, OpenFileId id){
// Check if id is in the range 0-19
if(!(id >= 0 && id < 20)) return -1;
// Check if this id exists
if(OpenFileTable[id] == NULL) return -1;
return OpenFileTable[id]->Write(buffer, size);
}
```
---
### int Read(char *buffer, int size, OpenFileId id);
1. **test/start.s**
```asm=
.globl Read
.ent Read
Read:
addiu $2,$0,SC_Read
syscall
j $31
.end Read
```
2. **userprog/syscall.h**
```c++=
#define SC_Read 7
```
3. **userprog/exception.cc**
Similar to **SC_Write**.
```c++=
void ExceptionHandler(ExceptionType which)
...
case SC_Read:
DEBUG(dbgSys, "Read a file, initiated by user program.\n");
numChar = kernel->machine->ReadRegister(4);
{
// acquire the buffer to "read" form the file to the buffer
char *buffer = &(kernel->machine->mainMemory[numChar]);
status = SysRead(buffer, (int)kernel->machine->ReadRegister(5), (int)kernel->machine->ReadRegister(6));
kernel->machine->WriteRegister(2, (int) status);
}
// check if successfully Read a file
if (status != -1) {
DEBUG(dbgSys, "Successfully read a file, initiated by user program.\n");
} else {
DEBUG(dbgSys, "Fail to read a file, initiated by user program.\n");
}
// Set Program Counter
kernel->machine->WriteRegister(PrevPCReg, kernel->machine->ReadRegister(PCReg));
kernel->machine->WriteRegister(PCReg, kernel->machine->ReadRegister(PCReg) + 4);
kernel->machine->WriteRegister(NextPCReg, kernel->machine->ReadRegister(PCReg)+4);
return;
ASSERTNOTREACHED();
break;
...
```
4. **userprog/ksyscall.h**
Similar to **SysWrite()**.
```c++=
int SysRead(char *buffer, int size, int id){
return kernel->fileSystem->ReadFile(buffer, size, id);
}
```
5. **filesys/filesys.h**
Similar to **WriteFile()**, Check id validation and read.
```c++=
int ReadFile(char *buffer, int size, OpenFileId id){
// Check if id is in the range: 0-19
if(!(id >= 0 && id < 20)) return -1;
// Check if this id exists
if(OpenFileTable[id] == NULL) return -1;
return OpenFileTable[id]->Read(buffer, size);
}
```
---
### int Close(OpenFileId id);
1. **test/start.s**
```acm=
.globl Close
.ent Close
Close:
addiu $2,$0,SC_Close
syscall
j $31
.end Close
```
2. **userprog/syscall.h**
```c++=
#define SC_Close 10
```
3. **userprog/exception.cc**
Similar to **SC_Create** but the arg now is the id, not the filename.
```c++=
void ExceptionHandler(ExceptionType which)
...
case SC_Close:
DEBUG(dbgSys, "Close a file, initiated by user program.\n");
// accquire the file with Id
val = kernel->machine->ReadRegister(4);
{
status = SysClose(val);
kernel->machine->WriteRegister(2, (int) status);
}
// check if successfully Close a file
if (status == 1) {
DEBUG(dbgSys, "Successfully close a file, initiated by user program.\n");
}
// Set Program Counter
kernel->machine->WriteRegister(PrevPCReg, kernel->machine->ReadRegister(PCReg));
kernel->machine->WriteRegister(PCReg, kernel->machine->ReadRegister(PCReg) + 4);
kernel->machine->WriteRegister(NextPCReg, kernel->machine->ReadRegister(PCReg)+4);
return;
ASSERTNOTREACHED();
break;
...
```
4. **userprog/ksyscall.h**
Similar to **SysCreate()**
```c++=
int SysClose(int id){
return kernel->fileSystem->CloseFile(id);
}
```
5. **filesys/filesys.h**
Check the id validation, if good, destruct the Openfile and clean up the tables.
```c++=
int CloseFile(OpenFileId id){
// Check if id is in the range: 0-19
if(id < 0 || id >= 20) return -1;
// Check if this id exists
if(OpenFileTable[id] == NULL) return -1;
// delete the OpenFile after closing the file
delete OpenFileTable[id];
// re-set
OpenFileName[id] = NULL;
OpenFileTable[id] = NULL;
return 1;
}
```
---
## III Thought:
### Difficulties
1. We think it’s quite hard to understand the flow of the function call at first, because we don’t realize that the functions in test programs are compiled as MIPS instructions and recognized as system call by exception handler. There are same function names like open, write, so we are confused. We think **Open()** and other function calls were a direct function call of some function inside Nachos, but it certainly isn’t. So it takes us quite a while to understand the whole thing.
2. There are numerous functions about open/read/write, so we’re not sure which should be invoked in our implemented functions.
3. NashOS is run on a simulated machine, and the user program is compiled to MIPS instruction. Both facts keep us from debugging in our familiar way i.e. one by one line execution in vscode.
4. We haven’t figured out how to work together in coding parts, it’s quite hard for us to cooperate on MobaXterm, since we can’t see each other’s work in real time. When we’re both writing code on the same file, if I click save, it would overwrite everything including her newly added code.
### Feedback
1. As mentioned previously, we do need a suggestion on how should we work together on the coding part, we'll be appreciated if you give us some advices :).
2. At first, it is difficult for us to understand the workflow of NachOS. After we follow the instructions and trace the codes step by step, we have a deeper understanding of system call. We know how system call interacts with file system; how to print integers from a keyboard and the mechanism of switching between kernel mode and user mode.
---