8ef22be4e3f43438f04da55a9a9ed4526b2ef88e
[gem5.git] / src / python / m5 / SimObject.py
1 # Copyright (c) 2004-2006 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: Steve Reinhardt
28 # Nathan Binkert
29
30 import math
31 import sys
32 import types
33
34 import proxy
35 import m5
36 from util import *
37
38 # These utility functions have to come first because they're
39 # referenced in params.py... otherwise they won't be defined when we
40 # import params below, and the recursive import of this file from
41 # params.py will not find these names.
42 def isSimObject(value):
43 return isinstance(value, SimObject)
44
45 def isSimObjectClass(value):
46 return issubclass(value, SimObject)
47
48 def isSimObjectSequence(value):
49 if not isinstance(value, (list, tuple)) or len(value) == 0:
50 return False
51
52 for val in value:
53 if not isNullPointer(val) and not isSimObject(val):
54 return False
55
56 return True
57
58 def isSimObjectOrSequence(value):
59 return isSimObject(value) or isSimObjectSequence(value)
60
61 # Have to import params up top since Param is referenced on initial
62 # load (when SimObject class references Param to create a class
63 # variable, the 'name' param)...
64 from params import *
65 # There are a few things we need that aren't in params.__all__ since
66 # normal users don't need them
67 from params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector
68 from proxy import *
69
70 noDot = False
71 try:
72 import pydot
73 except:
74 noDot = True
75
76 #####################################################################
77 #
78 # M5 Python Configuration Utility
79 #
80 # The basic idea is to write simple Python programs that build Python
81 # objects corresponding to M5 SimObjects for the desired simulation
82 # configuration. For now, the Python emits a .ini file that can be
83 # parsed by M5. In the future, some tighter integration between M5
84 # and the Python interpreter may allow bypassing the .ini file.
85 #
86 # Each SimObject class in M5 is represented by a Python class with the
87 # same name. The Python inheritance tree mirrors the M5 C++ tree
88 # (e.g., SimpleCPU derives from BaseCPU in both cases, and all
89 # SimObjects inherit from a single SimObject base class). To specify
90 # an instance of an M5 SimObject in a configuration, the user simply
91 # instantiates the corresponding Python object. The parameters for
92 # that SimObject are given by assigning to attributes of the Python
93 # object, either using keyword assignment in the constructor or in
94 # separate assignment statements. For example:
95 #
96 # cache = BaseCache(size='64KB')
97 # cache.hit_latency = 3
98 # cache.assoc = 8
99 #
100 # The magic lies in the mapping of the Python attributes for SimObject
101 # classes to the actual SimObject parameter specifications. This
102 # allows parameter validity checking in the Python code. Continuing
103 # the example above, the statements "cache.blurfl=3" or
104 # "cache.assoc='hello'" would both result in runtime errors in Python,
105 # since the BaseCache object has no 'blurfl' parameter and the 'assoc'
106 # parameter requires an integer, respectively. This magic is done
107 # primarily by overriding the special __setattr__ method that controls
108 # assignment to object attributes.
109 #
110 # Once a set of Python objects have been instantiated in a hierarchy,
111 # calling 'instantiate(obj)' (where obj is the root of the hierarchy)
112 # will generate a .ini file.
113 #
114 #####################################################################
115
116 # list of all SimObject classes
117 allClasses = {}
118
119 # dict to look up SimObjects based on path
120 instanceDict = {}
121
122 # The metaclass for SimObject. This class controls how new classes
123 # that derive from SimObject are instantiated, and provides inherited
124 # class behavior (just like a class controls how instances of that
125 # class are instantiated, and provides inherited instance behavior).
126 class MetaSimObject(type):
127 # Attributes that can be set only at initialization time
128 init_keywords = { 'abstract' : types.BooleanType,
129 'cxx_class' : types.StringType,
130 'cxx_type' : types.StringType,
131 'cxx_predecls' : types.ListType,
132 'swig_objdecls' : types.ListType,
133 'swig_predecls' : types.ListType,
134 'type' : types.StringType }
135 # Attributes that can be set any time
136 keywords = { 'check' : types.FunctionType }
137
138 # __new__ is called before __init__, and is where the statements
139 # in the body of the class definition get loaded into the class's
140 # __dict__. We intercept this to filter out parameter & port assignments
141 # and only allow "private" attributes to be passed to the base
142 # __new__ (starting with underscore).
143 def __new__(mcls, name, bases, dict):
144 assert name not in allClasses
145
146 # Copy "private" attributes, functions, and classes to the
147 # official dict. Everything else goes in _init_dict to be
148 # filtered in __init__.
149 cls_dict = {}
150 value_dict = {}
151 for key,val in dict.items():
152 if key.startswith('_') or isinstance(val, (types.FunctionType,
153 types.TypeType)):
154 cls_dict[key] = val
155 else:
156 # must be a param/port setting
157 value_dict[key] = val
158 if 'abstract' not in value_dict:
159 value_dict['abstract'] = False
160 cls_dict['_value_dict'] = value_dict
161 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
162 if 'type' in value_dict:
163 allClasses[name] = cls
164 return cls
165
166 # subclass initialization
167 def __init__(cls, name, bases, dict):
168 # calls type.__init__()... I think that's a no-op, but leave
169 # it here just in case it's not.
170 super(MetaSimObject, cls).__init__(name, bases, dict)
171
172 # initialize required attributes
173
174 # class-only attributes
175 cls._params = multidict() # param descriptions
176 cls._ports = multidict() # port descriptions
177
178 # class or instance attributes
179 cls._values = multidict() # param values
180 cls._port_refs = multidict() # port ref objects
181 cls._instantiated = False # really instantiated, cloned, or subclassed
182
183 # We don't support multiple inheritance. If you want to, you
184 # must fix multidict to deal with it properly.
185 if len(bases) > 1:
186 raise TypeError, "SimObjects do not support multiple inheritance"
187
188 base = bases[0]
189
190 # Set up general inheritance via multidicts. A subclass will
191 # inherit all its settings from the base class. The only time
192 # the following is not true is when we define the SimObject
193 # class itself (in which case the multidicts have no parent).
194 if isinstance(base, MetaSimObject):
195 cls._base = base
196 cls._params.parent = base._params
197 cls._ports.parent = base._ports
198 cls._values.parent = base._values
199 cls._port_refs.parent = base._port_refs
200 # mark base as having been subclassed
201 base._instantiated = True
202 else:
203 cls._base = None
204
205 # default keyword values
206 if 'type' in cls._value_dict:
207 if 'cxx_class' not in cls._value_dict:
208 cls._value_dict['cxx_class'] = cls._value_dict['type']
209
210 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
211
212 if 'cxx_predecls' not in cls._value_dict:
213 # A forward class declaration is sufficient since we are
214 # just declaring a pointer.
215 class_path = cls._value_dict['cxx_class'].split('::')
216 class_path.reverse()
217 decl = 'class %s;' % class_path[0]
218 for ns in class_path[1:]:
219 decl = 'namespace %s { %s }' % (ns, decl)
220 cls._value_dict['cxx_predecls'] = [decl]
221
222 if 'swig_predecls' not in cls._value_dict:
223 # A forward class declaration is sufficient since we are
224 # just declaring a pointer.
225 cls._value_dict['swig_predecls'] = \
226 cls._value_dict['cxx_predecls']
227
228 if 'swig_objdecls' not in cls._value_dict:
229 cls._value_dict['swig_objdecls'] = []
230
231 # Now process the _value_dict items. They could be defining
232 # new (or overriding existing) parameters or ports, setting
233 # class keywords (e.g., 'abstract'), or setting parameter
234 # values or port bindings. The first 3 can only be set when
235 # the class is defined, so we handle them here. The others
236 # can be set later too, so just emulate that by calling
237 # setattr().
238 for key,val in cls._value_dict.items():
239 # param descriptions
240 if isinstance(val, ParamDesc):
241 cls._new_param(key, val)
242
243 # port objects
244 elif isinstance(val, Port):
245 cls._new_port(key, val)
246
247 # init-time-only keywords
248 elif cls.init_keywords.has_key(key):
249 cls._set_keyword(key, val, cls.init_keywords[key])
250
251 # default: use normal path (ends up in __setattr__)
252 else:
253 setattr(cls, key, val)
254
255 def _set_keyword(cls, keyword, val, kwtype):
256 if not isinstance(val, kwtype):
257 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
258 (keyword, type(val), kwtype)
259 if isinstance(val, types.FunctionType):
260 val = classmethod(val)
261 type.__setattr__(cls, keyword, val)
262
263 def _new_param(cls, name, pdesc):
264 # each param desc should be uniquely assigned to one variable
265 assert(not hasattr(pdesc, 'name'))
266 pdesc.name = name
267 cls._params[name] = pdesc
268 if hasattr(pdesc, 'default'):
269 cls._set_param(name, pdesc.default, pdesc)
270
271 def _set_param(cls, name, value, param):
272 assert(param.name == name)
273 try:
274 cls._values[name] = param.convert(value)
275 except Exception, e:
276 msg = "%s\nError setting param %s.%s to %s\n" % \
277 (e, cls.__name__, name, value)
278 e.args = (msg, )
279 raise
280
281 def _new_port(cls, name, port):
282 # each port should be uniquely assigned to one variable
283 assert(not hasattr(port, 'name'))
284 port.name = name
285 cls._ports[name] = port
286 if hasattr(port, 'default'):
287 cls._cls_get_port_ref(name).connect(port.default)
288
289 # same as _get_port_ref, effectively, but for classes
290 def _cls_get_port_ref(cls, attr):
291 # Return reference that can be assigned to another port
292 # via __setattr__. There is only ever one reference
293 # object per port, but we create them lazily here.
294 ref = cls._port_refs.get(attr)
295 if not ref:
296 ref = cls._ports[attr].makeRef(cls)
297 cls._port_refs[attr] = ref
298 return ref
299
300 # Set attribute (called on foo.attr = value when foo is an
301 # instance of class cls).
302 def __setattr__(cls, attr, value):
303 # normal processing for private attributes
304 if attr.startswith('_'):
305 type.__setattr__(cls, attr, value)
306 return
307
308 if cls.keywords.has_key(attr):
309 cls._set_keyword(attr, value, cls.keywords[attr])
310 return
311
312 if cls._ports.has_key(attr):
313 cls._cls_get_port_ref(attr).connect(value)
314 return
315
316 if isSimObjectOrSequence(value) and cls._instantiated:
317 raise RuntimeError, \
318 "cannot set SimObject parameter '%s' after\n" \
319 " class %s has been instantiated or subclassed" \
320 % (attr, cls.__name__)
321
322 # check for param
323 param = cls._params.get(attr)
324 if param:
325 cls._set_param(attr, value, param)
326 return
327
328 if isSimObjectOrSequence(value):
329 # If RHS is a SimObject, it's an implicit child assignment.
330 # Classes don't have children, so we just put this object
331 # in _values; later, each instance will do a 'setattr(self,
332 # attr, _values[attr])' in SimObject.__init__ which will
333 # add this object as a child.
334 cls._values[attr] = value
335 return
336
337 # no valid assignment... raise exception
338 raise AttributeError, \
339 "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
340
341 def __getattr__(cls, attr):
342 if cls._values.has_key(attr):
343 return cls._values[attr]
344
345 raise AttributeError, \
346 "object '%s' has no attribute '%s'" % (cls.__name__, attr)
347
348 def __str__(cls):
349 return cls.__name__
350
351 def cxx_decl(cls):
352 code = "#ifndef __PARAMS__%s\n" % cls
353 code += "#define __PARAMS__%s\n\n" % cls
354
355 # The 'dict' attribute restricts us to the params declared in
356 # the object itself, not including inherited params (which
357 # will also be inherited from the base class's param struct
358 # here).
359 params = cls._params.local.values()
360 try:
361 ptypes = [p.ptype for p in params]
362 except:
363 print cls, p, p.ptype_str
364 print params
365 raise
366
367 # get a list of lists of predeclaration lines
368 predecls = []
369 predecls.extend(cls.cxx_predecls)
370 for p in params:
371 predecls.extend(p.cxx_predecls())
372 # remove redundant lines
373 predecls2 = []
374 for pd in predecls:
375 if pd not in predecls2:
376 predecls2.append(pd)
377 predecls2.sort()
378 code += "\n".join(predecls2)
379 code += "\n\n";
380
381 if cls._base:
382 code += '#include "params/%s.hh"\n\n' % cls._base.type
383
384 for ptype in ptypes:
385 if issubclass(ptype, Enum):
386 code += '#include "enums/%s.hh"\n' % ptype.__name__
387 code += "\n\n"
388
389 code += cls.cxx_struct(cls._base, params)
390
391 # close #ifndef __PARAMS__* guard
392 code += "\n#endif\n"
393 return code
394
395 def cxx_struct(cls, base, params):
396 if cls == SimObject:
397 return '#include "sim/sim_object_params.hh"\n'
398
399 # now generate the actual param struct
400 code = "struct %sParams" % cls
401 if base:
402 code += " : public %sParams" % base.type
403 code += "\n{\n"
404 if not hasattr(cls, 'abstract') or not cls.abstract:
405 if 'type' in cls.__dict__:
406 code += " %s create();\n" % cls.cxx_type
407 decls = [p.cxx_decl() for p in params]
408 decls.sort()
409 code += "".join([" %s\n" % d for d in decls])
410 code += "};\n"
411
412 return code
413
414 def swig_decl(cls):
415 code = '%%module %s\n' % cls
416
417 code += '%{\n'
418 code += '#include "params/%s.hh"\n' % cls
419 code += '%}\n\n'
420
421 # The 'dict' attribute restricts us to the params declared in
422 # the object itself, not including inherited params (which
423 # will also be inherited from the base class's param struct
424 # here).
425 params = cls._params.local.values()
426 ptypes = [p.ptype for p in params]
427
428 # get a list of lists of predeclaration lines
429 predecls = []
430 predecls.extend([ p.swig_predecls() for p in params ])
431 # flatten
432 predecls = reduce(lambda x,y:x+y, predecls, [])
433 # remove redundant lines
434 predecls2 = []
435 for pd in predecls:
436 if pd not in predecls2:
437 predecls2.append(pd)
438 predecls2.sort()
439 code += "\n".join(predecls2)
440 code += "\n\n";
441
442 if cls._base:
443 code += '%%import "params/%s.i"\n\n' % cls._base.type
444
445 for ptype in ptypes:
446 if issubclass(ptype, Enum):
447 code += '%%import "enums/%s.hh"\n' % ptype.__name__
448 code += "\n\n"
449
450 code += '%%import "params/%s_type.hh"\n\n' % cls
451 code += '%%include "params/%s.hh"\n\n' % cls
452
453 return code
454
455 # The SimObject class is the root of the special hierarchy. Most of
456 # the code in this class deals with the configuration hierarchy itself
457 # (parent/child node relationships).
458 class SimObject(object):
459 # Specify metaclass. Any class inheriting from SimObject will
460 # get this metaclass.
461 __metaclass__ = MetaSimObject
462 type = 'SimObject'
463 abstract = True
464
465 swig_objdecls = [ '%include "python/swig/sim_object.i"' ]
466
467 # Initialize new instance. For objects with SimObject-valued
468 # children, we need to recursively clone the classes represented
469 # by those param values as well in a consistent "deep copy"-style
470 # fashion. That is, we want to make sure that each instance is
471 # cloned only once, and that if there are multiple references to
472 # the same original object, we end up with the corresponding
473 # cloned references all pointing to the same cloned instance.
474 def __init__(self, **kwargs):
475 ancestor = kwargs.get('_ancestor')
476 memo_dict = kwargs.get('_memo')
477 if memo_dict is None:
478 # prepare to memoize any recursively instantiated objects
479 memo_dict = {}
480 elif ancestor:
481 # memoize me now to avoid problems with recursive calls
482 memo_dict[ancestor] = self
483
484 if not ancestor:
485 ancestor = self.__class__
486 ancestor._instantiated = True
487
488 # initialize required attributes
489 self._parent = None
490 self._children = {}
491 self._ccObject = None # pointer to C++ object
492 self._ccParams = None
493 self._instantiated = False # really "cloned"
494
495 # Inherit parameter values from class using multidict so
496 # individual value settings can be overridden.
497 self._values = multidict(ancestor._values)
498 # clone SimObject-valued parameters
499 for key,val in ancestor._values.iteritems():
500 if isSimObject(val):
501 setattr(self, key, val(_memo=memo_dict))
502 elif isSimObjectSequence(val) and len(val):
503 setattr(self, key, [ v(_memo=memo_dict) for v in val ])
504 # clone port references. no need to use a multidict here
505 # since we will be creating new references for all ports.
506 self._port_refs = {}
507 for key,val in ancestor._port_refs.iteritems():
508 self._port_refs[key] = val.clone(self, memo_dict)
509 # apply attribute assignments from keyword args, if any
510 for key,val in kwargs.iteritems():
511 setattr(self, key, val)
512
513 # "Clone" the current instance by creating another instance of
514 # this instance's class, but that inherits its parameter values
515 # and port mappings from the current instance. If we're in a
516 # "deep copy" recursive clone, check the _memo dict to see if
517 # we've already cloned this instance.
518 def __call__(self, **kwargs):
519 memo_dict = kwargs.get('_memo')
520 if memo_dict is None:
521 # no memo_dict: must be top-level clone operation.
522 # this is only allowed at the root of a hierarchy
523 if self._parent:
524 raise RuntimeError, "attempt to clone object %s " \
525 "not at the root of a tree (parent = %s)" \
526 % (self, self._parent)
527 # create a new dict and use that.
528 memo_dict = {}
529 kwargs['_memo'] = memo_dict
530 elif memo_dict.has_key(self):
531 # clone already done & memoized
532 return memo_dict[self]
533 return self.__class__(_ancestor = self, **kwargs)
534
535 def _get_port_ref(self, attr):
536 # Return reference that can be assigned to another port
537 # via __setattr__. There is only ever one reference
538 # object per port, but we create them lazily here.
539 ref = self._port_refs.get(attr)
540 if not ref:
541 ref = self._ports[attr].makeRef(self)
542 self._port_refs[attr] = ref
543 return ref
544
545 def __getattr__(self, attr):
546 if self._ports.has_key(attr):
547 return self._get_port_ref(attr)
548
549 if self._values.has_key(attr):
550 return self._values[attr]
551
552 raise AttributeError, "object '%s' has no attribute '%s'" \
553 % (self.__class__.__name__, attr)
554
555 # Set attribute (called on foo.attr = value when foo is an
556 # instance of class cls).
557 def __setattr__(self, attr, value):
558 # normal processing for private attributes
559 if attr.startswith('_'):
560 object.__setattr__(self, attr, value)
561 return
562
563 if self._ports.has_key(attr):
564 # set up port connection
565 self._get_port_ref(attr).connect(value)
566 return
567
568 if isSimObjectOrSequence(value) and self._instantiated:
569 raise RuntimeError, \
570 "cannot set SimObject parameter '%s' after\n" \
571 " instance been cloned %s" % (attr, `self`)
572
573 # must be SimObject param
574 param = self._params.get(attr)
575 if param:
576 try:
577 value = param.convert(value)
578 except Exception, e:
579 msg = "%s\nError setting param %s.%s to %s\n" % \
580 (e, self.__class__.__name__, attr, value)
581 e.args = (msg, )
582 raise
583 self._set_child(attr, value)
584 return
585
586 if isSimObjectOrSequence(value):
587 self._set_child(attr, value)
588 return
589
590 # no valid assignment... raise exception
591 raise AttributeError, "Class %s has no parameter %s" \
592 % (self.__class__.__name__, attr)
593
594
595 # this hack allows tacking a '[0]' onto parameters that may or may
596 # not be vectors, and always getting the first element (e.g. cpus)
597 def __getitem__(self, key):
598 if key == 0:
599 return self
600 raise TypeError, "Non-zero index '%s' to SimObject" % key
601
602 # clear out children with given name, even if it's a vector
603 def clear_child(self, name):
604 if not self._children.has_key(name):
605 return
606 child = self._children[name]
607 if isinstance(child, SimObjVector):
608 for i in xrange(len(child)):
609 del self._children["s%d" % (name, i)]
610 del self._children[name]
611
612 def add_child(self, name, value):
613 self._children[name] = value
614
615 def _maybe_set_parent(self, parent, name):
616 if not self._parent:
617 self._parent = parent
618 self._name = name
619 parent.add_child(name, self)
620
621 def _set_child(self, attr, value):
622 # if RHS is a SimObject, it's an implicit child assignment
623 # clear out old child with this name, if any
624 self.clear_child(attr)
625
626 if isSimObject(value):
627 value._maybe_set_parent(self, attr)
628 elif isSimObjectSequence(value):
629 value = SimObjVector(value)
630 if len(value) == 1:
631 value[0]._maybe_set_parent(self, attr)
632 else:
633 width = int(math.ceil(math.log(len(value))/math.log(10)))
634 for i,v in enumerate(value):
635 v._maybe_set_parent(self, "%s%0*d" % (attr, width, i))
636
637 self._values[attr] = value
638
639 def path(self):
640 if not self._parent:
641 return 'root'
642 ppath = self._parent.path()
643 if ppath == 'root':
644 return self._name
645 return ppath + "." + self._name
646
647 def __str__(self):
648 return self.path()
649
650 def ini_str(self):
651 return self.path()
652
653 def find_any(self, ptype):
654 if isinstance(self, ptype):
655 return self, True
656
657 found_obj = None
658 for child in self._children.itervalues():
659 if isinstance(child, ptype):
660 if found_obj != None and child != found_obj:
661 raise AttributeError, \
662 'parent.any matched more than one: %s %s' % \
663 (found_obj.path, child.path)
664 found_obj = child
665 # search param space
666 for pname,pdesc in self._params.iteritems():
667 if issubclass(pdesc.ptype, ptype):
668 match_obj = self._values[pname]
669 if found_obj != None and found_obj != match_obj:
670 raise AttributeError, \
671 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
672 found_obj = match_obj
673 return found_obj, found_obj != None
674
675 def unproxy(self, base):
676 return self
677
678 def unproxy_all(self):
679 for param in self._params.iterkeys():
680 value = self._values.get(param)
681 if value != None and proxy.isproxy(value):
682 try:
683 value = value.unproxy(self)
684 except:
685 print "Error in unproxying param '%s' of %s" % \
686 (param, self.path())
687 raise
688 setattr(self, param, value)
689
690 # Unproxy ports in sorted order so that 'append' operations on
691 # vector ports are done in a deterministic fashion.
692 port_names = self._ports.keys()
693 port_names.sort()
694 for port_name in port_names:
695 port = self._port_refs.get(port_name)
696 if port != None:
697 port.unproxy(self)
698
699 # Unproxy children in sorted order for determinism also.
700 child_names = self._children.keys()
701 child_names.sort()
702 for child in child_names:
703 self._children[child].unproxy_all()
704
705 def print_ini(self, ini_file):
706 print >>ini_file, '[' + self.path() + ']' # .ini section header
707
708 instanceDict[self.path()] = self
709
710 if hasattr(self, 'type'):
711 print >>ini_file, 'type=%s' % self.type
712
713 child_names = self._children.keys()
714 child_names.sort()
715 if len(child_names):
716 print >>ini_file, 'children=%s' % ' '.join(child_names)
717
718 param_names = self._params.keys()
719 param_names.sort()
720 for param in param_names:
721 value = self._values.get(param)
722 if value != None:
723 print >>ini_file, '%s=%s' % (param,
724 self._values[param].ini_str())
725
726 port_names = self._ports.keys()
727 port_names.sort()
728 for port_name in port_names:
729 port = self._port_refs.get(port_name, None)
730 if port != None:
731 print >>ini_file, '%s=%s' % (port_name, port.ini_str())
732
733 print >>ini_file # blank line between objects
734
735 for child in child_names:
736 self._children[child].print_ini(ini_file)
737
738 def getCCParams(self):
739 if self._ccParams:
740 return self._ccParams
741
742 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type)
743 cc_params = cc_params_struct()
744 cc_params.pyobj = self
745 cc_params.name = str(self)
746
747 param_names = self._params.keys()
748 param_names.sort()
749 for param in param_names:
750 value = self._values.get(param)
751 if value is None:
752 m5.fatal("%s.%s without default or user set value",
753 self.path(), param)
754
755 value = value.getValue()
756 if isinstance(self._params[param], VectorParamDesc):
757 assert isinstance(value, list)
758 vec = getattr(cc_params, param)
759 assert not len(vec)
760 for v in value:
761 vec.append(v)
762 else:
763 setattr(cc_params, param, value)
764
765 port_names = self._ports.keys()
766 port_names.sort()
767 for port_name in port_names:
768 port = self._port_refs.get(port_name, None)
769 if port != None:
770 setattr(cc_params, port_name, port)
771 self._ccParams = cc_params
772 return self._ccParams
773
774 # Get C++ object corresponding to this object, calling C++ if
775 # necessary to construct it. Does *not* recursively create
776 # children.
777 def getCCObject(self):
778 if not self._ccObject:
779 # Cycles in the configuration heirarchy are not supported. This
780 # will catch the resulting recursion and stop.
781 self._ccObject = -1
782 params = self.getCCParams()
783 self._ccObject = params.create()
784 elif self._ccObject == -1:
785 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
786 % self.path()
787 return self._ccObject
788
789 # Call C++ to create C++ object corresponding to this object and
790 # (recursively) all its children
791 def createCCObject(self):
792 self.getCCParams()
793 self.getCCObject() # force creation
794 for child in self._children.itervalues():
795 child.createCCObject()
796
797 def getValue(self):
798 return self.getCCObject()
799
800 # Create C++ port connections corresponding to the connections in
801 # _port_refs (& recursively for all children)
802 def connectPorts(self):
803 for portRef in self._port_refs.itervalues():
804 portRef.ccConnect()
805 for child in self._children.itervalues():
806 child.connectPorts()
807
808 def startDrain(self, drain_event, recursive):
809 count = 0
810 if isinstance(self, SimObject):
811 count += self._ccObject.drain(drain_event)
812 if recursive:
813 for child in self._children.itervalues():
814 count += child.startDrain(drain_event, True)
815 return count
816
817 def resume(self):
818 if isinstance(self, SimObject):
819 self._ccObject.resume()
820 for child in self._children.itervalues():
821 child.resume()
822
823 def getMemoryMode(self):
824 if not isinstance(self, m5.objects.System):
825 return None
826
827 return self._ccObject.getMemoryMode()
828
829 def changeTiming(self, mode):
830 if isinstance(self, m5.objects.System):
831 # i don't know if there's a better way to do this - calling
832 # setMemoryMode directly from self._ccObject results in calling
833 # SimObject::setMemoryMode, not the System::setMemoryMode
834 self._ccObject.setMemoryMode(mode)
835 for child in self._children.itervalues():
836 child.changeTiming(mode)
837
838 def takeOverFrom(self, old_cpu):
839 self._ccObject.takeOverFrom(old_cpu._ccObject)
840
841 # generate output file for 'dot' to display as a pretty graph.
842 # this code is currently broken.
843 def outputDot(self, dot):
844 label = "{%s|" % self.path
845 if isSimObject(self.realtype):
846 label += '%s|' % self.type
847
848 if self.children:
849 # instantiate children in same order they were added for
850 # backward compatibility (else we can end up with cpu1
851 # before cpu0).
852 for c in self.children:
853 dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
854
855 simobjs = []
856 for param in self.params:
857 try:
858 if param.value is None:
859 raise AttributeError, 'Parameter with no value'
860
861 value = param.value
862 string = param.string(value)
863 except Exception, e:
864 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
865 e.args = (msg, )
866 raise
867
868 if isSimObject(param.ptype) and string != "Null":
869 simobjs.append(string)
870 else:
871 label += '%s = %s\\n' % (param.name, string)
872
873 for so in simobjs:
874 label += "|<%s> %s" % (so, so)
875 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
876 tailport="w"))
877 label += '}'
878 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
879
880 # recursively dump out children
881 for c in self.children:
882 c.outputDot(dot)
883
884 # Function to provide to C++ so it can look up instances based on paths
885 def resolveSimObject(name):
886 obj = instanceDict[name]
887 return obj.getCCObject()
888
889 # __all__ defines the list of symbols that get exported when
890 # 'from config import *' is invoked. Try to keep this reasonably
891 # short to avoid polluting other namespaces.
892 __all__ = [ 'SimObject' ]