Simulation.py revision 6144:e330f7bc22ef
1# Copyright (c) 2006-2008 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Lisa Hsu
28
29from os import getcwd
30from os.path import join as joinpath
31import m5
32from m5.objects import *
33m5.AddToPath('../common')
34
35def setCPUClass(options):
36
37    atomic = False
38    if options.timing:
39        class TmpClass(TimingSimpleCPU): pass
40    elif options.detailed:
41        if not options.caches:
42            print "O3 CPU must be used with caches"
43            sys.exit(1)
44        class TmpClass(DerivO3CPU): pass
45    elif options.inorder:
46        if not options.caches:
47            print "InOrder CPU must be used with caches"
48            sys.exit(1)
49        class TmpClass(InOrderCPU): pass
50    else:
51        class TmpClass(AtomicSimpleCPU): pass
52        atomic = True
53
54    CPUClass = None
55    test_mem_mode = 'atomic'
56
57    if not atomic:
58        if options.checkpoint_restore != None or options.fast_forward:
59            CPUClass = TmpClass
60            class TmpClass(AtomicSimpleCPU): pass
61        else:
62            test_mem_mode = 'timing'
63
64    return (TmpClass, test_mem_mode, CPUClass)
65
66
67def run(options, root, testsys, cpu_class):
68    if options.maxtick:
69        maxtick = options.maxtick
70    elif options.maxtime:
71        simtime = m5.ticks.seconds(simtime)
72        print "simulating for: ", simtime
73        maxtick = simtime
74    else:
75        maxtick = m5.MaxTick
76
77    if options.checkpoint_dir:
78        cptdir = options.checkpoint_dir
79    elif m5.options.outdir:
80        cptdir = m5.options.outdir
81    else:
82        cptdir = getcwd()
83
84    if options.fast_forward and options.checkpoint_restore != None:
85        m5.fatal("Error: Can't specify both --fast-forward and --checkpoint-restore")
86
87    if options.standard_switch and not options.caches:
88        m5.fatal("Error: Must specify --caches when using --standard-switch")
89
90    np = options.num_cpus
91    max_checkpoints = options.max_checkpoints
92    switch_cpus = None
93
94    if options.prog_intvl:
95        for i in xrange(np):
96            testsys.cpu[i].progress_interval = options.prog_intvl
97
98    if cpu_class:
99        switch_cpus = [cpu_class(defer_registration=True, cpu_id=(np+i))
100                       for i in xrange(np)]
101
102        for i in xrange(np):
103            if options.fast_forward:
104                testsys.cpu[i].max_insts_any_thread = int(options.fast_forward)
105            switch_cpus[i].system =  testsys
106            if not m5.build_env['FULL_SYSTEM']:
107                switch_cpus[i].workload = testsys.cpu[i].workload
108            switch_cpus[i].clock = testsys.cpu[0].clock
109            # simulation period
110            if options.max_inst:
111                switch_cpus[i].max_insts_any_thread = options.max_inst
112
113        testsys.switch_cpus = switch_cpus
114        switch_cpu_list = [(testsys.cpu[i], switch_cpus[i]) for i in xrange(np)]
115
116    if options.standard_switch:
117        switch_cpus = [TimingSimpleCPU(defer_registration=True, cpu_id=(np+i))
118                       for i in xrange(np)]
119        switch_cpus_1 = [DerivO3CPU(defer_registration=True, cpu_id=(2*np+i))
120                        for i in xrange(np)]
121
122        for i in xrange(np):
123            switch_cpus[i].system =  testsys
124            switch_cpus_1[i].system =  testsys
125            if not m5.build_env['FULL_SYSTEM']:
126                switch_cpus[i].workload = testsys.cpu[i].workload
127                switch_cpus_1[i].workload = testsys.cpu[i].workload
128            switch_cpus[i].clock = testsys.cpu[0].clock
129            switch_cpus_1[i].clock = testsys.cpu[0].clock
130
131            # if restoring, make atomic cpu simulate only a few instructions
132            if options.checkpoint_restore != None:
133                testsys.cpu[i].max_insts_any_thread = 1
134            # Fast forward to specified location if we are not restoring
135            elif options.fast_forward:
136                testsys.cpu[i].max_insts_any_thread = int(options.fast_forward)
137            # Fast forward to a simpoint (warning: time consuming)
138            elif options.simpoint:
139                if testsys.cpu[i].workload[0].simpoint == 0:
140                    m5.fatal('simpoint not found')
141                testsys.cpu[i].max_insts_any_thread = \
142                    testsys.cpu[i].workload[0].simpoint
143            # No distance specified, just switch
144            else:
145                testsys.cpu[i].max_insts_any_thread = 1
146
147            # warmup period
148            if options.warmup_insts:
149                switch_cpus[i].max_insts_any_thread =  options.warmup_insts
150
151            # simulation period
152            if options.max_inst:
153                switch_cpus_1[i].max_insts_any_thread = options.max_inst
154
155            if not options.caches:
156                # O3 CPU must have a cache to work.
157                print "O3 CPU must be used with caches"
158                sys.exit(1)
159
160            testsys.switch_cpus = switch_cpus
161            testsys.switch_cpus_1 = switch_cpus_1
162            switch_cpu_list = [(testsys.cpu[i], switch_cpus[i]) for i in xrange(np)]
163            switch_cpu_list1 = [(switch_cpus[i], switch_cpus_1[i]) for i in xrange(np)]
164
165    # set the checkpoint in the cpu before m5.instantiate is called
166    if options.take_checkpoints != None and \
167           (options.simpoint or options.at_instruction):
168        offset = int(options.take_checkpoints)
169        # Set an instruction break point
170        if options.simpoint:
171            for i in xrange(np):
172                if testsys.cpu[i].workload[0].simpoint == 0:
173                    m5.fatal('no simpoint for testsys.cpu[%d].workload[0]', i)
174                checkpoint_inst = int(testsys.cpu[i].workload[0].simpoint) + offset
175                testsys.cpu[i].max_insts_any_thread = checkpoint_inst
176                # used for output below
177                options.take_checkpoints = checkpoint_inst
178        else:
179            options.take_checkpoints = offset
180            # Set all test cpus with the right number of instructions
181            # for the upcoming simulation
182            for i in xrange(np):
183                testsys.cpu[i].max_insts_any_thread = offset
184
185    m5.instantiate(root)
186
187    if options.checkpoint_restore != None:
188        from os.path import isdir, exists
189        from os import listdir
190        import re
191
192        if not isdir(cptdir):
193            m5.fatal("checkpoint dir %s does not exist!", cptdir)
194
195        if options.at_instruction:
196            checkpoint_dir = joinpath(cptdir, "cpt.%s.%s" % \
197                    (options.bench, options.checkpoint_restore))
198            if not exists(checkpoint_dir):
199                m5.fatal("Unable to find checkpoint directory %s",
200                         checkpoint_dir)
201
202            print "Restoring checkpoint ..."
203            m5.restoreCheckpoint(root, checkpoint_dir)
204            print "Done."
205        elif options.simpoint:
206            # assume workload 0 has the simpoint
207            if testsys.cpu[0].workload[0].simpoint == 0:
208                m5.fatal('Unable to find simpoint')
209
210            options.checkpoint_restore += \
211                int(testsys.cpu[0].workload[0].simpoint)
212
213            checkpoint_dir = joinpath(cptdir, "cpt.%s.%d" % \
214                    (options.bench, options.checkpoint_restore))
215            if not exists(checkpoint_dir):
216                m5.fatal("Unable to find checkpoint directory %s.%s",
217                        options.bench, options.checkpoint_restore)
218
219            print "Restoring checkpoint ..."
220            m5.restoreCheckpoint(root,checkpoint_dir)
221            print "Done."
222        else:
223            dirs = listdir(cptdir)
224            expr = re.compile('cpt\.([0-9]*)')
225            cpts = []
226            for dir in dirs:
227                match = expr.match(dir)
228                if match:
229                    cpts.append(match.group(1))
230
231            cpts.sort(lambda a,b: cmp(long(a), long(b)))
232
233            cpt_num = options.checkpoint_restore
234
235            if cpt_num > len(cpts):
236                m5.fatal('Checkpoint %d not found', cpt_num)
237
238            ## Adjust max tick based on our starting tick
239            maxtick = maxtick - int(cpts[cpt_num - 1])
240
241            ## Restore the checkpoint
242            m5.restoreCheckpoint(root,
243                    joinpath(cptdir, "cpt.%s" % cpts[cpt_num - 1]))
244
245    if options.standard_switch or cpu_class:
246        if options.standard_switch:
247            print "Switch at instruction count:%s" % \
248                    str(testsys.cpu[0].max_insts_any_thread)
249            exit_event = m5.simulate()
250        elif cpu_class and options.fast_forward:
251            print "Switch at instruction count:%s" % \
252                    str(testsys.cpu[0].max_insts_any_thread)
253            exit_event = m5.simulate()
254        else:
255            print "Switch at curTick count:%s" % str(10000)
256            exit_event = m5.simulate(10000)
257        print "Switched CPUS @ cycle = %s" % (m5.curTick())
258
259        # when you change to Timing (or Atomic), you halt the system
260        # given as argument.  When you are finished with the system
261        # changes (including switchCpus), you must resume the system
262        # manually.  You DON'T need to resume after just switching
263        # CPUs if you haven't changed anything on the system level.
264
265        m5.changeToTiming(testsys)
266        m5.switchCpus(switch_cpu_list)
267        m5.resume(testsys)
268
269        if options.standard_switch:
270            print "Switch at instruction count:%d" % \
271                    (testsys.switch_cpus[0].max_insts_any_thread)
272
273            #warmup instruction count may have already been set
274            if options.warmup_insts:
275                exit_event = m5.simulate()
276            else:
277                exit_event = m5.simulate(options.warmup)
278            print "Switching CPUS @ cycle = %s" % (m5.curTick())
279            print "Simulation ends instruction count:%d" % \
280                    (testsys.switch_cpus_1[0].max_insts_any_thread)
281            m5.drain(testsys)
282            m5.switchCpus(switch_cpu_list1)
283            m5.resume(testsys)
284
285    num_checkpoints = 0
286    exit_cause = ''
287
288    # Checkpoints being taken via the command line at <when> and at
289    # subsequent periods of <period>.  Checkpoint instructions
290    # received from the benchmark running are ignored and skipped in
291    # favor of command line checkpoint instructions.
292    if options.take_checkpoints != None :
293        if options.at_instruction or options.simpoint:
294            checkpoint_inst = int(options.take_checkpoints)
295
296            # maintain correct offset if we restored from some instruction
297            if options.checkpoint_restore != None:
298                checkpoint_inst += options.checkpoint_restore
299
300            print "Creating checkpoint at inst:%d" % (checkpoint_inst)
301            exit_event = m5.simulate()
302            print "exit cause = %s" % (exit_event.getCause())
303
304            # skip checkpoint instructions should they exist
305            while exit_event.getCause() == "checkpoint":
306                exit_event = m5.simulate()
307
308            if exit_event.getCause() == \
309                   "a thread reached the max instruction count":
310                m5.checkpoint(root, joinpath(cptdir, "cpt.%s.%d" % \
311                        (options.bench, checkpoint_inst)))
312                print "Checkpoint written."
313                num_checkpoints += 1
314
315            if exit_event.getCause() == "user interrupt received":
316                exit_cause = exit_event.getCause();
317        else:
318            when, period = options.take_checkpoints.split(",", 1)
319            when = int(when)
320            period = int(period)
321
322            exit_event = m5.simulate(when)
323            while exit_event.getCause() == "checkpoint":
324                exit_event = m5.simulate(when - m5.curTick())
325
326            if exit_event.getCause() == "simulate() limit reached":
327                m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
328                num_checkpoints += 1
329
330            sim_ticks = when
331            exit_cause = "maximum %d checkpoints dropped" % max_checkpoints
332            while num_checkpoints < max_checkpoints and \
333                    exit_event.getCause() == "simulate() limit reached":
334                if (sim_ticks + period) > maxtick:
335                    exit_event = m5.simulate(maxtick - sim_ticks)
336                    exit_cause = exit_event.getCause()
337                    break
338                else:
339                    exit_event = m5.simulate(period)
340                    sim_ticks += period
341                    while exit_event.getCause() == "checkpoint":
342                        exit_event = m5.simulate(sim_ticks - m5.curTick())
343                    if exit_event.getCause() == "simulate() limit reached":
344                        m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
345                        num_checkpoints += 1
346
347            if exit_event.getCause() != "simulate() limit reached":
348                exit_cause = exit_event.getCause();
349
350    else: # no checkpoints being taken via this script
351        if options.fast_forward:
352            m5.stats.reset()
353        print "**** REAL SIMULATION ****"
354        exit_event = m5.simulate(maxtick)
355
356        while exit_event.getCause() == "checkpoint":
357            m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
358            num_checkpoints += 1
359            if num_checkpoints == max_checkpoints:
360                exit_cause = "maximum %d checkpoints dropped" % max_checkpoints
361                break
362
363            exit_event = m5.simulate(maxtick - m5.curTick())
364            exit_cause = exit_event.getCause()
365
366    if exit_cause == '':
367        exit_cause = exit_event.getCause()
368    print 'Exiting @ cycle %i because %s' % (m5.curTick(), exit_cause)
369
370