qualcomm/qbox
Loading...
Searching...
No Matches
router.h
1/*
2 * Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All Rights Reserved.
3 * Author: GreenSocs 2022
4 *
5 * SPDX-License-Identifier: BSD-3-Clause
6 */
7
8#ifndef _GREENSOCS_BASE_COMPONENTS_ROUTER_H
9#define _GREENSOCS_BASE_COMPONENTS_ROUTER_H
10
11#include <cinttypes>
12#include <utility>
13#include <vector>
14#include <map>
15#include <set> // Required for std::set
16#include <limits> // Required for std::numeric_limits
17#include <memory> // Required for std::shared_ptrs
18#include <unordered_map> // Required for std::unordered_map
19#include <list> // Required for std::list
20#include <functional> // Required for std::less
21
22#define THREAD_SAFE true
23#if defined(THREAD_SAFE) and THREAD_SAFE
24#include <mutex>
25#include <shared_mutex>
26#endif
27#include <atomic>
28
29#include <cci_configuration>
30#include <systemc>
31#include <tlm>
32#include <scp/report.h>
33#include <scp/helpers.h>
34#include <cciutils.h>
35
36#include <tlm_utils/multi_passthrough_initiator_socket.h>
37#include <tlm_utils/multi_passthrough_target_socket.h>
38#include <tlm-extensions/pathid_extension.h>
39#include <tlm-extensions/underlying-dmi.h>
40
41#include <router_if.h>
42#include <module_factory_registery.h>
43#include <tlm_sockets_buswidth.h>
44
45namespace gs {
46
47template <typename Key, typename Value>
49{
50public:
51 virtual ~AddrMapCacheBase() = default;
52 virtual bool get(const Key& key, Value& value) = 0;
53 virtual void put(const Key& key, const Value& value, uint64_t size) = 0;
54 virtual void clear() = 0;
55
56 // Statistics interface
57 virtual uint64_t get_hits() const = 0;
58 virtual uint64_t get_misses() const = 0;
59 virtual void reset_stats() = 0;
60};
61
66template <typename Key, typename Value>
67class AddrMapNoCache : public AddrMapCacheBase<Key, Value>
68{
69public:
71 bool get(const Key& key, Value& value) override
72 {
73 (void)key; // Suppress unused parameter warning
74 (void)value; // Suppress unused parameter warning
75 return false;
76 }
77
79 void put(const Key& key, const Value& value, [[maybe_unused]] uint64_t size) override
80 {
81 (void)key; // Suppress unused parameter warning
82 (void)value; // Suppress unused parameter warning
83 }
84
86 void clear() override {}
87
88 // Statistics interface implementation
89 uint64_t get_hits() const override { return 0; }
90 uint64_t get_misses() const override { return 0; }
91 void reset_stats() override {}
92};
93
104template <unsigned int BUSWIDTH = DEFAULT_TLM_BUSWIDTH, template <typename, typename> class CacheType = AddrMapNoCache>
105class router : public sc_core::sc_module, public gs::router_if<BUSWIDTH>
106{
108 using TargetSocket = tlm::tlm_base_target_socket_b<BUSWIDTH, tlm::tlm_fw_transport_if<>,
109 tlm::tlm_bw_transport_if<>>;
111 using InitiatorSocket = tlm::tlm_base_initiator_socket_b<BUSWIDTH, tlm::tlm_fw_transport_if<>,
112 tlm::tlm_bw_transport_if<>>;
116 using initiator_socket_type = typename gs::router<
117 BUSWIDTH, CacheType>::template multi_passthrough_initiator_socket_spying<router<BUSWIDTH, CacheType>>;
119 using gs::router_if<BUSWIDTH>::bound_targets;
120
121 using CacheImpl = CacheType<uint64_t, std::shared_ptr<target_info>>;
140 template <typename TargetInfoType>
141 class addressMap
142 {
143 private:
150 struct Region {
151 uint64_t start;
152 uint64_t end;
153 std::shared_ptr<TargetInfoType> target;
154
155 Region(uint64_t s, uint64_t e, std::shared_ptr<TargetInfoType> t): start(s), end(e), target(t) {}
156 };
157
159 std::map<uint64_t, Region> m_regions;
160
161 CacheImpl m_cache;
162
180 void split_and_resolve(uint64_t new_start, uint64_t new_end, std::shared_ptr<TargetInfoType> new_target)
181 {
182 // Step 1: Collect all existing regions that overlap with the new region
183 std::vector<Region> overlapping_regions;
184 std::vector<uint64_t> keys_to_remove;
185
186 // Find overlapping regions using interval overlap test: (a.start < b.end && a.end > b.start)
187 for (const auto& [start_addr, region] : m_regions) {
188 if (region.start < new_end && region.end > new_start) {
189 overlapping_regions.push_back(region);
190 keys_to_remove.push_back(start_addr);
191 }
192 }
193
194 // Step 2: Remove overlapping regions from the map (they'll be re-added after splitting)
195 for (uint64_t key : keys_to_remove) {
196 m_regions.erase(key);
197 }
198
199 // Step 3: Create intervals for all regions that need to be resolved
200 struct Interval {
201 uint64_t start, end;
202 std::shared_ptr<TargetInfoType> target;
203 uint32_t priority;
204
205 Interval(uint64_t s, uint64_t e, std::shared_ptr<TargetInfoType> t)
206 : start(s), end(e), target(t), priority(t->priority)
207 {
208 }
209 };
210
211 std::vector<Interval> intervals;
212 intervals.reserve(overlapping_regions.size() + 1); // Optimize allocation
213
214 // Add the new region
215 intervals.emplace_back(new_start, new_end, new_target);
216
217 // Add all overlapping existing regions
218 for (const Region& region : overlapping_regions) {
219 intervals.emplace_back(region.start, region.end, region.target);
220 }
221
222 // Step 4: Create sorted list of all boundary points for segmentation
223 std::set<uint64_t> boundaries;
224 for (const Interval& interval : intervals) {
225 boundaries.insert(interval.start);
226 boundaries.insert(interval.end);
227 }
228
229 // Step 5: Process each segment between boundaries and resolve conflicts
230 auto boundary_it = boundaries.begin();
231 while (boundary_it != boundaries.end()) {
232 uint64_t seg_start = *boundary_it;
233 ++boundary_it;
234 if (boundary_it == boundaries.end()) break;
235 uint64_t seg_end = *boundary_it;
236
237 // Find the highest priority target for this segment
238 std::shared_ptr<TargetInfoType> best_target = nullptr;
239 uint32_t best_priority = UINT32_MAX;
240
241 for (const Interval& interval : intervals) {
242 // Check if this interval covers the current segment
243 if (interval.start <= seg_start && interval.end >= seg_end) {
244 if (interval.priority < best_priority) {
245 best_priority = interval.priority;
246 best_target = interval.target;
247 }
248 }
249 }
250
251 // Add the resolved segment to the final map
252 if (best_target) {
253 m_regions.emplace(seg_start, Region(seg_start, seg_end, best_target));
254 }
255 }
256
257 // Step 6: Check for completely shadowed regions and issue warnings
258 for (const Interval& interval : intervals) {
259 // Skip the newly added region (it can't be shadowed by itself)
260 if (interval.start == new_start && interval.end == new_end && interval.target == new_target) {
261 continue;
262 }
263
264 // Check if this interval is completely covered by higher priority regions
265 // We do this by checking if any part of this interval "wins" in the final mapping
266 bool completely_shadowed = true;
267
268 // Look through the final resolved regions to see if any belong to this interval's target
269 for (const auto& [seg_start, region] : m_regions) {
270 // Check if this final region overlaps with our interval and belongs to our target
271 if (region.target == interval.target && region.start < interval.end &&
272 region.end > interval.start) {
273 // This interval has at least some part that's not shadowed
274 completely_shadowed = false;
275 break;
276 }
277 }
278
279 if (completely_shadowed) {
280 std::stringstream ss;
281 ss << "Region '" << interval.target->name << "' (0x" << std::hex << interval.start << "-0x"
282 << (interval.end - 1) << ", priority " << std::dec << interval.priority
283 << ") is completely shadowed by higher priority regions and will never be accessed";
284 SC_REPORT_WARNING("addressMap", ss.str().c_str());
285 }
286 }
287 }
288
289 public:
291 addressMap() = default;
292
307 void add(std::shared_ptr<TargetInfoType> t_info)
308 {
309 uint64_t start = t_info->address;
310 uint64_t end = t_info->address + t_info->size;
311
312 split_and_resolve(start, end, t_info);
313
314 // Clear cache after map modification to ensure consistency
315 m_cache.clear();
316 }
317
331 std::shared_ptr<TargetInfoType> find(uint64_t address, uint64_t size)
332 {
333 // Fast path: check LRU cache first
334 std::shared_ptr<TargetInfoType> cached_result;
335 if (m_cache.get(address, cached_result)) {
336 return cached_result;
337 }
338
339 // Slow path: search the map using upper_bound for O(log n) lookup
340 // upper_bound finds the first region with start > address
341 auto it = m_regions.upper_bound(address);
342 if (it != m_regions.begin()) {
343 --it; // Move to the region that might contain our address
344
345 // Check if address falls within this region [start, end)
346 if (address >= it->second.start && address < it->second.end) {
347 // Cache the result for future lookups
348 m_cache.put(address, it->second.target, size);
349 return it->second.target;
350 }
351 }
352
353 // Address not found - cache the negative result to avoid repeated lookups
354 m_cache.put(address, nullptr, size);
355 return nullptr;
356 }
357
374 std::shared_ptr<TargetInfoType> find_region(uint64_t addr, tlm::tlm_dmi& dmi)
375 {
376 // First try to find a mapped region using the same logic as find()
377 auto it = m_regions.upper_bound(addr);
378 if (it != m_regions.begin()) {
379 --it;
380 if (addr >= it->second.start && addr < it->second.end) {
381 // Return the segment boundaries. After split_and_resolve, adjacent
382 // same-target segments are merged, so this segment represents the
383 // full contiguous range owned by this target. We must not use the
384 // original target range as it may span across higher-priority targets.
385 std::shared_ptr<TargetInfoType> target = it->second.target;
386 dmi.set_start_address(it->second.start);
387 dmi.set_end_address(it->second.end - 1); // inclusive end (Region.end is exclusive)
388 return target;
389 }
390 }
391
392 // Address is in a hole - calculate hole boundaries for DMI invalidation
393 uint64_t hole_start = 0;
394 uint64_t hole_end = std::numeric_limits<uint64_t>::max();
395
396 // Find the region immediately before this address
397 it = m_regions.upper_bound(addr);
398 if (it != m_regions.begin()) {
399 --it;
400 if (it->second.end <= addr) {
401 hole_start = it->second.end;
402 }
403 }
404
405 // Find the region immediately after this address
406 it = m_regions.upper_bound(addr);
407 if (it != m_regions.end()) {
408 hole_end = it->second.start;
409 }
410
411 // Set DMI boundaries for the hole
412 dmi.set_start_address(hole_start);
413 dmi.set_end_address(hole_end == 0 ? 0 : hole_end - 1); // Handle edge case
414 return nullptr;
415 }
416
422 void get_cache_stats(uint64_t& hits, uint64_t& misses) const
423 {
424 hits = m_cache.get_hits();
425 misses = m_cache.get_misses();
426 }
427
431 void reset_cache_stats() { m_cache.reset_stats(); }
432 };
433
434 SCP_LOGGER_VECTOR(D);
435 SCP_LOGGER(());
436 SCP_LOGGER((DMI), "dmi");
437
438private:
440 struct dmi_info {
441 std::set<int> initiators;
442 tlm::tlm_dmi dmi;
444 dmi_info(tlm::tlm_dmi& _dmi) { dmi = _dmi; }
445 };
447 std::map<uint64_t, dmi_info> m_dmi_info_map;
448
459 dmi_info* in_dmi_cache(tlm::tlm_dmi& dmi)
460 {
461 auto it = m_dmi_info_map.find(dmi.get_start_address());
462 if (it != m_dmi_info_map.end()) {
463 if (it->second.dmi.get_end_address() != dmi.get_end_address()) {
464 // Defensive guard: unreachable in normal operation. The only caller
465 // (record_dmi) detects differing end addresses and calls
466 // invalidate_direct_mem_ptr_ts to erase the old entry before reaching here.
467 std::stringstream ss;
468 ss << "Can't handle that: DMI overlap with differing end address (0x" << std::hex
469 << it->second.dmi.get_end_address() << " vs 0x" << dmi.get_end_address() << ")";
470 SC_REPORT_ERROR("DMI", ss.str().c_str());
471 }
472 return &(it->second);
473 }
474 auto insit = m_dmi_info_map.emplace(dmi.get_start_address(), dmi_info(dmi));
475 return &(insit.first->second);
476 }
477
488 void record_dmi(int id, tlm::tlm_dmi& dmi)
489 {
490 auto it = m_dmi_info_map.find(dmi.get_start_address());
491 if (it != m_dmi_info_map.end()) {
492 if (it->second.dmi.get_end_address() != dmi.get_end_address()) {
493 SCP_WARN((DMI)) << "A new DMI overlaps with an old one, invalidating the old one";
494 invalidate_direct_mem_ptr_ts(0, dmi.get_start_address(),
495 dmi.get_end_address()); // id will be ignored
496 }
497 }
498
499 dmi_info* dinfo = in_dmi_cache(dmi);
500 dinfo->initiators.insert(id);
501 }
502
512 void register_boundto(std::string s) override
513 {
514 s = gs::router_if<BUSWIDTH>::nameFromSocket(s);
515 // Create a shared_ptr for the new target_info
516 std::shared_ptr<target_info> ti_ptr = std::make_shared<target_info>();
517 ti_ptr->name = s;
518 ti_ptr->index = bound_targets.size(); // Current size will be its index
519 SCP_LOGGER_VECTOR_PUSH_BACK(D, ti_ptr->name);
520 SCP_DEBUG((D[ti_ptr->index])) << "Connecting : " << ti_ptr->name;
521 ti_ptr->chained = false;
522 std::string tmp = name();
523 int i;
524 for (i = 0; i < tmp.length(); i++)
525 if (s[i] != tmp[i]) break;
526 ti_ptr->shortname = s.substr(i);
527 bound_targets.push_back(ti_ptr); // Add shared_ptr to bound_targets
528 }
529
540 std::string txn_tostring(const target_info* ti, tlm::tlm_generic_payload& trans)
541 {
542 std::stringstream info;
543 const char* cmd = "UNKOWN";
544 switch (trans.get_command()) {
545 case tlm::TLM_IGNORE_COMMAND:
546 info << "IGNORE ";
547 break;
548 case tlm::TLM_WRITE_COMMAND:
549 info << "WRITE ";
550 break;
551 case tlm::TLM_READ_COMMAND:
552 info << "READ ";
553 break;
554 }
555
556 info << " address:"
557 << "0x" << std::hex << trans.get_address();
558 info << " len:" << trans.get_data_length();
559 unsigned char* ptr = trans.get_data_ptr();
560 if ((trans.get_command() == tlm::TLM_READ_COMMAND && trans.get_response_status() == tlm::TLM_OK_RESPONSE) ||
561 (trans.get_command() == tlm::TLM_WRITE_COMMAND &&
562 trans.get_response_status() == tlm::TLM_INCOMPLETE_RESPONSE)) {
563 info << " data:0x";
564 for (int i = trans.get_data_length(); i; i--) {
565 info << std::setw(2) << std::setfill('0') << std::hex << (unsigned int)(ptr[i - 1]);
566 }
567 }
568 info << " " << trans.get_response_string() << " ";
569 for (int i = 0; i < tlm::max_num_extensions(); i++) {
570 if (trans.get_extension(i)) {
571 info << " extn:" << i;
572 }
573 }
574 return info.str();
575 }
576
577public:
579 initiator_socket_type initiator_socket;
581 tlm_utils::multi_passthrough_target_socket<router<BUSWIDTH, CacheType>, BUSWIDTH> target_socket;
583 cci::cci_broker_handle m_broker;
584
585private:
587 std::vector<std::shared_ptr<target_info>> alias_targets;
589 addressMap<target_info> m_address_map;
591 std::vector<std::shared_ptr<target_info>> id_targets;
592
594 std::vector<PathIDExtension*> m_pathIDPool;
595#if defined(THREAD_SAFE) and THREAD_SAFE
597 std::mutex m_pool_mutex;
598#endif
599
609 void stamp_txn(int id, tlm::tlm_generic_payload& txn)
610 {
611 PathIDExtension* ext = nullptr;
612 txn.get_extension(ext);
613 if (ext == nullptr) {
614#if defined(THREAD_SAFE) and THREAD_SAFE
615 std::lock_guard<std::mutex> l(m_pool_mutex);
616#endif
617 if (m_pathIDPool.size() == 0) {
618 ext = new PathIDExtension();
619 } else {
620 ext = m_pathIDPool.back();
621 m_pathIDPool.pop_back();
622 }
623 txn.set_extension(ext);
624 }
625 ext->push_back(id);
626 }
627
637 void unstamp_txn(int id, tlm::tlm_generic_payload& txn)
638 {
639 PathIDExtension* ext;
640 txn.get_extension(ext);
641 assert(ext);
642 assert(ext->back() == id);
643 ext->pop_back();
644 if (ext->size() == 0) {
645#if defined(THREAD_SAFE) and THREAD_SAFE
646 std::lock_guard<std::mutex> l(m_pool_mutex);
647#endif
648 txn.clear_extension(ext);
649 m_pathIDPool.push_back(ext);
650 }
651 }
652
665 void b_transport(int id, tlm::tlm_generic_payload& trans, sc_core::sc_time& delay)
666 {
667 sc_dt::uint64 addr = trans.get_address();
668 auto ti = decode_address(trans);
669 if (!ti) {
670 SCP_WARN(())("Attempt to access unknown register at offset 0x{:x}", addr);
671 trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);
672 return;
673 }
674
675 stamp_txn(id, trans);
676 if (!ti->chained) {
677 SCP_TRACE((D[ti->index]), ti->name) << "Start b_transport :" << txn_tostring(ti.get(), trans);
678 }
679 if (trans.get_response_status() >= tlm::TLM_INCOMPLETE_RESPONSE) {
680 if (ti->use_offset) trans.set_address(addr - ti->address);
681
682 initiator_socket[ti->index]->b_transport(trans, delay);
683
684 if (ti->use_offset) trans.set_address(addr);
685 }
686 if (!ti->chained) {
687 SCP_TRACE((D[ti->index]), ti->name) << "Completed b_transport :" << txn_tostring(ti.get(), trans);
688 }
689 unstamp_txn(id, trans);
690 }
691
703 unsigned int transport_dbg(int id, tlm::tlm_generic_payload& trans)
704 {
705 // Ensure router is initialized (thread-safe)
706 lazy_initialize();
707
708 sc_dt::uint64 addr = trans.get_address();
709 auto ti = decode_address(trans);
710 if (!ti) {
711 trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);
712 return 0;
713 }
714
715 if (ti->use_offset) trans.set_address(addr - ti->address);
716 SCP_TRACE((D[ti->index]), ti->name) << "calling dbg_transport : " << scp::scp_txn_tostring(trans);
717 unsigned int ret = initiator_socket[ti->index]->transport_dbg(trans);
718 if (ti->use_offset) trans.set_address(addr);
719 return ret;
720 }
721
734 bool get_direct_mem_ptr(int id, tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data)
735 {
736 // Ensure router is initialized (thread-safe)
737 lazy_initialize();
738
739 sc_dt::uint64 addr = trans.get_address();
740
741 tlm::tlm_dmi dmi_data_hole;
742 auto ti = m_address_map.find_region(addr, dmi_data_hole);
743
744 UnderlyingDMITlmExtension* u_dmi;
745 trans.get_extension(u_dmi);
746 if (u_dmi) {
747 SCP_DEBUG(())
748 ("DMI info 0x{:x} 0x{:x} {}", dmi_data_hole.get_start_address(), dmi_data_hole.get_end_address(),
749 (ti ? "mapped" : "nomap"));
750 u_dmi->add_dmi(this, dmi_data_hole, (ti ? gs::tlm_dmi_ex::dmi_mapped : gs::tlm_dmi_ex::dmi_nomap));
751 }
752
753 if (!ti) {
754 return false;
755 }
756 if (ti->use_offset) trans.set_address(addr - ti->address);
757 SCP_TRACE((D[ti->index]), ti->name) << "calling get_direct_mem_ptr : " << scp::scp_txn_tostring(trans);
758 bool status = initiator_socket[ti->index]->get_direct_mem_ptr(trans, dmi_data);
759 if (ti->use_offset) trans.set_address(addr);
760 if (status) {
761 if (ti->use_offset) {
762 assert(dmi_data.get_start_address() < ti->size);
763 dmi_data.set_start_address(ti->address + dmi_data.get_start_address());
764 dmi_data.set_end_address(ti->address + dmi_data.get_end_address());
765 }
766 /* ensure we dont overspill the 'hole' we have in the address map */
767 if (dmi_data.get_start_address() < dmi_data_hole.get_start_address()) {
768 dmi_data.set_dmi_ptr(dmi_data.get_dmi_ptr() +
769 (dmi_data_hole.get_start_address() - dmi_data.get_start_address()));
770 dmi_data.set_start_address(dmi_data_hole.get_start_address());
771 }
772 if (dmi_data.get_end_address() > dmi_data_hole.get_end_address()) {
773 dmi_data.set_end_address(dmi_data_hole.get_end_address());
774 }
775 record_dmi(id, dmi_data);
776 }
777 SCP_DEBUG(())
778 ("Providing DMI (status {:x}) {:x} - {:x}", status, dmi_data.get_start_address(), dmi_data.get_end_address());
779 return status;
780 }
781
792 void invalidate_direct_mem_ptr(int id, sc_dt::uint64 start, sc_dt::uint64 end)
793 {
794 if (id_targets[id]->use_offset) {
795 start = id_targets[id]->address + start;
796 end = id_targets[id]->address + end;
797 }
798 invalidate_direct_mem_ptr_ts(id, start, end);
799 }
800
812 void invalidate_direct_mem_ptr_ts(int id, sc_dt::uint64 start, sc_dt::uint64 end)
813 {
814 auto it = m_dmi_info_map.upper_bound(start);
815
816 if (it != m_dmi_info_map.begin()) {
817 /*
818 * Start with the preceding region, as it may already cross the
819 * range we must invalidate.
820 */
821 it--;
822 }
823 std::set<int> initiators;
824
825 while (it != m_dmi_info_map.end()) {
826 tlm::tlm_dmi& r = it->second.dmi;
827
828 if (r.get_start_address() > end) {
829 /* We've got out of the invalidation range */
830 break;
831 }
832
833 if (r.get_end_address() < start) {
834 /* We are not in yet */
835 it++;
836 continue;
837 }
838 for (auto t : it->second.initiators) {
839 SCP_TRACE((DMI)) << "Queueing initiator " << t << " for invalidation, its bounds are [0x" << std::hex
840 << it->second.dmi.get_start_address() << " - 0x" << it->second.dmi.get_end_address()
841 << "]";
842 initiators.insert(t);
843 }
844 it = m_dmi_info_map.erase(it);
845 }
846 for (auto t : initiators) {
847 SCP_INFO((DMI)) << "Invalidating initiator " << t << " [0x" << std::hex << start << " - 0x" << end << "]";
848 target_socket[t]->invalidate_direct_mem_ptr(start, end);
849 }
850 }
851
852protected:
863 std::shared_ptr<target_info> decode_address(tlm::tlm_generic_payload& trans) override
864 {
865 lazy_initialize();
866
867 sc_dt::uint64 addr = trans.get_address();
868 return m_address_map.find(addr, trans.get_data_length());
869 }
870
876 virtual void before_end_of_elaboration() override
877 {
878 if (!lazy_init) lazy_initialize();
879 }
880
881private:
883 std::atomic<bool> m_initialized{ false };
885#if defined(THREAD_SAFE) and THREAD_SAFE
886 std::mutex m_init_mutex;
887#endif
888 std::list<std::string> get_matching_children(cci::cci_broker_handle broker, const std::string& prefix,
889 const std::vector<cci_name_value_pair>& list)
890 {
891 size_t prefix_len = prefix.length() + 1; // +1 for the dot separator
892 std::list<std::string> children;
893 for (const auto& p : list) {
894 if (p.first.find(prefix) == 0) {
895 // Extract the child name after the prefix
896 std::string child = p.first.substr(prefix_len, p.first.find(".", prefix_len) - prefix_len);
897 children.push_back(child);
898 }
899 }
900 children.sort();
901 children.unique();
902 return children;
903 }
904
918 void lazy_initialize() override
919 {
920 // Fast path: check if already initialized (lock-free)
921 if (m_initialized.load(std::memory_order_acquire)) {
922 return;
923 }
924
925#if defined(THREAD_SAFE) and THREAD_SAFE
926 // Slow path: acquire lock and initialize
927 std::lock_guard<std::mutex> lock(m_init_mutex);
928#endif
929
930 // Double-check: another thread may have initialized while we waited
931 if (m_initialized.load(std::memory_order_relaxed)) {
932 return;
933 }
934
935 // Perform initialization
936 // Get filtered range and convert to vector to materialize the results
937 auto all_alias_range = m_broker.get_unconsumed_preset_values([](const std::pair<std::string, cci_value>& iv) {
938 return iv.first.find(".aliases.") != std::string::npos;
939 });
940 std::vector<cci_name_value_pair> all_alias(all_alias_range.begin(), all_alias_range.end());
941
942 for (auto& ti_ptr : bound_targets) {
943 std::string name = ti_ptr->name;
944 std::string src;
945 if (gs::cci_get<std::string>(m_broker, ti_ptr->name + ".0", src)) {
946 // deal with an alias
947 if (m_broker.has_preset_value(ti_ptr->name + ".address") &&
948 m_broker.get_preset_cci_value(ti_ptr->name + ".address").is_number()) {
949 SCP_WARN((D[ti_ptr->index]), ti_ptr->name)
950 ("The configuration alias provided ({}) will be ignored as a valid address is also provided.", src);
951 } else {
952 if (src[0] == '&') src = (src.erase(0, 1)) + ".target_socket";
953 if (!m_broker.has_preset_value(src + ".address")) {
954 std::stringstream ss;
955 ss << "The configuration alias provided (" << src << ") can not be found.";
956 SC_REPORT_ERROR("router", ss.str().c_str());
957 }
958 name = src;
959 }
960 }
961
962 // Update the target_info object pointed to by ti_ptr
963 ti_ptr->address = gs::cci_get<uint64_t>(m_broker, name + ".address");
964 ti_ptr->size = gs::cci_get<uint64_t>(m_broker, name + ".size");
965 ti_ptr->use_offset = gs::cci_get_d<bool>(m_broker, name + ".relative_addresses", true);
966 ti_ptr->chained = gs::cci_get_d<bool>(m_broker, name + ".chained", false);
967 ti_ptr->priority = gs::cci_get_d<uint32_t>(m_broker, name + ".priority", 0);
968
969 SCP_INFO((D[ti_ptr->index]), ti_ptr->name)
970 << "Address map " << ti_ptr->name << " at address "
971 << "0x" << std::hex << ti_ptr->address << " size "
972 << "0x" << std::hex << ti_ptr->size << (ti_ptr->use_offset ? " (with relative address) " : " ")
973 << "priority : " << ti_ptr->priority;
974 if (ti_ptr->chained) SCP_DEBUG(())("{} is chained so debug will be suppressed", ti_ptr->name);
975
976 // Add the shared_ptr to the address map
977 m_address_map.add(ti_ptr);
978 for (std::string n : get_matching_children(m_broker, (ti_ptr->name + ".aliases"), all_alias)) {
979 std::string alias_name = ti_ptr->name + ".aliases." + n;
980 uint64_t address = gs::cci_get<uint64_t>(m_broker, alias_name + ".address");
981 uint64_t size = gs::cci_get<uint64_t>(m_broker, alias_name + ".size");
982 SCP_INFO((D[ti_ptr->index]), ti_ptr->name)("Adding alias {} {:#x} (size: {})", alias_name, address,
983 size);
984
985 // Create a new shared_ptr for the alias, copying from the current ti_ptr state
986 std::shared_ptr<target_info> alias_ti_ptr = std::make_shared<target_info>(*ti_ptr);
987 alias_ti_ptr->address = address;
988 alias_ti_ptr->size = size;
989 alias_ti_ptr->name = alias_name;
990 alias_targets.push_back(alias_ti_ptr); // Store shared_ptr in alias_targets
991
992 // Add aliases to the address map
993 m_address_map.add(alias_ti_ptr);
994 }
995 id_targets.push_back(ti_ptr); // Store shared_ptr in id_targets
996 }
997
998 // Mark as initialized (release semantics ensures all writes are visible)
999 m_initialized.store(true, std::memory_order_release);
1000 }
1001
1003 cci::cci_param<bool> lazy_init;
1004
1014public:
1015 explicit router(const sc_core::sc_module_name& nm, cci::cci_broker_handle broker = cci::cci_get_broker())
1016 : sc_core::sc_module(nm)
1017 , initiator_socket("initiator_socket", [&](std::string s) -> void { register_boundto(s); })
1018 , target_socket("target_socket")
1019 , m_address_map()
1020 , m_broker(broker)
1021 , lazy_init("lazy_init", false, "Initialize the router lazily (eg. during simulation rather than BEOL)")
1022 {
1023 SCP_DEBUG(()) << "router constructed";
1024
1025 target_socket.register_b_transport(this, &router<BUSWIDTH, CacheType>::b_transport);
1026 target_socket.register_transport_dbg(this, &router<BUSWIDTH, CacheType>::transport_dbg);
1027 target_socket.register_get_direct_mem_ptr(this, &router<BUSWIDTH, CacheType>::get_direct_mem_ptr);
1028 initiator_socket.register_invalidate_direct_mem_ptr(this,
1029 &router<BUSWIDTH, CacheType>::invalidate_direct_mem_ptr);
1030 SCP_DEBUG((DMI)) << "router Initializing DMI SCP reporting";
1031 }
1032
1034 router() = delete;
1035
1037 router(const router&) = delete;
1038
1039public:
1042 ~router() { m_pathIDPool.clear(); }
1043
1056 void add_target(TargetSocket& t, const uint64_t address, uint64_t size, bool masked = true,
1057 unsigned int priority = 0)
1058 {
1059 std::string s = gs::router_if<BUSWIDTH>::nameFromSocket(t.get_base_export().name());
1060 if (!m_broker.has_preset_value(s + ".address")) {
1061 m_broker.set_preset_cci_value(s + ".address", cci::cci_value(address));
1062 }
1063 if (!m_broker.has_preset_value(s + ".size")) {
1064 m_broker.set_preset_cci_value(s + ".size", cci::cci_value(size));
1065 }
1066 if (!m_broker.has_preset_value(s + ".relative_addresses")) {
1067 m_broker.set_preset_cci_value(s + ".relative_addresses", cci::cci_value(masked));
1068 }
1069 if (!m_broker.has_preset_value(s + ".priority")) {
1070 SCP_DEBUG(())("Setting prio to {}", priority);
1071 m_broker.set_preset_cci_value(s + ".priority", cci::cci_value(priority));
1072 }
1073 initiator_socket.bind(t);
1074 }
1075
1084 virtual void add_initiator(InitiatorSocket& i)
1085 {
1086 // hand bind the port/exports as we are using base classes
1087 (i.get_base_port())(target_socket.get_base_interface());
1088 (target_socket.get_base_port())(i.get_base_interface());
1089 }
1090
1099 void get_cache_stats(uint64_t& hits, uint64_t& misses) const { m_address_map.get_cache_stats(hits, misses); }
1100
1107 void reset_cache_stats() { m_address_map.reset_cache_stats(); }
1108};
1109} // namespace gs
1110
1111extern "C" void module_register();
1112#endif
Definition router.h:49
AddrMapNoCache - A cache implementation that never caches (always misses).
Definition router.h:68
bool get(const Key &key, Value &value) override
Always returns false (cache miss).
Definition router.h:71
void clear() override
Does nothing (nothing to clear).
Definition router.h:86
void put(const Key &key, const Value &value, uint64_t size) override
Does nothing (no caching).
Definition router.h:79
Definition pathid_extension.h:26
Definition router_if.h:25
A SystemC TLM router module for transaction routing based on address.
Definition router.h:106
virtual void before_end_of_elaboration() override
Called before end of elaboration to ensure lazy initialization.
Definition router.h:876
virtual void add_initiator(InitiatorSocket &i)
Adds an initiator to the router.
Definition router.h:1084
router(const sc_core::sc_module_name &nm, cci::cci_broker_handle broker=cci::cci_get_broker())
Constructor for the router module.
Definition router.h:1015
tlm_utils::multi_passthrough_target_socket< router< BUSWIDTH, CacheType >, BUSWIDTH > target_socket
Target socket to receive transactions from initiators.
Definition router.h:581
router()=delete
Deleted default constructor to enforce named instantiation.
initiator_socket_type initiator_socket
Initiator socket to connect to targets.
Definition router.h:579
void get_cache_stats(uint64_t &hits, uint64_t &misses) const
Get cache statistics (hits and misses).
Definition router.h:1099
void add_target(TargetSocket &t, const uint64_t address, uint64_t size, bool masked=true, unsigned int priority=0)
Adds a target to the router's address map.
Definition router.h:1056
std::shared_ptr< target_info > decode_address(tlm::tlm_generic_payload &trans) override
Decodes the address from a TLM generic payload to find the target.
Definition router.h:863
router(const router &)=delete
Deleted copy constructor.
cci::cci_broker_handle m_broker
CCI broker handle for configuration parameters.
Definition router.h:583
void reset_cache_stats()
Reset cache statistics to zero.
Definition router.h:1107
~router()
Destructor for the router module. Cleans up any remaining PathIDExtension objects in the pool.
Definition router.h:1042
Tool which reads a Lua configuration file and sets parameters.
Definition biflow.cc:10
Definition router_if.h:50