# run_alpha.py
# Simple configuration script (modified based on the original file at www.gem5.org)

import m5
from m5.objects import *
from m5.defines import buildEnv
import os, optparse, sys
from m5.util import addToPath
addToPath('./configs')
addToPath('../common')
addToPath('../ruby')
import Simulation
import CacheConfig
from Caches import *
import Ruby

import spec2006_process

if buildEnv['FULL_SYSTEM']:
    panic("This script requires system-emulation mode (*_SE).")

######################################################################
# Get paths we might need.  It's expected this file is in gem5/configs/spec2006.
######################################################################
config_path = os.path.dirname(os.path.abspath(__file__))
#print config_path
config_root = os.path.dirname(config_path)
#print config_root
m5_root = os.path.dirname(config_root)
#print m5_root

######################################################################
# Parse the options from user command
######################################################################
parser = optparse.OptionParser()

######################################################################
# Benchmark options
######################################################################

parser.add_option("-b", "--benchmark", default="",
                 help="The benchmarks to be loaded.")

parser.add_option("-c", "--chkpt", default="",
                 help="The checkpoint to load.")

parser.add_option("--ruby", action="store_true",
                 help="Enable the ruby memory system")

Ruby.define_options(parser)

execfile(os.path.join(config_root, "common", "Options.py"))

(options, args) = parser.parse_args()

if args:
    print "Error: script doesn't take any positional arguments"
    sys.exit(1)

if options.chkpt != "":
   process.chkpt = options.chkpt


######################################################################
#  multi-program support
######################################################################
multiprocesses = []
apps = []

if options.bench:
    apps = options.bench.split("-")
    if len(apps) != options.num_cpus:
        print "number of benchmarks not equal to set num_cpus!"
        sys.exit(1)

    for app in apps:
        try:
            if buildEnv['TARGET_ISA'] == 'alpha':
                exec("workload = %s('alpha', 'tru64', 'ref')" % app)
            else:
                exec("workload = %s(buildEnv['TARGET_ISA'], 'linux', 'ref')" % app)
            multiprocesses.append(workload.makeLiveProcess())
        except:
            print >>sys.stderr, "Unable to find workload for %s: %s" % (buildEnv['TARGET_ISA'], app)
            sys.exit(1)
else:
    # 'if' should be skipped and 'else' should be executed for SPEC2006
    # benchmark
    workloads = options.benchmark.split('-')
    if len(workloads) > 0:
        for wrkld in workloads:
            # benchmark "perlbench" has running problem
            #if wrkld == 'perlbench':
            #   process = spec2006_process.perlbench
            if wrkld == 'bzip2':
               process = spec2006_process.bzip2
            elif wrkld == 'gcc':
               process = spec2006_process.gcc
            elif wrkld == 'bwaves':
               process = spec2006_process.bwaves
            elif wrkld == 'gamess':
               process = spec2006_process.gamess
            elif wrkld == 'mcf':
               process = spec2006_process.mcf
            elif wrkld == 'milc':
               process = spec2006_process.milc
            elif wrkld == 'zeusmp':
               process = spec2006_process.zeusmp
            elif wrkld == 'gromacs':
               process = spec2006_process.gromacs
            elif wrkld == 'cactusADM':
               process = spec2006_process.cactusADM
            elif wrkld == 'leslie3d':
               process = spec2006_process.leslie3d
            elif wrkld == 'namd':
               process = spec2006_process.namd
            elif wrkld == 'gobmk':
               process = spec2006_process.gobmk;
            # benchmark "dealII" has crossing compilation problem
            #elif options.benchmark == 'dealII':
            #   process = spec2006_process.dealII
            elif wrkld == 'soplex':
               process = spec2006_process.soplex
            elif wrkld == 'povray':
               process = spec2006_process.povray
            elif wrkld == 'calculix':
               process = spec2006_process.calculix
            elif wrkld == 'hmmer':
               process = spec2006_process.hmmer
            elif wrkld == 'sjeng':
               process = spec2006_process.sjeng
            elif wrkld == 'GemsFDTD':
               process = spec2006_process.GemsFDTD
            elif wrkld == 'libquantum':
               process = spec2006_process.libquantum
            elif wrkld == 'h264ref':
               process = spec2006_process.h264ref
            elif wrkld == 'tonto':
               process = spec2006_process.tonto
            elif wrkld == 'lbm':
               process = spec2006_process.lbm
            elif wrkld == 'omnetpp':
               process = spec2006_process.omnetpp
            elif wrkld == 'astar':
               process = spec2006_process.astar
            elif wrkld == 'wrf':
               process = spec2006_process.wrf
            elif wrkld == 'sphinx3':
               process = spec2006_process.sphinx3
            # benchmark "dealII" has crossing compilation problem
            #elif options.benchmark == 'xalancbmk':
            #   process = spec2006_process.xalancbmk
            elif wrkld == 'specrand_i':
               process = spec2006_process.specrand_i
            elif wrkld == 'specrand_f':
               process = spec2006_process.specrand_f
            else:
                print "Error: %s is not a valid spec2006 benchmark." % wrkld
                sys.exit(1)
            multiprocesses.append(process)
    else:
        print "Error: no benchmark is specified"
        sys.exit(1)

######################################################################
#  multi-thread support
######################################################################
#workloads = options.cmd
#numThreads = 1
#
#if options.detailed or options.inorder:
#    #check for SMT workload
#    workloads = options.cmd.split(';')
#    if len(workloads) > 1:
#        process = []
#        smt_idx = 0
#        inputs = []
#        outputs = []
#        errouts = []
#
#        if options.input != "":
#            inputs = options.input.split(';')
#        if options.output != "":
#            outputs = options.output.split(';')
#        if options.errout != "":
#            errouts = options.errout.split(';')
#
#        for wrkld in workloads:
#            smt_process = LiveProcess()
#            smt_process.executable = wrkld
#            smt_process.cmd = wrkld + " " + options.options
#            if inputs and inputs[smt_idx]:
#                smt_process.input = inputs[smt_idx]
#            if outputs and outputs[smt_idx]:
#                smt_process.output = outputs[smt_idx]
#            if errouts and errouts[smt_idx]:
#                smt_process.errout = errouts[smt_idx]
#            process += [smt_process, ]
#            smt_idx += 1
#    numThreads = len(workloads)

######################################################################
#  generate CPU 
######################################################################
if options.ruby:
    if options.detailed:
        print >> sys.stderr, "Ruby only works with TimingSimpleCPU!!"
        sys.exit(1)
    elif not options.timing:
        print >> sys.stderr, "**** WARN:  using Timing CPU since it's needed by Ruby"

    # generate TimingSimple cpu
    class CPUClass(TimingSimpleCPU): pass
    test_mem_mode = 'timing'
    FutureClass = None
else:
    (CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)

# set cpu clock frequency
CPUClass.clock = options.clock

# set cpu number
np = options.num_cpus 

######################################################################
#  generate whole system (CPU + physical memory(4GB))
######################################################################
system = System(cpu = [CPUClass(cpu_id=i) for i in xrange(np)],
                physmem = PhysicalMemory(range=AddrRange("4096MB")),
                membus = Bus(), mem_mode = test_mem_mode)

######################################################################
#  generate ruby (memory system)
######################################################################
if options.ruby:
    options.use_map = True
    Ruby.create_system(options, system)
    # number of ruby port should be equal to cpu number
    assert(options.num_cpus == len(system.ruby._cpu_ruby_ports))
else:
    system.physmem.port = system.membus.port
    CacheConfig.config_cache(options, system)

######################################################################
#  assign workload to each cpu and connect each cpu to the ruby port
######################################################################
for i in xrange(np):   
    system.cpu[i].workload = multiprocesses[i]

    if options.ruby:
        system.cpu[i].icache_port = system.ruby._cpu_ruby_ports[i].port
        system.cpu[i].dcache_port = system.ruby._cpu_ruby_ports[i].port

    if options.fastmem:
        system.cpu[0].physmem_port = system.physmem.port


######################################################################
#  start simulation
######################################################################
root = Root(system = system)

Simulation.run(options, root, system, FutureClass)
