#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define TLB_SETS 16
#define TLB_WAYS 4
#define POBITS 12
typedef struct {
size_t vpn;
size_t ppn;
int valid;
int lru_counter;
} TLBEntry;
TLBEntry tlb[TLB_SETS][TLB_WAYS];
void tlb_clear() {
for (int i = 0; i < TLB_SETS; i++) {
for (int j = 0; j < TLB_WAYS; j++) {
tlb[i][j].valid = 0;
tlb[i][j].lru_counter = 0;
}
}
}
int tlb_peek(size_t va) {
size_t vpn = va >> POBITS;
int set = vpn % TLB_SETS;
for (int i = 0; i < TLB_WAYS; i++) {
if (tlb[set][i].valid && tlb[set][i].vpn == vpn) {
return tlb[set][i].lru_counter;
}
}
return 0;
}
void update_lru(int set, int way) {
int used_counter = tlb[set][way].lru_counter;
for (int i = 0; i < TLB_WAYS; i++) {
if (tlb[set][i].lru_counter < used_counter) {
tlb[set][i].lru_counter++;
}
}
tlb[set][way].lru_counter = 1;
}
size_t translate(size_t va) {
if (va >= 0x12345000 && va < 0x12346000) {
return 0x22345000 + (va - 0x12345000);
} else if (va >= 0x23456000 && va < 0x23457000) {
return 0x33456000 + (va - 0x23456000);
} else {
return (size_t)-1;
}
}
size_t tlb_translate(size_t va) {
size_t vpn = va >> POBITS;
int set = vpn % TLB_SETS;
for (int i = 0; i < TLB_WAYS; i++) {
if (tlb[set][i].valid && tlb[set][i].vpn == vpn) {
update_lru(set, i);
return (tlb[set][i].ppn << POBITS) | (va & ((1 << POBITS) - 1));
}
}
size_t pa = translate(vpn << POBITS);
if (pa == (size_t)-1) return (size_t)-1;
int lru_way = 0;
for (int i = 1; i < TLB_WAYS; i++) {
if (tlb[set][i].lru_counter > tlb[set][lru_way].lru_counter) {
lru_way = i;
}
}
tlb[set][lru_way].vpn = vpn;
tlb[set][lru_way].ppn = pa >> POBITS;
tlb[set][lru_way].valid = 1;
update_lru(set, lru_way);
return (tlb[set][lru_way].ppn << POBITS) | (va & ((1 << POBITS) - 1));
}
int main() {
tlb_clear();
printf("Translating VA: 0x12345678\n"); size_t pa = tlb_translate(0x12345678);
if (pa == (size_t)-1) {
printf("Translation failed for VA: 0x12345678\n"); } else {
printf("Translated PA: 0x%zx\n", pa
); }
printf("Translating VA: 0x23456789\n"); pa = tlb_translate(0x23456789);
if (pa == (size_t)-1) {
printf("Translation failed for VA: 0x23456789\n"); } else {
printf("Translated PA: 0x%zx\n", pa
); }
return 0;
}