-
Notifications
You must be signed in to change notification settings - Fork 746
Expand file tree
/
Copy pathcsr.py
More file actions
698 lines (573 loc) · 24.9 KB
/
Copy pathcsr.py
File metadata and controls
698 lines (573 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
#
# This file is part of LiteX.
#
# Copyright (c) 2015 Sebastien Bourdeauducq <sb@m-labs.hk>
# Copyright (c) 2015-2019 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2016-2019 Tim 'mithro' Ansell <me@mith.ro>
# Copyright (c) 2019 Sean Cross <sean@xobs.io>
# SPDX-License-Identifier: BSD-2-Clause
"""
Configuration and Status Registers
**********************************
The lowest-level description of a register is provided by the ``CSR`` class,
which maps to the value at a single address on the target bus. Also provided
are helper classes for dealing with values larger than the CSR buses data
width.
* ``CSRConstant``, for constant values.
* ``CSRStatus``, for providing information to the CPU.
* ``CSRStorage``, for allowing control via the CPU.
Generating register banks
=========================
A module can provide bus-independent CSRs by implementing a ``get_csrs`` method
that returns a list of instances of the classes described above.
Similarly, bus-independent memories can be returned as a list by a
``get_memories`` method.
To avoid listing those manually, a module can inherit from the ``AutoCSR``
class, which provides ``get_csrs`` and ``get_memories`` methods that scan for
CSR and memory attributes and return their list.
"""
from enum import IntEnum
from migen import *
from migen.util.misc import xdir
from migen.fhdl.tracer import get_obj_var_name
# Helpers ------------------------------------------------------------------------------------------
def _check_csr_location(n):
if n is None:
return
if not isinstance(n, int):
raise ValueError("CSR location should be an integer.")
if n < 0:
raise ValueError("CSR location should be non-negative.")
# CSRBase ------------------------------------------------------------------------------------------
class _CSRBase(DUID):
def __init__(self, size, name, n=None):
DUID.__init__(self)
_check_csr_location(n)
self.n = n
self.fixed = n is not None
self.size = size
self.name = get_obj_var_name(name)
if self.name is None:
raise ValueError("Cannot extract CSR name from code, need to specify.")
# CSRConstant --------------------------------------------------------------------------------------
class CSRConstant(DUID):
"""Register which contains a constant value.
Useful for providing information on how a HDL was instantiated to firmware
running on the device.
"""
def __init__(self, value, bits_sign=None, name=None, n=None):
DUID.__init__(self)
_check_csr_location(n)
self.n = n
self.fixed = n is not None
self.value = Constant(value, bits_sign)
self.name = get_obj_var_name(name)
self.constant = value
if self.name is None:
raise ValueError("Cannot extract CSR name from code, need to specify.")
def read(self):
"""Read method for simulation."""
yield
return self.constant
# CSR ----------------------------------------------------------------------------------------------
class CSR(_CSRBase):
"""Basic CSR register.
Parameters
----------
size : int
Size of the CSR register in bits.
Must be less than CSR bus width!
name : string
Provide (or override the name) of the CSR register.
Attributes
----------
wr_data : Signal(size), out
Contains the data written from the bus interface.
``wr_data`` is only valid when ``wr_stb`` is high.
wr_stb : Signal(), out
The strobe signal for ``wr_data``.
It is active for one cycle, after or during a write from the bus.
rd_data : Signal(size), in
The value to be read from the bus.
Must be provided at all times.
rd_stb : Signal(), out
The strobe signal for ``rd_data``.
It is active for one cycle, after or during a read from the bus.
r/re/w/we : Signal(), compatibility aliases
Historical names kept for compatibility:
``r``/``re`` alias ``wr_data``/``wr_stb`` and
``w``/``we`` alias ``rd_data``/``rd_stb``.
"""
def __init__(self, size=1, name=None, n=None):
_CSRBase.__init__(self, size, name, n)
self.wr_stb = Signal(name=self.name + "_re")
self.wr_data = Signal(self.size, name=self.name + "_r")
self.rd_stb = Signal(name=self.name + "_we")
self.rd_data = Signal(self.size, name=self.name + "_w")
# Compatibility aliases.
self.re = self.wr_stb
self.r = self.wr_data
self.we = self.rd_stb
self.w = self.rd_data
def read(self):
"""Read method for simulation."""
yield self.rd_stb.eq(1)
value = (yield self.rd_data)
yield
yield self.rd_stb.eq(0)
return value
def write(self, value):
"""Write method for simulation."""
yield self.wr_data.eq(value)
yield self.wr_stb.eq(1)
yield
yield self.wr_stb.eq(0)
class CSRGap(_CSRBase):
"""Reserve one or more locations in a fixed CSR bank layout.
When provided, ``n`` is the first reserved CSR index in the bank. Without
``n``, the gap is inserted at its natural declaration position. ``name`` is
used as the generated CSR name prefix, while ``name_start`` controls the
numeric suffix. Set ``name_start`` to ``None`` to use ``name`` as an exact
name for a single-location gap.
"""
def __init__(self, count=1, name="reserved", n=None, name_start=0):
if count < 1:
raise ValueError("CSRGap count must be >= 1.")
if name_start is None and count != 1:
raise ValueError("CSRGap name_start=None is only valid for a single-location gap.")
_CSRBase.__init__(self, 0, name, n)
self.count = count
self.name_start = name_start
def get_name(self, index):
if index < 0 or index >= self.count:
raise ValueError(f"CSRGap index {index} outside gap size {self.count}.")
if self.name_start is None:
return self.name
return f"{self.name}{self.name_start + index}"
def read(self):
yield
return 0
def write(self, value):
yield
def _expand_csr_gap(csr_gap):
return [CSR(name=csr_gap.get_name(i)) for i in range(csr_gap.count)]
class _CompoundCSR(_CSRBase, Module):
def __init__(self, size, name, n=None):
_CSRBase.__init__(self, size, name, n)
self.simple_csrs = []
def get_simple_csrs(self):
if not self.finalized:
raise FinalizeError
return self.simple_csrs
def do_finalize(self, busword):
raise NotImplementedError
# CSRAccess ----------------------------------------------------------------------------------------
class CSRAccess(IntEnum):
WriteOnly = 0
ReadOnly = 1
ReadWrite = 2
# CSRField -----------------------------------------------------------------------------------------
class CSRField(Signal):
"""CSR Field.
Parameters / Attributes
-----------------------
name : string
Name of the CSR field.
size : int
Size of the CSR field in bits.
offset : int (optional)
Offset of the CSR field on the CSR register in bits.
reset: int (optional)
Reset value of the CSR field.
description: string (optional)
Description of the CSR Field (can be used to document the code and/or to be reused by tools
to create the documentation).
pulse: boolean (optional)
Field value is only valid for one cycle when set to True. Only valid for 1-bit fields.
access: enum (optional)
Access type of the CSR field.
values: list (optional)
A list of supported values.
If this is specified, a table will be generated containing the values in the specified order.
The `value` must be an integer in order to allow for automatic constant generation in an IDE,
except "do not care" bits are allowed.
In the three-tuple variation, the middle value represents an enum value that can be displayed
instead of the value.
[
("0b0000", "disable the timer"),
("0b0001", "slow", "slow timer"),
("0b1xxx", "fast timer"),
]
"""
def __init__(self, name, size=1, offset=None, reset=0, description=None, pulse=False, access=None, values=None):
assert access is None or (access in CSRAccess.__members__.values())
self.name = name
self.size = size
self.offset = offset
self.reset_value = reset
self.description = description
self.access = access
self.pulse = pulse
self.values = values
Signal.__init__(self, size, name=name, reset=reset)
class CSRFieldAggregate:
"""CSR Field Aggregate."""
def __init__(self, fields, access):
self.check_names(fields)
self.check_ordering_overlap(fields)
self.fields = fields
for field in fields:
if field.access is None:
field.access = access
elif access == CSRAccess.ReadOnly:
assert not field.pulse
assert field.access == CSRAccess.ReadOnly
elif access == CSRAccess.ReadWrite:
assert field.access in [CSRAccess.ReadWrite, CSRAccess.WriteOnly]
if field.pulse:
field.access = CSRAccess.WriteOnly
setattr(self, field.name, field)
@staticmethod
def check_names(fields):
names = []
for field in fields:
if field.name in names:
raise ValueError("CSRField \"{}\" name is already used in CSR register".format(field.name))
else:
names.append(field.name)
@staticmethod
def check_ordering_overlap(fields):
offset = 0
for field in fields:
if field.offset is not None:
if field.offset < offset:
raise ValueError("CSRField ordering/overlap issue on \"{}\" field".format(field.name))
offset = field.offset
else:
field.offset = offset
offset += field.size
def get_size(self):
return self.fields[-1].offset + self.fields[-1].size
def get_reset(self):
reset = 0
for field in self.fields:
reset |= (field.reset_value << field.offset)
return reset
# CSRStatus ----------------------------------------------------------------------------------------
class CSRStatus(_CompoundCSR):
"""Status Register.
The ``CSRStatus`` class is meant to be used as a status register that is read-only from the CPU.
The user design is expected to drive its ``status`` signal.
The advantage of using ``CSRStatus`` instead of using ``CSR`` and driving ``w`` is that the
width of ``CSRStatus`` can be arbitrary.
Status registers larger than the bus word width are automatically broken down into several
``CSR`` registers to span several addresses.
*Be careful, though:* the atomicity of reads is not guaranteed.
Parameters
----------
size : int
Size of the CSR register in bits.
Can be bigger than the CSR bus width.
reset : string
Value of the register after reset.
name : string
Provide (or override the name) of the ``CSRStatus`` register.
Attributes
----------
status : Signal(size), in
The value of the CSRStatus register.
"""
def __init__(self, size=1, reset=0, fields=[], name=None, description=None, read_only=True, n=None):
if fields != []:
self.fields = CSRFieldAggregate(fields, CSRAccess.ReadOnly)
size = self.fields.get_size()
reset = self.fields.get_reset()
_CompoundCSR.__init__(self, size, name, n)
self.description = description
self.read_only = read_only
self.status = Signal(self.size, reset=reset)
self.rd_stb = Signal()
self.wr_stb = Signal()
self.we = self.rd_stb
self.re = self.wr_stb
if not read_only:
self.wr_data = Signal(self.size)
self.r = self.wr_data
for field in fields:
self.comb += self.status[field.offset:field.offset + field.size].eq(getattr(self.fields, field.name))
def do_finalize(self, busword, ordering):
nwords = (self.size + busword - 1)//busword
for i in reversed(range(nwords)) if ordering == "big" else range(nwords):
nbits = min(self.size - i*busword, busword)
sc = CSR(nbits, self.name + str(i) if nwords > 1 else self.name)
self.comb += sc.rd_data.eq(self.status[i*busword:i*busword+nbits])
self.simple_csrs.append(sc)
if not self.read_only:
lo = i*busword
hi = lo+nbits
self.sync += If(sc.wr_stb, self.wr_data[lo:hi].eq(sc.wr_data))
self.comb += self.rd_stb.eq(sc.rd_stb)
self.sync += self.wr_stb.eq(sc.wr_stb)
def read(self):
"""Read method for simulation."""
yield self.rd_stb.eq(1)
if hasattr(self, "fields"):
# In standalone simulation, CSRStatus is commonly used as a plain
# CSR object rather than as a submodule, so pack the live fields
# directly instead of relying on this module's internal comb logic.
value = 0
for field in [*self.fields.fields]:
value |= (yield getattr(self.fields, field.name)) << field.offset
else:
value = (yield self.status)
yield
yield self.rd_stb.eq(0)
return value
# CSRStorage ---------------------------------------------------------------------------------------
class CSRStorage(_CompoundCSR):
"""Control Register.
The ``CSRStorage`` class provides a memory location that can be read and written by the CPU, and read and optionally written by the design.
It can span several CSR addresses.
Parameters
----------
size : int
Size of the CSR register in bits. Can be bigger than the CSR bus width.
reset : string
Value of the register after reset.
reset_less : bool
If `True`, do not generate reset logic for CSRStorage.
atomic_write : bool
Provide an mechanism for atomic CPU writes is provided. When enabled, writes to the first
CSR addresses go to a back-buffer whose contents are atomically copied to the main buffer
when the last address is written.
write_from_dev : bool
Allow the design to update the CSRStorage value. *Warning*: The atomicity of reads by the
CPU is not guaranteed.
name : string
Provide (or override the name) of the ``CSRStatus`` register.
Attributes
----------
storage : Signal(size), out
Signal providing the value of the ``CSRStorage`` object.
wr_stb : Signal(), in
The strobe signal indicating a write to the ``CSRStorage`` register from the CPU. It is active
for one cycle, after or during a write from the bus.
re : Signal(), in
Compatibility alias for ``wr_stb``.
we : Signal(), out
The strobe signal to write to the ``CSRStorage`` register from the logic. Only available when
``write_from_dev == True``
dat_w : Signal(), out
The write data to write to the ``CSRStorage`` register from the logic. Only available when
``write_from_dev == True``
"""
def __init__(self, size=1, reset=0, reset_less=False, fields=[], atomic_write=False, write_from_dev=False, name=None, description=None, n=None):
if fields != []:
self.fields = CSRFieldAggregate(fields, CSRAccess.ReadWrite)
size = self.fields.get_size()
reset = self.fields.get_reset()
_CompoundCSR.__init__(self, size, name, n)
self.description = description
self.storage = Signal(self.size, reset=reset, reset_less=reset_less)
self.atomic_write = atomic_write
self.wr_stb = Signal()
self.re = self.wr_stb
if write_from_dev:
self.we = Signal()
self.dat_w = Signal(self.size)
self.sync += If(self.we, self.storage.eq(self.dat_w))
for field in [*fields]:
field_assign = getattr(self.fields, field.name).eq(self.storage[field.offset:field.offset + field.size])
if field.pulse:
self.comb += If(self.wr_stb, field_assign)
else:
self.comb += field_assign
def do_finalize(self, busword, ordering):
nwords = (self.size + busword - 1)//busword
# The CPU writes ascending addresses: with big ordering, word 0 (LSBs) is at the highest
# address and thus written last; with little ordering, word nwords-1 (MSBs) is written
# last. Commit the storage atomically on that last-written word.
commit_word = 0 if (ordering == "big") else (nwords - 1)
if nwords > 1 and self.atomic_write:
# The backstore holds all the words but the commit one.
backstore_width = {
"big" : self.size - busword, # Words 1..nwords-1.
"little" : (nwords - 1)*busword, # Words 0..nwords-2.
}[ordering]
backstore = Signal(backstore_width, name=self.name + "_backstore")
for i in reversed(range(nwords)) if ordering == "big" else range(nwords):
nbits = min(self.size - i*busword, busword)
sc = CSR(nbits, self.name + str(i) if nwords > 1 else self.name)
self.simple_csrs.append(sc)
lo = i*busword
hi = lo+nbits
# read
self.comb += sc.rd_data.eq(self.storage[lo:hi])
# write
if nwords > 1 and self.atomic_write:
if i != commit_word:
backstore_lo = lo - (busword if ordering == "big" else 0)
backstore_hi = hi - (busword if ordering == "big" else 0)
self.sync += If(sc.wr_stb,
backstore[backstore_lo:backstore_hi].eq(sc.wr_data))
else:
commit_value = {
"big" : Cat(sc.wr_data, backstore),
"little" : Cat(backstore, sc.wr_data),
}[ordering]
self.sync += If(sc.wr_stb, self.storage.eq(commit_value))
else:
self.sync += If(sc.wr_stb, self.storage[lo:hi].eq(sc.wr_data))
self.sync += self.wr_stb.eq(sc.wr_stb)
def read(self):
"""Read method for simulation.
Side effects: none (asynchronous)."""
return (yield self.storage)
def write(self, value):
"""Write method for simulation.
Side effects: synchronous advances simulation clk by one tick."""
if bits_for(value) > self.size:
raise ValueError(f"value {value} exceeds range of {self.size} bit CSR {self.name}.")
yield self.storage.eq(value)
yield self.wr_stb.eq(1)
if hasattr(self, "fields"):
for field in [*self.fields.fields]:
yield getattr(self.fields, field.name).eq((value >> field.offset) & (2**field.size -1))
yield
yield self.wr_stb.eq(0)
if hasattr(self, "fields"):
for field in [*self.fields.fields]:
if field.pulse:
yield getattr(self.fields, field.name).eq(0)
# AutoCSR & Helpers --------------------------------------------------------------------------------
def csrprefix(prefix, csrs, done):
for csr in csrs:
if csr.duid not in done:
csr.name = prefix + csr.name
done.add(csr.duid)
def memprefix(prefix, memories, done):
for memory in memories:
if memory.duid not in done:
memory.name_override = prefix + memory.name_override
done.add(memory.duid)
def _sort_gathered_items(items):
# Create list of variable items and sort it by DUID.
# --------------------------------------------------
variable_items = []
for item in items:
if not item.fixed:
variable_items.append(item)
variable_items = sorted(variable_items, key=lambda x: x.duid)
# Create list of fixed items:
# ---------------------------
fixed_items = []
for item in items:
if item.fixed:
fixed_items.append(item)
# Determine items length.
# -----------------------
# Set to length of provided items after expanding gaps.
items_length = 0
for item in items:
items_length += item.count if isinstance(item, CSRGap) else 1
# Eventually extend with fixed items:
for item in fixed_items:
item_count = item.count if isinstance(item, CSRGap) else 1
if (item.n + item_count) > items_length:
items_length = item.n + item_count
# Create list of sorted items:
# ----------------------------
# Create empty list.
sorted_items = [None for _ in range(items_length)]
# Fill fixed items.
for item in fixed_items:
if isinstance(item, CSRGap):
for i, csr in enumerate(_expand_csr_gap(item)):
location = item.n + i
if sorted_items[location] is not None:
csr0 = item.get_name(i)
csr1 = sorted_items[location].name
raise ValueError(f"CSR conflict on location {location} between {csr0} and {csr1}.")
sorted_items[location] = csr
continue
if sorted_items[item.n] is not None:
csr0 = item.name
csr1 = sorted_items[item.n].name
raise ValueError(f"CSR conflict on location {item.n} between {csr0} and {csr1}.")
sorted_items[item.n] = item
# Fill variable items in empty locations.
while len(variable_items):
item = variable_items.pop(0)
expanded_items = _expand_csr_gap(item) if isinstance(item, CSRGap) else [item]
for expanded_item in expanded_items:
for i in range(items_length):
if sorted_items[i] is None:
sorted_items[i] = expanded_item
break
else:
raise ValueError(f"No free CSR location for {item.name}.")
# Fill remaining location with reserved CSR.
for i in range(items_length):
if sorted_items[i] is None:
sorted_items[i] = CSR(name=f"reserved{i}")
# Verify all locations are filled.
assert None not in sorted_items
# Return.
return sorted_items
def _make_gatherer(method, cls, prefix_cb, sort_cb=None):
def gatherer(self, sort=False):
try:
exclude = self.autocsr_exclude
except AttributeError:
exclude = {}
try:
prefixed = self.__prefixed
except AttributeError:
prefixed = self.__prefixed = set()
r = []
for k, v in xdir(self, True):
if k not in exclude:
if isinstance(v, cls):
r.append(v)
elif hasattr(v, method) and callable(getattr(v, method)):
items = getattr(v, method)()
prefix_cb(k + "_", items, prefixed)
r += items
r = sorted(r, key=lambda x: x.duid)
if sort and sort_cb is not None:
r = sort_cb(r)
return r
return gatherer
class AutoCSR:
"""MixIn to provide bus independent access to CSR registers.
A module can inherit from the ``AutoCSR`` class, which provides ``get_csrs``, ``get_memories``
and ``get_constants`` methods that scan for CSR and memory attributes and return their list.
If the module has child objects that implement ``get_csrs``, ``get_memories`` or ``get_constants``,
they will be called by the``AutoCSR`` methods and their CSR and memories added to the lists returned,
with the child objects' names as prefixes.
"""
get_memories = _make_gatherer(method="get_memories", cls=Memory, prefix_cb=memprefix)
get_csrs = _make_gatherer(
method = "get_csrs",
cls = _CSRBase,
prefix_cb = csrprefix,
sort_cb = _sort_gathered_items,
)
get_constants = _make_gatherer(method="get_constants", cls=CSRConstant, prefix_cb=csrprefix)
class GenericBank(Module):
def __init__(self, description, busword, ordering="big"):
assert ordering in ["big", "little"]
# Turn description into simple CSRs and claim ownership of compound CSR modules
self.simple_csrs = []
for c in description:
if isinstance(c, CSRGap):
for csr in _expand_csr_gap(c):
assert csr.size <= busword
self.simple_csrs.append(csr)
elif isinstance(c, CSR):
assert c.size <= busword
self.simple_csrs.append(c)
elif hasattr(c, "finalize"):
c.finalize(busword, ordering)
self.simple_csrs += c.get_simple_csrs()
self.submodules += c