/*
 * Copyright (c) 2015, 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:
 *    Janik Schlemminger
 *    Matthias Jung
 */

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

using namespace std;

void ActivateChecker::delayToSatisfyConstraints(ScheduledCommand &command) const
{
    sc_assert(command.getCommand() == Command::Activate);

    ScheduledCommand lastCommandOnBank = state.getLastScheduledCommand(
                                             command.getBank());
    if (lastCommandOnBank.isValidCommand()) {
        if (lastCommandOnBank.getCommand() == Command::PreB
                || lastCommandOnBank.getCommand() == Command::Precharge
                || lastCommandOnBank.getCommand() == Command::PrechargeAll) {
            command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                  config.memSpec.tRP);
        } else if (lastCommandOnBank.getCommand() == Command::ReadA) {
            command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                  config.memSpec.tRTP + config.memSpec.tRP);
        } else if (lastCommandOnBank.getCommand() == Command::WriteA) {
            command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                  config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR +
                                                  config.memSpec.tRP);
        } else if (lastCommandOnBank.getCommand() == Command::AutoRefresh) {
            auto m = Configuration::getInstance().getRefMode();
            if (m == 4)
                command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                      config.memSpec.tRFC4);
            else if (m == 2)
                command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                      config.memSpec.tRFC2);
            else
                command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                      config.memSpec.tRFC);
        } else if (lastCommandOnBank.getCommand() == Command::PDNPX
                   || lastCommandOnBank.getCommand() == Command::PDNAX) {
            command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                  config.memSpec.tXP);
        } else if (lastCommandOnBank.getCommand() == Command::SREFX) {
            command.establishMinDistanceFromStart(lastCommandOnBank.getStart(),
                                                  config.memSpec.tXSR);
        } else
            reportFatal("Activate Checker",
                        "Activate can not follow " + commandToString(lastCommandOnBank.getCommand()));
    }

    delay_to_satisfy_activateToActivate_sameBank(command);

    while (!(state.bus.isFree(command.getStart())
             && satsfies_activateToActivate_differentBank(command)
             && satisfies_nActivateWindow(command))) {
        command.delayStart(config.memSpec.clk);
    }

}

void ActivateChecker::delay_to_satisfy_activateToActivate_sameBank(
    ScheduledCommand &command) const
{
    ScheduledCommand lastActivateOnBank = state.getLastCommand(Command::Activate,
                                                               command.getBank());
    if (lastActivateOnBank.isValidCommand()) {
        command.establishMinDistanceFromStart(lastActivateOnBank.getStart(),
                                              config.memSpec.tRC);
    }

    ScheduledCommand lastActBOnBank = state.getLastCommand(Command::ActB,
                                                           command.getBank());
    if (lastActBOnBank.isValidCommand()) {
        command.establishMinDistanceFromStart(lastActivateOnBank.getStart(),
                                              config.memSpec.tRC);
    }
}

bool ActivateChecker::satsfies_activateToActivate_differentBank(
    ScheduledCommand &command) const
{
    for (auto act : state.lastActivates) {
        sc_time time = act.first;
        sc_time tRRD = (command.getBankGroup() == act.second.getBankGroup()) ?
                       config.memSpec.tRRD_L : config.memSpec.tRRD_S;

        if ((time < command.getStart() && command.getStart() - time < tRRD)
                || (command.getStart() <= time && time - command.getStart() < tRRD))
            return false;
    }
    return true;
}

bool ActivateChecker::satisfies_nActivateWindow(ScheduledCommand &command) const
{
    /*
     * there may be activates scheduled in the future, so emplace
     * command in a copied set (not necessarily the last in time),
     * and check if the n-act constraint holds for the whole set.
     */
    if (state.lastActivates.size() >= config.memSpec.nActivate) {
        map<sc_time, ScheduledCommand> lastActivates = state.lastActivates;
        lastActivates.emplace(command.getStart(), command);
        auto upper = lastActivates.begin();
        advance(upper, config.memSpec.nActivate);
        auto lower = lastActivates.begin();

        while (upper != lastActivates.end()) {
            if (upper->first - lower->first < config.memSpec.tNAW)
                return false;
            ++upper;
            ++lower;
        }
    }

    return true;
}
