Simulation.py revision 5822:05ffa2c3c800
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')
34from Caches import L1Cache
35
36def setCPUClass(options):
37
38    atomic = False
39    if options.timing:
40        class TmpClass(TimingSimpleCPU): pass
41    elif options.detailed:
42        if not options.caches:
43            print "O3 CPU must be used with caches"
44            sys.exit(1)
45        class TmpClass(DerivO3CPU): pass
46    else:
47        class TmpClass(AtomicSimpleCPU): pass
48        atomic = True
49
50    CPUClass = None
51    test_mem_mode = 'atomic'
52
53    if not atomic:
54        if options.checkpoint_restore != None or options.fast_forward:
55            CPUClass = TmpClass
56            class TmpClass(AtomicSimpleCPU): pass
57        else:
58            test_mem_mode = 'timing'
59
60    return (TmpClass, test_mem_mode, CPUClass)
61
62
63def run(options, root, testsys, cpu_class):
64    if options.maxtick:
65        maxtick = options.maxtick
66    elif options.maxtime:
67        simtime = m5.ticks.seconds(simtime)
68        print "simulating for: ", simtime
69        maxtick = simtime
70    else:
71        maxtick = m5.MaxTick
72
73    if options.checkpoint_dir:
74        cptdir = options.checkpoint_dir
75    elif m5.options.outdir:
76        cptdir = m5.options.outdir
77    else:
78        cptdir = getcwd()
79
80    if options.fast_forward and options.checkpoint_restore != None:
81        m5.fatal("Error: Can't specify both --fast-forward and --checkpoint-restore")
82
83    if options.standard_switch and not options.caches:
84        m5.fatal("Error: Must specify --caches when using --standard-switch")
85
86    np = options.num_cpus
87    max_checkpoints = options.max_checkpoints
88    switch_cpus = None
89
90    if cpu_class:
91        switch_cpus = [cpu_class(defer_registration=True, cpu_id=(np+i))
92                       for i in xrange(np)]
93
94        for i in xrange(np):
95            if options.fast_forward:
96                testsys.cpu[i].max_insts_any_thread = int(options.fast_forward)
97            switch_cpus[i].system =  testsys
98            if not m5.build_env['FULL_SYSTEM']:
99                switch_cpus[i].workload = testsys.cpu[i].workload
100            switch_cpus[i].clock = testsys.cpu[0].clock
101            # simulation period
102            if options.max_inst:
103                switch_cpus[i].max_insts_any_thread = options.max_inst
104
105        testsys.switch_cpus = switch_cpus
106        switch_cpu_list = [(testsys.cpu[i], switch_cpus[i]) for i in xrange(np)]
107
108    if options.standard_switch:
109        switch_cpus = [TimingSimpleCPU(defer_registration=True, cpu_id=(np+i))
110                       for i in xrange(np)]
111        switch_cpus_1 = [DerivO3CPU(defer_registration=True, cpu_id=(2*np+i))
112                        for i in xrange(np)]
113
114        for i in xrange(np):
115            switch_cpus[i].system =  testsys
116            switch_cpus_1[i].system =  testsys
117            if not m5.build_env['FULL_SYSTEM']:
118                switch_cpus[i].workload = testsys.cpu[i].workload
119                switch_cpus_1[i].workload = testsys.cpu[i].workload
120            switch_cpus[i].clock = testsys.cpu[0].clock
121            switch_cpus_1[i].clock = testsys.cpu[0].clock
122
123            # if restoring, make atomic cpu simulate only a few instructions
124            if options.checkpoint_restore != None:
125                testsys.cpu[i].max_insts_any_thread = 1
126            # Fast forward to specified location if we are not restoring
127            elif options.fast_forward:
128                testsys.cpu[i].max_insts_any_thread = int(options.fast_forward)
129            # Fast forward to a simpoint (warning: time consuming)
130            elif options.simpoint:
131                if testsys.cpu[i].workload[0].simpoint == 0:
132                    m5.fatal('simpoint not found')
133                testsys.cpu[i].max_insts_any_thread = \
134                    testsys.cpu[i].workload[0].simpoint
135            # No distance specified, just switch
136            else:
137                testsys.cpu[i].max_insts_any_thread = 1
138
139            # warmup period
140            if options.warmup_insts:
141                switch_cpus[i].max_insts_any_thread =  options.warmup_insts
142
143            # simulation period
144            if options.max_inst:
145                switch_cpus_1[i].max_insts_any_thread = options.max_inst
146
147            if not options.caches:
148                # O3 CPU must have a cache to work.
149                switch_cpus_1[i].addPrivateSplitL1Caches(L1Cache(size = '32kB'),
150                                                         L1Cache(size = '64kB'))
151                switch_cpus_1[i].connectMemPorts(testsys.membus)
152
153            testsys.switch_cpus = switch_cpus
154            testsys.switch_cpus_1 = switch_cpus_1
155            switch_cpu_list = [(testsys.cpu[i], switch_cpus[i]) for i in xrange(np)]
156            switch_cpu_list1 = [(switch_cpus[i], switch_cpus_1[i]) for i in xrange(np)]
157
158    # set the checkpoint in the cpu before m5.instantiate is called
159    if options.take_checkpoints != None and \
160           (options.simpoint or options.at_instruction):
161        offset = int(options.take_checkpoints)
162        # Set an instruction break point
163        if options.simpoint:
164            for i in xrange(np):
165                if testsys.cpu[i].workload[0].simpoint == 0:
166                    m5.fatal('no simpoint for testsys.cpu[%d].workload[0]', i)
167                checkpoint_inst = int(testsys.cpu[i].workload[0].simpoint) + offset
168                testsys.cpu[i].max_insts_any_thread = checkpoint_inst
169                # used for output below
170                options.take_checkpoints = checkpoint_inst
171        else:
172            options.take_checkpoints = offset
173            # Set all test cpus with the right number of instructions
174            # for the upcoming simulation
175            for i in xrange(np):
176                testsys.cpu[i].max_insts_any_thread = offset
177
178    m5.instantiate(root)
179
180    if options.checkpoint_restore != None:
181        from os.path import isdir, exists
182        from os import listdir
183        import re
184
185        if not isdir(cptdir):
186            m5.fatal("checkpoint dir %s does not exist!", cptdir)
187
188        if options.at_instruction:
189            checkpoint_dir = joinpath(cptdir, "cpt.%s.%s" % \
190                    (options.bench, options.checkpoint_restore))
191            if not exists(checkpoint_dir):
192                m5.fatal("Unable to find checkpoint directory %s",
193                         checkpoint_dir)
194
195            print "Restoring checkpoint ..."
196            m5.restoreCheckpoint(root, checkpoint_dir)
197            print "Done."
198        elif options.simpoint:
199            # assume workload 0 has the simpoint
200            if testsys.cpu[0].workload[0].simpoint == 0:
201                m5.fatal('Unable to find simpoint')
202
203            options.checkpoint_restore += \
204                int(testsys.cpu[0].workload[0].simpoint)
205
206            checkpoint_dir = joinpath(cptdir, "cpt.%s.%d" % \
207                    (options.bench, options.checkpoint_restore))
208            if not exists(checkpoint_dir):
209                m5.fatal("Unable to find checkpoint directory %s.%s",
210                        options.bench, options.checkpoint_restore)
211
212            print "Restoring checkpoint ..."
213            m5.restoreCheckpoint(root,checkpoint_dir)
214            print "Done."
215        else:
216            dirs = listdir(cptdir)
217            expr = re.compile('cpt\.([0-9]*)')
218            cpts = []
219            for dir in dirs:
220                match = expr.match(dir)
221                if match:
222                    cpts.append(match.group(1))
223
224            cpts.sort(lambda a,b: cmp(long(a), long(b)))
225
226            cpt_num = options.checkpoint_restore
227
228            if cpt_num > len(cpts):
229                m5.fatal('Checkpoint %d not found', cpt_num)
230
231            ## Adjust max tick based on our starting tick
232            maxtick = maxtick - int(cpts[cpt_num - 1])
233
234            ## Restore the checkpoint
235            m5.restoreCheckpoint(root,
236                    joinpath(cptdir, "cpt.%s" % cpts[cpt_num - 1]))
237
238    if options.standard_switch or cpu_class:
239        if options.standard_switch:
240            print "Switch at instruction count:%s" % \
241                    str(testsys.cpu[0].max_insts_any_thread)
242            exit_event = m5.simulate()
243        elif cpu_class and options.fast_forward:
244            print "Switch at instruction count:%s" % \
245                    str(testsys.cpu[0].max_insts_any_thread)
246            exit_event = m5.simulate()
247        else:
248            print "Switch at curTick count:%s" % str(10000)
249            exit_event = m5.simulate(10000)
250        print "Switched CPUS @ cycle = %s" % (m5.curTick())
251
252        # when you change to Timing (or Atomic), you halt the system
253        # given as argument.  When you are finished with the system
254        # changes (including switchCpus), you must resume the system
255        # manually.  You DON'T need to resume after just switching
256        # CPUs if you haven't changed anything on the system level.
257
258        m5.changeToTiming(testsys)
259        m5.switchCpus(switch_cpu_list)
260        m5.resume(testsys)
261
262        if options.standard_switch:
263            print "Switch at instruction count:%d" % \
264                    (testsys.switch_cpus[0].max_insts_any_thread)
265
266            #warmup instruction count may have already been set
267            if options.warmup_insts:
268                exit_event = m5.simulate()
269            else:
270                exit_event = m5.simulate(options.warmup)
271            print "Switching CPUS @ cycle = %s" % (m5.curTick())
272            print "Simulation ends instruction count:%d" % \
273                    (testsys.switch_cpus_1[0].max_insts_any_thread)
274            m5.drain(testsys)
275            m5.switchCpus(switch_cpu_list1)
276            m5.resume(testsys)
277
278    num_checkpoints = 0
279    exit_cause = ''
280
281    # Checkpoints being taken via the command line at <when> and at
282    # subsequent periods of <period>.  Checkpoint instructions
283    # received from the benchmark running are ignored and skipped in
284    # favor of command line checkpoint instructions.
285    if options.take_checkpoints != None :
286        if options.at_instruction or options.simpoint:
287            checkpoint_inst = int(options.take_checkpoints)
288
289            # maintain correct offset if we restored from some instruction
290            if options.checkpoint_restore != None:
291                checkpoint_inst += options.checkpoint_restore
292
293            print "Creating checkpoint at inst:%d" % (checkpoint_inst)
294            exit_event = m5.simulate()
295            print "exit cause = %s" % (exit_event.getCause())
296
297            # skip checkpoint instructions should they exist
298            while exit_event.getCause() == "checkpoint":
299                exit_event = m5.simulate()
300
301            if exit_event.getCause() == \
302                   "a thread reached the max instruction count":
303                m5.checkpoint(root, joinpath(cptdir, "cpt.%s.%d" % \
304                        (options.bench, checkpoint_inst)))
305                print "Checkpoint written."
306                num_checkpoints += 1
307
308            if exit_event.getCause() == "user interrupt received":
309                exit_cause = exit_event.getCause();
310        else:
311            when, period = options.take_checkpoints.split(",", 1)
312            when = int(when)
313            period = int(period)
314
315            exit_event = m5.simulate(when)
316            while exit_event.getCause() == "checkpoint":
317                exit_event = m5.simulate(when - m5.curTick())
318
319            if exit_event.getCause() == "simulate() limit reached":
320                m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
321                num_checkpoints += 1
322
323            sim_ticks = when
324            exit_cause = "maximum %d checkpoints dropped" % max_checkpoints
325            while num_checkpoints < max_checkpoints and \
326                    exit_event.getCause() == "simulate() limit reached":
327                if (sim_ticks + period) > maxtick:
328                    exit_event = m5.simulate(maxtick - sim_ticks)
329                    exit_cause = exit_event.getCause()
330                    break
331                else:
332                    exit_event = m5.simulate(period)
333                    sim_ticks += period
334                    while exit_event.getCause() == "checkpoint":
335                        exit_event = m5.simulate(sim_ticks - m5.curTick())
336                    if exit_event.getCause() == "simulate() limit reached":
337                        m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
338                        num_checkpoints += 1
339
340            if exit_event.getCause() != "simulate() limit reached":
341                exit_cause = exit_event.getCause();
342
343    else: # no checkpoints being taken via this script
344        if options.fast_forward:
345            m5.stats.reset()
346        print "**** REAL SIMULATION ****"
347        exit_event = m5.simulate(maxtick)
348
349        while exit_event.getCause() == "checkpoint":
350            m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
351            num_checkpoints += 1
352            if num_checkpoints == max_checkpoints:
353                exit_cause = "maximum %d checkpoints dropped" % max_checkpoints
354                break
355
356            exit_event = m5.simulate(maxtick - m5.curTick())
357            exit_cause = exit_event.getCause()
358
359    if exit_cause == '':
360        exit_cause = exit_event.getCause()
361    print 'Exiting @ cycle %i because %s' % (m5.curTick(), exit_cause)
362
363