blob: 391820afd6f4ab1ab3d9a01b2b7e6ad72e71806b [file] [log] [blame]
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +00001# Copyright lowRISC contributors.
2# Licensed under the Apache License, Version 2.0, see LICENSE for details.
3# SPDX-License-Identifier: Apache-2.0
4
5'''Code representing an IP block for reggen'''
6
Rupert Swarbrick200d8b42021-03-08 12:32:11 +00007from typing import Dict, List, Optional, Sequence, Set, Tuple
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +00008
9import hjson # type: ignore
10
11from .alert import Alert
Rupert Swarbrick6c831292021-02-25 17:08:53 +000012from .bus_interfaces import BusInterfaces
Timothy Chen7c3de6e2021-07-19 16:46:45 -070013from .clocking import Clocking, ClockingItem
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000014from .inter_signal import InterSignal
Rupert Swarbrick985c9612021-03-31 08:47:06 +010015from .lib import (check_keys, check_name, check_int, check_bool,
Rupert Swarbrickd0cbfad2021-06-29 17:04:51 +010016 check_list, check_optional_str)
Philipp Wagner78194c82021-03-10 10:08:17 +000017from .params import ReggenParams, LocalParam
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000018from .reg_block import RegBlock
19from .signal import Signal
Michael Schaffnere8976ff2021-11-15 16:12:17 -080020from .countermeasure import CounterMeasure
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000021
22
23REQUIRED_FIELDS = {
24 'name': ['s', "name of the component"],
Rupert Swarbrickd0cbfad2021-06-29 17:04:51 +010025 'clocking': ['l', "clocking for the device"],
Rupert Swarbrick6c831292021-02-25 17:08:53 +000026 'bus_interfaces': ['l', "bus interfaces for the device"],
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000027 'registers': [
28 'l',
29 "list of register definition groups and "
30 "offset control groups"
31 ]
32}
33
34OPTIONAL_FIELDS = {
35 'alert_list': ['lnw', "list of peripheral alerts"],
36 'available_inout_list': ['lnw', "list of available peripheral inouts"],
37 'available_input_list': ['lnw', "list of available peripheral inputs"],
38 'available_output_list': ['lnw', "list of available peripheral outputs"],
Rupert Swarbrickda5ed152021-06-08 14:14:40 +010039 'expose_reg_if': ['pb', 'if set, expose reg interface in reg2hw signal'],
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000040 'hier_path': [
41 None,
42 'additional hierarchy path before the reg block instance'
43 ],
44 'interrupt_list': ['lnw', "list of peripheral interrupts"],
45 'inter_signal_list': ['l', "list of inter-module signals"],
46 'no_auto_alert_regs': [
47 's', "Set to true to suppress automatic "
48 "generation of alert test registers. "
49 "Defaults to true if no alert_list is present. "
50 "Otherwise this defaults to false. "
51 ],
52 'no_auto_intr_regs': [
53 's', "Set to true to suppress automatic "
54 "generation of interrupt registers. "
55 "Defaults to true if no interrupt_list is present. "
56 "Otherwise this defaults to false. "
57 ],
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000058 'param_list': ['lp', "list of parameters of the IP"],
59 'regwidth': ['d', "width of registers in bits (default 32)"],
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000060 'reset_request_list': ['l', 'list of signals requesting reset'],
61 'scan': ['pb', 'Indicates the module have `scanmode_i`'],
Timothy Chen21e6a4f2021-04-30 03:47:01 -070062 'scan_reset': ['pb', 'Indicates the module have `scan_rst_ni`'],
63 'scan_en': ['pb', 'Indicates the module has `scan_en_i`'],
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000064 'SPDX-License-Identifier': [
65 's', "License ientifier (if using pure json) "
66 "Only use this if unable to put this "
67 "information in a comment at the top of the "
68 "file."
69 ],
Michael Schaffnere8976ff2021-11-15 16:12:17 -080070 'wakeup_list': ['lnw', "list of peripheral wakeups"],
71 'countermeasures': ["ln", "list of countermeasures in this block"]
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000072}
73
74
Rupert Swarbrick200d8b42021-03-08 12:32:11 +000075class IpBlock:
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000076 def __init__(self,
77 name: str,
78 regwidth: int,
Philipp Wagner78194c82021-03-10 10:08:17 +000079 params: ReggenParams,
Rupert Swarbrick200d8b42021-03-08 12:32:11 +000080 reg_blocks: Dict[Optional[str], RegBlock],
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000081 interrupts: Sequence[Signal],
82 no_auto_intr: bool,
83 alerts: List[Alert],
84 no_auto_alert: bool,
85 scan: bool,
86 inter_signals: List[InterSignal],
Rupert Swarbrick6c831292021-02-25 17:08:53 +000087 bus_interfaces: BusInterfaces,
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000088 hier_path: Optional[str],
Rupert Swarbrickd0cbfad2021-06-29 17:04:51 +010089 clocking: Clocking,
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000090 xputs: Tuple[Sequence[Signal],
91 Sequence[Signal],
92 Sequence[Signal]],
93 wakeups: Sequence[Signal],
94 reset_requests: Sequence[Signal],
Rupert Swarbrickda5ed152021-06-08 14:14:40 +010095 expose_reg_if: bool,
Timothy Chen21e6a4f2021-04-30 03:47:01 -070096 scan_reset: bool,
Michael Schaffnere8976ff2021-11-15 16:12:17 -080097 scan_en: bool,
98 countermeasures: List[CounterMeasure]):
Rupert Swarbrick200d8b42021-03-08 12:32:11 +000099 assert reg_blocks
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000100
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000101 # Check that register blocks are in bijection with device interfaces
102 reg_block_names = reg_blocks.keys()
103 dev_if_names = [] # type: List[Optional[str]]
104 dev_if_names += bus_interfaces.named_devices
105 if bus_interfaces.has_unnamed_device:
106 dev_if_names.append(None)
107 assert set(reg_block_names) == set(dev_if_names)
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000108
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000109 self.name = name
110 self.regwidth = regwidth
111 self.reg_blocks = reg_blocks
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000112 self.params = params
113 self.interrupts = interrupts
114 self.no_auto_intr = no_auto_intr
115 self.alerts = alerts
116 self.no_auto_alert = no_auto_alert
117 self.scan = scan
118 self.inter_signals = inter_signals
Rupert Swarbrick6c831292021-02-25 17:08:53 +0000119 self.bus_interfaces = bus_interfaces
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000120 self.hier_path = hier_path
Rupert Swarbrickd0cbfad2021-06-29 17:04:51 +0100121 self.clocking = clocking
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000122 self.xputs = xputs
123 self.wakeups = wakeups
124 self.reset_requests = reset_requests
Rupert Swarbrickda5ed152021-06-08 14:14:40 +0100125 self.expose_reg_if = expose_reg_if
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000126 self.scan_reset = scan_reset
Timothy Chen21e6a4f2021-04-30 03:47:01 -0700127 self.scan_en = scan_en
Michael Schaffnere8976ff2021-11-15 16:12:17 -0800128 self.countermeasures = countermeasures
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000129
130 @staticmethod
131 def from_raw(param_defaults: List[Tuple[str, str]],
132 raw: object,
133 where: str) -> 'IpBlock':
134
135 rd = check_keys(raw, 'block at ' + where,
136 list(REQUIRED_FIELDS.keys()),
137 list(OPTIONAL_FIELDS.keys()))
138
139 name = check_name(rd['name'], 'name of block at ' + where)
140
141 what = '{} block at {}'.format(name, where)
142
143 r_regwidth = rd.get('regwidth')
144 if r_regwidth is None:
145 regwidth = 32
146 else:
147 regwidth = check_int(r_regwidth, 'regwidth field of ' + what)
148 if regwidth <= 0:
149 raise ValueError('Invalid regwidth field for {}: '
150 '{} is not positive.'
151 .format(what, regwidth))
152
Philipp Wagner78194c82021-03-10 10:08:17 +0000153 params = ReggenParams.from_raw('parameter list for ' + what,
154 rd.get('param_list', []))
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000155 try:
156 params.apply_defaults(param_defaults)
157 except (ValueError, KeyError) as err:
158 raise ValueError('Failed to apply defaults to params: {}'
159 .format(err)) from None
160
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000161 init_block = RegBlock(regwidth, params)
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000162
163 interrupts = Signal.from_raw_list('interrupt_list for block {}'
164 .format(name),
165 rd.get('interrupt_list', []))
166 alerts = Alert.from_raw_list('alert_list for block {}'
167 .format(name),
168 rd.get('alert_list', []))
169
Michael Schaffnere8976ff2021-11-15 16:12:17 -0800170 countermeasures = CounterMeasure.from_raw_list(
171 'countermeasure list for block {}'
172 .format(name),
173 rd.get('countermeasures', []))
174
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000175 no_auto_intr = check_bool(rd.get('no_auto_intr_regs', not interrupts),
176 'no_auto_intr_regs field of ' + what)
177
178 no_auto_alert = check_bool(rd.get('no_auto_alert_regs', not alerts),
179 'no_auto_alert_regs field of ' + what)
180
181 if interrupts and not no_auto_intr:
182 if interrupts[-1].bits.msb >= regwidth:
183 raise ValueError("Interrupt list for {} is too wide: "
184 "msb is {}, which doesn't fit with a "
185 "regwidth of {}."
186 .format(what,
187 interrupts[-1].bits.msb, regwidth))
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000188 init_block.make_intr_regs(interrupts)
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000189
190 if alerts:
191 if not no_auto_alert:
192 if len(alerts) > regwidth:
193 raise ValueError("Interrupt list for {} is too wide: "
194 "{} alerts don't fit with a regwidth of {}."
195 .format(what, len(alerts), regwidth))
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000196 init_block.make_alert_regs(alerts)
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000197
198 # Generate a NumAlerts parameter
199 existing_param = params.get('NumAlerts')
200 if existing_param is not None:
201 if ((not isinstance(existing_param, LocalParam) or
202 existing_param.param_type != 'int' or
203 existing_param.value != str(len(alerts)))):
204 raise ValueError('Conflicting definition of NumAlerts '
205 'parameter.')
206 else:
207 params.add(LocalParam(name='NumAlerts',
208 desc='Number of alerts',
209 param_type='int',
210 value=str(len(alerts))))
211
212 scan = check_bool(rd.get('scan', False), 'scan field of ' + what)
213
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000214 r_inter_signals = check_list(rd.get('inter_signal_list', []),
215 'inter_signal_list field')
216 inter_signals = [
217 InterSignal.from_raw('entry {} of the inter_signal_list field'
218 .format(idx + 1),
219 entry)
220 for idx, entry in enumerate(r_inter_signals)
221 ]
222
Rupert Swarbrick6c831292021-02-25 17:08:53 +0000223 bus_interfaces = (BusInterfaces.
224 from_raw(rd['bus_interfaces'],
225 'bus_interfaces field of ' + where))
226 inter_signals += bus_interfaces.inter_signals()
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000227
228 hier_path = check_optional_str(rd.get('hier_path', None),
229 'hier_path field of ' + what)
230
Rupert Swarbrickd0cbfad2021-06-29 17:04:51 +0100231 clocking = Clocking.from_raw(rd['clocking'],
232 'clocking field of ' + what)
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000233
Timothy Chena49ceb62021-07-13 14:59:09 -0700234 reg_blocks = RegBlock.build_blocks(init_block, rd['registers'],
235 bus_interfaces,
236 clocking)
237
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000238 xputs = (
239 Signal.from_raw_list('available_inout_list for block ' + name,
240 rd.get('available_inout_list', [])),
241 Signal.from_raw_list('available_input_list for block ' + name,
242 rd.get('available_input_list', [])),
243 Signal.from_raw_list('available_output_list for block ' + name,
244 rd.get('available_output_list', []))
245 )
246 wakeups = Signal.from_raw_list('wakeup_list for block ' + name,
247 rd.get('wakeup_list', []))
248 rst_reqs = Signal.from_raw_list('reset_request_list for block ' + name,
249 rd.get('reset_request_list', []))
250
Rupert Swarbrickda5ed152021-06-08 14:14:40 +0100251 expose_reg_if = check_bool(rd.get('expose_reg_if', False),
252 'expose_reg_if field of ' + what)
253
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000254 scan_reset = check_bool(rd.get('scan_reset', False),
255 'scan_reset field of ' + what)
256
Timothy Chen21e6a4f2021-04-30 03:47:01 -0700257 scan_en = check_bool(rd.get('scan_en', False),
Rupert Swarbrickba0bd322021-06-07 16:30:20 +0100258 'scan_en field of ' + what)
Timothy Chen21e6a4f2021-04-30 03:47:01 -0700259
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000260 # Check that register blocks are in bijection with device interfaces
261 reg_block_names = reg_blocks.keys()
262 dev_if_names = [] # type: List[Optional[str]]
263 dev_if_names += bus_interfaces.named_devices
264 if bus_interfaces.has_unnamed_device:
265 dev_if_names.append(None)
266 if set(reg_block_names) != set(dev_if_names):
267 raise ValueError("IP block {} defines device interfaces, named {} "
268 "but its registers don't match (they are keyed "
269 "by {})."
270 .format(name, dev_if_names,
271 list(reg_block_names)))
272
273 return IpBlock(name, regwidth, params, reg_blocks,
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000274 interrupts, no_auto_intr, alerts, no_auto_alert,
Rupert Swarbrick6c831292021-02-25 17:08:53 +0000275 scan, inter_signals, bus_interfaces,
Rupert Swarbrickd0cbfad2021-06-29 17:04:51 +0100276 hier_path, clocking, xputs,
Michael Schaffnere8976ff2021-11-15 16:12:17 -0800277 wakeups, rst_reqs, expose_reg_if, scan_reset, scan_en,
278 countermeasures)
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000279
280 @staticmethod
281 def from_text(txt: str,
282 param_defaults: List[Tuple[str, str]],
283 where: str) -> 'IpBlock':
284 '''Load an IpBlock from an hjson description in txt'''
285 return IpBlock.from_raw(param_defaults,
286 hjson.loads(txt, use_decimal=True),
287 where)
288
289 @staticmethod
290 def from_path(path: str,
291 param_defaults: List[Tuple[str, str]]) -> 'IpBlock':
292 '''Load an IpBlock from an hjson description in a file at path'''
Srikrishna Iyer18b8ed92021-04-26 15:54:44 -0700293 with open(path, 'r', encoding='utf-8') as handle:
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000294 return IpBlock.from_text(handle.read(), param_defaults,
295 'file at {!r}'.format(path))
296
297 def _asdict(self) -> Dict[str, object]:
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000298 ret = {
299 'name': self.name,
300 'regwidth': self.regwidth
301 }
302 if len(self.reg_blocks) == 1 and None in self.reg_blocks:
303 ret['registers'] = self.reg_blocks[None].as_dicts()
304 else:
305 ret['registers'] = {k: v.as_dicts()
306 for k, v in self.reg_blocks.items()}
307
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000308 ret['param_list'] = self.params.as_dicts()
309 ret['interrupt_list'] = self.interrupts
310 ret['no_auto_intr_regs'] = self.no_auto_intr
311 ret['alert_list'] = self.alerts
312 ret['no_auto_alert_regs'] = self.no_auto_alert
313 ret['scan'] = self.scan
314 ret['inter_signal_list'] = self.inter_signals
Rupert Swarbrick6c831292021-02-25 17:08:53 +0000315 ret['bus_interfaces'] = self.bus_interfaces.as_dicts()
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000316
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000317 if self.hier_path is not None:
318 ret['hier_path'] = self.hier_path
319
Rupert Swarbrickd0cbfad2021-06-29 17:04:51 +0100320 ret['clocking'] = self.clocking.items
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000321
322 inouts, inputs, outputs = self.xputs
323 if inouts:
324 ret['available_inout_list'] = inouts
325 if inputs:
326 ret['available_input_list'] = inputs
327 if outputs:
328 ret['available_output_list'] = outputs
329
330 if self.wakeups:
331 ret['wakeup_list'] = self.wakeups
332 if self.reset_requests:
333 ret['reset_request_list'] = self.reset_requests
334
335 ret['scan_reset'] = self.scan_reset
Timothy Chen21e6a4f2021-04-30 03:47:01 -0700336 ret['scan_en'] = self.scan_en
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000337
338 return ret
Rupert Swarbrick200d8b42021-03-08 12:32:11 +0000339
340 def get_rnames(self) -> Set[str]:
341 ret = set() # type: Set[str]
342 for rb in self.reg_blocks.values():
343 ret = ret.union(set(rb.name_to_offset.keys()))
344 return ret
Michael Schaffner74c4ff22021-03-30 15:43:46 -0700345
Rupert Swarbrick0f6eeaf2021-05-28 15:24:14 +0100346 def get_signals_as_list_of_dicts(self) -> List[Dict[str, object]]:
Michael Schaffner74c4ff22021-03-30 15:43:46 -0700347 '''Look up and return signal by name'''
348 result = []
349 for iodir, xput in zip(('inout', 'input', 'output'), self.xputs):
350 for sig in xput:
351 result.append(sig.as_nwt_dict(iodir))
352 return result
353
Rupert Swarbrick0f6eeaf2021-05-28 15:24:14 +0100354 def get_signal_by_name_as_dict(self, name: str) -> Dict[str, object]:
Michael Schaffner74c4ff22021-03-30 15:43:46 -0700355 '''Look up and return signal by name'''
356 sig_list = self.get_signals_as_list_of_dicts()
357 for sig in sig_list:
358 if sig['name'] == name:
359 return sig
360 else:
361 raise ValueError("Signal {} does not exist in IP block {}"
362 .format(name, self.name))
Timothy Chen7c3de6e2021-07-19 16:46:45 -0700363
364 def has_shadowed_reg(self) -> bool:
365 '''Return boolean indication whether reg block contains shadowed registers'''
366
367 for rb in self.reg_blocks.values():
368 if rb.has_shadowed_reg():
369 return True
370
371 # if we are here, then no one has has a shadowed register
372 return False
373
374 def get_primary_clock(self) -> ClockingItem:
375 '''Return primary clock of an block'''
376
377 return self.clocking.primary