@@ -199,6 +199,54 @@ void mmu_invalidate(hart_t *vm)
199199 }
200200}
201201
202+ /* Invalidate MMU caches for a specific virtual address range.
203+ * If size is 0 or -1, invalidate all caches (equivalent to mmu_invalidate()).
204+ * Otherwise, only invalidate cache entries whose VPN falls within
205+ * [start_addr >> PAGE_SHIFT, (start_addr + size - 1) >> PAGE_SHIFT].
206+ */
207+ void mmu_invalidate_range (hart_t * vm , uint32_t start_addr , uint32_t size )
208+ {
209+ /* SBI spec: size == 0 or size == -1 means flush entire address space */
210+ if (size == 0 || size == (uint32_t ) -1 ) {
211+ mmu_invalidate (vm );
212+ return ;
213+ }
214+
215+ /* Calculate VPN range: [start_vpn, end_vpn] inclusive.
216+ * Use 64-bit arithmetic to prevent overflow when (start_addr + size - 1)
217+ * exceeds UINT32_MAX. For example:
218+ * start_addr = 0xFFF00000, size = 0x00200000
219+ * 32-bit: 0xFFF00000 + 0x00200000 - 1 = 0x000FFFFF (wraps)
220+ * 64-bit: 0xFFF00000 + 0x00200000 - 1 = 0x100FFFFF (correct)
221+ * Clamp to RV32 address space maximum before calculating end_vpn.
222+ */
223+ uint32_t start_vpn = start_addr >> RV_PAGE_SHIFT ;
224+ uint64_t end_addr = (uint64_t ) start_addr + size - 1 ;
225+ if (end_addr > UINT32_MAX )
226+ end_addr = UINT32_MAX ;
227+ uint32_t end_vpn = (uint32_t ) end_addr >> RV_PAGE_SHIFT ;
228+
229+ /* Check each cache entry and invalidate if in range.
230+ * Since we only have 4 cache entries total (fetch: 1, load: 2, store: 1),
231+ * simple sequential checks are sufficient.
232+ */
233+ if (vm -> cache_fetch .n_pages >= start_vpn &&
234+ vm -> cache_fetch .n_pages <= end_vpn )
235+ vm -> cache_fetch .n_pages = 0xFFFFFFFF ;
236+
237+ if (vm -> cache_load [0 ].n_pages >= start_vpn &&
238+ vm -> cache_load [0 ].n_pages <= end_vpn )
239+ vm -> cache_load [0 ].n_pages = 0xFFFFFFFF ;
240+
241+ if (vm -> cache_load [1 ].n_pages >= start_vpn &&
242+ vm -> cache_load [1 ].n_pages <= end_vpn )
243+ vm -> cache_load [1 ].n_pages = 0xFFFFFFFF ;
244+
245+ if (vm -> cache_store .n_pages >= start_vpn &&
246+ vm -> cache_store .n_pages <= end_vpn )
247+ vm -> cache_store .n_pages = 0xFFFFFFFF ;
248+ }
249+
202250/* Pre-verify the root page table to minimize page table access during
203251 * translation time.
204252 */
0 commit comments