/*
 * 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 "PowerDownManager.h"
#include "../ControllerCore.h"
#include "../../../common/Utils.h"
#include "../../../common/DebugManager.h"
#include "../TimingCalculation.h"

using namespace tlm;

PowerDownManagerBankwise::PowerDownManagerBankwise(sc_module_name /*name*/,
                                                   ControllerCore &controllerCore) : controllerCore(controllerCore)
{
    for (Bank bank : controllerCore.getBanks()) {
        setUpDummy(powerDownPayloads[bank], bank);
        powerDownStates[bank] = PowerDownState::Awake;
        //controllerCore.controller.send(PDNTrigger, sc_time_stamp(), powerDownPayloads[bank]);
    }
}

void PowerDownManagerBankwise::sleep(Bank bank, sc_time time)
{
    if (!canSleep(bank) || isInPowerDown(bank))
        return;

    tlm_generic_payload &payload = powerDownPayloads[bank];

    PowerDownState state = powerDownStates[bank];
    if (state == PowerDownState::Awake) { //coming from active
        state = controllerCore.state->rowBufferStates->rowBufferIsOpen(
                    bank) ? PowerDownState::PDNActive : PowerDownState::PDNPrecharge;
    } else if (state ==
               PowerDownState::AwakeForRefresh) { //coming from refresh interrupting power down
        sc_assert(!controllerCore.state->rowBufferStates->rowBufferIsOpen(bank));

        if (controllerCore.state->getLastCommand(Command::PDNA, bank).getStart()
                >= controllerCore.state->getLastCommand(Command::PDNP, bank).getStart())
            state = PowerDownState::PDNPrecharge;
        else {
            state = PowerDownState::PDNSelfRefresh;
        }
    }

    Command cmd = IPowerDownManager::getSleepCommand(state);
    ScheduledCommand pdn(cmd, time, getMinExecutionTimeForPowerDownCmd(cmd),
                         DramExtension::getExtension(payload));
    controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn);

    if (state != PowerDownState::PDNSelfRefresh
            && controllerCore.refreshManager->hasCollision(pdn)) {
        return;
    } else {
        setPowerDownState(state, bank);
        sendPowerDownPayload(pdn);
    }
}

void PowerDownManagerBankwise::wakeUp(Bank bank, sc_time time)
{
    printDebugMessage("Waking up on bank " + to_string(bank.ID()) + " at " +
                      time.to_string() + " current power down state is " + powerDownStateToString(
                          powerDownStates[bank]));

    if (isAwakeForRefresh(bank)) {
        printDebugMessage("It was already awake for refresh on bank " + to_string(
                              bank.ID()) + " at " + time.to_string());
        setPowerDownState(PowerDownState::Awake, bank);
    } else if (isInPowerDown(bank)) {
        // Request wake up from power down. A Power Down Exit request will be generated (PDNAX, PDNPX, SREFX).
        Command pdnExitCmd = IPowerDownManager::getWakeUpCommand(powerDownStates[bank]);
        // Mount the command to be scheduled
        ScheduledCommand pdnExit(pdnExitCmd, time, getExecutionTime(pdnExitCmd,
                                                                    powerDownPayloads[bank]), DramExtension::getExtension(powerDownPayloads[bank]));
        // Ensure that time constraints are respected
        controllerCore.getCommandChecker(pdnExitCmd).delayToSatisfyConstraints(pdnExit);

        if (pdnExitCmd == Command::SREFX) {
            // Leaving Self Refresh. Plan the next refresh.
            controllerCore.refreshManager->reInitialize(bank, pdnExit.getEnd());
            printDebugMessage("Waking up. Leaving Self Refresh on Bank " + to_string(
                                  bank.ID()) + " at " + time.to_string() + " next refresh planned to " +
                              pdnExit.getEnd().to_string());
        }

        setPowerDownState(PowerDownState::Awake, bank);

        printDebugMessage("Sending power down exit command " + commandToString(
                              pdnExitCmd) + " on bank " + to_string(bank.ID()) + " at " + time.to_string() +
                          " start time " + pdnExit.getStart().to_string() +  " end time " +
                          pdnExit.getEnd().to_string());
        sendPowerDownPayload(pdnExit);
    }

    printDebugMessage("Awaken on bank " + to_string(bank.ID()) + " at " +
                      time.to_string() + " current power down state is " + powerDownStateToString(
                          powerDownStates[bank]));
}

void PowerDownManagerBankwise::wakeUpForRefresh(Bank bank, sc_time time)
{
    printDebugMessage("Waking up for refresh on bank " + to_string(
                          bank.ID()) + " at " + time.to_string() + " current power down state is " +
                      powerDownStateToString(powerDownStates[bank]));

    if (isInPowerDown(bank)) {
        // A Power Down Exit request will be generated (PDNAX, PDNPX, SREFX).
        Command pdnExitCmd = IPowerDownManager::getWakeUpCommand(powerDownStates[bank]);
        // Get the execution time for this request
        sc_time executionTime = getExecutionTime(pdnExitCmd, powerDownPayloads[bank]);
        // Mount the command to be scheduled
        ScheduledCommand pdnExit(pdnExitCmd, time, executionTime,
                                 DramExtension::getExtension(powerDownPayloads[bank]));

        setPowerDownState(PowerDownState::AwakeForRefresh, bank);

        printDebugMessage("Sending power down exit command " + commandToString(
                              pdnExitCmd) + " on bank " + to_string(bank.ID()) + " at " + time.to_string() +
                          " start time " + pdnExit.getStart().to_string() +  " end time " +
                          pdnExit.getEnd().to_string());
        sendPowerDownPayload(pdnExit);
    }

    printDebugMessage("Awaken for refresh on bank " + to_string(
                          bank.ID()) + " at " + time.to_string() + " current power down state is " +
                      powerDownStateToString(powerDownStates[bank]));
}

bool PowerDownManagerBankwise::isInPowerDown(Bank bank)
{
    return isIn(powerDownStates[bank], { PowerDownState::PDNActive, PowerDownState::PDNPrecharge, PowerDownState::PDNSelfRefresh });
}

bool PowerDownManagerBankwise::isInSelfRefresh(Bank bank)
{
    return powerDownStates[bank] == PowerDownState::PDNSelfRefresh;
}

bool PowerDownManagerBankwise::isAwakeForRefresh(Bank bank)
{
    return powerDownStates[bank] == PowerDownState::AwakeForRefresh;
}

bool PowerDownManagerBankwise::isAwake(Bank bank)
{
    return powerDownStates[bank] == PowerDownState::Awake;
}

void PowerDownManagerBankwise::setPowerDownState(PowerDownState state,
                                                 Bank bank)
{
    PowerDownState &bankstate = powerDownStates[bank];
    bankstate = state;
    printDebugMessage("Is now in state " + powerDownStateToString(
                          state) + " on Bank " + to_string(bank.ID()));
}

void PowerDownManagerBankwise::sendPowerDownPayload(ScheduledCommand &pdn)
{
    controllerCore.state->bus.moveCommandToNextFreeSlot(pdn);
    controllerCore.state->change(pdn);
    printDebugMessage("Sending power down command " + commandToString(
                          pdn.getCommand()) + " on bank " + to_string(pdn.getBank().ID()) + " start time "
                      + pdn.getStart().to_string() +  " end time " + pdn.getEnd().to_string());
    controllerCore.controller.send(pdn, powerDownPayloads[pdn.getBank()]);
}

bool PowerDownManagerBankwise::canSleep(Bank bank)
{
    return controllerCore.numberOfPayloads[bank] == 0;
}

void PowerDownManagerBankwise::triggerSleep(Bank bank, sc_time time)
{
    sleep(bank, time);
}

void PowerDownManagerBankwise::printDebugMessage(std::string message)
{
    DebugManager::getInstance().printDebugMessage(this->name(), message);
}

