/*
 * 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.
 *
 * Author: Éder F. Zulian
 */

#include <iostream>
#include <algorithm>
#include <set>
#include "ActBChecker.h"
#include "../../TimingCalculation.h"
#include "../../../../common/DebugManager.h"
#include "../../../Command.h"
#include "../../../../common/Utils.h"

using namespace std;

void ActBChecker::delayToSatisfyConstraints(ScheduledCommand &cmd) const
{
    sc_assert(cmd.getCommand() == Command::ActB);
    ScheduledCommand lcb = state.getLastScheduledCommand(cmd.getBank());
    if (lcb.isValidCommand()) {
        if (lcb.getCommand() == Command::PreB) {
            cmd.establishMinDistanceFromStart(lcb.getStart(),
                                              Configuration::getInstance().getTrpb());
        } else if (lcb.getCommand() == Command::Precharge
                   || lcb.getCommand() == Command::PrechargeAll) {
            cmd.establishMinDistanceFromStart(lcb.getStart(), config.memSpec.tRP);
        } else if (lcb.getCommand() == Command::ReadA) {
            cmd.establishMinDistanceFromStart(lcb.getStart(),
                                              config.memSpec.tRTP + config.memSpec.tRP);
        } else if (lcb.getCommand() == Command::WriteA) {
            cmd.establishMinDistanceFromStart(lcb.getStart(),
                                              config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR +
                                              config.memSpec.tRP);
        } else if (lcb.getCommand() == Command::AutoRefresh) {
            auto m = Configuration::getInstance().getRefMode();
            if (m == 4)
                cmd.establishMinDistanceFromStart(lcb.getStart(), config.memSpec.tRFC4);
            else if (m == 2)
                cmd.establishMinDistanceFromStart(lcb.getStart(), config.memSpec.tRFC2);
            else
                cmd.establishMinDistanceFromStart(lcb.getStart(), config.memSpec.tRFC);
        } else if (lcb.getCommand() == Command::PDNPX
                   || lcb.getCommand() == Command::PDNAX) {
            cmd.establishMinDistanceFromStart(lcb.getStart(), config.memSpec.tXP);
        } else if (lcb.getCommand() == Command::SREFX) {
            cmd.establishMinDistanceFromStart(lcb.getStart(), config.memSpec.tXSR);
        } else {
            reportFatal("ActB Checker",
                        "ActB can not follow " + commandToString(lcb.getCommand()));
        }
    }
    ScheduledCommand lc;
    if ((lc = state.getLastCommand(Command::PrechargeAll)).isValidCommand()) {
        cmd.establishMinDistanceFromStart(lc.getStart(), config.memSpec.tRP);
    }
    delay_to_satisfy_activateToActivate_sameBank(cmd);
    while (!(state.bus.isFree(cmd.getStart())
             && satsfies_activateToActivate_differentBank(cmd)
             && satisfies_nActivateWindow(cmd))) {
        cmd.delayStart(config.memSpec.clk);
    }
}

void ActBChecker::delay_to_satisfy_activateToActivate_sameBank(
    ScheduledCommand &cmd) const
{
    ScheduledCommand lastActOnBank = state.getLastCommand(Command::Activate,
                                                          cmd.getBank());
    if (lastActOnBank.isValidCommand()) {
        cmd.establishMinDistanceFromStart(lastActOnBank.getStart(), config.memSpec.tRC);
    }
    ScheduledCommand lastActBOnBank = state.getLastCommand(Command::ActB,
                                                           cmd.getBank());
    if (lastActBOnBank.isValidCommand()) {
        cmd.establishMinDistanceFromStart(lastActBOnBank.getStart(),
                                          Configuration::getInstance().getTrcb());
    }
}

bool ActBChecker::satsfies_activateToActivate_differentBank(
    ScheduledCommand &cmd) const
{
    for (auto act : state.lastActivatesB) {
        sc_time t = act.first, tRRD = (cmd.getBankGroup() == act.second.getBankGroup() ?
                                       Configuration::getInstance().getTrrdb_L() :
                                       Configuration::getInstance().getTrrdb_S());
        if ((t < cmd.getStart() && cmd.getStart() - t < tRRD) || (cmd.getStart() <= t
                                                                  && t - cmd.getStart() < tRRD)) {
            return false;
        }
    }
    for (auto act : state.lastActivates) {
        sc_time t = act.first, tRRD = (cmd.getBankGroup() == act.second.getBankGroup() ?
                                       config.memSpec.tRRD_L : config.memSpec.tRRD_S);
        if ((t < cmd.getStart() && cmd.getStart() - t < tRRD) || (cmd.getStart() <= t
                                                                  && t - cmd.getStart() < tRRD)) {
            return false;
        }
    }
    return true;
}

bool ActBChecker::satisfies_nActivateWindow(ScheduledCommand &cmd) const
{
    if (state.lastActivatesB.size() >= config.memSpec.nActivate) {
        map<sc_time, ScheduledCommand>lastActivates = state.lastActivatesB;
        lastActivates.emplace(cmd.getStart(), cmd);
        auto upper = lastActivates.begin();
        advance(upper, config.memSpec.nActivate);
        auto lower = lastActivates.begin();
        while (upper != lastActivates.end()) {
            if (upper->first - lower->first < Configuration::getInstance().getTfawb()) {
                return false;
            }
            ++upper;
            ++lower;
        }
    }
    return true;
}
