/*
 * 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 "WriteChecker.h"
#include "../../TimingCalculation.h"
#include "../../../../common/Utils.h"
#include "ReadChecker.h"

using namespace std;

void WriteChecker::delayToSatisfyConstraints(ScheduledCommand &command) const
{
    sc_assert(command.getCommand() == Command::Write
              || command.getCommand() == Command::WriteA);

    ScheduledCommand lastCommand = state.getLastScheduledCommand(command.getBank());

    if (lastCommand.isValidCommand()) {
        if (lastCommand.getCommand() == Command::Activate
                || lastCommand.getCommand() == Command::ActB) {
            command.establishMinDistanceFromStart(lastCommand.getStart(),
                                                  config.memSpec.tRCD);
        } else if (lastCommand.getCommand() == Command::Read) {
            command.establishMinDistanceFromStart(lastCommand.getStart(),
                                                  WriteChecker::readToWrite(lastCommand, command));
        } else if (lastCommand.getCommand() == Command::Write) {
            command.establishMinDistanceFromStart(lastCommand.getStart(),
                                                  WriteChecker::writeToWrite(lastCommand, command));
        } else if (lastCommand.getCommand() == Command::PDNPX
                   || lastCommand.getCommand() == Command::PDNAX) {
            command.establishMinDistanceFromStart(lastCommand.getStart(),
                                                  config.memSpec.tXP);
        } else
            reportFatal("Write Checker",
                        "Write can not follow " + commandToString(lastCommand.getCommand()));
    }

    while (!state.bus.isFree(command.getStart()) || collidesOnDataStrobe(command)) {
        command.delayStart(config.memSpec.clk);
    }
}

bool WriteChecker::collidesOnDataStrobe(ScheduledCommand &write) const
{
    for (ScheduledCommand &strobeCommand : state.lastDataStrobeCommands) {
        if (collidesWithStrobeCommand(write, strobeCommand))
            return true;
    }

    return false;
}

bool WriteChecker::collidesWithStrobeCommand(ScheduledCommand &write,
                                             ScheduledCommand &strobeCommand) const
{
    if (strobeCommand.getCommand() == Command::Write
            || strobeCommand.getCommand() == Command::WriteA) {
        return getDistance(write.getStart(),
                           strobeCommand.getStart()) < WriteChecker::writeToWrite(strobeCommand, write);
    } else if (strobeCommand.getCommand() == Command::Read
               || strobeCommand.getCommand() == Command::ReadA) {
        if (strobeCommand.getStart() >= write.getStart())
            return getDistance(write.getStart(),
                               strobeCommand.getStart()) < ReadChecker::writeToRead(write, strobeCommand);
        else
            return getDistance(strobeCommand.getStart(),
                               write.getStart()) < WriteChecker::readToWrite(strobeCommand, write);
    } else {
        reportFatal("Write Checker",
                    "Invalid strobeCommand in data strobe commands " + commandToString(
                        strobeCommand.getCommand()));
        return true;
    }
}

sc_time WriteChecker::writeToWrite(ScheduledCommand &firstWrite,
                                   ScheduledCommand &secondWrite)
{
    sc_assert(firstWrite.getCommand() == Command::Write
              || firstWrite.getCommand() == Command::WriteA);
    sc_assert(secondWrite.getCommand() == Command::Write
              || secondWrite.getCommand() == Command::WriteA);

    MemSpec &config = Configuration::getInstance().memSpec;
    sc_time tCCD = (firstWrite.getBankGroup() == secondWrite.getBankGroup()) ?
                   config.tCCD_L : config.tCCD_S;
    return max(tCCD, getWriteAccessTime());
}

sc_time WriteChecker::readToWrite(ScheduledCommand &read __attribute__((
                                                                           unused)), ScheduledCommand &write __attribute__((unused)))
{
    sc_assert(read.getCommand() == Command::Read
              || read.getCommand() == Command::ReadA);
    sc_assert(write.getCommand() == Command::Write
              || write.getCommand() == Command::WriteA);

    MemSpec &config = Configuration::getInstance().memSpec;
    return config.tRL + getReadAccessTime() - config.tWL + config.clk * 2;
}

