SystemC Library API Reference Manual
Reference documentation for the Simics SystemC Library.
 
Loading...
Searching...
No Matches
pcie_mapping_interconnect.h
Go to the documentation of this file.
1/*
2
3 © 2024 Intel Corporation
4
5 This software and the related documents are Intel copyrighted materials, and
6 your use of them is governed by the express license under which they were
7 provided to you ("License"). Unless the License provides otherwise, you may
8 not use, modify, copy, publish, distribute, disclose or transmit this software
9 or the related documents without Intel's prior written permission.
10
11 This software and the related documents are provided as is, with no express or
12 implied warranties, other than those that are expressly stated in the License.
13*/
14
15#ifndef SIMICS_SYSTEMC_COMPOSITE_PCIE_MAPPING_INTERCONNECT_H
16#define SIMICS_SYSTEMC_COMPOSITE_PCIE_MAPPING_INTERCONNECT_H
17
18#include <systemc>
19#include <tlm>
20#include <tlm_utils/multi_socket_bases.h>
21#include <tlm_utils/simple_initiator_socket.h>
22#include <tlm_utils/simple_target_socket.h>
23
24#include <simics/cc-api.h>
31
32#include <algorithm>
33#include <cstring>
34#include <sstream>
35#include <map>
36#include <vector>
37#include <stdexcept>
38#include <string>
39#include <utility> // pair, ignore
40
41namespace { // NOLINT(build/namespaces_headers)
42const char *const PCIE_MAPPING_INTERCONNECT_TAG = \
43 "intel/PcieMappingInterconnect";
44
46const char *pcieTypeName(simics::types::pcie_type_t t) {
47 switch (t) {
49 return "Not Set";
51 return "Memory";
53 return "I/O";
55 return "Config";
57 return "Message";
59 return "Other";
60 default:
61 return "Unknown";
62 }
63}
64
65std::string pcieDeviceIdStr(uint16_t device_id) {
66 std::ostringstream os;
67 os << "device id 0x" << std::hex << device_id
68 << " (" << std::dec << (device_id >> 8)
69 << ":" << ((device_id >> 3) & 0x1f)
70 << "." << (device_id & 7) << ")";
71 return os.str();
72}
73} // namespace
74
75namespace simics {
76namespace systemc {
77namespace composite {
78
81template<typename TSocket>
83 : public iface::ExtensionSender<TSocket> {
84 public:
86
87 // iface::ExtensionSender
91 }
95 }
96
98};
99
106template <unsigned int BUSWIDTH, typename TYPES>
107class PcieMappingInterconnect : public sc_core::sc_module {
108 // Socket types used by the interconnect
109 typedef tlm_utils::simple_target_socket<
110 PcieMappingInterconnect, BUSWIDTH, TYPES> target_socket_t;
111 typedef tlm_utils::simple_initiator_socket<
112 PcieMappingInterconnect, BUSWIDTH, TYPES> initiator_socket_t;
113 typedef struct {
114 tlm::tlm_target_socket<BUSWIDTH, TYPES> *tlm;
115 tlm_utils::multi_target_base<BUSWIDTH, TYPES> *multi;
116 } supported_target_socket_t;
117
118 public:
119#ifndef SYSTEMC_3_0_0
121#endif
123 sc_core::sc_module_name = "PcieMappingInterconnect")
124 : transaction_target_socket("transaction_target_socket"),
125 pcie_device_target_socket("dummy_pcie_device_target_socket"),
126 pcie_map_initiator_socket("pcie_map_initiator_socket"),
127 initiator_sockets_("initiator_socket"),
128 config_target_socket_(),
129 msg_target_socket_(),
130 pcie_map_target_socket_("pcie_map_target_socket") {
131 transaction_target_socket.register_b_transport(
132 this, &PcieMappingInterconnect::transaction_b_transport);
133 transaction_target_socket.register_transport_dbg(
134 this, &PcieMappingInterconnect::transaction_transport_dbg);
135 pcie_map_initiator_socket.register_invalidate_direct_mem_ptr(
136 this, &PcieMappingInterconnect::pcie_map_invalidate_direct_mem_ptr);
137 pcie_map_target_socket_.register_b_transport(
138 this, &PcieMappingInterconnect::pcie_map_b_transport);
139 pcie_map_target_socket_.register_transport_dbg(
140 this, &PcieMappingInterconnect::pcie_map_transport_dbg);
141 pcie_map_target_socket_.register_get_direct_mem_ptr(
142 this, &PcieMappingInterconnect::pcie_map_get_direct_mem_ptr);
143
145 pcie_map_extension_.init(&sender_);
146
147 // f0 is required
148 function_data_[0];
149
150 SC_METHOD(warmReset);
151 sensitive << warm_reset_pin.pos();
152 dont_initialize();
153
154 config_target_socket_.tlm = nullptr;
155 config_target_socket_.multi = nullptr;
156 msg_target_socket_.tlm = nullptr;
157 msg_target_socket_.multi = nullptr;
158 }
159
160 // sc_core::sc_module
162
163 // Called by (outer) composite class from PcieDevice::connected. The
164 // device_id parameter is a PCIe Requester ID; its Function Number field
165 // is discarded before this interconnect combines it with each function.
166 void connected(uint16_t device_id);
167
168 // Called by (outer) composite class from PcieDevice::disconnected
169 void disconnected(uint16_t device_id);
170
171 // Called by (outer) composite class from PcieDevice::hot_reset
172 void hotReset();
173
190 ConfObjectRef o,
191 iface::PcieSriovQueryInterface *sriov = nullptr);
192
193 // Create map helpers which are mapped on the cfg space. It contains
194 // PCI information like PCIe type and function id which is used to
195 // route the transaction to the right TLM2 socket
197
198 // Return the current map from address range to socket ID (Memory)
199 std::map<std::pair<size_t, size_t>, size_t> addressIdMemMap() const;
200
201 // Return the current map from address range to socket ID (IO)
202 std::map<std::pair<size_t, size_t>, size_t> addressIdIoMap() const;
203
204 // Sockets bound by external logic (see also private scope):
205 // Simics -> IC, intercepts the incoming PCIe transactions
207 // Dummy socket as PcieDevice is handled by connected/disconnected/hotReset
210 initiator_socket_t pcie_map_initiator_socket;
211 // Simics -> IC, receives warm reset signal
212 sc_core::sc_in<bool> warm_reset_pin;
213 // For MEM/IO, this parameter controls if the base address of the
214 // memory range is subtracted before sending the GP payload to endpoint
216
217 private:
218 // Called when warm_reset_pin is positive
219 void warmReset();
220
221 // Help methods
222 // Adds the BAR mappings of type with map info
223 void addMap(types::map_info_t info, types::pcie_type_t type);
224
225 // Removes the BAR mappings of type for socket ID
226 void delMap(size_t socket_id, types::pcie_type_t type);
227
228 // The supplied device_id passed to addFunction & delFunction should
229 // contain the full function ID and not just the function number.
230 // Adds the function's configuration header in the upstream target
231 void addFunction(uint16_t device_id);
232 // Removes the current mapping (if any) of this function's configuration
233 // header in the upstream target
234 void delFunction(uint16_t device_id);
235
236 // Cast sc_object to a supported target socket
237 void castToTarget(sc_core::sc_object *object,
238 supported_target_socket_t *target);
239
240 // Update the PCIe mapping
241 // @param function_id the config id used to index into function_data_,
242 // -1 means checks all config ids
243 // @param bar_id the bar id used to index into base_address,
244 // -1 means checks all bar ids
245 void updateMappings(int function_id = -1, int bar_id = -1);
246
247 /*
248 * When command register is written to, the mappings need to be re-evaluated
249 * and possibly updated.
250 *
251 * There is no error handling, so if the mapping fails this will only be
252 * logged but the access will still pass (i.e. transaction forwarded to
253 * target device where registers are updated without side-effects)
254 */
255 void updateCommand(uint16_t function_id, uint16_t old_command);
256
257 // Get up-to-date BAR/CMD information whenever we need it. It cannot be
258 // cached in the interconnect module as it might change over time by the
259 // model, reverse execution, checkpoint restore, ...
260 // @param id is the accessing initiator socket ID
261 // @param bar_id is the BAR number currently access, or -1 for config
262 // register access in which case all BARs must be retrieved
263 void retrieveFunctionData(size_t socket_id, int bar_id);
264
265 // Intercept Config space header write access and update the mapping table
266 void interceptCfgHeaderAccess(size_t socket_id,
267 tlm::tlm_generic_payload &trans); // NOLINT
268
269 // Find the id of the initiator_sockets_ list to route the transaction to
270 // based on the PCIe transaction type, function number and offset
271 size_t findSocketId(types::pcie_type_t type, uint16_t function_id,
272 tlm::tlm_generic_payload &trans) const; // NOLINT
273
274 // Return the created cfg map helper by device_id
275 conf_object_t *getCfgMapHelper(uint16_t device_id);
276
277 // Validate BAR info entries in bar_info_ right after getBarInfo().
278 // Reports configuration errors via SIM_LOG_ERROR_STR.
279 // Returns true if all entries are valid, false if any error was found.
280 // Override to skip or relax validation for special use cases.
281 virtual bool validateBarInfo(ConfObjectRef o);
282
283 // Validate and update TLM2 response status
284 // If it passes validation it returns the socket-id as well
285 size_t validateTransaction(tlm::tlm_generic_payload &trans); // NOLINT
286 /*
287 * The single entry for all incoming PCIe transactions from Simics
288 * Depends on the PCIe type (CFG/MEM/IO/MSG), the transaction is
289 * routed to the corresponding initiator socket towards the endpoint device
290 * For CFG space header write, updating the mapping table as well
291 */
292 void transaction_b_transport(tlm::tlm_generic_payload &trans, // NOLINT
293 sc_core::sc_time &t); // NOLINT
294 unsigned int transaction_transport_dbg(
295 tlm::tlm_generic_payload &trans); // NOLINT
296
297 void pcie_map_invalidate_direct_mem_ptr(sc_dt::uint64 start_range,
298 sc_dt::uint64 end_range);
299 void pcie_map_b_transport(
300 tlm::tlm_generic_payload &trans, // NOLINT: SystemC API
301 sc_core::sc_time &t); // NOLINT: SystemC API
302 unsigned int pcie_map_transport_dbg(
303 tlm::tlm_generic_payload &trans); // NOLINT: SystemC API
304 bool pcie_map_get_direct_mem_ptr(
305 tlm::tlm_generic_payload &trans, // NOLINT: SystemC API
306 tlm::tlm_dmi &dmi_data); // NOLINT: SystemC API
307
308 // Sockets created and bound by internal logic (see also public scope):
309 // IC -> Device, forwards the incoming PCIe transactions
310 sc_core::sc_vector<initiator_socket_t> initiator_sockets_;
311 supported_target_socket_t config_target_socket_;
312 supported_target_socket_t msg_target_socket_;
313 // Device -> IC, intercept upstream pcie-map transactions
314 target_socket_t pcie_map_target_socket_;
315
316 struct cfg_header_t {
317 uint16_t command; // command register
318 uint32_t base_address[7]; // 6 BARs + expansion ROM BAR
319 };
320 // Cache each function's cfg header, f0 is required
321 std::map<uint16_t, cfg_header_t> function_data_;
322 std::vector<iface::PcieBaseAddressRegisterQueryInterface::PCIeBar>
323 bar_info_;
324
325 // Extension and sender for talking to the Simics pcie upstream target
326 PcieMappingInterconnectExtensionSender<initiator_socket_t> sender_;
327 iface::PcieMapExtension pcie_map_extension_;
328
329 // Trigger hot reset on the device
330 iface::PcieResetInterface *reset_ {nullptr};
331
332 // A map to store MEM address ranges and corresponding socket IDs
333 std::map<std::pair<size_t, size_t>, size_t> address_id_mem_map_;
334 // A map to store IO address ranges and corresponding socket IDs
335 std::map<std::pair<size_t, size_t>, size_t> address_id_io_map_;
336 // A map from function_number/bar_offset to socket IDs
337 std::map<std::pair<size_t, size_t>, size_t> fn_bar_id_map_;
338
339 ConfObjectRef simulation_obj_ {nullptr};
340 // For PCIe gasket object, the pcie_device and transaction interfaces
341 // are implemented on the gasket_obj_. For other cases, it is the same
342 // object as simulation_obj_
343 ConfObjectRef gasket_obj_ {nullptr};
344
345 // In some case (for example ARI), function number has 8 bits
346 // This boolean variable is set when the function number from getBarInfo()
347 // returns a value greater than 7
348 bool function_number_has_8bits_ {false};
349
350 // PCIe Requester ID reported by connected(), with its Function Number
351 // field cleared. OR:ed with a function number for pcie_map operations.
352 uint16_t device_id_ {0};
353
354 // Optional static SR-IOV configuration provided by the device.
355 // When set, connected() uses it instead of transport_dbg.
356 iface::PcieSriovQueryInterface *sriov_query_ {nullptr};
357
358 // SR-IOV support ---------------------------------------------------------
359 // Populated by connected() from sriov_query_ (if set).
360 // One entry per PF that exposes VFs (multi-PF devices have multiple
361 // entries).
362 struct SriovState {
363 uint16_t cap_offset = 0; // Extended Cap byte offset in PF cfg
364 int pf_function = 0; // PF function number (SR-IOV cap owner)
365 int total_vfs = 0; // TotalVFs: hardware maximum (RO)
366 int first_vf_function = 0; // Function number of VF0
367 int vf_stride = 1; // VF Stride: step between VF functions
368
369 // Cached VF BAR base addresses, written by the OS into the SR-IOV
370 // Extended Capability BAR registers (+0x24..+0x38, 6 × 4-byte slots).
371 // Index i = (cap_rel_offset - 0x24) / 4, which equals
372 // (vf_cfg_bar_offset - 0x10) / 4 — the same index used by
373 // cfg_header_t::base_address[] for the VF config-header BAR:
374 // vf_bar[0] ↔ cap+0x24 ↔ VF cfg BAR offset 0x10
375 // vf_bar[1] ↔ cap+0x28 ↔ VF cfg BAR offset 0x14
376 // vf_bar[2] ↔ cap+0x2C ↔ VF cfg BAR offset 0x18
377 // vf_bar[3] ↔ cap+0x30 ↔ VF cfg BAR offset 0x1C
378 // vf_bar[4] ↔ cap+0x34 ↔ VF cfg BAR offset 0x20
379 // vf_bar[5] ↔ cap+0x38 ↔ VF cfg BAR offset 0x24
380 // The SR-IOV spec §9.3.3.14 guarantees every VF shares
381 // the same BAR layout.
382 uint32_t vf_bar[6] = {};
383
384 // Cached register values updated by interceptCfgHeaderAccess()
385 uint16_t control = 0;
386 uint16_t num_vfs = 0; // NumVFs: OS-programmed active VF count
387
388 bool containsFunction(int function) const {
389 const int offset = function - first_vf_function;
390 return offset >= 0 && offset % vf_stride == 0
391 && offset / vf_stride < total_vfs;
392 }
393 };
394 std::vector<SriovState> sriov_states_;
395
396 // Populate sriov_states_ from sriov_query_. Called from connect() so
397 // that SR-IOV config-space snooping works even when
398 // pcie_device.connected() is never invoked (e.g. direct upstream_target
399 // assignment in tests). Also called from connected() to reset runtime
400 // state on reconnect.
401 void setupSriovStates();
402
403 // Map/unmap VF config space in the Simics pcie_map
404 // (enable_function / disable_function).
405 // Triggered when VF Enable (SR-IOV Control bit 0) transitions.
406 void updateVfCfgMappings(SriovState &state, bool enable);
407
408 // Map/unmap VF BAR memory regions (add_map / del_map).
409 // Triggered when VF MSE (SR-IOV Control bit 3) transitions while
410 // VF Enable is set, or when VF Enable transitions while VF MSE is set.
411 void updateVfBarMappings(SriovState &state, bool enable);
412};
413
414template <unsigned int BUSWIDTH, typename TYPES>
416 // Because of the way SystemC has been designed, we cannot create new
417 // sockets dynamically ouside of the CTOR except for in the
418 // before_end_of_elaboration() method.
419
420 // Create initiator sockets equal to the number of Config, Mem/IO
421 // target sockets and Msg target socket
422 initiator_sockets_.init(function_data_.size() + bar_info_.size() + 1);
423
424 size_t socket_id = 0;
425 // Allocate and initialize function data based on device configuration
426 for (; socket_id < function_data_.size(); ++socket_id) {
427 if (config_target_socket_.tlm) {
428 initiator_sockets_[socket_id].bind(*config_target_socket_.tlm);
429 } else {
430 initiator_sockets_[socket_id].bind(*config_target_socket_.multi);
431 }
432 }
433
434 for (const auto &bar : bar_info_) {
435 supported_target_socket_t target = {};
436 castToTarget(bar.target_socket, &target);
437 if (target.tlm) {
438 initiator_sockets_[socket_id].bind(*target.tlm);
439 } else if (target.multi) {
440 initiator_sockets_[socket_id].bind(*target.multi);
441 } else {
442 SC_REPORT_ERROR(
443 PCIE_MAPPING_INTERCONNECT_TAG,
444 "BAR target_socket type is not supported");
445 }
446 fn_bar_id_map_[std::make_pair(bar.function, bar.offset)] = socket_id;
447 ++socket_id;
448 }
449
450 if (msg_target_socket_.tlm) {
451 initiator_sockets_[socket_id].bind(*msg_target_socket_.tlm);
452 } else {
453 initiator_sockets_[socket_id].bind(*msg_target_socket_.multi);
454 }
455}
456
457template <unsigned int BUSWIDTH, typename TYPES>
459 // Use the side effect of it to set device object on pcie map gasket.
460 // The device object is used internally for get the mapping helper port
461 // object
462 pcie_map_extension_.get_device_id(gasket_obj_);
463
464 const uint16_t function_mask =
465 function_number_has_8bits_ ? 0xffu : 0x7u;
466 device_id_ = device_id & static_cast<uint16_t>(~function_mask);
467
468 {
469 std::ostringstream os;
470 os << "connected(): raw device_id=0x" << std::hex << device_id
471 << ", ARI=" << std::boolalpha << function_number_has_8bits_
472 << ", masked device_id_=0x" << std::hex << device_id_;
473 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
474 }
475
476 // The PCIe Modeling Library requires endpoints to add their functions
477 // and map resources like Memory and I/O BARs. However, it is unlikely
478 // that these resources are configured before the connection. Therefore,
479 // we deviate from the PCIe DML Modeling Library by not performing the
480 // mapping at this stage.
481 for (const auto &fd : function_data_) {
482 delFunction(device_id_ | fd.first);
483 addFunction(device_id_ | fd.first);
484 }
485
486 // Populate SR-IOV state from the static PcieSriovQueryInterface.
487 setupSriovStates();
488
489 // PCIe SR-IOV spec §9.3.3.3: VF config space must remain hidden
490 // until VF Enable (SR-IOV Control bit 0) is set. All VF functions
491 // were registered above via add_function(); immediately suppress them
492 // with disable_function() so they start in the correct hidden state.
493 for (const auto &state : sriov_states_) {
494 for (int i = 0; i < state.total_vfs; ++i) {
495 const uint16_t fn = static_cast<uint16_t>(
496 state.first_vf_function
497 + i * state.vf_stride);
498 pcie_map_extension_.disable_function(device_id_ | fn);
499 }
500 }
501}
502
503template <unsigned int BUSWIDTH, typename TYPES>
505disconnected(uint16_t device_id) {
506 const uint16_t function_mask =
507 function_number_has_8bits_ ? 0xffu : 0x7u;
508 const uint16_t masked_device_id =
509 device_id & static_cast<uint16_t>(~function_mask);
510 if (masked_device_id != device_id_) {
511 SIM_LOG_ERROR(
512 simulation_obj_, Log_Configuration,
513 "disconnected() called with device_id 0x%x, but currently"
514 " connected to 0x%x", masked_device_id, device_id_);
515 }
516
517 for (auto &fd : function_data_) {
518 delFunction(device_id_ | fd.first);
519 // disabled both MEM and IO
520 fd.second.command = 0;
521 updateMappings(fd.first);
522 }
523}
524
525template <unsigned int BUSWIDTH, typename TYPES>
527 if (reset_) {
528 reset_->hotReset();
529 for (auto &fd : function_data_) {
530 // disabled both MEM and IO
531 fd.second.command = 0;
532 updateMappings(fd.first);
533 }
534 // Undo VF config space routing (governed by VF Enable, bit 0).
535 // BAR map cleanup was already performed by the updateMappings() loop
536 // above (fd.command → 0 for all VF functions including active VFs).
537 // Guard disable_function on VF Enable being set: if VFs were never
538 // enabled (or the device was already disconnected), pcie_map_extension_
539 // has no upstream provider and calling it would abort.
540 for (auto &state : sriov_states_) {
541 if (state.control & 0x1u) { // VF Enable was set
542 updateVfCfgMappings(state, false);
543 }
544 state.control = 0;
545 state.num_vfs = 0;
546 std::fill(std::begin(state.vf_bar), std::end(state.vf_bar), 0u);
547 }
548 }
549}
550
551template <unsigned int BUSWIDTH, typename TYPES>
553 if (reset_) {
554 reset_->warmReset();
555 for (auto &fd : function_data_) {
556 // disabled both MEM and IO
557 fd.second.command = 0;
558 updateMappings(fd.first);
559 }
560 }
561}
562
563template <unsigned int BUSWIDTH, typename TYPES>
564void PcieMappingInterconnect<BUSWIDTH, TYPES>::
565addFunction(uint16_t device_id) {
566 std::ostringstream os;
567 os << "Adding function for device_id: "
568 << device_id;
569 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
570 auto *map_helper = getCfgMapHelper(device_id);
571 if (map_helper == nullptr) {
572 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG,
573 "Failure to get map helper");
574 return;
575 }
576 pcie_map_extension_.add_function(map_helper, device_id);
577 if (sender_.failed_transaction_.payload()) {
578 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG,
579 "Failure to add function");
580 return;
581 }
582}
583
584template <unsigned int BUSWIDTH, typename TYPES>
585void PcieMappingInterconnect<BUSWIDTH, TYPES>::
586delFunction(uint16_t device_id) {
587 std::ostringstream os;
588 os << "Deleting function for device_id: "
589 << device_id;
590 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
591 auto *map_helper = getCfgMapHelper(device_id);
592 if (map_helper == nullptr) {
593 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG,
594 "Failure to get map helper");
595 return;
596 }
597 pcie_map_extension_.del_function(map_helper, device_id);
598 if (sender_.failed_transaction_.payload()) {
599 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG,
600 "Failure to delete function");
601 return;
602 }
603}
604
605template <unsigned int BUSWIDTH, typename TYPES>
606bool PcieMappingInterconnect<BUSWIDTH, TYPES>::
607validateBarInfo(ConfObjectRef o) {
608 // Track (function, offset) pairs to detect duplicates.
609 std::map<std::pair<int, int>, bool> seen;
610 bool valid = true;
611
612 for (const auto &bar : bar_info_) {
613 // Helper lambda: prepend a consistent BAR context prefix.
614 auto err = [&](const std::string &msg) {
615 std::ostringstream os;
616 os << "BAR (function=" << bar.function
617 << ", offset=0x" << std::hex << bar.offset
618 << "): " << msg;
619 SIM_LOG_ERROR_STR(o, Log_Configuration, os.str());
620 valid = false;
621 };
622
623 if (bar.function < 0) {
624 err("function number must be >= 0");
625 }
626
627 // size_bits >= 64 would cause UB in '1ULL << size_bits'
628 if (bar.size_bits <= 0 || bar.size_bits >= 64) {
629 std::ostringstream os;
630 os << "size_bits=" << bar.size_bits
631 << " is out of valid range [1, 63]";
632 err(os.str());
633 }
634
635 // PCIe Base Spec 6.0, Sec 7.5.1.2.1: I/O Space BARs are
636 // always 32-bit; there is no 64-bit I/O BAR support.
637 if (!bar.is_memory && bar.is_64bit) {
638 err("I/O BARs cannot be 64-bit");
639 }
640
641 // BAR offsets must be one of the six 4-byte-aligned standard BAR
642 // slots (0x10..0x24) or the Expansion ROM slot (0x30). Any other
643 // value would produce an out-of-bounds index in retrieveFunctionData
644 // via '(offset - 0x10) / 4'.
645 static constexpr int kValidOffsets[] = {
646 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x30};
647 if (std::none_of(std::begin(kValidOffsets),
648 std::end(kValidOffsets),
649 [&](int vo) { return bar.offset == vo; })) {
650 std::ostringstream os;
651 os << "offset=0x" << std::hex << bar.offset
652 << " is not a valid BAR offset;"
653 << " expected one of 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, or"
654 << " 0x30 (Expansion ROM)";
655 err(os.str());
656 }
657
658 // PCIe Base Spec 6.0, Sec 7.5.1.2.4: Expansion ROM BAR
659 // (offset 0x30) must be a memory BAR and cannot be 64-bit.
660 if (bar.offset == 0x30) {
661 if (!bar.is_memory) {
662 err("Expansion ROM BAR must have is_memory=true");
663 }
664 if (bar.is_64bit) {
665 err("Expansion ROM BAR cannot be 64-bit");
666 }
667 }
668
669 // Valid 64-bit BAR offsets: 0x10, 0x18, 0x20 (naturally
670 // aligned to 8 bytes)
671 if (bar.is_64bit && (bar.offset & 7) != 0) {
672 err("64-bit BAR must be naturally aligned to 8-byte boundary; "
673 "offset must be 0x10, 0x18, or 0x20");
674 }
675
676 // For non-64-bit BARs the register is 32-bit wide; a size
677 // exceeding 4 GiB is not addressable (PCIe Base Spec 6.0,
678 // Sec 7.5.1.2.1).
679 if (!bar.is_64bit && bar.size_bits > 32) {
680 std::ostringstream os;
681 os << "32-bit BAR size_bits=" << bar.size_bits
682 << " exceeds maximum of 32";
683 err(os.str());
684 }
685
686 if (bar.target_socket == nullptr) {
687 err("target_socket must not be null");
688 }
689
690 // Duplicate (function, offset) pairs corrupt the internal
691 // socket-ID map built in before_end_of_elaboration.
692 auto key = std::make_pair(bar.function, bar.offset);
693 if (seen.count(key)) {
694 err("duplicate BAR entry; each (function, offset)"
695 " pair must be unique");
696 } else {
697 seen[key] = true;
698 }
699 }
700
701 // Second pass: detect 64-bit BAR slot overlap.
702 // A 64-bit BAR at offset N implicitly consumes the upper-half slot at
703 // N+4. If a separate entry also uses N+4 for the same function,
704 // retrieveFunctionData() would read/write the same base_address slot
705 // inconsistently and before_end_of_elaboration() would build invalid maps.
706 // Collect the set of (function, offset) pairs claimed by 64-bit upper
707 // halves, then flag any explicit entry that collides with them.
708 std::map<std::pair<int, int>, int> upper_half_of;
709 for (const auto &bar : bar_info_) {
710 if (bar.is_64bit && bar.offset != 0x30) {
711 upper_half_of[std::make_pair(bar.function,
712 bar.offset + 4)] = bar.offset;
713 }
714 }
715 for (const auto &bar : bar_info_) {
716 auto it = upper_half_of.find(
717 std::make_pair(bar.function, bar.offset));
718 if (it != upper_half_of.end()) {
719 std::ostringstream os;
720 os << "BAR (function=" << bar.function
721 << ", offset=0x" << std::hex << bar.offset
722 << "): offset is already occupied as the upper 32-bit half"
723 << " of the 64-bit BAR at offset 0x" << it->second;
724 SIM_LOG_ERROR_STR(o, Log_Configuration, os.str());
725 valid = false;
726 }
727 }
728 return valid;
729}
730
731template <unsigned int BUSWIDTH, typename TYPES>
735 iface::PcieResetInterface *reset, ConfObjectRef o,
737 if (pci == nullptr) {
738 SIM_LOG_ERROR(
740 "PcieDeviceQueryInterface not implemented on the device");
741 return;
742 }
743
744 if (bar == nullptr) {
745 SIM_LOG_ERROR(
747 "PcieBaseAddressRegisterQueryInterface not implemented on"
748 " the device");
749 return;
750 }
751
752 if (reset == nullptr) {
753 SIM_LOG_ERROR(o, Log_Configuration,
754 "PcieResetInterface not implemented on the device");
755 return;
756 }
757
758 // Check the BAR info
759 bar_info_ = bar->getBarInfo();
760 if (!validateBarInfo(o)) {
761 bar_info_.clear();
762 return;
763 }
764
765 // Get the config target_socket from the device
766 castToTarget(pci->getConfigTargetSocket(), &config_target_socket_);
767
768 // Get the message target_socket from the device
769 castToTarget(pci->getMsgTargetSocket(), &msg_target_socket_);
770
771 // Set the reset interface
772 reset_ = reset;
773
774 // Calculate how many functions are there (f0 is required)
775 for (const auto &bar : bar_info_) {
776 if (function_data_.find(bar.function) == function_data_.end()) {
777 function_data_[bar.function];
778 if (bar.function > 7) {
779 function_number_has_8bits_ = true;
780 }
781 }
782 }
783
784 // Bind pcie_map_target_socket_ so device can call pcie_map interface
785 auto *initiator = dynamic_cast<
786 tlm::tlm_initiator_socket<BUSWIDTH, TYPES> *>(
788 if (initiator) {
789 pcie_map_target_socket_.bind(*initiator);
790 } else {
791 SIM_LOG_ERROR(o, Log_Configuration,
792 "object returned by getPcieMapInitiatorSocket was not"
793 " a tlm::tlm_initiator_socket.");
794 }
795
796 simulation_obj_ = o;
797 sriov_query_ = sriov;
798 setupSriovStates();
799 createCfgMapHelper();
800}
801
802template <unsigned int BUSWIDTH, typename TYPES>
803std::map<std::pair<size_t, size_t>, size_t>
805 return address_id_mem_map_;
806}
807
808template <unsigned int BUSWIDTH, typename TYPES>
809std::map<std::pair<size_t, size_t>, size_t>
811 return address_id_io_map_;
812}
813
814template <unsigned int BUSWIDTH, typename TYPES>
817 sriov_states_.clear();
818 if (sriov_query_ != nullptr) {
819 for (const auto &info : sriov_query_->getSriovInfo()) {
820 SriovState state = {};
821 state.cap_offset = info.cap_offset;
822 state.pf_function = info.pf_function;
823 state.total_vfs = info.total_vfs;
824 state.first_vf_function = info.first_vf_function;
825 state.vf_stride = (info.vf_stride <= 0) ? 1 : info.vf_stride;
826
827 // SR-IOV spec §9.3.3.10: VF BARs must be Memory Space only.
828 for (const auto &bi : bar_info_) {
829 const int fn = bi.function;
830 const bool is_vf = state.containsFunction(fn);
831 if (is_vf && !bi.is_memory) {
832 std::ostringstream oss;
833 oss << "SR-IOV: VF BAR (function=" << fn
834 << " offset=0x" << std::hex << bi.offset
835 << ") has is_memory=false; VF BARs must be"
836 " Memory Space only per PCIe SR-IOV spec";
837 SIM_LOG_ERROR(simulation_obj_, Log_Configuration,
838 "%s", oss.str().c_str());
839 }
840 }
841
842 sriov_states_.push_back(state);
843 }
844 }
845}
846
847// Map or unmap VF config space entries in the Simics pcie_map.
848// Called when VF Enable (SR-IOV Control bit 0) transitions.
849template <unsigned int BUSWIDTH, typename TYPES>
850void PcieMappingInterconnect<BUSWIDTH, TYPES>::
851updateVfCfgMappings(SriovState &state, bool enable) {
852 const int num_vfs = static_cast<int>(state.num_vfs);
853 {
854 std::ostringstream os;
855 os << "SR-IOV PF" << state.pf_function << ": "
856 << (enable ? "enabling " : "disabling ") << num_vfs
857 << " VF config space(s)";
858 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
859 }
860 for (int i = 0; i < num_vfs; ++i) {
861 const uint16_t fn = static_cast<uint16_t>(
862 state.first_vf_function + i * state.vf_stride);
863 if (enable) {
864 pcie_map_extension_.enable_function(device_id_ | fn);
865 } else {
866 pcie_map_extension_.disable_function(device_id_ | fn);
867 }
868 }
869}
870
871// Map or unmap VF BAR memory regions in the Simics pcie_map.
872// Called when VF MSE (SR-IOV Control bit 3) transitions while VF Enable is
873// set, or when VF Enable transitions while VF MSE is already set.
874template <unsigned int BUSWIDTH, typename TYPES>
875void PcieMappingInterconnect<BUSWIDTH, TYPES>::
876updateVfBarMappings(SriovState &state, bool enable) {
877 const int num_vfs = static_cast<int>(state.num_vfs);
878
879 // Iterate over VF0's BAR entries to discover the layout (size_bits,
880 // is_64bit etc.). The SR-IOV spec §9.3.3.14 guarantees every VF shares
881 // the same BAR layout. vf_bar[i] == (cap+0x24 + i*4) == cfg BAR offset
882 // (0x10+i*4), so the index maps 1:1 to cfg_header_t::base_address[].
883 for (const auto &bi : bar_info_) {
884 if (bi.function != state.first_vf_function || !bi.is_memory)
885 continue;
886
887 const int ba_idx = (bi.offset - 0x10) / 4;
888 if (ba_idx < 0 || ba_idx >= 6)
889 continue;
890
891 const int sz = bi.size_bits;
892 if (sz >= 64) {
893 // Silently skip bad configurations. This should be validated by
894 // the initial query and not here on each map/unmap call.
895 continue;
896 }
897 const uint32_t lo = state.vf_bar[ba_idx];
898 const uint32_t hi = (bi.is_64bit && ba_idx + 1 < 6)
899 ? state.vf_bar[ba_idx + 1] : 0u;
900 const uint64_t vf_bar_raw = (static_cast<uint64_t>(hi) << 32) | lo;
901 const uint64_t align_mask = ~((1ULL << sz) - 1ULL);
902 const uint64_t vf_base = vf_bar_raw & align_mask;
903
904 {
905 std::ostringstream os;
906 os << "SR-IOV PF" << state.pf_function
907 << " VF BAR (cfg 0x" << std::hex << bi.offset << "): "
908 << (enable ? "enabling " : "disabling ")
909 << std::dec << num_vfs << " VF BAR(s)";
910 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
911 }
912
913 // Loop only over the NumVFs VFs that are active (or were active).
914 for (int i = 0; i < num_vfs; ++i) {
915 const uint16_t fn = static_cast<uint16_t>(
916 state.first_vf_function + i * state.vf_stride);
917 auto it = function_data_.find(fn);
918 if (it == function_data_.end()) {
919 std::ostringstream os;
920 os << "SR-IOV PF" << state.pf_function
921 << ": VF function " << fn
922 << " not found in function_data_ — inconsistent SR-IOV"
923 " configuration (getSriovInfo() and getBarInfo()"
924 " disagree)";
925 SC_REPORT_ERROR(PCIE_MAPPING_INTERCONNECT_TAG,
926 os.str().c_str());
927 return;
928 }
929 auto &fd = it->second;
930 // VF Command register has MSE hardwired to 0 (PCIe spec
931 // §7.5.1.1.3) — do not use fd.command to gate VF BAR
932 // mappings. Drive add_map / del_map directly so that the
933 // VF's command register is never forged.
934 const size_t socket_id = fn_bar_id_map_.at(
935 std::make_pair(static_cast<size_t>(fn),
936 static_cast<size_t>(bi.offset)));
937 delMap(socket_id, types::PCIE_Type_Mem);
938 if (enable) {
939 const uint64_t vf_addr =
940 vf_base + static_cast<uint64_t>(i) * (1ULL << sz);
941 fd.base_address[ba_idx] = static_cast<uint32_t>(vf_addr);
942 if (bi.is_64bit && ba_idx + 1 < 7)
943 fd.base_address[ba_idx + 1] =
944 static_cast<uint32_t>(vf_addr >> 32);
945 const types::map_info_t info(
946 vf_addr, vf_addr, 1ULL << sz,
947 static_cast<int>(fn));
948 address_id_mem_map_[std::make_pair(
949 vf_addr, vf_addr + (1ULL << sz))] = socket_id;
950 addMap(info, types::PCIE_Type_Mem);
951 } else {
952 fd.base_address[ba_idx] = 0;
953 if (bi.is_64bit && ba_idx + 1 < 7)
954 fd.base_address[ba_idx + 1] = 0;
955 }
956 }
957 }
958}
959
960template <unsigned int BUSWIDTH, typename TYPES>
961void PcieMappingInterconnect<BUSWIDTH, TYPES>::
962retrieveFunctionData(size_t socket_id, int bar_id) {
963 if (initiator_sockets_.size() <= socket_id) {
964 std::ostringstream os;
965 os << "Invalid socket_id: " << socket_id;
966 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
967 return;
968 }
969
970 tlm::tlm_generic_payload trans;
971 // The data pointer, length and stream width attribute are reused
972 // since they are not modifiable by the target according to the spec
973 uint32_t value = 0;
974 trans.set_data_ptr(reinterpret_cast<unsigned char *>(&value));
975 trans.set_data_length(4);
976 trans.set_streaming_width(4);
977
978 trans.set_command(tlm::TLM_READ_COMMAND);
979 trans.set_address(0x4);
980
981 auto ret = initiator_sockets_[socket_id]->transport_dbg(trans);
982 if (ret == 0) {
983 // The target is not able to perform the transport_dbg.
984 // The PCIe interconnector is unable to get the up-to-date
985 // BAR/CMD information which may cause unexpected behavior
986 return;
987 }
988
989 auto fd = function_data_.begin();
990 std::advance(fd, socket_id);
991 fd->second.command = value;
992
993 // NOTE: the IO, Mem32, Mem64 bits are ignored by updateMapping,
994 // no need to filter them out here
995 for (const auto &bar : bar_info_) {
996 // BarInfo holds _all_ BARs for _all_ functions. This can probably
997 // be done in a much more clever way that avoids iterating over the
998 // entire BarInfo for each function in the outer loop.
999 if (bar.function != fd->first) {
1000 continue;
1001 }
1002
1003 int expected_bar_id = bar.offset == 0x30 ? 6 : (bar.offset - 0x10) / 4;
1004 // bar_id == -1 => read all bars
1005 if (bar_id != -1 && bar_id != expected_bar_id) {
1006 continue;
1007 }
1008
1009 trans.set_address(bar.offset);
1010 initiator_sockets_[socket_id]->transport_dbg(trans);
1011 fd->second.base_address[expected_bar_id] = value;
1012 if (bar.is_64bit) {
1013 if (expected_bar_id == 6) {
1014 SC_REPORT_ERROR(
1015 PCIE_MAPPING_INTERCONNECT_TAG,
1016 "Expansion ROM BAR can't support 64-bit address");
1017 } else {
1018 // Read higher 32 bits in next BAR
1019 trans.set_address(bar.offset + 4);
1020 initiator_sockets_[socket_id]->transport_dbg(trans);
1021 fd->second.base_address[expected_bar_id + 1] = value;
1022 }
1023 }
1024 }
1025}
1026
1027template <unsigned int BUSWIDTH, typename TYPES>
1028void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1029addMap(types::map_info_t info, types::pcie_type_t type) {
1030 std::ostringstream os;
1031 os << "Adding mapping of type: "
1032 << pcieTypeName(type);
1033 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
1034 pcie_map_extension_.add_map(info, type);
1035 if (sender_.failed_transaction_.payload()) {
1036 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, "Failure to add map");
1037 return;
1038 }
1039}
1040
1041template <unsigned int BUSWIDTH, typename TYPES>
1042void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1043delMap(size_t socket_id, types::pcie_type_t type) {
1044 types::map_info_t::physical_address_t base = 0xffffffffffffffff;
1045 if (type == types::PCIE_Type_Mem) {
1046 auto it = std::find_if(
1047 address_id_mem_map_.begin(),
1048 address_id_mem_map_.end(),
1049 [socket_id](
1050 const std::pair<std::pair<size_t, size_t>, size_t> &entry) {
1051 return entry.second == socket_id;
1052 });
1053
1054 if (it != address_id_mem_map_.end()) {
1055 base = it->first.first;
1056 address_id_mem_map_.erase(it);
1057 }
1058 } else if (type == types::PCIE_Type_IO) {
1059 auto it = std::find_if(
1060 address_id_io_map_.begin(),
1061 address_id_io_map_.end(),
1062 [socket_id](
1063 const std::pair<std::pair<size_t, size_t>, size_t> &entry) {
1064 return entry.second == socket_id;
1065 });
1066
1067 if (it != address_id_io_map_.end()) {
1068 base = it->first.first;
1069 address_id_io_map_.erase(it);
1070 }
1071 }
1072
1073 if (base != 0xffffffffffffffff) {
1074 std::ostringstream os;
1075 os << "Deleting mapping of type: "
1076 << pcieTypeName(type) << ", base: 0x" << std::hex << base;
1077 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
1078
1079 pcie_map_extension_.del_map(base, type);
1080 if (sender_.failed_transaction_.payload()) {
1081 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, "Failure to del map");
1082 return;
1083 }
1084 }
1085}
1086
1087template <unsigned int BUSWIDTH, typename TYPES>
1088void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1089updateMappings(int function_id, int bar_id) {
1090 for (const auto &bi : bar_info_) {
1091 if (function_id != -1 && bi.function != function_id) {
1092 continue;
1093 }
1094
1095 auto header = function_data_.at(bi.function);
1096
1097 int expected_bar_id = bi.offset == 0x30 ? 6 : (bi.offset - 0x10) / 4;
1098 if (bar_id != -1 && bar_id != expected_bar_id) {
1099 continue;
1100 }
1101
1102 uint64_t base_address = header.base_address[expected_bar_id];
1103 if (bi.is_64bit) {
1104 if (expected_bar_id == 6) {
1105 SC_REPORT_ERROR(
1106 PCIE_MAPPING_INTERCONNECT_TAG,
1107 "Expansion ROM BAR can't support 64-bit address");
1108 } else {
1109 base_address |= static_cast<uint64_t>(
1110 header.base_address[expected_bar_id + 1]) << 32;
1111 }
1112 }
1113
1114 bool enable = header.command & 1;
1116 if (bi.is_memory) {
1117 type = types::PCIE_Type_Mem;
1118 if (bi.offset == 0x30) {
1119 enable = base_address & 1;
1120 } else {
1121 enable = (header.command >> 1) & 1;
1122 }
1123 }
1124 base_address &= ~((1ULL << bi.size_bits) - 1);
1125 size_t socket_id = fn_bar_id_map_.at(
1126 std::make_pair(bi.function, bi.offset));
1127 delMap(socket_id, type);
1128 if (enable) {
1129 // The `start` field in map_info_t is set to base,
1130 // so later when receiving the transaction, the address
1131 // can be used to route the transaction to the right socket
1132 types::map_info_t info(base_address, base_address,
1133 1ULL << bi.size_bits, function_id);
1134 auto address_range = std::make_pair(info.base,
1135 info.base + info.length);
1136
1137 if (bi.is_memory) {
1138 address_id_mem_map_[address_range] = socket_id;
1139 std::ostringstream os;
1140 os << "Memory address for function " << bi.function
1141 << " and bar ID " << expected_bar_id
1142 << " in range of [0x" << std::hex << info.base
1143 << "-0x" << info.base + info.length << "] maps to socket ID "
1144 << socket_id;
1145 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
1146 } else {
1147 address_id_io_map_[address_range] = socket_id;
1148 std::ostringstream os;
1149 os << "IO address for function " << bi.function
1150 << " and bar ID " << expected_bar_id
1151 << " in range of [0x" << std::hex << info.base
1152 << "-0x" << info.base + info.length << "] maps to socket ID "
1153 << socket_id;
1154 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
1155 }
1156 addMap(info, type);
1157 }
1158 }
1159}
1160
1161template <unsigned int BUSWIDTH, typename TYPES>
1162void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1163updateCommand(uint16_t function_id, uint16_t old_command) {
1164 if (function_data_[function_id].command != old_command) {
1165 updateMappings(function_id);
1166 }
1167}
1168
1169template <unsigned int BUSWIDTH, typename TYPES>
1170void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1171interceptCfgHeaderAccess(size_t socket_id,
1172 tlm::tlm_generic_payload &trans) { // NOLINT
1173 unsigned int size = trans.get_data_length();
1174 // Check assumptions (but leave it up to target device to report errors)
1175 if (trans.get_byte_enable_ptr() || trans.get_streaming_width() != size) {
1176 return;
1177 }
1178
1179 // We are only interested in write access to BARn or Command regs
1180 if (!trans.is_write()) {
1181 return;
1182 }
1183
1184 // Maximum size is 8
1185 uint64_t *data = reinterpret_cast<uint64_t *>(trans.get_data_ptr());
1186
1187 auto it = function_data_.begin();
1188 std::advance(it, socket_id);
1189 uint16_t function_id = it->first;
1190 auto &header = it->second;
1191 sc_dt::uint64 offset = trans.get_address();
1192 const bool is_vf = std::any_of(
1193 sriov_states_.begin(), sriov_states_.end(),
1194 [function_id](const SriovState &state) {
1195 return state.containsFunction(function_id);
1196 });
1197 switch (offset) {
1198 case 0x04: { // command & status
1199 uint16_t command = 0;
1200 std::memcpy(&command, trans.get_data_ptr(),
1201 std::min<size_t>(size, sizeof command));
1202 if (is_vf) {
1203 constexpr uint16_t vf_command_roz_mask = 0x403u;
1204 if (command & vf_command_roz_mask) {
1205 SIM_LOG_SPEC_VIOLATION(
1206 1, simulation_obj_, Log_Configuration,
1207 "SR-IOV VF function %u: Command I/O Space Enable, "
1208 "Memory Space Enable and Interrupt Disable are "
1209 "hardwired to zero; "
1210 "ignoring attempts to set these bits",
1211 static_cast<unsigned int>(function_id));
1212 }
1213 // VF decoding is controlled by the PF's SR-IOV Control, not
1214 // by Command. Do not read VF BAR slots into the derived cache.
1215 header.command = command & ~vf_command_roz_mask;
1216 break;
1217 }
1218 uint16_t old_command = header.command;
1219 retrieveFunctionData(socket_id, -1);
1220 header.command = command;
1221 updateCommand(function_id, old_command);
1222 break;
1223 }
1224 case 0x10: // BAR0-BAR5
1225 case 0x14:
1226 case 0x18:
1227 case 0x1c:
1228 case 0x20:
1229 case 0x24:
1230 case 0x30: { // Expansion ROM BAR
1231 int bar_id = offset == 0x30 ? 6 : (offset - 0x10) / 4;
1232 if (is_vf) {
1233 uint64_t value = 0;
1234 std::memcpy(&value, trans.get_data_ptr(),
1235 std::min<size_t>(size, sizeof value));
1236 if (value != 0) {
1237 SIM_LOG_SPEC_VIOLATION(
1238 1, simulation_obj_, Log_Configuration,
1239 "SR-IOV VF function %u: config-header BAR%d is "
1240 "hardwired to zero; ignoring nonzero write",
1241 static_cast<unsigned int>(function_id), bar_id);
1242 }
1243 // Keep derived VF addresses and mappings controlled by the PF.
1244 break;
1245 }
1246 retrieveFunctionData(socket_id, bar_id);
1247 // NOTE: the IO, Mem32, Mem64 bits are ignored by
1248 // updateMapping, no need to filter them out here. In
1249 // addition, any bits less than the size of the BAR as defined
1250 // by the BarInfo will also be ignored/truncated by
1251 // updateMapping; making sure we always send a naturally
1252 // aligned address to Simics
1253 header.base_address[bar_id] = *data & 0xffffffff;
1254 if (bar_id != 6 && size == 8 && !(offset % 8)) {
1255 header.base_address[bar_id + 1] = *data >> 32;
1256 }
1257 updateMappings(function_id, bar_id);
1258 break;
1259 }
1260 }
1261
1262 // SR-IOV Extended Capability snooping — iterate all PF SR-IOV groups.
1263 for (auto &state : sriov_states_) {
1264 if (static_cast<int>(function_id) != state.pf_function)
1265 continue;
1266 const sc_dt::uint64 cap = state.cap_offset;
1267 const uint32_t written = static_cast<uint32_t>(*data);
1268 if (offset == cap + 0x08) {
1269 const uint16_t old_ctrl = state.control;
1270 state.control = static_cast<uint16_t>(written & 0xFFFFu);
1271 // Per PCIe SR-IOV spec §9.3.3.3, the two bits have separate roles:
1272 // VF Enable (bit 0): VFs become enumerable; their config space
1273 // is accessible → enable_function / disable_function.
1274 // VF MSE (bit 3): VF memory space (BARs) responds to memory
1275 // transactions; requires VF Enable to be set first
1276 // → add_map / del_map.
1277 // The two transitions are handled independently so that software
1278 // can set VF Enable alone to probe VF config space before
1279 // committing BAR resources.
1280 const bool vf_enable_was = old_ctrl & 0x1u;
1281 const bool vf_enable_now = state.control & 0x1u;
1282 const bool vf_mse_was = (old_ctrl >> 3) & 0x1u;
1283 const bool vf_mse_now = (state.control >> 3) & 0x1u;
1284 const bool bars_were_live = vf_enable_was && vf_mse_was;
1285 const bool bars_are_live = vf_enable_now && vf_mse_now;
1286 if (vf_enable_was != vf_enable_now) {
1287 updateVfCfgMappings(state, vf_enable_now);
1288 }
1289 if (bars_were_live != bars_are_live) {
1290 updateVfBarMappings(state, bars_are_live);
1291 }
1292 } else if (offset == cap + 0x10) { // NumVFs (OS-programmed)
1293 const uint16_t num_vfs = static_cast<uint16_t>(written & 0xFFFFu);
1294 if (num_vfs > state.total_vfs) {
1295 std::ostringstream os;
1296 os << "SR-IOV: NumVFs (" << num_vfs
1297 << ") exceeds TotalVFs (" << state.total_vfs
1298 << ") for PF" << state.pf_function
1299 << "; retaining previous NumVFs (" << state.num_vfs
1300 << ")";
1301 SC_REPORT_WARNING(PCIE_MAPPING_INTERCONNECT_TAG,
1302 os.str().c_str());
1303 } else {
1304 state.num_vfs = num_vfs;
1305 }
1306 } else if (offset >= cap + 0x24 && offset < cap + 0x24 + 6 * 4) {
1307 // VF BAR registers +0x24..+0x38 (6 × 4-byte slots, §9.3.3.14).
1308 // Index = (cap_rel - 0x24)/4 == (vf_cfg_offset - 0x10)/4,
1309 // matching vf_bar[] and cfg_header_t::base_address[] directly.
1310 const int idx = static_cast<int>((offset - (cap + 0x24)) / 4);
1311 state.vf_bar[idx] = written;
1312 // §9.3.3.14: a VF BAR write changes the base address for ALL
1313 // VFs (BARb_VFv = VF_BARb + v×aperture). If BARs are live
1314 // (VF Enable && VF MSE), del_map old ranges and add_map new
1315 // ranges for every active VF.
1316 const bool vf_en = (state.control & 0x1u) != 0;
1317 const bool vf_mse = ((state.control >> 3) & 0x1u) != 0;
1318 if (vf_en && vf_mse)
1319 updateVfBarMappings(state, true);
1320 }
1321 break; // each function_id matches at most one PF group
1322 }
1323}
1324
1325template <unsigned int BUSWIDTH, typename TYPES>
1326size_t PcieMappingInterconnect<BUSWIDTH, TYPES>::
1327findSocketId(types::pcie_type_t type, uint16_t function_id,
1328 tlm::tlm_generic_payload &trans) const { // NOLINT
1329 if (type == types::PCIE_Type_Cfg) {
1330 auto found = function_data_.find(function_id);
1331 if (found == function_data_.end()) {
1332 std::ostringstream os;
1333 os << "Function id(" << function_id
1334 << ") not found for this device";
1335 throw std::invalid_argument {
1336 os.str()
1337 };
1338 }
1339 return std::distance(function_data_.begin(), found);
1340 } else if (type == types::PCIE_Type_Mem) {
1341 size_t address = trans.get_address();
1342 for (const auto &entry : address_id_mem_map_) {
1343 auto startAddress = entry.first.first;
1344 auto endAddress = entry.first.second;
1345 auto id = entry.second;
1346
1347 if (address >= startAddress && address < endAddress) {
1348 if (enable_base_address_subtraction) {
1349 trans.set_address(address - startAddress);
1350 }
1351 return id;
1352 }
1353 }
1354 throw std::invalid_argument {
1355 "Unable to find the initiator_socket to forward the MEM transaction"
1356 };
1357 } else if (type == types::PCIE_Type_IO) {
1358 size_t address = trans.get_address();
1359 for (const auto &entry : address_id_io_map_) {
1360 auto startAddress = entry.first.first;
1361 auto endAddress = entry.first.second;
1362 auto id = entry.second;
1363
1364 if (address >= startAddress && address < endAddress) {
1365 if (enable_base_address_subtraction) {
1366 trans.set_address(address - startAddress);
1367 }
1368 return id;
1369 }
1370 }
1371 throw std::invalid_argument {
1372 "Unable to find the initiator_socket to forward the IO transaction"
1373 };
1374 } else if (type == types::PCIE_Type_Msg) {
1375 return function_data_.size() + bar_info_.size();
1376 }
1377 throw std::invalid_argument {
1378 "Unsupported PCIe type"
1379 };
1380}
1381
1382template <unsigned int BUSWIDTH, typename TYPES>
1385 auto *map_helper = SIM_get_class("pcie_map_helper_cpp");
1386 if (map_helper == nullptr) {
1387 SIM_LOG_ERROR(
1388 simulation_obj_, Log_Configuration,
1389 "Simics class pcie_map_helper_cpp is required."
1390 "Try load the module pcie-map-helper-c++ first.");
1391 return;
1392 }
1393
1394 if (SIM_c_get_interface(simulation_obj_, "pcie_device") == nullptr) {
1395 // Make sure simulation_obj_ is ready to be used by other objects
1396 if (!SIM_object_is_configured(simulation_obj_)) {
1397 SIM_LOG_ERROR(
1398 simulation_obj_, Log_Configuration,
1399 "Simulation object is not configured yet, cannot get"
1400 " its gasket_list attribute");
1401 return;
1402 }
1403
1404 // For PCIe gasket object, the interface is not implemented
1405 // on the simulation object, but rather the gasket object
1406 auto gasket_list = SIM_get_attribute(simulation_obj_, "gasket_list");
1407 int gasket_count = SIM_attr_list_size(gasket_list);
1408 for (int i = 0; i < gasket_count; ++i) {
1409 auto obj = SIM_attr_object(SIM_attr_list_item(gasket_list, i));
1410 if (SIM_c_get_interface(obj, "pcie_device")) {
1411 gasket_obj_ = obj;
1412 break;
1413 }
1414 }
1415 if (gasket_obj_.object() == nullptr) {
1416 SIM_LOG_ERROR(
1417 simulation_obj_, Log_Configuration,
1418 "No gasket object implemented the required"
1419 " pcie_device interface");
1420 return;
1421 }
1422 } else {
1423 gasket_obj_ = simulation_obj_.object();
1424 }
1425
1426 for (const auto &fd : function_data_) {
1427 auto pcie_type = std_to_attr<>(
1428 std::pair<std::string, int>("pcie_type", types::PCIE_Type_Cfg));
1429 auto forward_target = std_to_attr<>(
1430 std::pair<std::string, ConfObjectRef>("forward_target",
1431 gasket_obj_));
1432 auto function_id = std_to_attr<>(
1433 std::pair<std::string, int>("function_id", fd.first));
1434 attr_value_t attr = SIM_make_attr_list(3, pcie_type, forward_target,
1435 function_id);
1436
1437 auto obj_name = gasket_obj_.name() + ".port.cfg" + \
1438 std::to_string(fd.first);
1439 auto *o = SIM_get_object(obj_name.c_str());
1440 if (o == nullptr) {
1441 std::ignore = SIM_clear_exception();
1442 o = SIM_create_object(map_helper, obj_name.c_str(), attr);
1443 }
1444 assert(o);
1445 SIM_attr_free(&attr);
1446 }
1447}
1448
1449template <unsigned int BUSWIDTH, typename TYPES>
1451getCfgMapHelper(uint16_t device_id) {
1452 std::string name = "port.cfg";
1453 if (function_number_has_8bits_) {
1454 name += std::to_string(device_id & 0xff);
1455 } else {
1456 name += std::to_string(device_id & 7);
1457 }
1458 auto map_helper = SIM_object_descendant(gasket_obj_, name.c_str());
1459 if (!map_helper) {
1460 SIM_LOG_CRITICAL(simulation_obj_, Log_Configuration,
1461 "Could not find map helper object with name '%s.%s'",
1462 gasket_obj_.name().c_str(), name.c_str());
1463 }
1464 return map_helper;
1465}
1466
1467template <unsigned int BUSWIDTH, typename TYPES>
1468size_t PcieMappingInterconnect<BUSWIDTH, TYPES>::
1469validateTransaction(tlm::tlm_generic_payload &trans) { // NOLINT
1470 PcieTlmExtension *pcie_ext = nullptr;
1471 trans.get_extension<PcieTlmExtension>(pcie_ext);
1472
1473 if (pcie_ext == nullptr) {
1474 trans.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
1475 SC_REPORT_ERROR(PCIE_MAPPING_INTERCONNECT_TAG,
1476 "PcieTlmExtension is required but not found");
1477 return 0;
1478 }
1479
1480 std::ostringstream os;
1481 os << "Received a PCIe transaction with type "
1482 << pcieTypeName(pcie_ext->type);
1483 if (pcie_ext->device_id_set) {
1484 os << ", " << pcieDeviceIdStr(pcie_ext->device_id);
1485 }
1486 os << ", address 0x" << std::hex << trans.get_address() << std::endl;
1487 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
1488
1489 if (pcie_ext->type == types::PCIE_Type_Not_Set
1490 || pcie_ext->type == types::PCIE_Type_Other) {
1491 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG,
1492 "Only support following PCIe types: MEM/IO/CFG/MSG");
1493 trans.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
1494 return 0;
1495 }
1496
1497 if (pcie_ext->type == types::PCIE_Type_Cfg
1498 && !pcie_ext->device_id_set) {
1499 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG,
1500 "PCIe device ID ATOM is required");
1501 trans.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
1502 return 0;
1503 }
1504
1505 size_t socket_id = 0;
1506 try {
1507 // For ARI (function numbers > 7) use 8-bit function extraction,
1508 // otherwise mask to the standard 3-bit function field.
1509 const uint16_t fn = function_number_has_8bits_
1510 ? (pcie_ext->device_id & 0xFF)
1511 : (pcie_ext->device_id & 7);
1512 socket_id = findSocketId(pcie_ext->type, fn, trans);
1513 } catch (const std::exception &e) {
1514 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, e.what());
1515 trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);
1516 return 0;
1517 }
1518
1519 if (socket_id >= initiator_sockets_.size()) {
1520 os.clear();
1521 os << "Initiator socket ID " << socket_id << " not created yet";
1522 SC_REPORT_INFO(PCIE_MAPPING_INTERCONNECT_TAG, os.str().c_str());
1523 trans.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
1524 return 0;
1525 }
1526
1527 if (pcie_ext->type == types::PCIE_Type_Cfg) {
1528 interceptCfgHeaderAccess(socket_id, trans);
1529 }
1530
1531 return socket_id;
1532}
1533
1534template <unsigned int BUSWIDTH, typename TYPES>
1535void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1536transaction_b_transport(tlm::tlm_generic_payload &trans, // NOLINT: SystemC API
1537 sc_core::sc_time &t) { // NOLINT: SystemC API
1538 trans.set_response_status(tlm::TLM_OK_RESPONSE);
1539 size_t socket_id = validateTransaction(trans);
1540 if (trans.get_response_status() == tlm::TLM_OK_RESPONSE) {
1541 initiator_sockets_.at(socket_id)->b_transport(trans, t);
1542 }
1543}
1544
1545template <unsigned int BUSWIDTH, typename TYPES>
1546unsigned int PcieMappingInterconnect<BUSWIDTH, TYPES>::
1547transaction_transport_dbg(tlm::tlm_generic_payload &trans) { // NOLINT
1548 trans.set_response_status(tlm::TLM_OK_RESPONSE);
1549 size_t socket_id = validateTransaction(trans);
1550 if (trans.get_response_status() == tlm::TLM_OK_RESPONSE) {
1551 return initiator_sockets_.at(socket_id)->transport_dbg(trans);
1552 } else {
1553 return 0;
1554 }
1555}
1556
1557/*
1558 * For pcie-map, just relay the incoming BW transaction to target socket
1559 */
1560template <unsigned int BUSWIDTH, typename TYPES>
1561void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1562pcie_map_invalidate_direct_mem_ptr(sc_dt::uint64 start_range,
1563 sc_dt::uint64 end_range) {
1564 pcie_map_target_socket_->invalidate_direct_mem_ptr(start_range,
1565 end_range);
1566}
1567
1568/*
1569 * For pcie-map, just relay the incoming transaction to outgoing socket
1570 */
1571template <unsigned int BUSWIDTH, typename TYPES>
1572void PcieMappingInterconnect<BUSWIDTH, TYPES>::pcie_map_b_transport(
1573 tlm::tlm_generic_payload &trans, // NOLINT
1574 sc_core::sc_time &t) { // NOLINT
1575 pcie_map_initiator_socket->b_transport(trans, t);
1576}
1577
1578/*
1579 * For pcie-map, just relay the incoming transaction to outgoing socket
1580 */
1581template <unsigned int BUSWIDTH, typename TYPES>
1582unsigned int PcieMappingInterconnect<BUSWIDTH, TYPES>::pcie_map_transport_dbg(
1583 tlm::tlm_generic_payload &trans) { // NOLINT
1584 return pcie_map_initiator_socket->transport_dbg(trans);
1585}
1586
1587/*
1588 * For pcie-map, just relay the incoming transaction to outgoing socket
1589 */
1590template <unsigned int BUSWIDTH, typename TYPES>
1591bool PcieMappingInterconnect<BUSWIDTH, TYPES>::pcie_map_get_direct_mem_ptr(
1592 tlm::tlm_generic_payload &trans, // NOLINT
1593 tlm::tlm_dmi &dmi_data) { // NOLINT
1594 return pcie_map_initiator_socket->get_direct_mem_ptr(trans, dmi_data);
1595}
1596
1597template <unsigned int BUSWIDTH, typename TYPES>
1598void PcieMappingInterconnect<BUSWIDTH, TYPES>::
1599castToTarget(sc_core::sc_object *object, supported_target_socket_t *target) {
1600 if (object == nullptr) {
1601 SC_REPORT_ERROR(PCIE_MAPPING_INTERCONNECT_TAG,
1602 "Unable to castToTarget from a nullptr");
1603 return;
1604 }
1605
1606 auto *tlm_target = dynamic_cast<
1607 tlm::tlm_target_socket<BUSWIDTH, TYPES> *>(object);
1608 if (tlm_target) {
1609 target->tlm = tlm_target;
1610 return;
1611 }
1612
1613 auto *multi_target = dynamic_cast<
1614 tlm_utils::multi_target_base<BUSWIDTH, TYPES> *>(object);
1615 if (multi_target) {
1616 target->multi = multi_target;
1617 return;
1618 }
1619
1620 SC_REPORT_ERROR(PCIE_MAPPING_INTERCONNECT_TAG,
1621 "Unable to dynamic-cast PCIe target socket");
1622}
1623
1624} // namespace composite
1625} // namespace systemc
1626} // namespace simics
1627
1628#endif
void send_extension(iface::Transaction *transaction) override
Called by extension after the extension is set on the payload.
Definition: pcie_mapping_interconnect.h:88
virtual ~PcieMappingInterconnectExtensionSender()
Definition: pcie_mapping_interconnect.h:85
iface::Transaction failed_transaction_
Definition: pcie_mapping_interconnect.h:97
void send_failed(iface::Transaction *transaction) override
Called by extension if method_call invocation was missing.
Definition: pcie_mapping_interconnect.h:92
Definition: pcie_mapping_interconnect.h:107
PcieMappingInterconnect(sc_core::sc_module_name="PcieMappingInterconnect")
Definition: pcie_mapping_interconnect.h:122
void connected(uint16_t device_id)
Definition: pcie_mapping_interconnect.h:458
void before_end_of_elaboration() override
Definition: pcie_mapping_interconnect.h:415
bool enable_base_address_subtraction
Definition: pcie_mapping_interconnect.h:215
initiator_socket_t pcie_map_initiator_socket
IC -> Simics, forwards the upstream pcie-map transactions.
Definition: pcie_mapping_interconnect.h:210
void connect(iface::PcieDeviceQueryInterface *pci, iface::PcieBaseAddressRegisterQueryInterface *bar, iface::PcieResetInterface *reset, ConfObjectRef o, iface::PcieSriovQueryInterface *sriov=nullptr)
Called by (outer) composite class to retrieve the required information to connect the IC with the PCI...
Definition: pcie_mapping_interconnect.h:733
void hotReset()
Definition: pcie_mapping_interconnect.h:526
void createCfgMapHelper()
Definition: pcie_mapping_interconnect.h:1384
target_socket_t pcie_device_target_socket
Definition: pcie_mapping_interconnect.h:208
std::map< std::pair< size_t, size_t >, size_t > addressIdMemMap() const
Definition: pcie_mapping_interconnect.h:804
target_socket_t transaction_target_socket
Definition: pcie_mapping_interconnect.h:206
void disconnected(uint16_t device_id)
Definition: pcie_mapping_interconnect.h:505
sc_core::sc_in< bool > warm_reset_pin
Definition: pcie_mapping_interconnect.h:212
std::map< std::pair< size_t, size_t >, size_t > addressIdIoMap() const
Definition: pcie_mapping_interconnect.h:810
Generic extension sender initialized with a TLM2 initiator socket of TSocket type.
Definition: extension_sender.h:33
void send_extension(Transaction *transaction) override
Called by extension after the extension is set on the payload.
Definition: extension_sender.h:53
void init(TSocket *socket)
Definition: extension_sender.h:38
Transaction transaction() override
Called by extension to get a new Transaction.
Definition: extension_sender.h:47
void send_failed(Transaction *transaction) override
Called by extension if method_call invocation was missing.
Definition: extension_sender.h:56
void init(ExtensionSenderInterface *sender, tlm::tlm_generic_payload *payload)
Deprecated, use the init(ExtensionSenderInterface *sender) instead.
Definition: extension.h:43
Interface that allows the Simics glue to perform snooping and automatic connection of the device's ta...
Definition: pcie_device_query_interface.h:53
virtual std::vector< PCIeBar > getBarInfo()=0
BAR register information.
Interface required from a SystemC PCIe device in order to connect to Simics.
Definition: pcie_device_query_interface.h:30
virtual sc_core::sc_object * getMsgTargetSocket()=0
Target socket for downstream PCIe message transactions.
virtual sc_core::sc_object * getConfigTargetSocket()=0
Target socket for downstream PCIe configuration transactions.
virtual sc_core::sc_object * getPcieMapInitiatorSocket()=0
Initiator socket for upstream PCIe transactions and map operations.
Extension for Simics pcie_map interface.
Definition: pcie_map_extension.h:26
Definition: pcie_device_query_interface.h:94
Interface providing static SR-IOV configuration to the PcieMappingInterconnect.
Definition: pcie_device_query_interface.h:133
Class that encapsulates a generic_payload and returns it to the TransactionPool when the Transaction ...
Definition: transaction.h:29
conf_object_t * SIM_create_object(conf_class_t *NOTNULL cls, const char *name, attr_value_t attrs)
conf_object_t * SIM_get_object(const char *NOTNULL name)
attr_value_t SIM_get_attribute(conf_object_t *NOTNULL obj, const char *name)
conf_class_t * SIM_get_class(const char *NOTNULL name)
@ Log_Configuration
Definition: adapter_log_groups.h:23
pcie_type_t
Definition: pcie_type.h:20
@ PCIE_Type_Cfg
Definition: pcie_type.h:24
@ PCIE_Type_Mem
Definition: pcie_type.h:22
@ PCIE_Type_Msg
Definition: pcie_type.h:25
@ PCIE_Type_Not_Set
Definition: pcie_type.h:21
@ PCIE_Type_Other
Definition: pcie_type.h:26
@ PCIE_Type_IO
Definition: pcie_type.h:23
Definition: adapter.h:79
Reduced, stand-alone, version of the Simics map_info_t struct.
Definition: map_info.h:23
uint64_t physical_address_t
Definition: map_info.h:24