The user is asking for a page replacement algorithm for a custom operating system, but they haven't given specific constraints or requirements. I think I should clarify their goals, like minimizing page faults and ensuring fairness.
There are a couple of algorithms I could propose, such as a hybrid between LRU and CLOCK. It may be useful to structure my response to address key aspects like algorithm details, data structures, and integration with the OS. This way, I'm covering the necessary bases without overwhelming them.Choosing a page replacement algorithm
I’m zeroing in on a concrete algorithm for a general-purpose OS. A good option might be a CLOCK variant that’s aware of the working set, perhaps calling it a "WSClock-like algorithm." This approach approximates the working set and can handle clean and dirty bits, which helps with I/O clustering.
However, I should consider simpler options like Adaptive Replacement Cache (ARC), but it's patented. CLOCK-Pro is another choice but may also be patented, so I’ll be cautious about potential IP issues. The user hasn’t directly asked about patents, but it’s safer to recommend widely used algorithms like CLOCK, LRU, or NRU instead.Designing a custom page replacement algorithm
I think it's better to design a custom algorithm, like an "Aging CLOCK" or a "two-handed clock" with active and inactive lists, somewhat inspired by Linux's LRU list. While the exact Linux algorithm may be bound by the GPL, I can develop the concept. I propose creating "Active/Inactive LRU lists with second-chance reference bits." This would involve maintaining two lists for pages, promoting them to active upon reference and reclaiming from the inactive list when free frames are needed, using reference and dirty bits for second chances. This design is robust, widely used, and could include global counters for tuning and per-page structures for reference and dirty bits.Planning the response
I’m organizing my response into several sections. First, I’ll state the design goals and assumptions, like demand-paging with hardware support, noting that we assume the presence of reference and dirty bits.
In the second section, I'll outline a high-level design using an adaptive two-list CLOCK-LRU algorithm, with an active list for recently used pages and an inactive list for cold pages. I can suggest a background scanner to balance these lists.
Next, I’ll detail the data structures, such as a page structure that includes various reference bits and links, along with global lists. Finally, I’ll explain the algorithm details, including handling page access, balancing the lists, and the reclamation routine for managing eviction and writebacks.Designing the page replacement algorithm
To build my page replacement algorithm, I need to include key operations for handling page evictions. When pages are clean and unreferenced, I'll evict them by unmapping from processes and adding them to the free list. If the inactive list is empty, I’ll demote pages from the active tail.
I'll also incorporate additional heuristics for things like aging counters and thrashing detection to manage working sets effectively. In my structured response, I plan to present the algorithm called "Active/Inactive Clock (AIC)," focusing on detailed pseudocode, data structures, and tuning variations while ensuring it fits general OS contexts without directly copying Linux's code. Below is a complete design for a practical, general-purpose page replacement algorithm suitable for a custom OS. It’s a low-overhead approximation of LRU using active/inactive lists and reference bits, similar in spirit to what modern Unix-like systems do.
1. Goals & assumptions
Goals
Low page-fault rate on typical workloads.
Low overhead (no full LRU queues, no per-access traps).
Works for both file-backed and anonymous pages.
Reasonable behavior under memory pressure and during thrashing.
Assumptions
Hardware MMU with per-page:
Present bit
Reference (accessed) bit
Dirty (modified) bit
OS maintains a struct page for each physical frame.
Demand-paging system with a backing store (swap and/or files).
If some of these are missing (e.g., no reference bit), I’ll mention adaptations at the end.
2. High-level idea: Active/Inactive Clock (AIC)
Maintain two main sets of resident pages:
Active list: Pages that have been used recently (protected working set).
Inactive list: Pages that are colder and are candidates for eviction.
Use reference bits to give “second chances” and adaptively move pages between lists:
When a page is referenced:
Mark its reference bit.
If it’s on the inactive list, promote it to the active list.
When memory is needed:
Reclaim from the tail of the inactive list.
If a candidate has its reference bit set, clear the bit and move it back to the active list (second chance).
If it’s not referenced and clean → evict.
If it’s not referenced but dirty → start write-back; evict once clean.
This approximates LRU without maintaining a precise total ordering.
3. Data structures
3.1 Per-page metadata
c
typedef enum {
PAGE_FILE, // file-backed page
PAGE_ANON // anonymous (swap-backed)
} page_type_t;
typedef struct page {
uintptr_t frame_number; // physical frame index
bool in_active; // true if in active list, else inactive or free
bool referenced; // shadow of hardware ref bit (optional)
bool dirty; // shadow of hardware dirty bit (optional)
page_type_t type;
void *backing_object; // file or swap object
uint64_t backing_offset; // offset within that object
struct page *prev, *next; // for list linkage
} page_t;
You may keep referenced and dirty as software shadows kept in sync by periodically reading/clearing the PTE bits.
3.2 Global state
c
typedef struct {
page_t *head;
page_t *tail;
uint64_t length;
} page_list_t;
page_list_t active_list;
page_list_t inactive_list;
page_list_t free_list; // completely free frames
// Targets (can be tunable):
uint64_t total_pages; // total physical frames
uint64_t target_active; // e.g., ~2/3 of non-free pages
uint64_t target_inactive; // e.g., ~1/3 of non-free pages
// Locks (at least one each or a global VM lock)
spinlock_t active_lock;
spinlock_t inactive_lock;
spinlock_t free_lock;
You’ll also maintain per-process page tables pointing to these page_t structures.
4. Core algorithm behavior
4.1 On page fault
When a process references a virtual address vaddr that is not present:
Resolve the backing object
For file-backed memory: determine file and offset.
For anonymous memory: determine swap slot (or allocate one if needed).
Obtain a physical frame
If free_list not empty: pop one.
Else: call reclaim_pages(needed = 1).
Read page from backing store (if not already resident elsewhere).
Map into page table
Mark present.
Clear hardware reference bit.
Set hardware dirty bit to 0 (will be set on writes).
Insert into inactive list (new pages start inactive):
push_front(&inactive_list, page);
This allows the algorithm to decide whether the page should become “active” based on subsequent references.
4.2 On page access (reference handling)
You usually do not trap on every access. Instead, you periodically scan page tables (or selected pages) to:
Read and clear the hardware reference bit.
If the bit was set:
Mark the page as referenced.
If the page is on the inactive list → move it to the head of the active list.
Pseudo-step typically done by a background VM daemon:
Frequency of this scanning is a tuning knob (e.g., every 100 ms, or tied to number of page faults).
4.3 Balancing active vs. inactive lists
A separate background daemon (like kswapd/pageout) runs periodically or when memory is low:
Keeps active_list.length near target_active.
Keeps inactive_list.length near target_inactive.
Policy:
If active list is too big, demote pages from tail of active to head of inactive, possibly clearing their referenced flag.
If inactive list is too small, demote more from active until targets are met.
c
void balance_lists() {
uint64_t non_free = total_pages - free_list.length;
target_active = non_free * 2 / 3;
target_inactive = non_free - target_active;
while (active_list.length > target_active) {
page_t *p = pop_back(&active_list); // least recently active
p->in_active = false;
p->referenced = false; // reset its recency
push_front(&inactive_list, p);
}
// If inactive_list is too small, you can similarly demote more.
}
4.4 Selecting a victim page (reclamation)
The reclamation routine tries to free frames until it satisfies the request (or hits some limit):
c
uint64_t reclaim_pages(uint64_t needed) {
uint64_t reclaimed = 0;
balance_lists();
while (reclaimed < needed) {
if (inactive_list.length == 0) {
// No candidates: demote from active
balance_lists();
if (inactive_list.length == 0) break; // can't reclaim more
}
page_t *victim = pop_back(&inactive_list);
// Refresh reference & dirty from hardware:
bool hw_ref = read_and_clear_hw_ref_bit(victim);
bool hw_dirty = read_hw_dirty_bit(victim);
victim->referenced |= hw_ref;
victim->dirty |= hw_dirty;
if (victim->referenced) {
// Give a second chance: move back to active
victim->referenced = false; // consumed
move_to_active(victim);
continue;
}
if (victim->dirty) {
// Schedule write-back and put it on a "laundry" queue
schedule_writeback(victim);
// After I/O completes, the page will be placed back on the
// inactive list but now clean, to be reclaimed later.
continue;
}
// Clean & unreferenced: evict
unmap_from_all_processes(victim);
remove_from_backing_if_needed(victim); // optional
add_to_free_list(victim);
reclaimed++;
}
return reclaimed;
}
Key points:
Second chance: The ref bit gives pages one more chance before eviction.
Write-back separation: Avoid blocking reclaim on I/O; write dirty pages in background.
Bias against evicting hot pages: Because referenced pages are promoted to active, pages that remain on inactive without being referenced are more likely to be truly cold.
5. Integration details
5.1 File-backed vs anonymous pages
File-backed pages
Clean eviction: just drop them; they can be re-read from file.
Dirty eviction: write back to file then treat as clean.
Anonymous pages
Must have a swap slot; if dirty and not yet in swap, allocate a swap slot and write page contents.
On clean eviction (after writeback), the swap slot holds the current content.
5.2 Handling thrashing
To avoid system-wide thrashing:
Track global page fault rate.
If it exceeds a threshold:
Increase reclamation aggressiveness (scan more pages).
Optionally impose per-process working set limits:
E.g., keep a per-process count of pages on active+inactive lists.
When reclaiming, prefer pages from processes that exceed some share of memory.
5.3 Concurrency
Protect each list with a spinlock or mutex.
The page fault handler, reclaim daemon, and write-back daemon can run concurrently.
Consider batching: reclaim in chunks to reduce lock contention.
6. Possible enhancements
You can extend the above baseline in multiple ways, depending on needs:
Aging
Maintain a small integer age per page that you shift and OR with the ref bit on each scan, to approximate LRU with more history.
Priority-based eviction
Mark certain pages as “pinned” or “high priority” (e.g., kernel data structures) that are never or rarely evicted.
Use separate queues or priority levels.
Sequential access detection
If a file is being read sequentially and a page is accessed only once, avoid promoting it to active.
This prevents sequential scans from polluting the active list.
NUMA-aware variants
Maintain separate lists per NUMA node.
Prefer reclaiming from a node’s local memory when a CPU on that node runs out.
7. If you lack hardware reference/dirty bits
If your MMU does not provide these bits:
Software reference bit emulation
Periodically clear present bits in PTEs of candidate pages; on next access you take a page fault:
In the handler: mark the page referenced and restore present bit.
Do this only for inactive pages or for a sampling subset to keep overhead manageable.
Software dirty bit
Map pages read-only until a write fault occurs, then mark dirty and restore write permission.
This increases fault overhead but works in minimal hardware environments.
8. Summary
The proposed Active/Inactive Clock (AIC) algorithm:
Uses two lists (active/inactive) plus hardware reference/dirty bits.
Promotes recently referenced pages to active, and evicts cold, clean pages from inactive.
Gives each candidate a second chance based on the reference bit.
Handles dirty pages with asynchronous write-back before eviction.
Is simple, efficient, and proven in practice as a good approximation to LRU.
If you share some constraints (e.g., embedded vs server, presence/absence of MMU features, whether this is for a class project or production), I can tailor this design further and provide more concrete pseudocode or data-structure layouts.