soc: add initial DMA bus support (optionally provided by CPU(s) for cache coherency).
[litex.git] / litex / soc / integration / soc.py
1 # This file is Copyright (c) 2014-2020 Florent Kermarrec <florent@enjoy-digital.fr>
2 # This file is Copyright (c) 2013-2014 Sebastien Bourdeauducq <sb@m-labs.hk>
3 # This file is Copyright (c) 2019 Gabriel L. Somlo <somlo@cmu.edu>
4 # License: BSD
5
6 import logging
7 import time
8 import datetime
9 from math import log2, ceil
10
11 from migen import *
12
13 from litex.soc.cores import cpu
14 from litex.soc.cores.identifier import Identifier
15 from litex.soc.cores.timer import Timer
16 from litex.soc.cores.spi_flash import SpiFlash
17 from litex.soc.cores.spi import SPIMaster
18
19 from litex.soc.interconnect.csr import *
20 from litex.soc.interconnect import csr_bus
21 from litex.soc.interconnect import stream
22 from litex.soc.interconnect import wishbone
23 from litex.soc.interconnect import axi
24
25 logging.basicConfig(level=logging.INFO)
26
27 # Helpers ------------------------------------------------------------------------------------------
28
29 def auto_int(x):
30 return int(x, 0)
31
32 def colorer(s, color="bright"):
33 header = {
34 "bright": "\x1b[1m",
35 "green": "\x1b[32m",
36 "cyan": "\x1b[36m",
37 "red": "\x1b[31m",
38 "yellow": "\x1b[33m",
39 "underline": "\x1b[4m"}[color]
40 trailer = "\x1b[0m"
41 return header + str(s) + trailer
42
43 def build_time(with_time=True):
44 fmt = "%Y-%m-%d %H:%M:%S" if with_time else "%Y-%m-%d"
45 return datetime.datetime.fromtimestamp(time.time()).strftime(fmt)
46
47 # SoCConstant --------------------------------------------------------------------------------------
48
49 def SoCConstant(value):
50 return value
51
52 # SoCRegion ----------------------------------------------------------------------------------------
53
54 class SoCRegion:
55 def __init__(self, origin=None, size=None, mode="rw", cached=True, linker=False):
56 self.logger = logging.getLogger("SoCRegion")
57 self.origin = origin
58 self.size = size
59 if size != 2**log2_int(size, False):
60 self.logger.info("Region size {} internally from {} to {}.".format(
61 colorer("rounded", color="cyan"),
62 colorer("0x{:08x}".format(size)),
63 colorer("0x{:08x}".format(2**log2_int(size, False)))))
64 self.size_pow2 = 2**log2_int(size, False)
65 self.mode = mode
66 self.cached = cached
67 self.linker = linker
68
69 def decoder(self, bus):
70 origin = self.origin
71 size = self.size_pow2
72 if (origin & (size - 1)) != 0:
73 self.logger.error("Origin needs to be aligned on size:")
74 self.logger.error(self)
75 raise
76 origin >>= int(log2(bus.data_width//8)) # bytes to words aligned
77 size >>= int(log2(bus.data_width//8)) # bytes to words aligned
78 return lambda a: (a[log2_int(size):] == (origin >> log2_int(size)))
79
80 def __str__(self):
81 r = ""
82 if self.origin is not None:
83 r += "Origin: {}, ".format(colorer("0x{:08x}".format(self.origin)))
84 if self.size is not None:
85 r += "Size: {}, ".format(colorer("0x{:08x}".format(self.size)))
86 r += "Mode: {}, ".format(colorer(self.mode.upper()))
87 r += "Cached: {} ".format(colorer(self.cached))
88 r += "Linker: {}".format(colorer(self.linker))
89 return r
90
91 class SoCIORegion(SoCRegion): pass
92
93 # SoCCSRRegion -------------------------------------------------------------------------------------
94
95 class SoCCSRRegion:
96 def __init__(self, origin, busword, obj):
97 self.origin = origin
98 self.busword = busword
99 self.obj = obj
100
101 # SoCBusHandler ------------------------------------------------------------------------------------
102
103 class SoCBusHandler(Module):
104 supported_standard = ["wishbone"]
105 supported_data_width = [32, 64]
106 supported_address_width = [32]
107
108 # Creation -------------------------------------------------------------------------------------
109 def __init__(self, name="SoCBusHandler", standard="wishbone", data_width=32, address_width=32, timeout=1e6, reserved_regions={}):
110 self.logger = logging.getLogger(name)
111 self.logger.info("Creating Bus Handler...")
112
113 # Check Standard
114 if standard not in self.supported_standard:
115 self.logger.error("Unsupported {} {}, supporteds: {:s}".format(
116 colorer("Bus standard", color="red"),
117 colorer(standard),
118 colorer(", ".join(self.supported_standard))))
119 raise
120
121 # Check Data Width
122 if data_width not in self.supported_data_width:
123 self.logger.error("Unsupported {} {}, supporteds: {:s}".format(
124 colorer("Data Width", color="red"),
125 colorer(data_width),
126 colorer(", ".join(str(x) for x in self.supported_data_width))))
127 raise
128
129 # Check Address Width
130 if address_width not in self.supported_address_width:
131 self.logger.error("Unsupported {} {}, supporteds: {:s}".format(
132 colorer("Address Width", color="red"),
133 colorer(address_width),
134 colorer(", ".join(str(x) for x in self.supported_address_width))))
135 raise
136
137 # Create Bus
138 self.standard = standard
139 self.data_width = data_width
140 self.address_width = address_width
141 self.masters = {}
142 self.slaves = {}
143 self.regions = {}
144 self.io_regions = {}
145 self.timeout = timeout
146 self.logger.info("{}-bit {} Bus, {}GiB Address Space.".format(
147 colorer(data_width), colorer(standard), colorer(2**address_width/2**30)))
148
149 # Adding reserved regions
150 self.logger.info("Adding {} Bus Regions...".format(colorer("reserved", color="cyan")))
151 for name, region in reserved_regions.items():
152 if isinstance(region, int):
153 region = SoCRegion(origin=region, size=0x1000000)
154 self.add_region(name, region)
155
156 self.logger.info("Bus Handler {}.".format(colorer("created", color="green")))
157
158 # Add/Allog/Check Regions ----------------------------------------------------------------------
159 def add_region(self, name, region):
160 allocated = False
161 if name in self.regions.keys() or name in self.io_regions.keys():
162 self.logger.error("{} already declared as Region:".format(colorer(name, color="red")))
163 self.logger.error(self)
164 raise
165 # Check if SoCIORegion
166 if isinstance(region, SoCIORegion):
167 self.io_regions[name] = region
168 overlap = self.check_regions_overlap(self.io_regions)
169 if overlap is not None:
170 self.logger.error("IO Region {} between {} and {}:".format(
171 colorer("overlap", color="red"),
172 colorer(overlap[0]),
173 colorer(overlap[1])))
174 self.logger.error(str(self.io_regions[overlap[0]]))
175 self.logger.error(str(self.io_regions[overlap[1]]))
176 raise
177 self.logger.info("{} Region {} at {}.".format(
178 colorer(name, color="underline"),
179 colorer("added", color="green"),
180 str(region)))
181 # Check if SoCRegion
182 elif isinstance(region, SoCRegion):
183 # If no origin specified, allocate region.
184 if region.origin is None:
185 allocated = True
186 region = self.alloc_region(name, region.size, region.cached)
187 self.regions[name] = region
188 # Else add region and check for overlaps.
189 else:
190 if not region.cached:
191 if not self.check_region_is_io(region):
192 self.logger.error("{} Region {}: {}.".format(
193 colorer(name),
194 colorer("not in IO region", color="red"),
195 str(region)))
196 self.logger.error(self)
197 raise
198 self.regions[name] = region
199 overlap = self.check_regions_overlap(self.regions)
200 if overlap is not None:
201 self.logger.error("Region {} between {} and {}:".format(
202 colorer("overlap", color="red"),
203 colorer(overlap[0]),
204 colorer(overlap[1])))
205 self.logger.error(str(self.regions[overlap[0]]))
206 self.logger.error(str(self.regions[overlap[1]]))
207 raise
208 self.logger.info("{} Region {} at {}.".format(
209 colorer(name, color="underline"),
210 colorer("allocated" if allocated else "added", color="cyan" if allocated else "green"),
211 str(region)))
212 else:
213 self.logger.error("{} is not a supported Region.".format(colorer(name, color="red")))
214 raise
215
216 def alloc_region(self, name, size, cached=True):
217 self.logger.info("Allocating {} Region of size {}...".format(
218 colorer("Cached" if cached else "IO"),
219 colorer("0x{:08x}".format(size))))
220
221 # Limit Search Regions
222 if cached == False:
223 search_regions = self.io_regions
224 else:
225 search_regions = {"main": SoCRegion(origin=0x00000000, size=2**self.address_width-1)}
226
227 # Iterate on Search_Regions to find a Candidate
228 for _, search_region in search_regions.items():
229 origin = search_region.origin
230 while (origin + size) < (search_region.origin + search_region.size_pow2):
231 # Create a Candicate.
232 candidate = SoCRegion(origin=origin, size=size, cached=cached)
233 overlap = False
234 # Check Candidate does not overlap with allocated existing regions
235 for _, allocated in self.regions.items():
236 if self.check_regions_overlap({"0": allocated, "1": candidate}) is not None:
237 origin = allocated.origin + allocated.size_pow2
238 overlap = True
239 break
240 if not overlap:
241 # If no overlap, the Candidate is selected
242 return candidate
243
244 self.logger.error("Not enough Address Space to allocate Region.")
245 raise
246
247 def check_regions_overlap(self, regions, check_linker=False):
248 i = 0
249 while i < len(regions):
250 n0 = list(regions.keys())[i]
251 r0 = regions[n0]
252 for n1 in list(regions.keys())[i+1:]:
253 r1 = regions[n1]
254 if r0.linker or r1.linker:
255 if not check_linker:
256 continue
257 if r0.origin >= (r1.origin + r1.size_pow2):
258 continue
259 if r1.origin >= (r0.origin + r0.size_pow2):
260 continue
261 return (n0, n1)
262 i += 1
263 return None
264
265 def check_region_is_in(self, region, container):
266 is_in = True
267 if not (region.origin >= container.origin):
268 is_in = False
269 if not ((region.origin + region.size) < (container.origin + container.size)):
270 is_in = False
271 return is_in
272
273 def check_region_is_io(self, region):
274 is_io = False
275 for _, io_region in self.io_regions.items():
276 if self.check_region_is_in(region, io_region):
277 is_io = True
278 return is_io
279
280 # Add Master/Slave -----------------------------------------------------------------------------
281 def add_adapter(self, name, interface, direction="m2s"):
282 assert direction in ["m2s", "s2m"]
283
284 if isinstance(interface, wishbone.Interface):
285 if interface.data_width != self.data_width:
286 new_interface = wishbone.Interface(data_width=self.data_width)
287 if direction == "m2s":
288 converter = wishbone.Converter(master=interface, slave=new_interface)
289 if direction == "s2m":
290 converter = wishbone.Converter(master=new_interface, slave=interface)
291 self.submodules += converter
292 else:
293 new_interface = interface
294 elif isinstance(interface, axi.AXILiteInterface):
295 # Data width conversion
296 intermediate = axi.AXILiteInterface(data_width=self.data_width)
297 if direction == "m2s":
298 converter = axi.AXILiteConverter(master=interface, slave=intermediate)
299 if direction == "s2m":
300 converter = axi.AXILiteConverter(master=intermediate, slave=interface)
301 self.submodules += converter
302 # Bus type conversion
303 new_interface = wishbone.Interface(data_width=self.data_width)
304 if direction == "m2s":
305 converter = axi.AXILite2Wishbone(axi_lite=intermediate, wishbone=new_interface)
306 elif direction == "s2m":
307 converter = axi.Wishbone2AXILite(wishbone=new_interface, axi_lite=intermediate)
308 self.submodules += converter
309 else:
310 raise TypeError(interface)
311
312 fmt = "{name} Bus {converted} from {frombus} {frombits}-bit to {tobus} {tobits}-bit."
313 frombus = "Wishbone" if isinstance(interface, wishbone.Interface) else "AXILite"
314 tobus = "Wishbone" if isinstance(new_interface, wishbone.Interface) else "AXILite"
315 frombits = interface.data_width
316 tobits = new_interface.data_width
317 if frombus != tobus or frombits != tobits:
318 self.logger.info(fmt.format(
319 name = colorer(name),
320 converted = colorer("converted", color="cyan"),
321 frombus = colorer("Wishbone" if isinstance(interface, wishbone.Interface) else "AXILite"),
322 frombits = colorer(interface.data_width),
323 tobus = colorer("Wishbone" if isinstance(new_interface, wishbone.Interface) else "AXILite"),
324 tobits = colorer(new_interface.data_width)))
325 return new_interface
326
327 def add_master(self, name=None, master=None):
328 if name is None:
329 name = "master{:d}".format(len(self.masters))
330 if name in self.masters.keys():
331 self.logger.error("{} {} as Bus Master:".format(
332 colorer(name),
333 colorer("already declared", color="red")))
334 self.logger.error(self)
335 raise
336 master = self.add_adapter(name, master, "m2s")
337 self.masters[name] = master
338 self.logger.info("{} {} as Bus Master.".format(
339 colorer(name, color="underline"),
340 colorer("added", color="green")))
341
342 def add_slave(self, name=None, slave=None, region=None):
343 no_name = name is None
344 no_region = region is None
345 if no_name and no_region:
346 self.logger.error("Please {} {} or/and {} of Bus Slave.".format(
347 colorer("specify", color="red"),
348 colorer("name"),
349 colorer("region")))
350 raise
351 if no_name:
352 name = "slave{:d}".format(len(self.slaves))
353 if no_region:
354 region = self.regions.get(name, None)
355 if region is None:
356 self.logger.error("{} Region {}.".format(
357 colorer(name),
358 colorer("not found", color="red")))
359 raise
360 else:
361 self.add_region(name, region)
362 if name in self.slaves.keys():
363 self.logger.error("{} {} as Bus Slave:".format(
364 colorer(name),
365 colorer("already declared", color="red")))
366 self.logger.error(self)
367 raise
368 slave = self.add_adapter(name, slave, "s2m")
369 self.slaves[name] = slave
370 self.logger.info("{} {} as Bus Slave.".format(
371 colorer(name, color="underline"),
372 colorer("added", color="green")))
373
374 # Str ------------------------------------------------------------------------------------------
375 def __str__(self):
376 r = "{}-bit {} Bus, {}GiB Address Space.\n".format(
377 colorer(self.data_width), colorer(self.standard), colorer(2**self.address_width/2**30))
378 r += "IO Regions: ({})\n".format(len(self.io_regions.keys())) if len(self.io_regions.keys()) else ""
379 io_regions = {k: v for k, v in sorted(self.io_regions.items(), key=lambda item: item[1].origin)}
380 for name, region in io_regions.items():
381 r += colorer(name, color="underline") + " "*(20-len(name)) + ": " + str(region) + "\n"
382 r += "Bus Regions: ({})\n".format(len(self.regions.keys())) if len(self.regions.keys()) else ""
383 regions = {k: v for k, v in sorted(self.regions.items(), key=lambda item: item[1].origin)}
384 for name, region in regions.items():
385 r += colorer(name, color="underline") + " "*(20-len(name)) + ": " + str(region) + "\n"
386 r += "Bus Masters: ({})\n".format(len(self.masters.keys())) if len(self.masters.keys()) else ""
387 for name in self.masters.keys():
388 r += "- {}\n".format(colorer(name, color="underline"))
389 r += "Bus Slaves: ({})\n".format(len(self.slaves.keys())) if len(self.slaves.keys()) else ""
390 for name in self.slaves.keys():
391 r += "- {}\n".format(colorer(name, color="underline"))
392 r = r[:-1]
393 return r
394
395 # SoCLocHandler --------------------------------------------------------------------------------------
396
397 class SoCLocHandler(Module):
398 # Creation -------------------------------------------------------------------------------------
399 def __init__(self, name, n_locs):
400 self.name = name
401 self.locs = {}
402 self.n_locs = n_locs
403
404 # Add ------------------------------------------------------------------------------------------
405 def add(self, name, n=None, use_loc_if_exists=False):
406 allocated = False
407 if not (use_loc_if_exists and name in self.locs.keys()):
408 if name in self.locs.keys():
409 self.logger.error("{} {} name {}.".format(
410 colorer(name), self.name, colorer("already used", color="red")))
411 self.logger.error(self)
412 raise
413 if n in self.locs.values():
414 self.logger.error("{} {} Location {}.".format(
415 colorer(n), self.name, colorer("already used", color="red")))
416 self.logger.error(self)
417 raise
418 if n is None:
419 allocated = True
420 n = self.alloc(name)
421 else:
422 if n < 0:
423 self.logger.error("{} {} Location should be {}.".format(
424 colorer(n),
425 self.name,
426 colorer("positive", color="red")))
427 raise
428 if n > self.n_locs:
429 self.logger.error("{} {} Location {} than maximum: {}.".format(
430 colorer(n),
431 self.name,
432 colorer("higher", color="red"),
433 colorer(self.n_locs)))
434 raise
435 self.locs[name] = n
436 else:
437 n = self.locs[name]
438 self.logger.info("{} {} {} at Location {}.".format(
439 colorer(name, color="underline"),
440 self.name,
441 colorer("allocated" if allocated else "added", color="cyan" if allocated else "green"),
442 colorer(n)))
443
444 # Alloc ----------------------------------------------------------------------------------------
445 def alloc(self, name):
446 for n in range(self.n_locs):
447 if n not in self.locs.values():
448 return n
449 self.logger.error("Not enough Locations.")
450 self.logger.error(self)
451 raise
452
453 # Str ------------------------------------------------------------------------------------------
454 def __str__(self):
455 r = "{} Locations: ({})\n".format(self.name, len(self.locs.keys())) if len(self.locs.keys()) else ""
456 locs = {k: v for k, v in sorted(self.locs.items(), key=lambda item: item[1])}
457 length = 0
458 for name in locs.keys():
459 if len(name) > length: length = len(name)
460 for name in locs.keys():
461 r += "- {}{}: {}\n".format(colorer(name, color="underline"), " "*(length + 1 - len(name)), colorer(self.locs[name]))
462 return r
463
464 # SoCCSRHandler ------------------------------------------------------------------------------------
465
466 class SoCCSRHandler(SoCLocHandler):
467 supported_data_width = [8, 32]
468 supported_address_width = [14+i for i in range(4)]
469 supported_alignment = [32]
470 supported_paging = [0x800*2**i for i in range(4)]
471
472 # Creation -------------------------------------------------------------------------------------
473 def __init__(self, data_width=32, address_width=14, alignment=32, paging=0x800, reserved_csrs={}):
474 SoCLocHandler.__init__(self, "CSR", n_locs=alignment//8*(2**address_width)//paging)
475 self.logger = logging.getLogger("SoCCSRHandler")
476 self.logger.info("Creating CSR Handler...")
477
478 # Check Data Width
479 if data_width not in self.supported_data_width:
480 self.logger.error("Unsupported {} {}, supporteds: {:s}".format(
481 colorer("Data Width", color="red"),
482 colorer(data_width),
483 colorer(", ".join(str(x) for x in self.supported_data_width))))
484 raise
485
486 # Check Address Width
487 if address_width not in self.supported_address_width:
488 self.logger.error("Unsupported {} {} supporteds: {:s}".format(
489 colorer("Address Width", color="red"),
490 colorer(address_width),
491 colorer(", ".join(str(x) for x in self.supported_address_width))))
492 raise
493
494 # Check Alignment
495 if alignment not in self.supported_alignment:
496 self.logger.error("Unsupported {}: {} supporteds: {:s}".format(
497 colorer("Alignment", color="red"),
498 colorer(alignment),
499 colorer(", ".join(str(x) for x in self.supported_alignment))))
500 raise
501 if data_width > alignment:
502 self.logger.error("Alignment ({}) {} Data Width ({})".format(
503 colorer(alignment),
504 colorer("should be >=", color="red"),
505 colorer(data_width)))
506 raise
507
508 # Check Paging
509 if paging not in self.supported_paging:
510 self.logger.error("Unsupported {} 0x{}, supporteds: {:s}".format(
511 colorer("Paging", color="red"),
512 colorer("{:x}".format(paging)),
513 colorer(", ".join("0x{:x}".format(x) for x in self.supported_paging))))
514 raise
515
516 # Create CSR Handler
517 self.data_width = data_width
518 self.address_width = address_width
519 self.alignment = alignment
520 self.paging = paging
521 self.masters = {}
522 self.regions = {}
523 self.logger.info("{}-bit CSR Bus, {}-bit Aligned, {}KiB Address Space, {}B Paging (Up to {} Locations).".format(
524 colorer(self.data_width),
525 colorer(self.alignment),
526 colorer(2**self.address_width/2**10),
527 colorer(self.paging),
528 colorer(self.n_locs)))
529
530 # Adding reserved CSRs
531 self.logger.info("Adding {} CSRs...".format(colorer("reserved", color="cyan")))
532 for name, n in reserved_csrs.items():
533 self.add(name, n)
534
535 self.logger.info("CSR Handler {}.".format(colorer("created", color="green")))
536
537 # Add Master -----------------------------------------------------------------------------------
538 def add_master(self, name=None, master=None):
539 if name is None:
540 name = "master{:d}".format(len(self.masters))
541 if name in self.masters.keys():
542 self.logger.error("{} {} as CSR Master:".format(
543 colorer(name),
544 colorer("already declared", color="red")))
545 self.logger.error(self)
546 raise
547 if master.data_width != self.data_width:
548 self.logger.error("{} Master/Handler Data Width {} ({} vs {}).".format(
549 colorer(name),
550 colorer("missmatch", color="red"),
551 colorer(master.data_width),
552 colorer(self.data_width)))
553 raise
554 self.masters[name] = master
555 self.logger.info("{} {} as CSR Master.".format(
556 colorer(name, color="underline"),
557 colorer("added", color="green")))
558
559 # Add Region -----------------------------------------------------------------------------------
560 def add_region(self, name, region):
561 # FIXME: add checks
562 self.regions[name] = region
563
564 # Address map ----------------------------------------------------------------------------------
565 def address_map(self, name, memory):
566 if memory is not None:
567 name = name + "_" + memory.name_override
568 if self.locs.get(name, None) is None:
569 self.logger.error("CSR {} {}.".format(
570 colorer(name),
571 colorer("not found", color="red")))
572 self.logger.error(self)
573 raise
574 return self.locs[name]
575
576 # Str ------------------------------------------------------------------------------------------
577 def __str__(self):
578 r = "{}-bit CSR Bus, {}-bit Aligned, {}KiB Address Space, {}B Paging (Up to {} Locations).\n".format(
579 colorer(self.data_width),
580 colorer(self.alignment),
581 colorer(2**self.address_width/2**10),
582 colorer(self.paging),
583 colorer(self.n_locs))
584 r += SoCLocHandler.__str__(self)
585 r = r[:-1]
586 return r
587
588 # SoCIRQHandler ------------------------------------------------------------------------------------
589
590 class SoCIRQHandler(SoCLocHandler):
591 # Creation -------------------------------------------------------------------------------------
592 def __init__(self, n_irqs=32, reserved_irqs={}):
593 SoCLocHandler.__init__(self, "IRQ", n_locs=n_irqs)
594 self.logger = logging.getLogger("SoCIRQHandler")
595 self.logger.info("Creating IRQ Handler...")
596
597 # Check IRQ Number
598 if n_irqs > 32:
599 self.logger.error("Unsupported IRQs number: {} supporteds: {:s}".format(
600 colorer(n, color="red"), colorer("Up to 32", color="green")))
601 raise
602
603 # Create IRQ Handler
604 self.logger.info("IRQ Handler (up to {} Locations).".format(colorer(n_irqs)))
605
606 # Adding reserved IRQs
607 self.logger.info("Adding {} IRQs...".format(colorer("reserved", color="cyan")))
608 for name, n in reserved_irqs.items():
609 self.add(name, n)
610
611 self.logger.info("IRQ Handler {}.".format(colorer("created", color="green")))
612
613 # Str ------------------------------------------------------------------------------------------
614 def __str__(self):
615 r ="IRQ Handler (up to {} Locations).\n".format(colorer(self.n_locs))
616 r += SoCLocHandler.__str__(self)
617 r = r[:-1]
618 return r
619
620 # SoCController ------------------------------------------------------------------------------------
621
622 class SoCController(Module, AutoCSR):
623 def __init__(self,
624 with_reset = True,
625 with_scratch = True,
626 with_errors = True):
627
628 if with_reset:
629 self._reset = CSRStorage(1, description="""Write a ``1`` to this register to reset the SoC.""")
630 if with_scratch:
631 self._scratch = CSRStorage(32, reset=0x12345678, description="""
632 Use this register as a scratch space to verify that software read/write accesses
633 to the Wishbone/CSR bus are working correctly. The initial reset value of 0x1234578
634 can be used to verify endianness.""")
635 if with_errors:
636 self._bus_errors = CSRStatus(32, description="Total number of Wishbone bus errors (timeouts) since start.")
637
638 # # #
639
640 # Reset
641 if with_reset:
642 self.reset = Signal()
643 self.comb += self.reset.eq(self._reset.re)
644
645 # Errors
646 if with_errors:
647 self.bus_error = Signal()
648 bus_errors = Signal(32)
649 self.sync += [
650 If(bus_errors != (2**len(bus_errors)-1),
651 If(self.bus_error, bus_errors.eq(bus_errors + 1))
652 )
653 ]
654 self.comb += self._bus_errors.status.eq(bus_errors)
655
656 # SoC ----------------------------------------------------------------------------------------------
657
658 class SoC(Module):
659 mem_map = {}
660 def __init__(self, platform, sys_clk_freq,
661 bus_standard = "wishbone",
662 bus_data_width = 32,
663 bus_address_width = 32,
664 bus_timeout = 1e6,
665 bus_reserved_regions = {},
666
667 csr_data_width = 32,
668 csr_address_width = 14,
669 csr_paging = 0x800,
670 csr_reserved_csrs = {},
671
672 irq_n_irqs = 32,
673 irq_reserved_irqs = {},
674 ):
675
676 self.logger = logging.getLogger("SoC")
677 self.logger.info(colorer(" __ _ __ _ __ ", color="bright"))
678 self.logger.info(colorer(" / / (_) /____ | |/_/ ", color="bright"))
679 self.logger.info(colorer(" / /__/ / __/ -_)> < ", color="bright"))
680 self.logger.info(colorer(" /____/_/\\__/\\__/_/|_| ", color="bright"))
681 self.logger.info(colorer(" Build your hardware, easily!", color="bright"))
682
683 self.logger.info(colorer("-"*80, color="bright"))
684 self.logger.info(colorer("Creating SoC... ({})".format(build_time())))
685 self.logger.info(colorer("-"*80, color="bright"))
686 self.logger.info("FPGA device : {}.".format(platform.device))
687 self.logger.info("System clock: {:3.2f}MHz.".format(sys_clk_freq/1e6))
688
689 # SoC attributes ---------------------------------------------------------------------------
690 self.platform = platform
691 self.sys_clk_freq = sys_clk_freq
692 self.constants = {}
693 self.csr_regions = {}
694
695 # SoC Bus Handler --------------------------------------------------------------------------
696 self.submodules.bus = SoCBusHandler(
697 standard = bus_standard,
698 data_width = bus_data_width,
699 address_width = bus_address_width,
700 timeout = bus_timeout,
701 reserved_regions = bus_reserved_regions,
702 )
703
704 # SoC Bus Handler --------------------------------------------------------------------------
705 self.submodules.csr = SoCCSRHandler(
706 data_width = csr_data_width,
707 address_width = csr_address_width,
708 alignment = 32,
709 paging = csr_paging,
710 reserved_csrs = csr_reserved_csrs,
711 )
712
713 # SoC IRQ Handler --------------------------------------------------------------------------
714 self.submodules.irq = SoCIRQHandler(
715 n_irqs = irq_n_irqs,
716 reserved_irqs = irq_reserved_irqs
717 )
718
719 self.logger.info(colorer("-"*80, color="bright"))
720 self.logger.info(colorer("Initial SoC:"))
721 self.logger.info(colorer("-"*80, color="bright"))
722 self.logger.info(self.bus)
723 self.logger.info(self.csr)
724 self.logger.info(self.irq)
725 self.logger.info(colorer("-"*80, color="bright"))
726
727 self.add_config("CLOCK_FREQUENCY", int(sys_clk_freq))
728
729 # SoC Helpers ----------------------------------------------------------------------------------
730 def check_if_exists(self, name):
731 if hasattr(self, name):
732 self.logger.error("{} SubModule already {}.".format(
733 colorer(name),
734 colorer("declared", color="red")))
735 raise
736
737 def add_constant(self, name, value=None):
738 name = name.upper()
739 if name in self.constants.keys():
740 self.logger.error("{} Constant already {}.".format(
741 colorer(name),
742 colorer("declared", color="red")))
743 raise
744 self.constants[name] = SoCConstant(value)
745
746 def add_config(self, name, value=None):
747 name = "CONFIG_" + name
748 if isinstance(value, str):
749 self.add_constant(name + "_" + value)
750 else:
751 self.add_constant(name, value)
752
753 # SoC Main Components --------------------------------------------------------------------------
754 def add_controller(self, name="ctrl", **kwargs):
755 self.check_if_exists(name)
756 setattr(self.submodules, name, SoCController(**kwargs))
757 self.csr.add(name, use_loc_if_exists=True)
758
759 def add_ram(self, name, origin, size, contents=[], mode="rw"):
760 ram_bus = wishbone.Interface(data_width=self.bus.data_width)
761 ram = wishbone.SRAM(size, bus=ram_bus, init=contents, read_only=(mode == "r"))
762 self.bus.add_slave(name, ram.bus, SoCRegion(origin=origin, size=size, mode=mode))
763 self.check_if_exists(name)
764 self.logger.info("RAM {} {} {}.".format(
765 colorer(name),
766 colorer("added", color="green"),
767 self.bus.regions[name]))
768 setattr(self.submodules, name, ram)
769
770 def add_rom(self, name, origin, size, contents=[]):
771 self.add_ram(name, origin, size, contents, mode="r")
772
773 def add_csr_bridge(self, origin):
774 self.submodules.csr_bridge = wishbone.Wishbone2CSR(
775 bus_csr = csr_bus.Interface(
776 address_width = self.csr.address_width,
777 data_width = self.csr.data_width))
778 csr_size = 2**(self.csr.address_width + 2)
779 csr_region = SoCRegion(origin=origin, size=csr_size, cached=False)
780 self.bus.add_slave("csr", self.csr_bridge.wishbone, csr_region)
781 self.csr.add_master(name="bridge", master=self.csr_bridge.csr)
782 self.add_config("CSR_DATA_WIDTH", self.csr.data_width)
783 self.add_config("CSR_ALIGNMENT", self.csr.alignment)
784
785 def add_cpu(self, name="vexriscv", variant="standard", cls=None, reset_address=None):
786 if name not in cpu.CPUS.keys():
787 self.logger.error("{} CPU {}, supporteds: {}.".format(
788 colorer(name),
789 colorer("not supported", color="red"),
790 colorer(", ".join(cpu.CPUS.keys()))))
791 raise
792 # Add CPU
793 cpu_cls = cls if cls is not None else cpu.CPUS[name]
794 if variant not in cpu_cls.variants:
795 self.logger.error("{} CPU variant {}, supporteds: {}.".format(
796 colorer(variant),
797 colorer("not supported", color="red"),
798 colorer(", ".join(cpu_cls.variants))))
799 raise
800 self.submodules.cpu = cpu_cls(self.platform, variant)
801 # Update SoC with CPU constraints
802 for n, (origin, size) in enumerate(self.cpu.io_regions.items()):
803 self.bus.add_region("io{}".format(n), SoCIORegion(origin=origin, size=size, cached=False))
804 self.mem_map.update(self.cpu.mem_map) # FIXME
805 # Add Bus Masters/CSR/IRQs
806 if not isinstance(self.cpu, cpu.CPUNone):
807 if reset_address is None:
808 reset_address = self.mem_map["rom"]
809 self.cpu.set_reset_address(reset_address)
810 for n, cpu_bus in enumerate(self.cpu.periph_buses):
811 self.bus.add_master(name="cpu_bus{}".format(n), master=cpu_bus)
812 self.csr.add("cpu", use_loc_if_exists=True)
813 if hasattr(self.cpu, "interrupt"):
814 for name, loc in self.cpu.interrupts.items():
815 self.irq.add(name, loc)
816 self.add_config("CPU_HAS_INTERRUPT")
817
818 # Create optional DMA Bus (for Cache Coherence)
819 if hasattr(self.cpu, "dma_bus"):
820 self.submodules.dma_bus = SoCBusHandler(
821 name = "SoCDMABusHandler",
822 standard = "wishbone",
823 data_width = self.bus.data_width,
824 )
825 dma_bus = wishbone.Interface(data_width=self.bus.data_width)
826 self.dma_bus.add_slave("dma", slave=dma_bus, region=SoCRegion(origin=0x00000000, size=0x80000000)) # FIXME: size
827 self.submodules += wishbone.Converter(dma_bus, self.cpu.dma_bus)
828
829 # Connect SoCController's reset to CPU reset
830 if hasattr(self, "ctrl"):
831 if hasattr(self.ctrl, "reset"):
832 self.comb += self.cpu.reset.eq(self.ctrl.reset)
833 self.add_config("CPU_RESET_ADDR", reset_address)
834 # Add constants
835 self.add_config("CPU_TYPE", str(name))
836 self.add_config("CPU_VARIANT", str(variant.split('+')[0]))
837 self.add_constant("CONFIG_CPU_HUMAN_NAME", getattr(self.cpu, "human_name", "Unknown"))
838 if hasattr(self.cpu, "nop"):
839 self.add_constant("CONFIG_CPU_NOP", self.cpu.nop)
840
841 def add_timer(self, name="timer0"):
842 self.check_if_exists(name)
843 setattr(self.submodules, name, Timer())
844 self.csr.add(name, use_loc_if_exists=True)
845 if hasattr(self.cpu, "interrupt"):
846 self.irq.add(name, use_loc_if_exists=True)
847
848 # SoC finalization -----------------------------------------------------------------------------
849 def do_finalize(self):
850 self.logger.info(colorer("-"*80, color="bright"))
851 self.logger.info(colorer("Finalized SoC:"))
852 self.logger.info(colorer("-"*80, color="bright"))
853 self.logger.info(self.bus)
854 if hasattr(self, "dma_bus"):
855 self.logger.info(self.dma_bus)
856 self.logger.info(self.csr)
857 self.logger.info(self.irq)
858 self.logger.info(colorer("-"*80, color="bright"))
859
860 # SoC Bus Interconnect ---------------------------------------------------------------------
861 if len(self.bus.masters) and len(self.bus.slaves):
862 # If 1 bus_master, 1 bus_slave and no address translation, use InterconnectPointToPoint.
863 if ((len(self.bus.masters) == 1) and
864 (len(self.bus.slaves) == 1) and
865 (next(iter(self.bus.regions.values())).origin == 0)):
866 self.submodules.bus_interconnect = wishbone.InterconnectPointToPoint(
867 master = next(iter(self.bus.masters.values())),
868 slave = next(iter(self.bus.slaves.values())))
869 # Otherwise, use InterconnectShared.
870 else:
871 self.submodules.bus_interconnect = wishbone.InterconnectShared(
872 masters = self.bus.masters.values(),
873 slaves = [(self.bus.regions[n].decoder(self.bus), s) for n, s in self.bus.slaves.items()],
874 register = True,
875 timeout_cycles = self.bus.timeout)
876 if hasattr(self, "ctrl") and self.bus.timeout is not None:
877 if hasattr(self.ctrl, "bus_error"):
878 self.comb += self.ctrl.bus_error.eq(self.bus_interconnect.timeout.error)
879 self.bus.logger.info("Interconnect: {} ({} <-> {}).".format(
880 colorer(self.bus_interconnect.__class__.__name__),
881 colorer(len(self.bus.masters)),
882 colorer(len(self.bus.slaves))))
883 self.add_constant("CONFIG_BUS_STANDARD", self.bus.standard.upper())
884 self.add_constant("CONFIG_BUS_DATA_WIDTH", self.bus.data_width)
885 self.add_constant("CONFIG_BUS_ADDRESS_WIDTH", self.bus.address_width)
886
887 # SoC DMA Bus Interconnect (Cache Coherence) -----------------------------------------------
888 if hasattr(self, "dma_bus"):
889 if len(self.dma_bus.masters) and len(self.dma_bus.slaves):
890 # If 1 bus_master, 1 bus_slave and no address translation, use InterconnectPointToPoint.
891 if ((len(self.dma_bus.masters) == 1) and
892 (len(self.dma_bus.slaves) == 1) and
893 (next(iter(self.dma_bus.regions.values())).origin == 0)):
894 self.submodules.bus_interconnect = wishbone.InterconnectPointToPoint(
895 master = next(iter(self.dma_bus.masters.values())),
896 slave = next(iter(self.dma_bus.slaves.values())))
897 # Otherwise, use InterconnectShared.
898 else:
899 self.submodules.dma_bus_interconnect = wishbone.InterconnectShared(
900 masters = self.dma_bus.masters.values(),
901 slaves = [(self.dma_bus.regions[n].decoder(self.dma_bus), s) for n, s in self.dma_bus.slaves.items()],
902 register = True)
903 self.bus.logger.info("DMA Interconnect: {} ({} <-> {}).".format(
904 colorer(self.dma_bus_interconnect.__class__.__name__),
905 colorer(len(self.dma_bus.masters)),
906 colorer(len(self.dma_bus.slaves))))
907 self.add_constant("CONFIG_CPU_HAS_DMA_BUS")
908
909 # SoC CSR Interconnect ---------------------------------------------------------------------
910 self.submodules.csr_bankarray = csr_bus.CSRBankArray(self,
911 address_map = self.csr.address_map,
912 data_width = self.csr.data_width,
913 address_width = self.csr.address_width,
914 alignment = self.csr.alignment,
915 paging = self.csr.paging,
916 soc_bus_data_width = self.bus.data_width)
917 if len(self.csr.masters):
918 self.submodules.csr_interconnect = csr_bus.InterconnectShared(
919 masters = list(self.csr.masters.values()),
920 slaves = self.csr_bankarray.get_buses())
921
922 # Add CSRs regions
923 for name, csrs, mapaddr, rmap in self.csr_bankarray.banks:
924 self.csr.add_region(name, SoCCSRRegion(
925 origin = (self.bus.regions["csr"].origin + self.csr.paging*mapaddr),
926 busword = self.csr.data_width,
927 obj = csrs))
928
929 # Add Memory regions
930 for name, memory, mapaddr, mmap in self.csr_bankarray.srams:
931 self.csr.add_region(name + "_" + memory.name_override, SoCCSRRegion(
932 origin = (self.bus.regions["csr"].origin + self.csr.paging*mapaddr),
933 busword = self.csr.data_width,
934 obj = memory))
935
936 # Sort CSR regions by origin
937 self.csr.regions = {k: v for k, v in sorted(self.csr.regions.items(), key=lambda item: item[1].origin)}
938
939 # Add CSRs / Config items to constants
940 for name, constant in self.csr_bankarray.constants:
941 self.add_constant(name + "_" + constant.name, constant.value.value)
942
943 # SoC CPU Check ----------------------------------------------------------------------------
944 if not isinstance(self.cpu, cpu.CPUNone):
945 if "sram" not in self.bus.regions.keys():
946 self.logger.error("CPU needs {} Region to be {} as Bus or Linker Region.".format(
947 colorer("sram"),
948 colorer("defined", color="red")))
949 self.logger.error(self.bus)
950 raise
951 cpu_reset_address_valid = False
952 for name, container in self.bus.regions.items():
953 if self.bus.check_region_is_in(
954 region = SoCRegion(origin=self.cpu.reset_address, size=self.bus.data_width//8),
955 container = container):
956 cpu_reset_address_valid = True
957 if name == "rom":
958 self.cpu.use_rom = True
959 if not cpu_reset_address_valid:
960 self.logger.error("CPU needs {} to be in a {} Region.".format(
961 colorer("reset address 0x{:08x}".format(self.cpu.reset_address)),
962 colorer("defined", color="red")))
963 self.logger.error(self.bus)
964 raise
965
966 # SoC IRQ Interconnect ---------------------------------------------------------------------
967 if hasattr(self, "cpu"):
968 if hasattr(self.cpu, "interrupt"):
969 for name, loc in sorted(self.irq.locs.items()):
970 if name in self.cpu.interrupts.keys():
971 continue
972 if hasattr(self, name):
973 module = getattr(self, name)
974 if not hasattr(module, "ev"):
975 self.logger.error("EventManager {} in {} SubModule.".format(
976 colorer("not found", color="red"),
977 colorer(name)))
978 raise
979 self.comb += self.cpu.interrupt[loc].eq(module.ev.irq)
980 self.add_constant(name + "_INTERRUPT", loc)
981
982 # SoC build ------------------------------------------------------------------------------------
983 def build(self, *args, **kwargs):
984 self.build_name = kwargs.pop("build_name", self.platform.name)
985 kwargs.update({"build_name": self.build_name})
986 return self.platform.build(self, *args, **kwargs)
987
988 # LiteXSoC -----------------------------------------------------------------------------------------
989
990 class LiteXSoC(SoC):
991 # Add Identifier -------------------------------------------------------------------------------
992 def add_identifier(self, name="identifier", identifier="LiteX SoC", with_build_time=True):
993 self.check_if_exists(name)
994 if with_build_time:
995 identifier += " " + build_time()
996 setattr(self.submodules, name, Identifier(identifier))
997 self.csr.add(name + "_mem", use_loc_if_exists=True)
998
999 # Add UART -------------------------------------------------------------------------------------
1000 def add_uart(self, name, baudrate=115200, fifo_depth=16):
1001 from litex.soc.cores import uart
1002
1003 # Stub / Stream
1004 if name in ["stub", "stream"]:
1005 self.submodules.uart = uart.UART(tx_fifo_depth=0, rx_fifo_depth=0)
1006 if name == "stub":
1007 self.comb += self.uart.sink.ready.eq(1)
1008
1009 # UARTBone / Bridge
1010 elif name in ["uartbone", "bridge"]:
1011 self.add_uartbone(baudrate=baudrate)
1012
1013 # Crossover
1014 elif name in ["crossover"]:
1015 self.submodules.uart = uart.UARTCrossover()
1016
1017 # Model/Sim
1018 elif name in ["model", "sim"]:
1019 self.submodules.uart_phy = uart.RS232PHYModel(self.platform.request("serial"))
1020 self.submodules.uart = ResetInserter()(uart.UART(self.uart_phy,
1021 tx_fifo_depth = fifo_depth,
1022 rx_fifo_depth = fifo_depth))
1023
1024 # JTAG Atlantic
1025 elif name in ["jtag_atlantic"]:
1026 from litex.soc.cores.jtag import JTAGAtlantic
1027 self.submodules.uart_phy = JTAGAtlantic()
1028 self.submodules.uart = ResetInserter()(uart.UART(self.uart_phy,
1029 tx_fifo_depth = fifo_depth,
1030 rx_fifo_depth = fifo_depth))
1031
1032 # JTAG UART
1033 elif name in ["jtag_uart"]:
1034 from litex.soc.cores.jtag import JTAGPHY
1035 self.submodules.uart_phy = JTAGPHY(device=self.platform.device)
1036 self.submodules.uart = ResetInserter()(uart.UART(self.uart_phy,
1037 tx_fifo_depth = fifo_depth,
1038 rx_fifo_depth = fifo_depth))
1039
1040 # USB ACM (with ValentyUSB core)
1041 elif name in ["usb_acm"]:
1042 import valentyusb.usbcore.io as usbio
1043 import valentyusb.usbcore.cpu.cdc_eptri as cdc_eptri
1044 usb_pads = self.platform.request("usb")
1045 usb_iobuf = usbio.IoBuf(usb_pads.d_p, usb_pads.d_n, usb_pads.pullup)
1046 self.submodules.uart = cdc_eptri.CDCUsb(usb_iobuf)
1047
1048 # Classic UART
1049 else:
1050 self.submodules.uart_phy = uart.UARTPHY(
1051 pads = self.platform.request(name),
1052 clk_freq = self.sys_clk_freq,
1053 baudrate = baudrate)
1054 self.submodules.uart = ResetInserter()(uart.UART(self.uart_phy,
1055 tx_fifo_depth = fifo_depth,
1056 rx_fifo_depth = fifo_depth))
1057
1058 self.csr.add("uart_phy", use_loc_if_exists=True)
1059 self.csr.add("uart", use_loc_if_exists=True)
1060 if hasattr(self.cpu, "interrupt"):
1061 self.irq.add("uart", use_loc_if_exists=True)
1062 else:
1063 self.add_constant("UART_POLLING")
1064
1065 # Add UARTbone ---------------------------------------------------------------------------------
1066 def add_uartbone(self, name="serial", baudrate=115200):
1067 from litex.soc.cores import uart
1068 self.submodules.uartbone = uart.UARTBone(
1069 pads = self.platform.request(name),
1070 clk_freq = self.sys_clk_freq,
1071 baudrate = baudrate)
1072 self.bus.add_master(name="uartbone", master=self.uartbone.wishbone)
1073
1074 # Add SDRAM ------------------------------------------------------------------------------------
1075 def add_sdram(self, name, phy, module, origin, size=None, with_soc_interconnect=True,
1076 l2_cache_size = 8192,
1077 l2_cache_min_data_width = 128,
1078 l2_cache_reverse = True,
1079 l2_cache_full_memory_we = True,
1080 **kwargs):
1081
1082 # Imports
1083 from litedram.common import LiteDRAMNativePort
1084 from litedram.core import LiteDRAMCore
1085 from litedram.frontend.wishbone import LiteDRAMWishbone2Native
1086 from litedram.frontend.axi import LiteDRAMAXI2Native
1087
1088 # LiteDRAM core
1089 self.submodules.sdram = LiteDRAMCore(
1090 phy = phy,
1091 geom_settings = module.geom_settings,
1092 timing_settings = module.timing_settings,
1093 clk_freq = self.sys_clk_freq,
1094 **kwargs)
1095 self.csr.add("sdram")
1096
1097 # Save SPD data to be able to verify it at runtime
1098 if hasattr(module, "_spd_data"):
1099 # pack the data into words of bus width
1100 bytes_per_word = self.bus.data_width // 8
1101 mem = [0] * ceil(len(module._spd_data) / bytes_per_word)
1102 for i in range(len(mem)):
1103 for offset in range(bytes_per_word):
1104 mem[i] <<= 8
1105 if self.cpu.endianness == "little":
1106 offset = bytes_per_word - 1 - offset
1107 spd_byte = i * bytes_per_word + offset
1108 if spd_byte < len(module._spd_data):
1109 mem[i] |= module._spd_data[spd_byte]
1110 self.add_rom(
1111 name="spd",
1112 origin=self.mem_map.get("spd", None),
1113 size=len(module._spd_data),
1114 contents=mem,
1115 )
1116
1117 if not with_soc_interconnect: return
1118
1119 # Compute/Check SDRAM size
1120 sdram_size = 2**(module.geom_settings.bankbits +
1121 module.geom_settings.rowbits +
1122 module.geom_settings.colbits)*phy.settings.databits//8
1123 if size is not None:
1124 sdram_size = min(sdram_size, size)
1125
1126 # Add SDRAM region
1127 self.bus.add_region("main_ram", SoCRegion(origin=origin, size=sdram_size))
1128
1129 # SoC [<--> L2 Cache] <--> LiteDRAM --------------------------------------------------------
1130 if len(self.cpu.memory_buses):
1131 # When CPU has at least a direct memory bus, connect them directly to LiteDRAM.
1132 for mem_bus in self.cpu.memory_buses:
1133 # Request a LiteDRAM native port.
1134 port = self.sdram.crossbar.get_port()
1135 port.data_width = 2**int(log2(port.data_width)) # Round to nearest power of 2.
1136
1137 # Check if bus is an AXI bus and connect it.
1138 if isinstance(mem_bus, axi.AXIInterface):
1139 # If same data_width, connect it directly.
1140 if port.data_width == mem_bus.data_width:
1141 self.logger.info("Matching AXI MEM data width ({})\n".format(port.data_width))
1142 self.submodules += LiteDRAMAXI2Native(
1143 axi = self.cpu.mem_axi,
1144 port = port,
1145 base_address = self.bus.regions["main_ram"].origin)
1146 # If different data_width, do the adaptation and connect it via Wishbone.
1147 else:
1148 self.logger.info("Converting MEM data width: {} to {} via Wishbone".format(
1149 port.data_width,
1150 self.cpu.mem_axi.data_width))
1151 # FIXME: replace WB data-width converter with native AXI converter!!!
1152 mem_wb = wishbone.Interface(
1153 data_width = self.cpu.mem_axi.data_width,
1154 adr_width = 32-log2_int(self.cpu.mem_axi.data_width//8))
1155 # NOTE: AXI2Wishbone FSMs must be reset with the CPU!
1156 mem_a2w = ResetInserter()(axi.AXI2Wishbone(
1157 axi = self.cpu.mem_axi,
1158 wishbone = mem_wb,
1159 base_address = 0))
1160 self.comb += mem_a2w.reset.eq(ResetSignal() | self.cpu.reset)
1161 self.submodules += mem_a2w
1162 litedram_wb = wishbone.Interface(port.data_width)
1163 self.submodules += LiteDRAMWishbone2Native(
1164 wishbone = litedram_wb,
1165 port = port,
1166 base_address = origin)
1167 self.submodules += wishbone.Converter(mem_wb, litedram_wb)
1168 # Check if bus is a Native bus and connect it.
1169 if isinstance(mem_bus, LiteDRAMNativePort):
1170 # If same data_width, connect it directly.
1171 if port.data_width == mem_bus.data_width:
1172 self.comb += mem_bus.cmd.connect(port.cmd)
1173 self.comb += mem_bus.wdata.connect(port.wdata)
1174 self.comb += port.rdata.connect(mem_bus.rdata)
1175 # Else raise Error.
1176 else:
1177 raise NotImplementedError
1178 else:
1179 # When CPU has no direct memory interface, create a Wishbone Slave interface to LiteDRAM.
1180
1181 # Request a LiteDRAM native port.
1182 port = self.sdram.crossbar.get_port()
1183 port.data_width = 2**int(log2(port.data_width)) # Round to nearest power of 2.
1184
1185 # Create Wishbone Slave.
1186 wb_sdram = wishbone.Interface()
1187 self.bus.add_slave("main_ram", wb_sdram)
1188
1189 # L2 Cache
1190 if l2_cache_size != 0:
1191 # Insert L2 cache inbetween Wishbone bus and LiteDRAM
1192 l2_cache_size = max(l2_cache_size, int(2*port.data_width/8)) # Use minimal size if lower
1193 l2_cache_size = 2**int(log2(l2_cache_size)) # Round to nearest power of 2
1194 l2_cache_data_width = max(port.data_width, l2_cache_min_data_width)
1195 l2_cache = wishbone.Cache(
1196 cachesize = l2_cache_size//4,
1197 master = wb_sdram,
1198 slave = wishbone.Interface(l2_cache_data_width),
1199 reverse = l2_cache_reverse)
1200 if l2_cache_full_memory_we:
1201 l2_cache = FullMemoryWE()(l2_cache)
1202 self.submodules.l2_cache = l2_cache
1203 litedram_wb = self.l2_cache.slave
1204 else:
1205 litedram_wb = wishbone.Interface(port.data_width)
1206 self.submodules += wishbone.Converter(wb_sdram, litedram_wb)
1207 self.add_config("L2_SIZE", l2_cache_size)
1208
1209 # Wishbone Slave <--> LiteDRAM bridge
1210 self.submodules.wishbone_bridge = LiteDRAMWishbone2Native(litedram_wb, port,
1211 base_address = self.bus.regions["main_ram"].origin)
1212
1213 # Add Ethernet ---------------------------------------------------------------------------------
1214 def add_ethernet(self, name="ethmac", phy=None):
1215 # Imports
1216 from liteeth.mac import LiteEthMAC
1217 # MAC
1218 ethmac = LiteEthMAC(
1219 phy = phy,
1220 dw = 32,
1221 interface = "wishbone",
1222 endianness = self.cpu.endianness)
1223 setattr(self.submodules, name, ethmac)
1224 ethmac_region = SoCRegion(origin=self.mem_map.get(name, None), size=0x2000, cached=False)
1225 self.bus.add_slave(name=name, slave=ethmac.bus, region=ethmac_region)
1226 self.add_csr(name)
1227 self.add_interrupt(name)
1228 # Timing constraints
1229 if hasattr(phy, "crg"):
1230 eth_rx_clk = phy.crg.cd_eth_rx.clk
1231 eth_tx_clk = phy.crg.cd_eth_tx.clk
1232 else:
1233 eth_rx_clk = phy.cd_eth_rx.clk
1234 eth_tx_clk = phy.cd_eth_tx.clk
1235 self.platform.add_period_constraint(eth_rx_clk, 1e9/phy.rx_clk_freq)
1236 self.platform.add_period_constraint(eth_tx_clk, 1e9/phy.tx_clk_freq)
1237 self.platform.add_false_path_constraints(
1238 self.crg.cd_sys.clk,
1239 eth_rx_clk,
1240 eth_tx_clk)
1241
1242 # Add Etherbone --------------------------------------------------------------------------------
1243 def add_etherbone(self, name="etherbone", phy=None,
1244 mac_address = 0x10e2d5000000,
1245 ip_address = "192.168.1.50",
1246 udp_port = 1234):
1247 # Imports
1248 from liteeth.core import LiteEthUDPIPCore
1249 from liteeth.frontend.etherbone import LiteEthEtherbone
1250 # Core
1251 ethcore = LiteEthUDPIPCore(
1252 phy = self.ethphy,
1253 mac_address = mac_address,
1254 ip_address = ip_address,
1255 clk_freq = self.clk_freq)
1256 ethcore = ClockDomainsRenamer("eth_tx")(ethcore)
1257 self.submodules += ethcore
1258
1259 # Clock domain renaming
1260 self.clock_domains.cd_etherbone = ClockDomain("etherbone")
1261 self.comb += self.cd_etherbone.clk.eq(ClockSignal("sys"))
1262 self.comb += self.cd_etherbone.rst.eq(ResetSignal("sys"))
1263
1264 # Etherbone
1265 etherbone = LiteEthEtherbone(ethcore.udp, udp_port, cd="etherbone")
1266 setattr(self.submodules, name, etherbone)
1267 self.add_wb_master(etherbone.wishbone.bus)
1268 # Timing constraints
1269 if hasattr(phy, "crg"):
1270 eth_rx_clk = phy.crg.cd_eth_rx.clk
1271 eth_tx_clk = phy.crg.cd_eth_tx.clk
1272 else:
1273 eth_rx_clk = phy.cd_eth_rx.clk
1274 eth_tx_clk = phy.cd_eth_tx.clk
1275 self.platform.add_period_constraint(eth_rx_clk, 1e9/phy.rx_clk_freq)
1276 self.platform.add_period_constraint(eth_tx_clk, 1e9/phy.tx_clk_freq)
1277 self.platform.add_false_path_constraints(
1278 self.crg.cd_sys.clk,
1279 eth_rx_clk,
1280 eth_tx_clk)
1281
1282 # Add SPI Flash --------------------------------------------------------------------------------
1283 def add_spi_flash(self, name="spiflash", mode="4x", dummy_cycles=None, clk_freq=None):
1284 assert dummy_cycles is not None # FIXME: Get dummy_cycles from SPI Flash
1285 assert mode in ["1x", "4x"]
1286 if clk_freq is None: clk_freq = self.clk_freq/2 # FIXME: Get max clk_freq from SPI Flash
1287 spiflash = SpiFlash(
1288 pads = self.platform.request(name if mode == "1x" else name + mode),
1289 dummy = dummy_cycles,
1290 div = ceil(self.clk_freq/clk_freq),
1291 with_bitbang = True,
1292 endianness = self.cpu.endianness)
1293 spiflash.add_clk_primitive(self.platform.device)
1294 setattr(self.submodules, name, spiflash)
1295 self.add_memory_region(name, self.mem_map[name], 0x1000000) # FIXME: Get size from SPI Flash
1296 self.add_wb_slave(self.mem_map[name], spiflash.bus)
1297 self.add_csr(name)
1298
1299 # Add SPI SDCard -------------------------------------------------------------------------------
1300 def add_spi_sdcard(self, name="spisdcard", spi_clk_freq=400e3):
1301 pads = self.platform.request(name)
1302 if hasattr(pads, "rst"):
1303 self.comb += pads.rst.eq(0)
1304 spisdcard = SPIMaster(pads, 8, self.sys_clk_freq, spi_clk_freq)
1305 spisdcard.add_clk_divider()
1306 setattr(self.submodules, name, spisdcard)
1307 self.add_csr(name)
1308
1309 # Add SDCard -----------------------------------------------------------------------------------
1310 def add_sdcard(self, name="sdcard", mode="read+write", use_emulator=False):
1311 assert mode in ["read", "write", "read+write"]
1312 # Imports
1313 from litesdcard.emulator import SDEmulator
1314 from litesdcard.phy import SDPHY
1315 from litesdcard.core import SDCore
1316 from litesdcard.frontend.dma import SDBlock2MemDMA, SDMem2BlockDMA
1317
1318 # Emulator / Pads
1319 if use_emulator:
1320 sdemulator = SDEmulator(self.platform)
1321 self.submodules += sdemulator
1322 sdcard_pads = sdemulator.pads
1323 else:
1324 sdcard_pads = self.platform.request(name)
1325
1326 # Core
1327 self.submodules.sdphy = SDPHY(sdcard_pads, self.platform.device, self.clk_freq)
1328 self.submodules.sdcore = SDCore(self.sdphy)
1329 self.add_csr("sdphy")
1330 self.add_csr("sdcore")
1331
1332 # Block2Mem DMA
1333 if "read" in mode:
1334 bus = wishbone.Interface(data_width=self.bus.data_width, adr_width=self.bus.address_width)
1335 self.submodules.sdblock2mem = SDBlock2MemDMA(bus=bus, endianness=self.cpu.endianness)
1336 self.comb += self.sdcore.source.connect(self.sdblock2mem.sink)
1337 dma_bus = self.bus if not hasattr(self, "dma_bus") else self.dma_bus
1338 dma_bus.add_master("sdblock2mem", master=bus)
1339 self.add_csr("sdblock2mem")
1340
1341 # Mem2Block DMA
1342 if "write" in mode:
1343 bus = wishbone.Interface(data_width=self.bus.data_width, adr_width=self.bus.address_width)
1344 self.submodules.sdmem2block = SDMem2BlockDMA(bus=bus, endianness=self.cpu.endianness)
1345 self.comb += self.sdmem2block.source.connect(self.sdcore.sink)
1346 dma_bus = self.bus if not hasattr(self, "dma_bus") else self.dma_bus
1347 dma_bus.add_master("sdmem2block", master=bus)
1348 self.add_csr("sdmem2block")