------------------------------------------------------------------------------
MC logo
NRU Implementation
[^] CSc 422 Assignment 4
------------------------------------------------------------------------------
[CSc 422 Assignment 1] [CSc 422 Assignment 2] [CSc 422 Assignment 3] [CSc 422 Assignment 4]
[Replacement Main] [replacement_h] [replacement_cpp] [FIFO Class] [LRU Class] [LRU Implementation] [NRU Class] [NRU Implementation] [Reader Test Class]
nru.cpp
#include "nru.h"

// Attempt to choose a page to replace using an NRU algorithm.  This
// implementation searches all the real pages, and starts each search
// with the page after the last one found.
unsigned long NRUReplacementAlg::fault(const Ref &r) {
        // Stuff we found (by class).  The class 3 is filled in with the
        // starting page.  It may not be class 3, but we won't use the entry
        // unless it happens to be true (in fact, when all pages are class 3).
        bool found[4] = { false, false, false, true };
        unsigned long which[4] = { 0, 0, 0, m_scan_start };

        // Search for one of each class.  If we find a 0, end the search.
        unsigned long scan = m_scan_start;
        do {  // If it rolls around, will find a cleared entry.
                int pageclass = cl(get_PTE_by_frame(scan));
                if(pageclass < 3 && !found[pageclass]) {
                        found[pageclass] = true;
                        which[pageclass] = scan;
                        if(pageclass == 0) break;
                }

                increal(scan);
        } while(scan != m_scan_start);

        // See what we found, and return it.
        for(int cl = 0; cl <= 3; ++cl) {
                // The last entry of found[] is true, so this if will always
                // be true in some iteration.
                if(found[cl]) {
                        m_scan_start = which[cl];
                        return increal(m_scan_start);
                }
        }
}

// Clear all the referenced bits.
void NRUReplacementAlg::maint()
{
        for(unsigned long frameno = 0; frameno < get_num_frames(); ++frameno) {
                PTE *pte = get_PTE_by_frame(frameno);
                if(pte) pte->clr_ref();
        }
}