calculate_tag Function:
The calculate_tag function computes the tag for a given memory address and cache size. The tag uniquely identifies a block of memory within a cache set.
c
uint32_t calculate_tag(uint32_t address, uint32_t cache_size) { return address / BLOCK_SIZE / cache_size; }
calculate_index Function:
The calculate_index function calculates the cache index for a given memory address and cache size. The index determines the specific set in the cache where the data will be stored.
c
uint32_t calculate_index(uint32_t address, uint32_t cache_size) { return (address / BLOCK_SIZE) % cache_size; }
check_cache Function:
The check_cache function checks whether the requested data is present in the cache. It takes the cache itself, the target address, and a pointer to store the retrieved data as input.
c
bool check_cache(CacheLine *cache, uint32_t cache_size, uint32_t address, uint8_t* data) { uint32_t tag = calculate_tag(address, cache_size); uint32_t index = calculate_index(address, cache_size); if (cache[index].valid && cache[index].tag == tag) { memcpy(data, cache[index].data, BLOCK_SIZE); return true; } return false; }
update_cache Function:
The update_cache function updates the cache with new data. It adds or updates the data within the cache and ensures it is marked as valid.
c
void update_cache(CacheLine *cache, uint32_t cache_size, uint32_t address, uint8_t* data) { uint32_t tag = calculate_tag(address, cache_size); uint32_t index = calculate_index(address, cache_size); cache[index].tag = tag; memcpy(cache[index].data, data, BLOCK_SIZE); cache[index].valid = true; }