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