/*
 * Copyright (c) 2017, University of Kaiserslautern
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors:
 *    Matthias Jung
 */

#include "Fr_Fcfs_read_priority.h"

// The FR_FCFS_Read_Priority works exactly like the FR_FCFS but reads are
// prioratized over writes. For detailed documentation look into the FR_FCFS.

std::pair<Command, gp *> FR_FCFS_RP::getNextRequest(Bank bank)
{
    // If the bank is empty like Bank0 in the example we do nothing:
    if (buffer[bank].empty()) {
        return pair<Command, tlm::tlm_generic_payload *>(Command::NOP, NULL);
    }

    // Order of Priority:
    // 1. Read Hits (Hazard Check)
    // 2. Write Hits
    // 3. Read Miss (Hazard Check)
    // 4. Write Miss

    // 1. Seach for read hit:
    for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) {
        gp *read = *it;

        if (read->get_command() == tlm::TLM_READ_COMMAND) {
            // If there is a row hit:
            if (DramExtension::getRow(read)
                    == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) {
                if (hazardDetection(bank, it) == false) {
                    buffer[bank].erase(it);
                    printDebugMessage("Read Hit found");
                    return pair<Command, gp *>(getReadWriteCommand(*read), read);
                }
            }
        }
    }

    // 2. Search for write hit:
    for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) {
        gp *write = *it;

        if (write->get_command() == tlm::TLM_WRITE_COMMAND) {
            // If there is a row hit:
            if (DramExtension::getRow(write)
                    == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) {
                buffer[bank].erase(it);
                printDebugMessage("Write Hit found");
                return pair<Command, gp *>(getReadWriteCommand(*write), write);
            }
        }
    }

    // For now return the oldest request but prefere also reads before writes:

    // 3. Search for read miss:
    for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) {
        gp *read = *it;

        if (read->get_command() == tlm::TLM_READ_COMMAND) {
            if (hazardDetection(bank, it) == false) {
                printDebugMessage("Read miss found");
                return pair<Command, gp *>(getNextCommand(read), read);
            }
        }
    }

    // 3. Search for write miss:
    for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) {
        gp *write = *it;

        if (write->get_command() == tlm::TLM_WRITE_COMMAND) {
            printDebugMessage("Write miss found");
            return pair<Command, gp *>(getNextCommand(write), write);
        }
    }

    reportFatal("FR_FCFS_RP", "Never should go here ...");
    return pair<Command, tlm::tlm_generic_payload *>(Command::NOP, NULL);
}

// There is a hazard if a read is found which will be scheduled before a write
// to the same column and the same row of the same bank:
bool FR_FCFS_RP::hazardDetection(Bank bank, std::deque<gp *>::iterator ext)
{
    gp *read = *ext;

    //for(unsigned long i=0; i < id; i++)
    for (auto it = buffer[bank].begin(); it != ext; it++) {
        gp *write = *it;
        if (write->get_command() == tlm::TLM_WRITE_COMMAND) {
            if ((DramExtension::getExtension(read).getColumn()
                    == DramExtension::getExtension(write).getColumn())
                    && (DramExtension::getExtension(read).getRow()
                        == DramExtension::getExtension(write).getRow())) {
                printDebugMessage("Hazard Detected");
                return true;
            }
        }
    }
    return false;
}

void FR_FCFS_RP::printDebugMessage(std::string message)
{
    DebugManager::getInstance().printDebugMessage("FR_FCFS_RP", message);
}
