# -*- coding: utf-8 -*-
# Copyright (c) 2019 The Regents of the University of California.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# 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;
# neither the name of the copyright holders 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
# OWNER 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: Mahyar Samani

from __future__ import print_function
from __future__ import absolute_import

import math
import optparse

import m5
from m5.objects import *
from m5.util import addToPath
from m5.stats import periodicStatDump

addToPath('../')

from common import ObjectList
from common import MemConfig


# Adding the system memory

system = System(membus = IOXBar(width = 32))
system.clk_domain = SrcClockDomain(clock = '2.0GHz',
                                   voltage_domain =
                                   VoltageDomain(voltage = '1V'))

mem_range = AddrRange('256MB')
system.mem_ranges = [mem_range]


system.mmap_using_noreserve = True

options.mem_channels = 1
options.external_memory_system = 0
options.tlm_memory = 0
options.elastic_trace_en = 0
MemConfig.config_mem(options, system)

if not isinstance(system.mem_ctrls[0], m5.objects.DRAMCtrl):
    fatal("This script assumes the memory is a DRAMCtrl subclass")


system.mem_ctrls[0].null = True

system.mem_ctrls[0].addr_mapping = options.addr_map

period = 250000000

nbr_banks = system.mem_ctrls[0].banks_per_rank.value


burst_size = int((system.mem_ctrls[0].devices_per_rank.value *
                  system.mem_ctrls[0].device_bus_width.value *
                  system.mem_ctrls[0].burst_length.value) / 8)

page_size = system.mem_ctrls[0].devices_per_rank.value * \
    system.mem_ctrls[0].device_rowbuffer_size.value


itt =  getattr(system.mem_ctrls[0].tBURST_MIN, 'value',
               system.mem_ctrls[0].tBURST.value) * 1000000000000

max_addr = mem_range.end


max_stride = min(512, page_size)

# Creating the system traffic gen
# it will act as the system processor
system.tgen = PyTrafficGen()

# Creating the system monitor
# TODO: Add documentation on CommMonitor()
system.monitor = CommMonitor()

# Connecting the traffic gen to the system
# monitor and connecting monitor to memory
system.tgen.port = system.monitor.slave
system.monitor.master = system.membus.slave

system.system_port = system.membus.slave


periodicStatDump(period)

# Creating root and setting memory mode to
# timing. Probably the only rational choice
# for mem_mode is timing
root = Root(full_system = False, system = system)
root.system.mem_mode = 'timing'


m5.instantiate()

# This generator block will create a random traffic
# generator with the following parameters.
# 0 as read %
# max_addr as the biggest reference creasted
# burst_size as burst size
# TODO: Add documentation on other parameters
def rand():
    addr_map = ObjectList.dram_addr_map_list.get(options.addr_map)
    generator = system.tgen.createDram()
    for stride_size in range(burst_size, max_stride + 1, burst_size):
        for bank in range(1, nbr_banks + 1):
            num_seq_pkts = int(math.ceil(float(stride_size) / burst_size))
            yield generator(period,
                            0, max_addr, burst_size, int(itt), int(itt),
                            options.rd_perc, 0,
                            num_seq_pkts, page_size, nbr_banks, bank,
                            addr_map, options.mem_ranks)
    yield system.tgen.createExit(0)

# Starting the traffic generator
system.tgen.start(trace())

m5.simulate()

