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

using namespace std;

void ReadChecker::delayToSatisfyConstraints(ScheduledCommand &command) const
{
    sc_assert(command.getCommand() == Command::Read
              || command.getCommand() == Command::ReadA);
    delayToSatisfyDLL(command);
    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(),
                                                  ReadChecker::readToRead(lastCommand, command));
        } else if (lastCommand.getCommand() == Command::Write) {
            command.establishMinDistanceFromStart(lastCommand.getStart(),
                                                  ReadChecker::writeToRead(lastCommand, command));
        } else if (lastCommand.getCommand() == Command::PDNPX
                   || lastCommand.getCommand() == Command::PDNAX) {
            command.establishMinDistanceFromStart(lastCommand.getStart(),
                                                  config.memSpec.tXP);
        } else
            reportFatal("Read Checker",
                        "Read can not follow " + commandToString(lastCommand.getCommand()));
    }

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

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

    return false;
}

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

void ReadChecker::delayToSatisfyDLL(ScheduledCommand &read) const
{
    ScheduledCommand lastSREFX = state.getLastCommand(Command::SREFX,
                                                      read.getBank());
    if (lastSREFX.isValidCommand())
        read.establishMinDistanceFromStart(lastSREFX.getStart(),
                                           config.memSpec.tXSRDLL);
}

sc_time ReadChecker::readToRead(ScheduledCommand &firstRead,
                                ScheduledCommand &secondRead)
{
    sc_assert(firstRead.getCommand() == Command::Read
              || firstRead.getCommand() == Command::ReadA);
    sc_assert(secondRead.getCommand() == Command::Read
              || secondRead.getCommand() == Command::ReadA);

    MemSpec &config = Configuration::getInstance().memSpec;
    sc_time tCCD = (firstRead.getBankGroup() == secondRead.getBankGroup()) ?
                   config.tCCD_L : config.tCCD_S;
    return max(tCCD, getReadAccessTime());
}

sc_time ReadChecker::writeToRead(ScheduledCommand &write,
                                 ScheduledCommand &read)
{
    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;
    sc_time tWTR = (write.getBankGroup() == read.getBankGroup()) ? config.tWTR_L :
                   config.tWTR_S;
    return config.tWL + getWriteAccessTime() + tWTR;
}

