StateMachine.py (6882:898047a3672c) StateMachine.py (6888:de8e755aca4f)
1# Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
2# Copyright (c) 2009 The Hewlett-Packard Development Company
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met: redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer;
9# redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the
11# documentation and/or other materials provided with the distribution;
12# neither the name of the copyright holders nor the names of its
13# contributors may be used to endorse or promote products derived from
14# this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28from m5.util import code_formatter, orderdict
29
30from slicc.symbols.Symbol import Symbol
31from slicc.symbols.Var import Var
32import slicc.generate.html as html
33
34python_class_map = {"int": "Int",
35 "string": "String",
36 "bool": "Bool",
37 "CacheMemory": "RubyCache",
38 "Sequencer": "RubySequencer",
39 "DirectoryMemory": "RubyDirectoryMemory",
40 "MemoryControl": "RubyMemoryControl",
1# Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
2# Copyright (c) 2009 The Hewlett-Packard Development Company
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met: redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer;
9# redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the
11# documentation and/or other materials provided with the distribution;
12# neither the name of the copyright holders nor the names of its
13# contributors may be used to endorse or promote products derived from
14# this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28from m5.util import code_formatter, orderdict
29
30from slicc.symbols.Symbol import Symbol
31from slicc.symbols.Var import Var
32import slicc.generate.html as html
33
34python_class_map = {"int": "Int",
35 "string": "String",
36 "bool": "Bool",
37 "CacheMemory": "RubyCache",
38 "Sequencer": "RubySequencer",
39 "DirectoryMemory": "RubyDirectoryMemory",
40 "MemoryControl": "RubyMemoryControl",
41 "DMASequencer": "DMASequencer"
41 }
42
43class StateMachine(Symbol):
44 def __init__(self, symtab, ident, location, pairs, config_parameters):
45 super(StateMachine, self).__init__(symtab, ident, location, pairs)
46 self.table = None
47 self.config_parameters = config_parameters
48 for param in config_parameters:
49 if param.pointer:
50 var = Var(symtab, param.name, location, param.type_ast.type,
51 "(*m_%s_ptr)" % param.name, {}, self)
52 else:
53 var = Var(symtab, param.name, location, param.type_ast.type,
54 "m_%s" % param.name, {}, self)
55 self.symtab.registerSym(param.name, var)
56
57 self.states = orderdict()
58 self.events = orderdict()
59 self.actions = orderdict()
60 self.transitions = []
61 self.in_ports = []
62 self.functions = []
63 self.objects = []
64
65 self.message_buffer_names = []
66
67 def __repr__(self):
68 return "[StateMachine: %s]" % self.ident
69
70 def addState(self, state):
71 assert self.table is None
72 self.states[state.ident] = state
73
74 def addEvent(self, event):
75 assert self.table is None
76 self.events[event.ident] = event
77
78 def addAction(self, action):
79 assert self.table is None
80
81 # Check for duplicate action
82 for other in self.actions.itervalues():
83 if action.ident == other.ident:
84 action.warning("Duplicate action definition: %s" % action.ident)
85 action.error("Duplicate action definition: %s" % action.ident)
86 if action.short == other.short:
87 other.warning("Duplicate action shorthand: %s" % other.ident)
88 other.warning(" shorthand = %s" % other.short)
89 action.warning("Duplicate action shorthand: %s" % action.ident)
90 action.error(" shorthand = %s" % action.short)
91
92 self.actions[action.ident] = action
93
94 def addTransition(self, trans):
95 assert self.table is None
96 self.transitions.append(trans)
97
98 def addInPort(self, var):
99 self.in_ports.append(var)
100
101 def addFunc(self, func):
102 # register func in the symbol table
103 self.symtab.registerSym(str(func), func)
104 self.functions.append(func)
105
106 def addObject(self, obj):
107 self.objects.append(obj)
108
109 # Needs to be called before accessing the table
110 def buildTable(self):
111 assert self.table is None
112
113 table = {}
114
115 for trans in self.transitions:
116 # Track which actions we touch so we know if we use them
117 # all -- really this should be done for all symbols as
118 # part of the symbol table, then only trigger it for
119 # Actions, States, Events, etc.
120
121 for action in trans.actions:
122 action.used = True
123
124 index = (trans.state, trans.event)
125 if index in table:
126 table[index].warning("Duplicate transition: %s" % table[index])
127 trans.error("Duplicate transition: %s" % trans)
128 table[index] = trans
129
130 # Look at all actions to make sure we used them all
131 for action in self.actions.itervalues():
132 if not action.used:
133 error_msg = "Unused action: %s" % action.ident
134 if "desc" in action:
135 error_msg += ", " + action.desc
136 action.warning(error_msg)
137 self.table = table
138
139 def writeCodeFiles(self, path):
140 self.printControllerPython(path)
141 self.printControllerHH(path)
142 self.printControllerCC(path)
143 self.printCSwitch(path)
144 self.printCWakeup(path)
145 self.printProfilerCC(path)
146 self.printProfilerHH(path)
147
148 for func in self.functions:
149 func.writeCodeFiles(path)
150
151 def printControllerPython(self, path):
152 code = code_formatter()
153 ident = self.ident
154 py_ident = "%s_Controller" % ident
155 c_ident = "%s_Controller" % self.ident
156 code('''
157from m5.params import *
158from m5.SimObject import SimObject
159from Controller import RubyController
160
161class $py_ident(RubyController):
162 type = '$py_ident'
163''')
164 code.indent()
165 for param in self.config_parameters:
166 dflt_str = ''
167 if param.default is not None:
168 dflt_str = str(param.default) + ', '
169 if python_class_map.has_key(param.type_ast.type.c_ident):
170 python_type = python_class_map[param.type_ast.type.c_ident]
171 code('${{param.name}} = Param.${{python_type}}(${dflt_str}"")')
172 else:
173 self.error("Unknown c++ to python class conversion for c++ " \
174 "type: '%s'. Please update the python_class_map " \
175 "in StateMachine.py", param.type_ast.type.c_ident)
176 code.dedent()
177 code.write(path, '%s.py' % py_ident)
178
179
180 def printControllerHH(self, path):
181 '''Output the method declarations for the class declaration'''
182 code = code_formatter()
183 ident = self.ident
184 c_ident = "%s_Controller" % self.ident
185
186 self.message_buffer_names = []
187
188 code('''
189/** \\file $ident.hh
190 *
191 * Auto generated C++ code started by $__file__:$__line__
192 * Created by slicc definition of Module "${{self.short}}"
193 */
194
195#ifndef ${ident}_CONTROLLER_H
196#define ${ident}_CONTROLLER_H
197
198#include "params/$c_ident.hh"
199
200#include "mem/ruby/common/Global.hh"
201#include "mem/ruby/common/Consumer.hh"
202#include "mem/ruby/slicc_interface/AbstractController.hh"
203#include "mem/protocol/TransitionResult.hh"
204#include "mem/protocol/Types.hh"
205#include "mem/protocol/${ident}_Profiler.hh"
206''')
207
208 seen_types = set()
209 for var in self.objects:
210 if var.type.ident not in seen_types and not var.type.isPrimitive:
211 code('#include "mem/protocol/${{var.type.c_ident}}.hh"')
212 seen_types.add(var.type.ident)
213
214 # for adding information to the protocol debug trace
215 code('''
216extern stringstream ${ident}_transitionComment;
217
218class $c_ident : public AbstractController {
219#ifdef CHECK_COHERENCE
220#endif /* CHECK_COHERENCE */
221public:
222 typedef ${c_ident}Params Params;
223 $c_ident(const Params *p);
224 static int getNumControllers();
225 void init();
226 MessageBuffer* getMandatoryQueue() const;
227 const int & getVersion() const;
228 const string toString() const;
229 const string getName() const;
230 const MachineType getMachineType() const;
231 void initNetworkPtr(Network* net_ptr) { m_net_ptr = net_ptr; }
232 void print(ostream& out) const;
233 void printConfig(ostream& out) const;
234 void wakeup();
235 void printStats(ostream& out) const { s_profiler.dumpStats(out); }
236 void clearStats() { s_profiler.clearStats(); }
237 void blockOnQueue(Address addr, MessageBuffer* port);
238 void unblock(Address addr);
239private:
240''')
241
242 code.indent()
243 # added by SS
244 for param in self.config_parameters:
245 if param.pointer:
246 code('${{param.type_ast.type}}* m_${{param.ident}}_ptr;')
247 else:
248 code('${{param.type_ast.type}} m_${{param.ident}};')
249
250 code('''
251int m_number_of_TBEs;
252
253TransitionResult doTransition(${ident}_Event event, ${ident}_State state, const Address& addr); // in ${ident}_Transitions.cc
254TransitionResult doTransitionWorker(${ident}_Event event, ${ident}_State state, ${ident}_State& next_state, const Address& addr); // in ${ident}_Transitions.cc
255string m_name;
256int m_transitions_per_cycle;
257int m_buffer_size;
258int m_recycle_latency;
259map< string, string > m_cfg;
260NodeID m_version;
261Network* m_net_ptr;
262MachineID m_machineID;
263bool m_is_blocking;
264map< Address, MessageBuffer* > m_block_map;
265${ident}_Profiler s_profiler;
266static int m_num_controllers;
267// Internal functions
268''')
269
270 for func in self.functions:
271 proto = func.prototype
272 if proto:
273 code('$proto')
274
275 code('''
276
277// Actions
278''')
279 for action in self.actions.itervalues():
280 code('/** \\brief ${{action.desc}} */')
281 code('void ${{action.ident}}(const Address& addr);')
282
283 # the controller internal variables
284 code('''
285
286// Object
287''')
288 for var in self.objects:
289 th = var.get("template_hack", "")
290 code('${{var.type.c_ident}}$th* m_${{var.c_ident}}_ptr;')
291
292 if var.type.ident == "MessageBuffer":
293 self.message_buffer_names.append("m_%s_ptr" % var.c_ident)
294
295 code.dedent()
296 code('};')
297 code('#endif // ${ident}_CONTROLLER_H')
298 code.write(path, '%s.hh' % c_ident)
299
300 def printControllerCC(self, path):
301 '''Output the actions for performing the actions'''
302
303 code = code_formatter()
304 ident = self.ident
305 c_ident = "%s_Controller" % self.ident
306
307 code('''
308/** \\file $ident.cc
309 *
310 * Auto generated C++ code started by $__file__:$__line__
311 * Created by slicc definition of Module "${{self.short}}"
312 */
313
314#include "mem/ruby/common/Global.hh"
315#include "mem/ruby/slicc_interface/RubySlicc_includes.hh"
316#include "mem/protocol/${ident}_Controller.hh"
317#include "mem/protocol/${ident}_State.hh"
318#include "mem/protocol/${ident}_Event.hh"
319#include "mem/protocol/Types.hh"
320#include "mem/ruby/system/System.hh"
321''')
322
323 # include object classes
324 seen_types = set()
325 for var in self.objects:
326 if var.type.ident not in seen_types and not var.type.isPrimitive:
327 code('#include "mem/protocol/${{var.type.c_ident}}.hh"')
328 seen_types.add(var.type.ident)
329
330 code('''
331$c_ident *
332${c_ident}Params::create()
333{
334 return new $c_ident(this);
335}
336
337
338int $c_ident::m_num_controllers = 0;
339
340stringstream ${ident}_transitionComment;
341#define APPEND_TRANSITION_COMMENT(str) (${ident}_transitionComment << str)
342/** \\brief constructor */
343$c_ident::$c_ident(const Params *p)
344 : AbstractController(p)
345{
346 m_version = p->version;
347 m_transitions_per_cycle = p->transitions_per_cycle;
348 m_buffer_size = p->buffer_size;
349 m_recycle_latency = p->recycle_latency;
350 m_number_of_TBEs = p->number_of_TBEs;
351''')
352 code.indent()
353
354 #
355 # After initializing the universal machine parameters, initialize the
356 # this machines config parameters. Also detemine if these configuration
357 # params include a sequencer. This information will be used later for
358 # contecting the sequencer back to the L1 cache controller.
359 #
360 contains_sequencer = False
361 for param in self.config_parameters:
42 }
43
44class StateMachine(Symbol):
45 def __init__(self, symtab, ident, location, pairs, config_parameters):
46 super(StateMachine, self).__init__(symtab, ident, location, pairs)
47 self.table = None
48 self.config_parameters = config_parameters
49 for param in config_parameters:
50 if param.pointer:
51 var = Var(symtab, param.name, location, param.type_ast.type,
52 "(*m_%s_ptr)" % param.name, {}, self)
53 else:
54 var = Var(symtab, param.name, location, param.type_ast.type,
55 "m_%s" % param.name, {}, self)
56 self.symtab.registerSym(param.name, var)
57
58 self.states = orderdict()
59 self.events = orderdict()
60 self.actions = orderdict()
61 self.transitions = []
62 self.in_ports = []
63 self.functions = []
64 self.objects = []
65
66 self.message_buffer_names = []
67
68 def __repr__(self):
69 return "[StateMachine: %s]" % self.ident
70
71 def addState(self, state):
72 assert self.table is None
73 self.states[state.ident] = state
74
75 def addEvent(self, event):
76 assert self.table is None
77 self.events[event.ident] = event
78
79 def addAction(self, action):
80 assert self.table is None
81
82 # Check for duplicate action
83 for other in self.actions.itervalues():
84 if action.ident == other.ident:
85 action.warning("Duplicate action definition: %s" % action.ident)
86 action.error("Duplicate action definition: %s" % action.ident)
87 if action.short == other.short:
88 other.warning("Duplicate action shorthand: %s" % other.ident)
89 other.warning(" shorthand = %s" % other.short)
90 action.warning("Duplicate action shorthand: %s" % action.ident)
91 action.error(" shorthand = %s" % action.short)
92
93 self.actions[action.ident] = action
94
95 def addTransition(self, trans):
96 assert self.table is None
97 self.transitions.append(trans)
98
99 def addInPort(self, var):
100 self.in_ports.append(var)
101
102 def addFunc(self, func):
103 # register func in the symbol table
104 self.symtab.registerSym(str(func), func)
105 self.functions.append(func)
106
107 def addObject(self, obj):
108 self.objects.append(obj)
109
110 # Needs to be called before accessing the table
111 def buildTable(self):
112 assert self.table is None
113
114 table = {}
115
116 for trans in self.transitions:
117 # Track which actions we touch so we know if we use them
118 # all -- really this should be done for all symbols as
119 # part of the symbol table, then only trigger it for
120 # Actions, States, Events, etc.
121
122 for action in trans.actions:
123 action.used = True
124
125 index = (trans.state, trans.event)
126 if index in table:
127 table[index].warning("Duplicate transition: %s" % table[index])
128 trans.error("Duplicate transition: %s" % trans)
129 table[index] = trans
130
131 # Look at all actions to make sure we used them all
132 for action in self.actions.itervalues():
133 if not action.used:
134 error_msg = "Unused action: %s" % action.ident
135 if "desc" in action:
136 error_msg += ", " + action.desc
137 action.warning(error_msg)
138 self.table = table
139
140 def writeCodeFiles(self, path):
141 self.printControllerPython(path)
142 self.printControllerHH(path)
143 self.printControllerCC(path)
144 self.printCSwitch(path)
145 self.printCWakeup(path)
146 self.printProfilerCC(path)
147 self.printProfilerHH(path)
148
149 for func in self.functions:
150 func.writeCodeFiles(path)
151
152 def printControllerPython(self, path):
153 code = code_formatter()
154 ident = self.ident
155 py_ident = "%s_Controller" % ident
156 c_ident = "%s_Controller" % self.ident
157 code('''
158from m5.params import *
159from m5.SimObject import SimObject
160from Controller import RubyController
161
162class $py_ident(RubyController):
163 type = '$py_ident'
164''')
165 code.indent()
166 for param in self.config_parameters:
167 dflt_str = ''
168 if param.default is not None:
169 dflt_str = str(param.default) + ', '
170 if python_class_map.has_key(param.type_ast.type.c_ident):
171 python_type = python_class_map[param.type_ast.type.c_ident]
172 code('${{param.name}} = Param.${{python_type}}(${dflt_str}"")')
173 else:
174 self.error("Unknown c++ to python class conversion for c++ " \
175 "type: '%s'. Please update the python_class_map " \
176 "in StateMachine.py", param.type_ast.type.c_ident)
177 code.dedent()
178 code.write(path, '%s.py' % py_ident)
179
180
181 def printControllerHH(self, path):
182 '''Output the method declarations for the class declaration'''
183 code = code_formatter()
184 ident = self.ident
185 c_ident = "%s_Controller" % self.ident
186
187 self.message_buffer_names = []
188
189 code('''
190/** \\file $ident.hh
191 *
192 * Auto generated C++ code started by $__file__:$__line__
193 * Created by slicc definition of Module "${{self.short}}"
194 */
195
196#ifndef ${ident}_CONTROLLER_H
197#define ${ident}_CONTROLLER_H
198
199#include "params/$c_ident.hh"
200
201#include "mem/ruby/common/Global.hh"
202#include "mem/ruby/common/Consumer.hh"
203#include "mem/ruby/slicc_interface/AbstractController.hh"
204#include "mem/protocol/TransitionResult.hh"
205#include "mem/protocol/Types.hh"
206#include "mem/protocol/${ident}_Profiler.hh"
207''')
208
209 seen_types = set()
210 for var in self.objects:
211 if var.type.ident not in seen_types and not var.type.isPrimitive:
212 code('#include "mem/protocol/${{var.type.c_ident}}.hh"')
213 seen_types.add(var.type.ident)
214
215 # for adding information to the protocol debug trace
216 code('''
217extern stringstream ${ident}_transitionComment;
218
219class $c_ident : public AbstractController {
220#ifdef CHECK_COHERENCE
221#endif /* CHECK_COHERENCE */
222public:
223 typedef ${c_ident}Params Params;
224 $c_ident(const Params *p);
225 static int getNumControllers();
226 void init();
227 MessageBuffer* getMandatoryQueue() const;
228 const int & getVersion() const;
229 const string toString() const;
230 const string getName() const;
231 const MachineType getMachineType() const;
232 void initNetworkPtr(Network* net_ptr) { m_net_ptr = net_ptr; }
233 void print(ostream& out) const;
234 void printConfig(ostream& out) const;
235 void wakeup();
236 void printStats(ostream& out) const { s_profiler.dumpStats(out); }
237 void clearStats() { s_profiler.clearStats(); }
238 void blockOnQueue(Address addr, MessageBuffer* port);
239 void unblock(Address addr);
240private:
241''')
242
243 code.indent()
244 # added by SS
245 for param in self.config_parameters:
246 if param.pointer:
247 code('${{param.type_ast.type}}* m_${{param.ident}}_ptr;')
248 else:
249 code('${{param.type_ast.type}} m_${{param.ident}};')
250
251 code('''
252int m_number_of_TBEs;
253
254TransitionResult doTransition(${ident}_Event event, ${ident}_State state, const Address& addr); // in ${ident}_Transitions.cc
255TransitionResult doTransitionWorker(${ident}_Event event, ${ident}_State state, ${ident}_State& next_state, const Address& addr); // in ${ident}_Transitions.cc
256string m_name;
257int m_transitions_per_cycle;
258int m_buffer_size;
259int m_recycle_latency;
260map< string, string > m_cfg;
261NodeID m_version;
262Network* m_net_ptr;
263MachineID m_machineID;
264bool m_is_blocking;
265map< Address, MessageBuffer* > m_block_map;
266${ident}_Profiler s_profiler;
267static int m_num_controllers;
268// Internal functions
269''')
270
271 for func in self.functions:
272 proto = func.prototype
273 if proto:
274 code('$proto')
275
276 code('''
277
278// Actions
279''')
280 for action in self.actions.itervalues():
281 code('/** \\brief ${{action.desc}} */')
282 code('void ${{action.ident}}(const Address& addr);')
283
284 # the controller internal variables
285 code('''
286
287// Object
288''')
289 for var in self.objects:
290 th = var.get("template_hack", "")
291 code('${{var.type.c_ident}}$th* m_${{var.c_ident}}_ptr;')
292
293 if var.type.ident == "MessageBuffer":
294 self.message_buffer_names.append("m_%s_ptr" % var.c_ident)
295
296 code.dedent()
297 code('};')
298 code('#endif // ${ident}_CONTROLLER_H')
299 code.write(path, '%s.hh' % c_ident)
300
301 def printControllerCC(self, path):
302 '''Output the actions for performing the actions'''
303
304 code = code_formatter()
305 ident = self.ident
306 c_ident = "%s_Controller" % self.ident
307
308 code('''
309/** \\file $ident.cc
310 *
311 * Auto generated C++ code started by $__file__:$__line__
312 * Created by slicc definition of Module "${{self.short}}"
313 */
314
315#include "mem/ruby/common/Global.hh"
316#include "mem/ruby/slicc_interface/RubySlicc_includes.hh"
317#include "mem/protocol/${ident}_Controller.hh"
318#include "mem/protocol/${ident}_State.hh"
319#include "mem/protocol/${ident}_Event.hh"
320#include "mem/protocol/Types.hh"
321#include "mem/ruby/system/System.hh"
322''')
323
324 # include object classes
325 seen_types = set()
326 for var in self.objects:
327 if var.type.ident not in seen_types and not var.type.isPrimitive:
328 code('#include "mem/protocol/${{var.type.c_ident}}.hh"')
329 seen_types.add(var.type.ident)
330
331 code('''
332$c_ident *
333${c_ident}Params::create()
334{
335 return new $c_ident(this);
336}
337
338
339int $c_ident::m_num_controllers = 0;
340
341stringstream ${ident}_transitionComment;
342#define APPEND_TRANSITION_COMMENT(str) (${ident}_transitionComment << str)
343/** \\brief constructor */
344$c_ident::$c_ident(const Params *p)
345 : AbstractController(p)
346{
347 m_version = p->version;
348 m_transitions_per_cycle = p->transitions_per_cycle;
349 m_buffer_size = p->buffer_size;
350 m_recycle_latency = p->recycle_latency;
351 m_number_of_TBEs = p->number_of_TBEs;
352''')
353 code.indent()
354
355 #
356 # After initializing the universal machine parameters, initialize the
357 # this machines config parameters. Also detemine if these configuration
358 # params include a sequencer. This information will be used later for
359 # contecting the sequencer back to the L1 cache controller.
360 #
361 contains_sequencer = False
362 for param in self.config_parameters:
362 if param.name == "sequencer":
363 if param.name == "sequencer" or param.name == "dma_sequencer":
363 contains_sequencer = True
364 if param.pointer:
365 code('m_${{param.name}}_ptr = p->${{param.name}};')
366 else:
367 code('m_${{param.name}} = p->${{param.name}};')
368
369 #
370 # For the l1 cache controller, add the special atomic support which
371 # includes passing the sequencer a pointer to the controller.
372 #
373 if self.ident == "L1Cache":
374 if not contains_sequencer:
375 self.error("The L1Cache controller must include the sequencer " \
376 "configuration parameter")
377
378 code('''
379m_sequencer_ptr->setController(this);
380''')
364 contains_sequencer = True
365 if param.pointer:
366 code('m_${{param.name}}_ptr = p->${{param.name}};')
367 else:
368 code('m_${{param.name}} = p->${{param.name}};')
369
370 #
371 # For the l1 cache controller, add the special atomic support which
372 # includes passing the sequencer a pointer to the controller.
373 #
374 if self.ident == "L1Cache":
375 if not contains_sequencer:
376 self.error("The L1Cache controller must include the sequencer " \
377 "configuration parameter")
378
379 code('''
380m_sequencer_ptr->setController(this);
381''')
382 #
383 # For the DMA controller, pass the sequencer a pointer to the
384 # controller.
385 #
386 if self.ident == "DMA":
387 if not contains_sequencer:
388 self.error("The DMA controller must include the sequencer " \
389 "configuration parameter")
381
390
391 code('''
392m_dma_sequencer_ptr->setController(this);
393''')
394
382 code('m_num_controllers++;')
383 for var in self.objects:
384 if var.ident.find("mandatoryQueue") >= 0:
385 code('m_${{var.c_ident}}_ptr = new ${{var.type.c_ident}}();')
386
387 code.dedent()
388 code('''
389}
390
391void $c_ident::init()
392{
393 m_machineID.type = MachineType_${ident};
394 m_machineID.num = m_version;
395
396 // Objects
397 s_profiler.setVersion(m_version);
398''')
399
400 code.indent()
401 for var in self.objects:
402 vtype = var.type
403 vid = "m_%s_ptr" % var.c_ident
404 if "network" not in var:
405 # Not a network port object
406 if "primitive" in vtype:
407 code('$vid = new ${{vtype.c_ident}};')
408 if "default" in var:
409 code('(*$vid) = ${{var["default"]}};')
410 else:
411 # Normal Object
412 # added by SS
413 if "factory" in var:
414 code('$vid = ${{var["factory"]}};')
415 elif var.ident.find("mandatoryQueue") < 0:
416 th = var.get("template_hack", "")
417 expr = "%s = new %s%s" % (vid, vtype.c_ident, th)
418
419 args = ""
420 if "non_obj" not in vtype and not vtype.isEnumeration:
421 if expr.find("TBETable") >= 0:
422 args = "m_number_of_TBEs"
423 else:
424 args = var.get("constructor_hack", "")
425 args = "(%s)" % args
426
427 code('$expr$args;')
428 else:
429 code(';')
430
431 code('assert($vid != NULL);')
432
433 if "default" in var:
434 code('(*$vid) = ${{var["default"]}}; // Object default')
435 elif "default" in vtype:
436 code('(*$vid) = ${{vtype["default"]}}; // Type ${{vtype.ident}} default')
437
438 # Set ordering
439 if "ordered" in var and "trigger_queue" not in var:
440 # A buffer
441 code('$vid->setOrdering(${{var["ordered"]}});')
442
443 # Set randomization
444 if "random" in var:
445 # A buffer
446 code('$vid->setRandomization(${{var["random"]}});')
447
448 # Set Priority
449 if vtype.isBuffer and \
450 "rank" in var and "trigger_queue" not in var:
451 code('$vid->setPriority(${{var["rank"]}});')
452 else:
453 # Network port object
454 network = var["network"]
455 ordered = var["ordered"]
456 vnet = var["virtual_network"]
457
458 assert var.machine is not None
459 code('''
460$vid = m_net_ptr->get${network}NetQueue(m_version+MachineType_base_number(string_to_MachineType("${{var.machine.ident}}")), $ordered, $vnet);
461''')
462
463 code('assert($vid != NULL);')
464
465 # Set ordering
466 if "ordered" in var:
467 # A buffer
468 code('$vid->setOrdering(${{var["ordered"]}});')
469
470 # Set randomization
471 if "random" in var:
472 # A buffer
473 code('$vid->setRandomization(${{var["random"]}})')
474
475 # Set Priority
476 if "rank" in var:
477 code('$vid->setPriority(${{var["rank"]}})')
478
479 # Set buffer size
480 if vtype.isBuffer:
481 code('''
482if (m_buffer_size > 0) {
483 $vid->setSize(m_buffer_size);
484}
485''')
486
487 # set description (may be overriden later by port def)
488 code('$vid->setDescription("[Version " + int_to_string(m_version) + ", ${ident}, name=${{var.c_ident}}]");')
489
490 # Set the queue consumers
491 code.insert_newline()
492 for port in self.in_ports:
493 code('${{port.code}}.setConsumer(this);')
494
495 # Set the queue descriptions
496 code.insert_newline()
497 for port in self.in_ports:
498 code('${{port.code}}.setDescription("[Version " + int_to_string(m_version) + ", $ident, $port]");')
499
500 # Initialize the transition profiling
501 code.insert_newline()
502 for trans in self.transitions:
503 # Figure out if we stall
504 stall = False
505 for action in trans.actions:
506 if action.ident == "z_stall":
507 stall = True
508
509 # Only possible if it is not a 'z' case
510 if not stall:
511 state = "%s_State_%s" % (self.ident, trans.state.ident)
512 event = "%s_Event_%s" % (self.ident, trans.event.ident)
513 code('s_profiler.possibleTransition($state, $event);')
514
515 # added by SS to initialize recycle_latency of message buffers
516 for buf in self.message_buffer_names:
517 code("$buf->setRecycleLatency(m_recycle_latency);")
518
519 code.dedent()
520 code('}')
521
522 has_mandatory_q = False
523 for port in self.in_ports:
524 if port.code.find("mandatoryQueue_ptr") >= 0:
525 has_mandatory_q = True
526
527 if has_mandatory_q:
528 mq_ident = "m_%s_mandatoryQueue_ptr" % self.ident
529 else:
530 mq_ident = "NULL"
531
532 code('''
533int $c_ident::getNumControllers() {
534 return m_num_controllers;
535}
536
537MessageBuffer* $c_ident::getMandatoryQueue() const {
538 return $mq_ident;
539}
540
541const int & $c_ident::getVersion() const{
542 return m_version;
543}
544
545const string $c_ident::toString() const{
546 return "$c_ident";
547}
548
549const string $c_ident::getName() const{
550 return m_name;
551}
552const MachineType $c_ident::getMachineType() const{
553 return MachineType_${ident};
554}
555
556void $c_ident::blockOnQueue(Address addr, MessageBuffer* port) {
557 m_is_blocking = true;
558 m_block_map[addr] = port;
559}
560void $c_ident::unblock(Address addr) {
561 m_block_map.erase(addr);
562 if (m_block_map.size() == 0) {
563 m_is_blocking = false;
564 }
565}
566
567void $c_ident::print(ostream& out) const { out << "[$c_ident " << m_version << "]"; }
568
569void $c_ident::printConfig(ostream& out) const {
570 out << "$c_ident config: " << m_name << endl;
571 out << " version: " << m_version << endl;
572 for (map<string, string>::const_iterator it = m_cfg.begin(); it != m_cfg.end(); it++) {
573 out << " " << (*it).first << ": " << (*it).second << endl;
574 }
575}
576
577// Actions
578''')
579
580 for action in self.actions.itervalues():
581 if "c_code" not in action:
582 continue
583
584 code('''
585/** \\brief ${{action.desc}} */
586void $c_ident::${{action.ident}}(const Address& addr)
587{
588 DEBUG_MSG(GENERATED_COMP, HighPrio, "executing");
589 ${{action["c_code"]}}
590}
591
592''')
593 code.write(path, "%s.cc" % c_ident)
594
595 def printCWakeup(self, path):
596 '''Output the wakeup loop for the events'''
597
598 code = code_formatter()
599 ident = self.ident
600
601 code('''
602// Auto generated C++ code started by $__file__:$__line__
603// ${ident}: ${{self.short}}
604
605#include "mem/ruby/common/Global.hh"
606#include "mem/ruby/slicc_interface/RubySlicc_includes.hh"
607#include "mem/protocol/${ident}_Controller.hh"
608#include "mem/protocol/${ident}_State.hh"
609#include "mem/protocol/${ident}_Event.hh"
610#include "mem/protocol/Types.hh"
611#include "mem/ruby/system/System.hh"
612
613void ${ident}_Controller::wakeup()
614{
615
616 int counter = 0;
617 while (true) {
618 // Some cases will put us into an infinite loop without this limit
619 assert(counter <= m_transitions_per_cycle);
620 if (counter == m_transitions_per_cycle) {
621 g_system_ptr->getProfiler()->controllerBusy(m_machineID); // Count how often we\'re fully utilized
622 g_eventQueue_ptr->scheduleEvent(this, 1); // Wakeup in another cycle and try again
623 break;
624 }
625''')
626
627 code.indent()
628 code.indent()
629
630 # InPorts
631 #
632 for port in self.in_ports:
633 code.indent()
634 code('// ${ident}InPort $port')
635 code('${{port["c_code_in_port"]}}')
636 code.dedent()
637
638 code('')
639
640 code.dedent()
641 code.dedent()
642 code('''
643 break; // If we got this far, we have nothing left todo
644 }
645}
646''')
647
648 code.write(path, "%s_Wakeup.cc" % self.ident)
649
650 def printCSwitch(self, path):
651 '''Output switch statement for transition table'''
652
653 code = code_formatter()
654 ident = self.ident
655
656 code('''
657// Auto generated C++ code started by $__file__:$__line__
658// ${ident}: ${{self.short}}
659
660#include "mem/ruby/common/Global.hh"
661#include "mem/protocol/${ident}_Controller.hh"
662#include "mem/protocol/${ident}_State.hh"
663#include "mem/protocol/${ident}_Event.hh"
664#include "mem/protocol/Types.hh"
665#include "mem/ruby/system/System.hh"
666
667#define HASH_FUN(state, event) ((int(state)*${ident}_Event_NUM)+int(event))
668
669#define GET_TRANSITION_COMMENT() (${ident}_transitionComment.str())
670#define CLEAR_TRANSITION_COMMENT() (${ident}_transitionComment.str(""))
671
672TransitionResult ${ident}_Controller::doTransition(${ident}_Event event, ${ident}_State state, const Address& addr
673)
674{
675 ${ident}_State next_state = state;
676
677 DEBUG_NEWLINE(GENERATED_COMP, MedPrio);
678 DEBUG_MSG(GENERATED_COMP, MedPrio, *this);
679 DEBUG_EXPR(GENERATED_COMP, MedPrio, g_eventQueue_ptr->getTime());
680 DEBUG_EXPR(GENERATED_COMP, MedPrio,state);
681 DEBUG_EXPR(GENERATED_COMP, MedPrio,event);
682 DEBUG_EXPR(GENERATED_COMP, MedPrio,addr);
683
684 TransitionResult result = doTransitionWorker(event, state, next_state, addr);
685
686 if (result == TransitionResult_Valid) {
687 DEBUG_EXPR(GENERATED_COMP, MedPrio, next_state);
688 DEBUG_NEWLINE(GENERATED_COMP, MedPrio);
689 s_profiler.countTransition(state, event);
690 if (Debug::getProtocolTrace()) {
691 g_system_ptr->getProfiler()->profileTransition("${ident}", m_version, addr,
692 ${ident}_State_to_string(state),
693 ${ident}_Event_to_string(event),
694 ${ident}_State_to_string(next_state), GET_TRANSITION_COMMENT());
695 }
696 CLEAR_TRANSITION_COMMENT();
697 ${ident}_setState(addr, next_state);
698
699 } else if (result == TransitionResult_ResourceStall) {
700 if (Debug::getProtocolTrace()) {
701 g_system_ptr->getProfiler()->profileTransition("${ident}", m_version, addr,
702 ${ident}_State_to_string(state),
703 ${ident}_Event_to_string(event),
704 ${ident}_State_to_string(next_state),
705 "Resource Stall");
706 }
707 } else if (result == TransitionResult_ProtocolStall) {
708 DEBUG_MSG(GENERATED_COMP, HighPrio, "stalling");
709 DEBUG_NEWLINE(GENERATED_COMP, MedPrio);
710 if (Debug::getProtocolTrace()) {
711 g_system_ptr->getProfiler()->profileTransition("${ident}", m_version, addr,
712 ${ident}_State_to_string(state),
713 ${ident}_Event_to_string(event),
714 ${ident}_State_to_string(next_state),
715 "Protocol Stall");
716 }
717 }
718
719 return result;
720}
721
722TransitionResult ${ident}_Controller::doTransitionWorker(${ident}_Event event, ${ident}_State state, ${ident}_State& next_state, const Address& addr
723)
724{
725 switch(HASH_FUN(state, event)) {
726''')
727
728 # This map will allow suppress generating duplicate code
729 cases = orderdict()
730
731 for trans in self.transitions:
732 case_string = "%s_State_%s, %s_Event_%s" % \
733 (self.ident, trans.state.ident, self.ident, trans.event.ident)
734
735 case = code_formatter()
736 # Only set next_state if it changes
737 if trans.state != trans.nextState:
738 ns_ident = trans.nextState.ident
739 case('next_state = ${ident}_State_${ns_ident};')
740
741 actions = trans.actions
742
743 # Check for resources
744 case_sorter = []
745 res = trans.resources
746 for key,val in res.iteritems():
747 if key.type.ident != "DNUCAStopTable":
748 val = '''
749if (!%s.areNSlotsAvailable(%s)) {
750 return TransitionResult_ResourceStall;
751}
752''' % (key.code, val)
753 case_sorter.append(val)
754
755
756 # Emit the code sequences in a sorted order. This makes the
757 # output deterministic (without this the output order can vary
758 # since Map's keys() on a vector of pointers is not deterministic
759 for c in sorted(case_sorter):
760 case("$c")
761
762 # Figure out if we stall
763 stall = False
764 for action in actions:
765 if action.ident == "z_stall":
766 stall = True
767 break
768
769 if stall:
770 case('return TransitionResult_ProtocolStall;')
771 else:
772 for action in actions:
773 case('${{action.ident}}(addr);')
774 case('return TransitionResult_Valid;')
775
776 case = str(case)
777
778 # Look to see if this transition code is unique.
779 if case not in cases:
780 cases[case] = []
781
782 cases[case].append(case_string)
783
784 # Walk through all of the unique code blocks and spit out the
785 # corresponding case statement elements
786 for case,transitions in cases.iteritems():
787 # Iterative over all the multiple transitions that share
788 # the same code
789 for trans in transitions:
790 code(' case HASH_FUN($trans):')
791 code(' {')
792 code(' $case')
793 code(' }')
794
795 code('''
796 default:
797 WARN_EXPR(m_version);
798 WARN_EXPR(g_eventQueue_ptr->getTime());
799 WARN_EXPR(addr);
800 WARN_EXPR(event);
801 WARN_EXPR(state);
802 ERROR_MSG(\"Invalid transition\");
803 }
804 return TransitionResult_Valid;
805}
806''')
807 code.write(path, "%s_Transitions.cc" % self.ident)
808
809 def printProfilerHH(self, path):
810 code = code_formatter()
811 ident = self.ident
812
813 code('''
814// Auto generated C++ code started by $__file__:$__line__
815// ${ident}: ${{self.short}}
816
817#ifndef ${ident}_PROFILER_H
818#define ${ident}_PROFILER_H
819
820#include "mem/ruby/common/Global.hh"
821#include "mem/protocol/${ident}_State.hh"
822#include "mem/protocol/${ident}_Event.hh"
823
824class ${ident}_Profiler {
825 public:
826 ${ident}_Profiler();
827 void setVersion(int version);
828 void countTransition(${ident}_State state, ${ident}_Event event);
829 void possibleTransition(${ident}_State state, ${ident}_Event event);
830 void dumpStats(ostream& out) const;
831 void clearStats();
832
833 private:
834 int m_counters[${ident}_State_NUM][${ident}_Event_NUM];
835 int m_event_counters[${ident}_Event_NUM];
836 bool m_possible[${ident}_State_NUM][${ident}_Event_NUM];
837 int m_version;
838};
839
840#endif // ${ident}_PROFILER_H
841''')
842 code.write(path, "%s_Profiler.hh" % self.ident)
843
844 def printProfilerCC(self, path):
845 code = code_formatter()
846 ident = self.ident
847
848 code('''
849// Auto generated C++ code started by $__file__:$__line__
850// ${ident}: ${{self.short}}
851
852#include "mem/protocol/${ident}_Profiler.hh"
853
854${ident}_Profiler::${ident}_Profiler()
855{
856 for (int state = 0; state < ${ident}_State_NUM; state++) {
857 for (int event = 0; event < ${ident}_Event_NUM; event++) {
858 m_possible[state][event] = false;
859 m_counters[state][event] = 0;
860 }
861 }
862 for (int event = 0; event < ${ident}_Event_NUM; event++) {
863 m_event_counters[event] = 0;
864 }
865}
866void ${ident}_Profiler::setVersion(int version)
867{
868 m_version = version;
869}
870void ${ident}_Profiler::clearStats()
871{
872 for (int state = 0; state < ${ident}_State_NUM; state++) {
873 for (int event = 0; event < ${ident}_Event_NUM; event++) {
874 m_counters[state][event] = 0;
875 }
876 }
877
878 for (int event = 0; event < ${ident}_Event_NUM; event++) {
879 m_event_counters[event] = 0;
880 }
881}
882void ${ident}_Profiler::countTransition(${ident}_State state, ${ident}_Event event)
883{
884 assert(m_possible[state][event]);
885 m_counters[state][event]++;
886 m_event_counters[event]++;
887}
888void ${ident}_Profiler::possibleTransition(${ident}_State state, ${ident}_Event event)
889{
890 m_possible[state][event] = true;
891}
892void ${ident}_Profiler::dumpStats(ostream& out) const
893{
894 out << " --- ${ident} " << m_version << " ---" << endl;
895 out << " - Event Counts -" << endl;
896 for (int event = 0; event < ${ident}_Event_NUM; event++) {
897 int count = m_event_counters[event];
898 out << (${ident}_Event) event << " " << count << endl;
899 }
900 out << endl;
901 out << " - Transitions -" << endl;
902 for (int state = 0; state < ${ident}_State_NUM; state++) {
903 for (int event = 0; event < ${ident}_Event_NUM; event++) {
904 if (m_possible[state][event]) {
905 int count = m_counters[state][event];
906 out << (${ident}_State) state << " " << (${ident}_Event) event << " " << count;
907 if (count == 0) {
908 out << " <-- ";
909 }
910 out << endl;
911 }
912 }
913 out << endl;
914 }
915}
916''')
917 code.write(path, "%s_Profiler.cc" % self.ident)
918
919 # **************************
920 # ******* HTML Files *******
921 # **************************
922 def frameRef(self, click_href, click_target, over_href, over_target_num,
923 text):
924 code = code_formatter(fix_newlines=False)
925 code("""<A href=\"$click_href\" target=\"$click_target\" onMouseOver=\"if (parent.frames[$over_target_num].location != parent.location + '$over_href') { parent.frames[$over_target_num].location='$over_href' }\" >${{html.formatShorthand(text)}}</A>""")
926 return str(code)
927
928 def writeHTMLFiles(self, path):
929 # Create table with no row hilighted
930 self.printHTMLTransitions(path, None)
931
932 # Generate transition tables
933 for state in self.states.itervalues():
934 self.printHTMLTransitions(path, state)
935
936 # Generate action descriptions
937 for action in self.actions.itervalues():
938 name = "%s_action_%s.html" % (self.ident, action.ident)
939 code = html.createSymbol(action, "Action")
940 code.write(path, name)
941
942 # Generate state descriptions
943 for state in self.states.itervalues():
944 name = "%s_State_%s.html" % (self.ident, state.ident)
945 code = html.createSymbol(state, "State")
946 code.write(path, name)
947
948 # Generate event descriptions
949 for event in self.events.itervalues():
950 name = "%s_Event_%s.html" % (self.ident, event.ident)
951 code = html.createSymbol(event, "Event")
952 code.write(path, name)
953
954 def printHTMLTransitions(self, path, active_state):
955 code = code_formatter()
956
957 code('''
958<HTML><BODY link="blue" vlink="blue">
959
960<H1 align="center">${{html.formatShorthand(self.short)}}:
961''')
962 code.indent()
963 for i,machine in enumerate(self.symtab.getAllType(StateMachine)):
964 mid = machine.ident
965 if i != 0:
966 extra = " - "
967 else:
968 extra = ""
969 if machine == self:
970 code('$extra$mid')
971 else:
972 code('$extra<A target="Table" href="${mid}_table.html">$mid</A>')
973 code.dedent()
974
975 code("""
976</H1>
977
978<TABLE border=1>
979<TR>
980 <TH> </TH>
981""")
982
983 for event in self.events.itervalues():
984 href = "%s_Event_%s.html" % (self.ident, event.ident)
985 ref = self.frameRef(href, "Status", href, "1", event.short)
986 code('<TH bgcolor=white>$ref</TH>')
987
988 code('</TR>')
989 # -- Body of table
990 for state in self.states.itervalues():
991 # -- Each row
992 if state == active_state:
993 color = "yellow"
994 else:
995 color = "white"
996
997 click = "%s_table_%s.html" % (self.ident, state.ident)
998 over = "%s_State_%s.html" % (self.ident, state.ident)
999 text = html.formatShorthand(state.short)
1000 ref = self.frameRef(click, "Table", over, "1", state.short)
1001 code('''
1002<TR>
1003 <TH bgcolor=$color>$ref</TH>
1004''')
1005
1006 # -- One column for each event
1007 for event in self.events.itervalues():
1008 trans = self.table.get((state,event), None)
1009 if trans is None:
1010 # This is the no transition case
1011 if state == active_state:
1012 color = "#C0C000"
1013 else:
1014 color = "lightgrey"
1015
1016 code('<TD bgcolor=$color>&nbsp;</TD>')
1017 continue
1018
1019 next = trans.nextState
1020 stall_action = False
1021
1022 # -- Get the actions
1023 for action in trans.actions:
1024 if action.ident == "z_stall" or \
1025 action.ident == "zz_recycleMandatoryQueue":
1026 stall_action = True
1027
1028 # -- Print out "actions/next-state"
1029 if stall_action:
1030 if state == active_state:
1031 color = "#C0C000"
1032 else:
1033 color = "lightgrey"
1034
1035 elif active_state and next.ident == active_state.ident:
1036 color = "aqua"
1037 elif state == active_state:
1038 color = "yellow"
1039 else:
1040 color = "white"
1041
1042 fix = code.nofix()
1043 code('<TD bgcolor=$color>')
1044 for action in trans.actions:
1045 href = "%s_action_%s.html" % (self.ident, action.ident)
1046 ref = self.frameRef(href, "Status", href, "1",
1047 action.short)
1048 code(' $ref\n')
1049 if next != state:
1050 if trans.actions:
1051 code('/')
1052 click = "%s_table_%s.html" % (self.ident, next.ident)
1053 over = "%s_State_%s.html" % (self.ident, next.ident)
1054 ref = self.frameRef(click, "Table", over, "1", next.short)
1055 code("$ref")
1056 code("</TD>\n")
1057 code.fix(fix)
1058
1059 # -- Each row
1060 if state == active_state:
1061 color = "yellow"
1062 else:
1063 color = "white"
1064
1065 click = "%s_table_%s.html" % (self.ident, state.ident)
1066 over = "%s_State_%s.html" % (self.ident, state.ident)
1067 ref = self.frameRef(click, "Table", over, "1", state.short)
1068 code('''
1069 <TH bgcolor=$color>$ref</TH>
1070</TR>
1071''')
1072 code('''
1073<TR>
1074 <TH> </TH>
1075''')
1076
1077 for event in self.events.itervalues():
1078 href = "%s_Event_%s.html" % (self.ident, event.ident)
1079 ref = self.frameRef(href, "Status", href, "1", event.short)
1080 code('<TH bgcolor=white>$ref</TH>')
1081 code('''
1082</TR>
1083</TABLE>
1084</BODY></HTML>
1085''')
1086
1087
1088 if active_state:
1089 name = "%s_table_%s.html" % (self.ident, active_state.ident)
1090 else:
1091 name = "%s_table.html" % self.ident
1092 code.write(path, name)
1093
1094__all__ = [ "StateMachine" ]
395 code('m_num_controllers++;')
396 for var in self.objects:
397 if var.ident.find("mandatoryQueue") >= 0:
398 code('m_${{var.c_ident}}_ptr = new ${{var.type.c_ident}}();')
399
400 code.dedent()
401 code('''
402}
403
404void $c_ident::init()
405{
406 m_machineID.type = MachineType_${ident};
407 m_machineID.num = m_version;
408
409 // Objects
410 s_profiler.setVersion(m_version);
411''')
412
413 code.indent()
414 for var in self.objects:
415 vtype = var.type
416 vid = "m_%s_ptr" % var.c_ident
417 if "network" not in var:
418 # Not a network port object
419 if "primitive" in vtype:
420 code('$vid = new ${{vtype.c_ident}};')
421 if "default" in var:
422 code('(*$vid) = ${{var["default"]}};')
423 else:
424 # Normal Object
425 # added by SS
426 if "factory" in var:
427 code('$vid = ${{var["factory"]}};')
428 elif var.ident.find("mandatoryQueue") < 0:
429 th = var.get("template_hack", "")
430 expr = "%s = new %s%s" % (vid, vtype.c_ident, th)
431
432 args = ""
433 if "non_obj" not in vtype and not vtype.isEnumeration:
434 if expr.find("TBETable") >= 0:
435 args = "m_number_of_TBEs"
436 else:
437 args = var.get("constructor_hack", "")
438 args = "(%s)" % args
439
440 code('$expr$args;')
441 else:
442 code(';')
443
444 code('assert($vid != NULL);')
445
446 if "default" in var:
447 code('(*$vid) = ${{var["default"]}}; // Object default')
448 elif "default" in vtype:
449 code('(*$vid) = ${{vtype["default"]}}; // Type ${{vtype.ident}} default')
450
451 # Set ordering
452 if "ordered" in var and "trigger_queue" not in var:
453 # A buffer
454 code('$vid->setOrdering(${{var["ordered"]}});')
455
456 # Set randomization
457 if "random" in var:
458 # A buffer
459 code('$vid->setRandomization(${{var["random"]}});')
460
461 # Set Priority
462 if vtype.isBuffer and \
463 "rank" in var and "trigger_queue" not in var:
464 code('$vid->setPriority(${{var["rank"]}});')
465 else:
466 # Network port object
467 network = var["network"]
468 ordered = var["ordered"]
469 vnet = var["virtual_network"]
470
471 assert var.machine is not None
472 code('''
473$vid = m_net_ptr->get${network}NetQueue(m_version+MachineType_base_number(string_to_MachineType("${{var.machine.ident}}")), $ordered, $vnet);
474''')
475
476 code('assert($vid != NULL);')
477
478 # Set ordering
479 if "ordered" in var:
480 # A buffer
481 code('$vid->setOrdering(${{var["ordered"]}});')
482
483 # Set randomization
484 if "random" in var:
485 # A buffer
486 code('$vid->setRandomization(${{var["random"]}})')
487
488 # Set Priority
489 if "rank" in var:
490 code('$vid->setPriority(${{var["rank"]}})')
491
492 # Set buffer size
493 if vtype.isBuffer:
494 code('''
495if (m_buffer_size > 0) {
496 $vid->setSize(m_buffer_size);
497}
498''')
499
500 # set description (may be overriden later by port def)
501 code('$vid->setDescription("[Version " + int_to_string(m_version) + ", ${ident}, name=${{var.c_ident}}]");')
502
503 # Set the queue consumers
504 code.insert_newline()
505 for port in self.in_ports:
506 code('${{port.code}}.setConsumer(this);')
507
508 # Set the queue descriptions
509 code.insert_newline()
510 for port in self.in_ports:
511 code('${{port.code}}.setDescription("[Version " + int_to_string(m_version) + ", $ident, $port]");')
512
513 # Initialize the transition profiling
514 code.insert_newline()
515 for trans in self.transitions:
516 # Figure out if we stall
517 stall = False
518 for action in trans.actions:
519 if action.ident == "z_stall":
520 stall = True
521
522 # Only possible if it is not a 'z' case
523 if not stall:
524 state = "%s_State_%s" % (self.ident, trans.state.ident)
525 event = "%s_Event_%s" % (self.ident, trans.event.ident)
526 code('s_profiler.possibleTransition($state, $event);')
527
528 # added by SS to initialize recycle_latency of message buffers
529 for buf in self.message_buffer_names:
530 code("$buf->setRecycleLatency(m_recycle_latency);")
531
532 code.dedent()
533 code('}')
534
535 has_mandatory_q = False
536 for port in self.in_ports:
537 if port.code.find("mandatoryQueue_ptr") >= 0:
538 has_mandatory_q = True
539
540 if has_mandatory_q:
541 mq_ident = "m_%s_mandatoryQueue_ptr" % self.ident
542 else:
543 mq_ident = "NULL"
544
545 code('''
546int $c_ident::getNumControllers() {
547 return m_num_controllers;
548}
549
550MessageBuffer* $c_ident::getMandatoryQueue() const {
551 return $mq_ident;
552}
553
554const int & $c_ident::getVersion() const{
555 return m_version;
556}
557
558const string $c_ident::toString() const{
559 return "$c_ident";
560}
561
562const string $c_ident::getName() const{
563 return m_name;
564}
565const MachineType $c_ident::getMachineType() const{
566 return MachineType_${ident};
567}
568
569void $c_ident::blockOnQueue(Address addr, MessageBuffer* port) {
570 m_is_blocking = true;
571 m_block_map[addr] = port;
572}
573void $c_ident::unblock(Address addr) {
574 m_block_map.erase(addr);
575 if (m_block_map.size() == 0) {
576 m_is_blocking = false;
577 }
578}
579
580void $c_ident::print(ostream& out) const { out << "[$c_ident " << m_version << "]"; }
581
582void $c_ident::printConfig(ostream& out) const {
583 out << "$c_ident config: " << m_name << endl;
584 out << " version: " << m_version << endl;
585 for (map<string, string>::const_iterator it = m_cfg.begin(); it != m_cfg.end(); it++) {
586 out << " " << (*it).first << ": " << (*it).second << endl;
587 }
588}
589
590// Actions
591''')
592
593 for action in self.actions.itervalues():
594 if "c_code" not in action:
595 continue
596
597 code('''
598/** \\brief ${{action.desc}} */
599void $c_ident::${{action.ident}}(const Address& addr)
600{
601 DEBUG_MSG(GENERATED_COMP, HighPrio, "executing");
602 ${{action["c_code"]}}
603}
604
605''')
606 code.write(path, "%s.cc" % c_ident)
607
608 def printCWakeup(self, path):
609 '''Output the wakeup loop for the events'''
610
611 code = code_formatter()
612 ident = self.ident
613
614 code('''
615// Auto generated C++ code started by $__file__:$__line__
616// ${ident}: ${{self.short}}
617
618#include "mem/ruby/common/Global.hh"
619#include "mem/ruby/slicc_interface/RubySlicc_includes.hh"
620#include "mem/protocol/${ident}_Controller.hh"
621#include "mem/protocol/${ident}_State.hh"
622#include "mem/protocol/${ident}_Event.hh"
623#include "mem/protocol/Types.hh"
624#include "mem/ruby/system/System.hh"
625
626void ${ident}_Controller::wakeup()
627{
628
629 int counter = 0;
630 while (true) {
631 // Some cases will put us into an infinite loop without this limit
632 assert(counter <= m_transitions_per_cycle);
633 if (counter == m_transitions_per_cycle) {
634 g_system_ptr->getProfiler()->controllerBusy(m_machineID); // Count how often we\'re fully utilized
635 g_eventQueue_ptr->scheduleEvent(this, 1); // Wakeup in another cycle and try again
636 break;
637 }
638''')
639
640 code.indent()
641 code.indent()
642
643 # InPorts
644 #
645 for port in self.in_ports:
646 code.indent()
647 code('// ${ident}InPort $port')
648 code('${{port["c_code_in_port"]}}')
649 code.dedent()
650
651 code('')
652
653 code.dedent()
654 code.dedent()
655 code('''
656 break; // If we got this far, we have nothing left todo
657 }
658}
659''')
660
661 code.write(path, "%s_Wakeup.cc" % self.ident)
662
663 def printCSwitch(self, path):
664 '''Output switch statement for transition table'''
665
666 code = code_formatter()
667 ident = self.ident
668
669 code('''
670// Auto generated C++ code started by $__file__:$__line__
671// ${ident}: ${{self.short}}
672
673#include "mem/ruby/common/Global.hh"
674#include "mem/protocol/${ident}_Controller.hh"
675#include "mem/protocol/${ident}_State.hh"
676#include "mem/protocol/${ident}_Event.hh"
677#include "mem/protocol/Types.hh"
678#include "mem/ruby/system/System.hh"
679
680#define HASH_FUN(state, event) ((int(state)*${ident}_Event_NUM)+int(event))
681
682#define GET_TRANSITION_COMMENT() (${ident}_transitionComment.str())
683#define CLEAR_TRANSITION_COMMENT() (${ident}_transitionComment.str(""))
684
685TransitionResult ${ident}_Controller::doTransition(${ident}_Event event, ${ident}_State state, const Address& addr
686)
687{
688 ${ident}_State next_state = state;
689
690 DEBUG_NEWLINE(GENERATED_COMP, MedPrio);
691 DEBUG_MSG(GENERATED_COMP, MedPrio, *this);
692 DEBUG_EXPR(GENERATED_COMP, MedPrio, g_eventQueue_ptr->getTime());
693 DEBUG_EXPR(GENERATED_COMP, MedPrio,state);
694 DEBUG_EXPR(GENERATED_COMP, MedPrio,event);
695 DEBUG_EXPR(GENERATED_COMP, MedPrio,addr);
696
697 TransitionResult result = doTransitionWorker(event, state, next_state, addr);
698
699 if (result == TransitionResult_Valid) {
700 DEBUG_EXPR(GENERATED_COMP, MedPrio, next_state);
701 DEBUG_NEWLINE(GENERATED_COMP, MedPrio);
702 s_profiler.countTransition(state, event);
703 if (Debug::getProtocolTrace()) {
704 g_system_ptr->getProfiler()->profileTransition("${ident}", m_version, addr,
705 ${ident}_State_to_string(state),
706 ${ident}_Event_to_string(event),
707 ${ident}_State_to_string(next_state), GET_TRANSITION_COMMENT());
708 }
709 CLEAR_TRANSITION_COMMENT();
710 ${ident}_setState(addr, next_state);
711
712 } else if (result == TransitionResult_ResourceStall) {
713 if (Debug::getProtocolTrace()) {
714 g_system_ptr->getProfiler()->profileTransition("${ident}", m_version, addr,
715 ${ident}_State_to_string(state),
716 ${ident}_Event_to_string(event),
717 ${ident}_State_to_string(next_state),
718 "Resource Stall");
719 }
720 } else if (result == TransitionResult_ProtocolStall) {
721 DEBUG_MSG(GENERATED_COMP, HighPrio, "stalling");
722 DEBUG_NEWLINE(GENERATED_COMP, MedPrio);
723 if (Debug::getProtocolTrace()) {
724 g_system_ptr->getProfiler()->profileTransition("${ident}", m_version, addr,
725 ${ident}_State_to_string(state),
726 ${ident}_Event_to_string(event),
727 ${ident}_State_to_string(next_state),
728 "Protocol Stall");
729 }
730 }
731
732 return result;
733}
734
735TransitionResult ${ident}_Controller::doTransitionWorker(${ident}_Event event, ${ident}_State state, ${ident}_State& next_state, const Address& addr
736)
737{
738 switch(HASH_FUN(state, event)) {
739''')
740
741 # This map will allow suppress generating duplicate code
742 cases = orderdict()
743
744 for trans in self.transitions:
745 case_string = "%s_State_%s, %s_Event_%s" % \
746 (self.ident, trans.state.ident, self.ident, trans.event.ident)
747
748 case = code_formatter()
749 # Only set next_state if it changes
750 if trans.state != trans.nextState:
751 ns_ident = trans.nextState.ident
752 case('next_state = ${ident}_State_${ns_ident};')
753
754 actions = trans.actions
755
756 # Check for resources
757 case_sorter = []
758 res = trans.resources
759 for key,val in res.iteritems():
760 if key.type.ident != "DNUCAStopTable":
761 val = '''
762if (!%s.areNSlotsAvailable(%s)) {
763 return TransitionResult_ResourceStall;
764}
765''' % (key.code, val)
766 case_sorter.append(val)
767
768
769 # Emit the code sequences in a sorted order. This makes the
770 # output deterministic (without this the output order can vary
771 # since Map's keys() on a vector of pointers is not deterministic
772 for c in sorted(case_sorter):
773 case("$c")
774
775 # Figure out if we stall
776 stall = False
777 for action in actions:
778 if action.ident == "z_stall":
779 stall = True
780 break
781
782 if stall:
783 case('return TransitionResult_ProtocolStall;')
784 else:
785 for action in actions:
786 case('${{action.ident}}(addr);')
787 case('return TransitionResult_Valid;')
788
789 case = str(case)
790
791 # Look to see if this transition code is unique.
792 if case not in cases:
793 cases[case] = []
794
795 cases[case].append(case_string)
796
797 # Walk through all of the unique code blocks and spit out the
798 # corresponding case statement elements
799 for case,transitions in cases.iteritems():
800 # Iterative over all the multiple transitions that share
801 # the same code
802 for trans in transitions:
803 code(' case HASH_FUN($trans):')
804 code(' {')
805 code(' $case')
806 code(' }')
807
808 code('''
809 default:
810 WARN_EXPR(m_version);
811 WARN_EXPR(g_eventQueue_ptr->getTime());
812 WARN_EXPR(addr);
813 WARN_EXPR(event);
814 WARN_EXPR(state);
815 ERROR_MSG(\"Invalid transition\");
816 }
817 return TransitionResult_Valid;
818}
819''')
820 code.write(path, "%s_Transitions.cc" % self.ident)
821
822 def printProfilerHH(self, path):
823 code = code_formatter()
824 ident = self.ident
825
826 code('''
827// Auto generated C++ code started by $__file__:$__line__
828// ${ident}: ${{self.short}}
829
830#ifndef ${ident}_PROFILER_H
831#define ${ident}_PROFILER_H
832
833#include "mem/ruby/common/Global.hh"
834#include "mem/protocol/${ident}_State.hh"
835#include "mem/protocol/${ident}_Event.hh"
836
837class ${ident}_Profiler {
838 public:
839 ${ident}_Profiler();
840 void setVersion(int version);
841 void countTransition(${ident}_State state, ${ident}_Event event);
842 void possibleTransition(${ident}_State state, ${ident}_Event event);
843 void dumpStats(ostream& out) const;
844 void clearStats();
845
846 private:
847 int m_counters[${ident}_State_NUM][${ident}_Event_NUM];
848 int m_event_counters[${ident}_Event_NUM];
849 bool m_possible[${ident}_State_NUM][${ident}_Event_NUM];
850 int m_version;
851};
852
853#endif // ${ident}_PROFILER_H
854''')
855 code.write(path, "%s_Profiler.hh" % self.ident)
856
857 def printProfilerCC(self, path):
858 code = code_formatter()
859 ident = self.ident
860
861 code('''
862// Auto generated C++ code started by $__file__:$__line__
863// ${ident}: ${{self.short}}
864
865#include "mem/protocol/${ident}_Profiler.hh"
866
867${ident}_Profiler::${ident}_Profiler()
868{
869 for (int state = 0; state < ${ident}_State_NUM; state++) {
870 for (int event = 0; event < ${ident}_Event_NUM; event++) {
871 m_possible[state][event] = false;
872 m_counters[state][event] = 0;
873 }
874 }
875 for (int event = 0; event < ${ident}_Event_NUM; event++) {
876 m_event_counters[event] = 0;
877 }
878}
879void ${ident}_Profiler::setVersion(int version)
880{
881 m_version = version;
882}
883void ${ident}_Profiler::clearStats()
884{
885 for (int state = 0; state < ${ident}_State_NUM; state++) {
886 for (int event = 0; event < ${ident}_Event_NUM; event++) {
887 m_counters[state][event] = 0;
888 }
889 }
890
891 for (int event = 0; event < ${ident}_Event_NUM; event++) {
892 m_event_counters[event] = 0;
893 }
894}
895void ${ident}_Profiler::countTransition(${ident}_State state, ${ident}_Event event)
896{
897 assert(m_possible[state][event]);
898 m_counters[state][event]++;
899 m_event_counters[event]++;
900}
901void ${ident}_Profiler::possibleTransition(${ident}_State state, ${ident}_Event event)
902{
903 m_possible[state][event] = true;
904}
905void ${ident}_Profiler::dumpStats(ostream& out) const
906{
907 out << " --- ${ident} " << m_version << " ---" << endl;
908 out << " - Event Counts -" << endl;
909 for (int event = 0; event < ${ident}_Event_NUM; event++) {
910 int count = m_event_counters[event];
911 out << (${ident}_Event) event << " " << count << endl;
912 }
913 out << endl;
914 out << " - Transitions -" << endl;
915 for (int state = 0; state < ${ident}_State_NUM; state++) {
916 for (int event = 0; event < ${ident}_Event_NUM; event++) {
917 if (m_possible[state][event]) {
918 int count = m_counters[state][event];
919 out << (${ident}_State) state << " " << (${ident}_Event) event << " " << count;
920 if (count == 0) {
921 out << " <-- ";
922 }
923 out << endl;
924 }
925 }
926 out << endl;
927 }
928}
929''')
930 code.write(path, "%s_Profiler.cc" % self.ident)
931
932 # **************************
933 # ******* HTML Files *******
934 # **************************
935 def frameRef(self, click_href, click_target, over_href, over_target_num,
936 text):
937 code = code_formatter(fix_newlines=False)
938 code("""<A href=\"$click_href\" target=\"$click_target\" onMouseOver=\"if (parent.frames[$over_target_num].location != parent.location + '$over_href') { parent.frames[$over_target_num].location='$over_href' }\" >${{html.formatShorthand(text)}}</A>""")
939 return str(code)
940
941 def writeHTMLFiles(self, path):
942 # Create table with no row hilighted
943 self.printHTMLTransitions(path, None)
944
945 # Generate transition tables
946 for state in self.states.itervalues():
947 self.printHTMLTransitions(path, state)
948
949 # Generate action descriptions
950 for action in self.actions.itervalues():
951 name = "%s_action_%s.html" % (self.ident, action.ident)
952 code = html.createSymbol(action, "Action")
953 code.write(path, name)
954
955 # Generate state descriptions
956 for state in self.states.itervalues():
957 name = "%s_State_%s.html" % (self.ident, state.ident)
958 code = html.createSymbol(state, "State")
959 code.write(path, name)
960
961 # Generate event descriptions
962 for event in self.events.itervalues():
963 name = "%s_Event_%s.html" % (self.ident, event.ident)
964 code = html.createSymbol(event, "Event")
965 code.write(path, name)
966
967 def printHTMLTransitions(self, path, active_state):
968 code = code_formatter()
969
970 code('''
971<HTML><BODY link="blue" vlink="blue">
972
973<H1 align="center">${{html.formatShorthand(self.short)}}:
974''')
975 code.indent()
976 for i,machine in enumerate(self.symtab.getAllType(StateMachine)):
977 mid = machine.ident
978 if i != 0:
979 extra = " - "
980 else:
981 extra = ""
982 if machine == self:
983 code('$extra$mid')
984 else:
985 code('$extra<A target="Table" href="${mid}_table.html">$mid</A>')
986 code.dedent()
987
988 code("""
989</H1>
990
991<TABLE border=1>
992<TR>
993 <TH> </TH>
994""")
995
996 for event in self.events.itervalues():
997 href = "%s_Event_%s.html" % (self.ident, event.ident)
998 ref = self.frameRef(href, "Status", href, "1", event.short)
999 code('<TH bgcolor=white>$ref</TH>')
1000
1001 code('</TR>')
1002 # -- Body of table
1003 for state in self.states.itervalues():
1004 # -- Each row
1005 if state == active_state:
1006 color = "yellow"
1007 else:
1008 color = "white"
1009
1010 click = "%s_table_%s.html" % (self.ident, state.ident)
1011 over = "%s_State_%s.html" % (self.ident, state.ident)
1012 text = html.formatShorthand(state.short)
1013 ref = self.frameRef(click, "Table", over, "1", state.short)
1014 code('''
1015<TR>
1016 <TH bgcolor=$color>$ref</TH>
1017''')
1018
1019 # -- One column for each event
1020 for event in self.events.itervalues():
1021 trans = self.table.get((state,event), None)
1022 if trans is None:
1023 # This is the no transition case
1024 if state == active_state:
1025 color = "#C0C000"
1026 else:
1027 color = "lightgrey"
1028
1029 code('<TD bgcolor=$color>&nbsp;</TD>')
1030 continue
1031
1032 next = trans.nextState
1033 stall_action = False
1034
1035 # -- Get the actions
1036 for action in trans.actions:
1037 if action.ident == "z_stall" or \
1038 action.ident == "zz_recycleMandatoryQueue":
1039 stall_action = True
1040
1041 # -- Print out "actions/next-state"
1042 if stall_action:
1043 if state == active_state:
1044 color = "#C0C000"
1045 else:
1046 color = "lightgrey"
1047
1048 elif active_state and next.ident == active_state.ident:
1049 color = "aqua"
1050 elif state == active_state:
1051 color = "yellow"
1052 else:
1053 color = "white"
1054
1055 fix = code.nofix()
1056 code('<TD bgcolor=$color>')
1057 for action in trans.actions:
1058 href = "%s_action_%s.html" % (self.ident, action.ident)
1059 ref = self.frameRef(href, "Status", href, "1",
1060 action.short)
1061 code(' $ref\n')
1062 if next != state:
1063 if trans.actions:
1064 code('/')
1065 click = "%s_table_%s.html" % (self.ident, next.ident)
1066 over = "%s_State_%s.html" % (self.ident, next.ident)
1067 ref = self.frameRef(click, "Table", over, "1", next.short)
1068 code("$ref")
1069 code("</TD>\n")
1070 code.fix(fix)
1071
1072 # -- Each row
1073 if state == active_state:
1074 color = "yellow"
1075 else:
1076 color = "white"
1077
1078 click = "%s_table_%s.html" % (self.ident, state.ident)
1079 over = "%s_State_%s.html" % (self.ident, state.ident)
1080 ref = self.frameRef(click, "Table", over, "1", state.short)
1081 code('''
1082 <TH bgcolor=$color>$ref</TH>
1083</TR>
1084''')
1085 code('''
1086<TR>
1087 <TH> </TH>
1088''')
1089
1090 for event in self.events.itervalues():
1091 href = "%s_Event_%s.html" % (self.ident, event.ident)
1092 ref = self.frameRef(href, "Status", href, "1", event.short)
1093 code('<TH bgcolor=white>$ref</TH>')
1094 code('''
1095</TR>
1096</TABLE>
1097</BODY></HTML>
1098''')
1099
1100
1101 if active_state:
1102 name = "%s_table_%s.html" % (self.ident, active_state.ident)
1103 else:
1104 name = "%s_table.html" % self.ident
1105 code.write(path, name)
1106
1107__all__ = [ "StateMachine" ]