The issues you're encountering in your memory simulator are likely due to improper handling of the TLB (Translation Lookaside Buffer) and the context switching mechanism. Specifically, the main problems appear to be:
- Global TLB Index: Using a global index (
global_tlb_index) for all processes can cause TLB entries to be overwritten incorrectly across different processes.
- TLB Initialization: The TLB entries are not initialized to an invalid state, which can lead to false positives during TLB lookups.
- Context Switch Logging: The
current_pid is printed before updating it, leading to misleading log messages.
Below are the detailed fixes and the corrected code:
1. Use a Per-Process TLB Index
Instead of using a global TLB index (global_tlb_index), you should use a per-process TLB index (tlb_index[MAX_PROCESSES]). This ensures that each process manages its own TLB entries independently, preventing interference between processes.
Changes Required:
- Remove the
global_tlb_index.
- Use
tlb_index[current_pid] for each process's TLB updates.
2. Initialize TLB Entries to Invalid
Before starting to use the TLB, it's crucial to initialize all TLB entries to an invalid state. This prevents the simulator from mistakenly considering uninitialized entries as valid, which can lead to incorrect memory accesses.
Changes Required:
- Initialize all TLB entries to
valid = FALSE at the start of the program.
3. Correct Context Switch Logging
The current_pid should be updated before logging the context switch to reflect the new process accurately.
Changes Required:
- Update
current_pid before writing the log message.
Corrected Code
Below is the corrected version of your code with the necessary modifications:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAX_PROCESSES 4
#define MAX_REGISTERS 2
#define MAX_PAGES 64
#define PAGE_SIZE 32
#define TLB_SIZE 16
// Output file
FILE* output_file;
// TLB replacement strategy (FIFO or LRU)
char* strategy;
// State variables
int define_called = FALSE;
int current_pid = 0;
int registers[MAX_PROCESSES][MAX_REGISTERS];
int page_table[MAX_PROCESSES][MAX_PAGES];
int memory[1024];
int tlb_entry_number[MAX_PROCESSES][MAX_PAGES];
int off_bits = 0;
// TLB structure
typedef struct {
int vpn;
int pfn;
int valid;
int timestamp;
} TLBEntry;
TLBEntry tlb[MAX_PROCESSES][TLB_SIZE];
int tlb_index[MAX_PROCESSES] = {0};
// Function to tokenize input
char** tokenize_input(char* input) {
char** tokens = NULL;
char* token = strtok(input, " ");
int num_tokens = 0;
while (token != NULL) {
num_tokens++;
tokens = realloc(tokens, num_tokens * sizeof(char*));
tokens[num_tokens - 1] = malloc(strlen(token) + 1);
strcpy(tokens[num_tokens - 1], token);
token = strtok(NULL, " ");
}
num_tokens++;
tokens = realloc(tokens, num_tokens * sizeof(char*));
tokens[num_tokens - 1] = NULL;
return tokens;
}
// TLB lookup
int tlb_lookup(int vpn, int* pfn) {
for (int i = 0; i < TLB_SIZE; i++) {
if (tlb[current_pid][i].valid && tlb[current_pid][i].vpn == vpn) {
*pfn = tlb[current_pid][i].pfn;
fprintf(output_file, "Current PID: %d. Translating. Lookup for VPN %d hit in TLB entry %d. PFN is %d\n",
current_pid, vpn, i, *pfn);
return TRUE;
}
}
// On TLB miss, output miss message and do not update TLB here directly
fprintf(output_file, "Current PID: %d. Translating. Lookup for VPN %d caused a TLB miss\n", current_pid, vpn);
return FALSE;
}
// Per-process TLB update
void tlb_update(int vpn, int pfn) {
int entry_index = tlb_index[current_pid] % TLB_SIZE;
tlb[current_pid][entry_index].vpn = vpn;
tlb[current_pid][entry_index].pfn = pfn;
tlb[current_pid][entry_index].valid = TRUE;
// Depending on the replacement strategy, you might need to update the timestamp here
tlb_entry_number[current_pid][vpn] = entry_index;
tlb_index[current_pid]++;
}
// Function to handle loading an immediate into a register
void handle_load(char** tokens) {
if (strcmp(tokens[1], "r1") == 0 || strcmp(tokens[1], "r2") == 0) {
int reg_index = (strcmp(tokens[1], "r1") == 0) ? 0 : 1;
int value = atoi(tokens[2] + 1); // Skip the '#' character
registers[current_pid][reg_index] = value;
fprintf(output_file, "Current PID: %d. Loaded immediate %d into register %s\n", current_pid, value, tokens[1]);
} else {
fprintf(output_file, "Current PID: %d. Error: invalid register operand %s\n", current_pid, tokens[1]);
}
}
// Function to handle add operation
void handle_add() {
int result = registers[current_pid][0] + registers[current_pid][1];
fprintf(output_file, "Current PID: %d. Added contents of registers r1 (%d) and r2 (%d). Result: %d\n",
current_pid, registers[current_pid][0], registers[current_pid][1], result);
registers[current_pid][0] = result;
}
// Function to map a virtual page to a physical frame
void handle_map(char** tokens) {
int vpn = atoi(tokens[1]);
int pfn = atoi(tokens[2]);
if (vpn < 0 || vpn >= MAX_PAGES) {
fprintf(output_file, "Current PID: %d. Error: VPN %d out of range\n", current_pid, vpn);
return;
}
if (pfn < 0 || pfn >= 1024 / PAGE_SIZE) {
fprintf(output_file, "Current PID: %d. Error: PFN %d out of range\n", current_pid, pfn);
return;
}
// Update the page table
page_table[current_pid][vpn] = pfn;
// Update the TLB entry with the new mapping
tlb_update(vpn, pfn);
fprintf(output_file, "Current PID: %d. Mapped virtual page number %d to physical frame number %d\n", current_pid, vpn, pfn);
}
// Function to unmap a virtual page
void handle_unmap(char** tokens) {
int vpn = atoi(tokens[1]);
if (vpn < 0 || vpn >= MAX_PAGES) {
fprintf(output_file, "Current PID: %d. Error: VPN %d out of range\n", current_pid, vpn);
return;
}
// Invalidate any TLB entry for this VPN
for (int i = 0; i < TLB_SIZE; i++) {
if (tlb[current_pid][i].vpn == vpn && tlb[current_pid][i].valid) {
tlb[current_pid][i].valid = FALSE;
}
}
// Invalidate in the page table
page_table[current_pid][vpn] = -1;
fprintf(output_file, "Current PID: %d. Unmapped virtual page number %d\n", current_pid, vpn);
}
// Function to handle store operation
void handle_store(char** tokens) {
int addr = atoi(tokens[1]);
int reg_value = (tokens[2][0] == '#') ? atoi(tokens[2] + 1) : registers[current_pid][atoi(&tokens[2][1]) - 1];
int vpn = addr >> off_bits; // Calculate VPN by shifting address right by off_bits
int offset = addr & ((1 << off_bits) - 1); // Offset mask based on off_bits
if (vpn < 0 || vpn >= MAX_PAGES) {
fprintf(output_file, "Current PID: %d. Error: VPN %d out of range for address %d\n", current_pid, vpn, addr);
return;
}
int pfn;
if (!tlb_lookup(vpn, &pfn)) {
// If TLB miss, fall back to page table
pfn = page_table[current_pid][vpn];
if (pfn != -1) {
tlb_update(vpn, pfn); // Update TLB if mapping is in page table
fprintf(output_file, "Current PID: %d. Translating. Successfully mapped VPN %d to PFN %d\n", current_pid, vpn, pfn);
} else {
fprintf(output_file, "Current PID: %d. Error: attempted to store to unmapped address %d\n", current_pid, addr);
return;
}
}
int phys_addr = (pfn << off_bits) | offset;
if (phys_addr < 0 || phys_addr >= 1024) {
fprintf(output_file, "Current PID: %d. Error: physical address %d out of range\n", current_pid, phys_addr);
return;
}
memory[phys_addr] = reg_value;
if (tokens[2][0] == '#') {
fprintf(output_file, "Current PID: %d. Stored immediate %d into location %d\n", current_pid, reg_value, addr);
} else {
fprintf(output_file, "Current PID: %d. Stored value of register %s (%d) into location %d\n", current_pid, tokens[2], reg_value, addr);
}
}
// handle_load_mem function
void handle_load_mem(char** tokens) {
int addr = atoi(tokens[2]);
int vpn = addr >> off_bits; // Calculate VPN by shifting address right by off_bits
int offset = addr & ((1 << off_bits) - 1); // Offset mask based on off_bits
if (vpn < 0 || vpn >= MAX_PAGES) {
fprintf(output_file, "Current PID: %d. Error: VPN %d out of range for address %d\n", current_pid, vpn, addr);
return;
}
int pfn;
if (!tlb_lookup(vpn, &pfn)) {
// If TLB miss, fall back to page table
pfn = page_table[current_pid][vpn];
if (pfn != -1) {
tlb_update(vpn, pfn); // Update TLB if mapping is in page table
fprintf(output_file, "Current PID: %d. Translating. Successfully mapped VPN %d to PFN %d\n", current_pid, vpn, pfn);
} else {
fprintf(output_file, "Current PID: %d. Error: attempted to load from unmapped address %d\n", current_pid, addr);
return;
}
}
int phys_addr = (pfn << off_bits) | offset;
if (phys_addr < 0 || phys_addr >= 1024) {
fprintf(output_file, "Current PID: %d. Error: physical address %d out of range\n", current_pid, phys_addr);
return;
}
int reg_index = (strcmp(tokens[1], "r1") == 0) ? 0 : 1;
registers[current_pid][reg_index] = memory[phys_addr];
fprintf(output_file, "Current PID: %d. Loaded value of location %d (%d) into register %s\n", current_pid, addr, memory[phys_addr], tokens[1]);
}
// Function to inspect page table entry
void handle_pinspect(char** tokens) {
int vpn = atoi(tokens[1]);
if (vpn < 0 || vpn >= MAX_PAGES) {
fprintf(output_file, "Current PID: %d. Error: VPN %d out of range for inspection\n", current_pid, vpn);
return;
}
int pfn = page_table[current_pid][vpn];
fprintf(output_file, "Current PID: %d. Inspected page table entry %d. Physical frame number: %d. Valid: %d\n",
current_pid, vpn, pfn, (pfn != -1));
}
// Function to inspect TLB entry
void handle_tinspect(char** tokens) {
int tlbn = atoi(tokens[1]);
if (tlbn >= 0 && tlbn < TLB_SIZE) {
TLBEntry entry = tlb[current_pid][tlbn];
fprintf(output_file, "Current PID: %d. Inspected TLB entry %d. VPN: %d. PFN: %d. Valid: %d. PID: %d\n",
current_pid, tlbn, entry.vpn, entry.pfn, entry.valid, current_pid);
} else {
fprintf(output_file, "Current PID: %d. Error: TLB number %d out of range\n", current_pid, tlbn);
}
}
// Function to inspect physical memory location
void handle_linspect(char** tokens) {
int pl = atoi(tokens[1]);
if (pl >= 0 && pl < 1024) { // Assuming 1024 is max physical memory size
fprintf(output_file, "Current PID: %d. Inspected physical location %d. Content: %d\n",
current_pid, pl, memory[pl]);
} else {
fprintf(output_file, "Current PID: %d. Error: physical location %d out of range\n", current_pid, pl);
}
}
// Function to inspect register
void handle_rinspect(char** tokens) {
if (strcmp(tokens[1], "r1") == 0 || strcmp(tokens[1], "r2") == 0) {
int reg_index = (strcmp(tokens[1], "r1") == 0) ? 0 : 1;
fprintf(output_file, "Current PID: %d. Inspected register %s. Content: %d\n",
current_pid, tokens[1], registers[current_pid][reg_index]);
} else {
fprintf(output_file, "Current PID: %d. Error: invalid register operand %s\n", current_pid, tokens[1]);
}
}
int main(int argc, char* argv[]) {
const char usage[] = "Usage: memsym.out <strategy> <input trace> <output trace>\n";
char* input_trace;
char* output_trace;
char buffer[1024];
// Parse command line arguments
if (argc != 4) {
printf("%s", usage);
return 1;
}
strategy = argv[1];
input_trace = argv[2];
output_trace = argv[3];
// Initialize memory and page tables
memset(memory, 0, sizeof(memory));
for (int i = 0; i < MAX_PROCESSES; i++) {
for (int j = 0; j < MAX_PAGES; j++) {
page_table[i][j] = -1;
}
}
memset(tlb_entry_number, 0, sizeof(tlb_entry_number));
// Initialize TLB entries to invalid
for(int i = 0; i < MAX_PROCESSES; i++) {
for(int j = 0; j < TLB_SIZE; j++) {
tlb[i][j].valid = FALSE;
tlb[i][j].vpn = -1;
tlb[i][j].pfn = -1;
tlb[i][j].timestamp = 0;
}
}
// Open input and output files
FILE* input_file = fopen(input_trace, "r");
if (!input_file) {
fprintf(stderr, "Error: Cannot open input file %s\n", input_trace);
return 1;
}
output_file = fopen(output_trace, "w");
if (!output_file) {
fprintf(stderr, "Error: Cannot open output file %s\n", output_trace);
fclose(input_file);
return 1;
}
while (!feof(input_file)) {
// Read input file line by line
char *rez = fgets(buffer, sizeof(buffer), input_file);
if (!rez) {
// No more lines to read
break;
} else {
// Remove the newline character if present
size_t len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') {
buffer[len - 1] = '\0';
}
}
char** tokens = tokenize_input(buffer);
// Ignore comments
if (tokens[0] && tokens[0][0] == '%') {
for (int i = 0; tokens[i] != NULL; i++)
free(tokens[i]);
free(tokens);
continue;
}
// Implement the memory simulator
if (tokens[0] != NULL) {
if (strcmp(tokens[0], "define") == 0) {
if (define_called) {
fprintf(output_file, "Current PID: 0. Error: multiple calls to define in the same trace\n");
break;
} else {
define_called = TRUE;
if (argc < 4) {
fprintf(output_file, "Current PID: 0. Error: insufficient arguments for define\n");
break;
}
off_bits = atoi(tokens[1]); // Capture OFF bits
int PFN_bits = atoi(tokens[2]);
int VPN_bits = atoi(tokens[3]);
fprintf(output_file, "Current PID: 0. Memory instantiation complete. OFF bits: %d. PFN bits: %d. VPN bits: %d\n", off_bits, PFN_bits, VPN_bits);
}
} else if (strcmp(tokens[0], "ctxswitch") == 0) {
if (!define_called) {
fprintf(output_file, "Current PID: 0. Error: attempt to execute instruction before define\n");
break;
}
int new_pid = atoi(tokens[1]);
if (new_pid < 0 || new_pid >= MAX_PROCESSES) {
fprintf(output_file, "Current PID: %d. Invalid context switch to process %d\n", current_pid, new_pid);
break;
} else {
// Update current_pid before logging
int old_pid = current_pid;
current_pid = new_pid;
fprintf(output_file, "Switched execution context from process %d to process %d\n", old_pid, new_pid);
}
} else if (strcmp(tokens[0], "load") == 0) {
if (!define_called) {
fprintf(output_file, "Current PID: 0. Error: attempt to execute instruction before define\n");
break;
}
if (tokens[2][0] == '#') {
handle_load(tokens);
} else {
handle_load_mem(tokens);
}
} else if (strcmp(tokens[0], "add") == 0) {
if (!define_called) {
fprintf(output_file, "Current PID: 0. Error: attempt to execute instruction before define\n");
break;
}
handle_add();
} else if (strcmp(tokens[0], "map") == 0) {
handle_map(tokens);
} else if (strcmp(tokens[0], "unmap") == 0) {
handle_unmap(tokens);
} else if (strcmp(tokens[0], "store") == 0) {
handle_store(tokens);
} else if (strcmp(tokens[0], "pinspect") == 0) {
handle_pinspect(tokens);
} else if (strcmp(tokens[0], "tinspect") == 0) {
handle_tinspect(tokens);
} else if (strcmp(tokens[0], "linspect") == 0) {
handle_linspect(tokens);
} else if (strcmp(tokens[0], "rinspect") == 0) {
handle_rinspect(tokens);
} else {
fprintf(output_file, "Current PID: %d. Error: Unknown instruction %s\n", current_pid, tokens[0]);
break;
}
}
// Deallocate tokens
for (int i = 0; tokens[i] != NULL; i++)
free(tokens[i]);
free(tokens);
}
// Close input and output files
fclose(input_file);
fclose(output_file);
return 0;
}
Summary of Fixes
-
Per-Process TLB Indexing:
- Removed the global
global_tlb_index.
- Implemented per-process
tlb_index[MAX_PROCESSES] to manage TLB updates independently for each process.
-
TLB Initialization:
- Added initialization of all TLB entries to
invalid in the main function to ensure that no stale entries are considered valid at the start.
-
Context Switch Logging:
- Modified the logging in the
ctxswitch section to update current_pid before logging the switch, ensuring accurate log messages.
-
Additional Enhancements:
- Added boundary checks for VPN and PFN in
handle_map, handle_unmap, handle_store, and handle_load_mem to prevent out-of-range errors.
- Improved error messages for unknown instructions and insufficient arguments in the
define command.
Testing
After applying these fixes, re-run your test suites. The following changes should resolve the previously failing tests:
- Test 3.4: Load from Unmapped Memory: With correct TLB initialization and per-process TLB indexing, loading from an unmapped address should now correctly trigger an error.
- Test 4.2: Inspecting the Page Table: Properly updating and maintaining the page table with accurate mappings allows for correct inspection.
- Test 5.1: Mapping All the Things: Independent TLB management per process ensures that mapping multiple pages across different processes doesn't interfere with each other.
Final Notes
-
TLB Replacement Strategy: Currently, the code uses a FIFO approach by incrementing the tlb_index. If you need to implement LRU or another strategy, additional logic will be required to manage timestamps or access patterns.
-
Error Handling: Ensure that all possible edge cases are handled gracefully, such as invalid instructions, out-of-range addresses, and invalid register names.
Implementing these corrections should stabilize your memory simulator and pass all the test cases. If further issues arise, consider adding more comprehensive logging or using a debugger to trace the execution flow and state changes.