From b6d90c98238f3bdec7fe5bc55b5e9b4d53b4f982 Mon Sep 17 00:00:00 2001 From: Mingyu Ma Date: Wed, 2 Dec 2026 01:31:06 +0100 Subject: [PATCH] v1model core: find PHV fields and P4 objects once per program The v1model core looked up about thirty PHV fields and four P4 objects by name on every packet (phv->get_field("standard_metadata.egress_spec"), get_pipeline("ingress"), ...), each a string hash and a map lookup. It now finds them once per program, from the first packet's PHV: the parser, pipelines and deparser, and for each field the index of its header in the PHV and its offset there (every PHV of a program has the same headers), read with PHV::get_field(header, offset). A program swap, which happens only when the switch holds no packet, makes it find them again. - ProgramObjects, PhvField, Program(), FindField() (also for aliases such as intrinsic_metadata.*), Required() in P4CoreV1model; the standard fields that simple_switch requires stop the simulation with a message if a program lacks them (BMv2 threw std::out_of_range before). - All per-packet paths: ReceivePacket, the ingress, EnqueueNow, the egress, clones, recirculation, resubmission, multicast, the VOQ path, and the queue scheduler's input and output fields. - Same traffic, CPU time of the traffic (medians, taking turns with main): one switch 6.6 % faster, fat trees k=4 12 % and k=8 14 %. - Test (suite p4-packet, p4src/metadata/timestamps.stf): the ingress and egress timestamps and the parser error reach the program. No test read them before, so mutants that dropped these writes passed. - Docs: performance.md, TODO.md, test/Readme.md (261 cases). Co-Authored-By: Claude Opus 5.5 --- doc/TODO.md | 10 +- doc/performance.md | 15 +- model/p4-core-v1model.cc | 259 +++++-- model/p4-core-v1model.h | 84 ++ test/Readme.md | 4 +- test/p4-packet-test-suite.cc | 3 + test/p4src/metadata/metadata_v1model.json | 890 ++++++++++++++++++++++ test/p4src/metadata/metadata_v1model.p4 | 92 +++ test/p4src/metadata/timestamps.stf | 14 + 9 files changed, 1278 insertions(+), 93 deletions(-) create mode 100644 test/p4src/metadata/metadata_v1model.json create mode 100644 test/p4src/metadata/metadata_v1model.p4 create mode 100644 test/p4src/metadata/timestamps.stf diff --git a/doc/TODO.md b/doc/TODO.md index 2dc7160..26a7142 100644 --- a/doc/TODO.md +++ b/doc/TODO.md @@ -149,10 +149,12 @@ the run time in the default build. `counter_reset`, `mc_node_update`, the PRE commands of PNA, ...) still starts the Python CLI for the whole file, at about 85 ms per switch. Add them to the loader, with cases in `p4-flow-table-loader`, when a flow table needs them. -- **Fields and objects looked up by name per packet.** The v1model core calls - `phv->get_field("standard_metadata...")` about ten times per packet, and - `get_pipeline("ingress")` and the like: 3 to 4 %, and cache misses in large - networks. Proposal: resolve them once per program (and again after a swap). +- **Fields and objects looked up by name per packet.** Done for the v1model + core: it finds its PHV fields, parser, pipelines and deparser once per + program (and again after a swap), which made one switch 6.6 % and fat trees + 12 to 14 % faster ([performance.md](performance.md)). The PSA, PNA and + pipeline cores still look them up by name on every packet; the same change + would suit them. - **The time per hop grows with the network**: the instructions per hop stay the same, but from k=4 to k=8 the cycles per hop double (77,000 to 151,000), as the state of 80 BMv2 switches no longer fits in the caches. Fewer allocations and diff --git a/doc/performance.md b/doc/performance.md index 7fca746..aa92180 100644 --- a/doc/performance.md +++ b/doc/performance.md @@ -238,11 +238,18 @@ the C and C++ libraries (`malloc`, `memcpy`, `std::string`, ...) and in ns-3's for them: 9 to 11 % of the time, and 28 % (one switch) to 43 % (fat tree) of the instructions of the optimized build (next section). P4sim's log patch for BMv2 makes the macros check the level first ([Build options](#build-options)). -- **Fields by name.** P4sim's v1model core reads and writes about ten +- **Fields by name.** P4sim's v1model core read and wrote about ten `standard_metadata` and intrinsic fields per packet with - `phv->get_field("standard_metadata.egress_spec")` and finds its parser, + `phv->get_field("standard_metadata.egress_spec")` and found its parser, pipelines and deparser by name (`get_pipeline("ingress")`): each a string hash - and a map lookup, and in a large network a cache miss. + and a map lookup, and in a large network a cache miss. It now finds them once + per program (December 2026), and keeps for each field its header and offset in + the PHV. CPU time of the traffic, the median of three to five runs taking + turns with the version before, the same traffic: one switch (200,000 packets) + 4.10 s → 3.85 s (6.6 %), a k=4 fat tree 2.75 s → 2.45 s (12 %), k=8 + 2.79 s → 2.44 s (14 %): more than the 3 to 4 % of the profile, as the large + networks also lose cache misses. The PSA, PNA and pipeline cores still look + them up by name. - **P4sim's glue** has no single hot spot: the largest items are the switched-Ethernet channel (4 %), the egress dequeue (1 %), `Receive()` (1 %) and `ConvertToBmPacket()` (1 to 2 %), which allocates and copies each frame @@ -340,7 +347,7 @@ Ranked by gain for the cost. | 2 | Make BMv2's log macros check the level before they build their message. Done where `install.sh` and the `Dockerfile` build BMv2 (`patches/bmv2-log-level-check.patch`); upstream proposal pending | the effect of `--disable-logging-macros` without losing `BmLogLevel`: in the default build 23 to 40 % of the instructions, 1.4 to 1.7 times the speed | a BMv2 rebuild for a BMv2 installed otherwise | | 3 | Done: flow tables load in the process (`FlowTableLoader` `Auto`, the default) instead of one Python CLI per switch | init of k=16 from 228 s to 3.9 s, k=8 from 12 s to 0.4 s; 3 file descriptors per switch instead of 8 | – | | 4 | Raise the soft limit of open files to the hard limit when switches start | more than about 330 switches (120 with the runtime CLI) without `ulimit -n` | a few lines | -| 5 | Resolve the PHV fields and P4 objects that the v1model core uses once per program | 3 to 4 %, more in large networks | small | +| 5 | Done for v1model: the core finds the PHV fields and P4 objects it uses once per program | one switch 6.6 %, fat trees 12 % (k=4) and 14 % (k=8) | – | | 6 | Use switched-Ethernet ports instead of CSMA bridge ports | 25 to 30 % per packet; no CSMA losses at line rate | a choice in the user's script | | – | BMv2 `-O3`, `--disable-elogger` | none | – | diff --git a/model/p4-core-v1model.cc b/model/p4-core-v1model.cc index cfc28c9..61ac57d 100644 --- a/model/p4-core-v1model.cc +++ b/model/p4-core-v1model.cc @@ -34,6 +34,7 @@ #include #include // tracing info to file +#include #include #include #include @@ -240,6 +241,7 @@ void P4CoreV1model::ProgramSwapped() { ResolveSchedulerFields(); // the new program may name them differently + m_program.found = false; // and has other objects and another PHV } void @@ -345,42 +347,42 @@ P4CoreV1model::EventDrivenEgressDequeue(uint32_t port) // ---- Run the egress pipeline on the dequeued packet ---- NS_LOG_FUNCTION("Egress processing for the packet (event-driven)"); bm::PHV* phv = bm_packet->get_phv(); - bm::Pipeline* egress_mau = this->get_pipeline("egress"); - bm::Deparser* deparser = this->get_deparser("deparser"); + const ProgramObjects& p = Program(phv); + bm::Pipeline* egress_mau = p.egress; + bm::Deparser* deparser = p.deparser; - if (phv->has_field("intrinsic_metadata.egress_global_timestamp")) + if (p.egressTimestamp.Exists()) { - phv->get_field("intrinsic_metadata.egress_global_timestamp").set(GetTimeStamp()); + p.egressTimestamp.In(phv).set(GetTimeStamp()); } if (m_enableQueueingMetadata) { - uint64_t enq_timestamp = phv->get_field("queueing_metadata.enq_timestamp").get(); - phv->get_field("queueing_metadata.deq_timedelta").set(GetTimeStamp() - enq_timestamp); + uint64_t enq_timestamp = p.enqTimestamp.In(phv).get(); + p.deqTimedelta.In(phv).set(GetTimeStamp() - enq_timestamp); // With strict priority, the queue is the packet's priority, as in simple_switch - phv->get_field("queueing_metadata.deq_qdepth").set(info.depth); - if (phv->has_field("queueing_metadata.qid")) + p.deqQdepth.In(phv).set(info.depth); + if (p.qid.Exists()) { - phv->get_field("queueing_metadata.qid").set(info.queueId); + p.qid.In(phv).set(info.queueId); } } // What the scheduler tells the egress (GetOutputFields()) - for (size_t i = 0; i < m_outputFields.size(); i++) + for (size_t i = 0; i < p.outputFields.size(); i++) { - if (!m_outputFields[i].empty()) + if (p.outputFields[i].Exists()) { - phv->get_field(m_outputFields[i]).set(info.fields[i]); + p.outputFields[i].In(phv).set(info.fields[i]); } } - phv->get_field("standard_metadata.egress_port").set(out_port); + p.egressPort.In(phv).set(out_port); - bm::Field& f_egress_spec = phv->get_field("standard_metadata.egress_spec"); + bm::Field& f_egress_spec = p.egressSpec.In(phv); f_egress_spec.set(0); - phv->get_field("standard_metadata.packet_length") - .set(bm_packet->get_register(RegisterAccess::PACKET_LENGTH_REG_IDX)); + p.packetLength.In(phv).set(bm_packet->get_register(RegisterAccess::PACKET_LENGTH_REG_IDX)); egress_mau->apply(bm_packet.get()); @@ -403,8 +405,7 @@ P4CoreV1model::EventDrivenEgressDequeue(uint32_t port) bm::PHV* phv_copy = packet_copy->get_phv(); bm::FieldList* field_list = this->get_field_list(clone_field_list); field_list->copy_fields_between_phvs(phv_copy, phv); - phv_copy->get_field("standard_metadata.instance_type") - .set(PKT_INSTANCE_TYPE_EGRESS_CLONE); + p.instanceType.In(phv_copy).set(PKT_INSTANCE_TYPE_EGRESS_CLONE); auto packet_size = bm_packet->get_register(RegisterAccess::PACKET_LENGTH_REG_IDX); RegisterAccess::clear_all(packet_copy.get()); packet_copy->set_register(RegisterAccess::PACKET_LENGTH_REG_IDX, packet_size); @@ -444,11 +445,11 @@ P4CoreV1model::EventDrivenEgressDequeue(uint32_t port) bm::PHV* phv_copy = packet_copy->get_phv(); phv_copy->reset_metadata(); field_list->copy_fields_between_phvs(phv_copy, phv); - phv_copy->get_field("standard_metadata.instance_type").set(PKT_INSTANCE_TYPE_RECIRC); + p.instanceType.In(phv_copy).set(PKT_INSTANCE_TYPE_RECIRC); size_t packet_size = packet_copy->get_data_size(); RegisterAccess::clear_all(packet_copy.get()); packet_copy->set_register(RegisterAccess::PACKET_LENGTH_REG_IDX, packet_size); - phv_copy->get_field("standard_metadata.packet_length").set(packet_size); + p.packetLength.In(phv_copy).set(packet_size); packet_copy->set_ingress_length(packet_size); if (!AdmitToIngress(InputBuffer::PacketType::RECIRCULATE, std::move(packet_copy))) { @@ -606,17 +607,17 @@ P4CoreV1model::ReceivePacket(Ptr packetIn, RegisterAccess::set_ns_address(bm_packet.get(), addr_index); // setting standard metadata - phv->get_field("standard_metadata.ingress_port").set(inPort); + const ProgramObjects& p = Program(phv); + p.ingressPort.In(phv).set(inPort); // using packet register 0 to store length, this register will be updated for // each add_header / remove_header primitive call bm_packet->set_register(RegisterAccess::PACKET_LENGTH_REG_IDX, len); - phv->get_field("standard_metadata.packet_length").set(len); - bm::Field& f_instance_type = phv->get_field("standard_metadata.instance_type"); - f_instance_type.set(PKT_INSTANCE_TYPE_NORMAL); - if (phv->has_field("intrinsic_metadata.ingress_global_timestamp")) + p.packetLength.In(phv).set(len); + p.instanceType.In(phv).set(PKT_INSTANCE_TYPE_NORMAL); + if (p.ingressTimestamp.Exists()) { - phv->get_field("intrinsic_metadata.ingress_global_timestamp").set(GetTimeStamp()); + p.ingressTimestamp.In(phv).set(GetTimeStamp()); } uint64_t packetId = bm_packet->get_packet_id(); @@ -661,9 +662,10 @@ P4CoreV1model::HandleIngressPipeline() if (bm_packet == nullptr) return; - bm::Parser* parser = this->get_parser("parser"); - bm::Pipeline* ingress_mau = this->get_pipeline("ingress"); bm::PHV* phv = bm_packet->get_phv(); + const ProgramObjects& p = Program(phv); + bm::Parser* parser = p.parser; + bm::Pipeline* ingress_mau = p.ingress; uint32_t ingress_port = bm_packet->get_ingress_port(); @@ -686,14 +688,13 @@ P4CoreV1model::HandleIngressPipeline() IngressPass pass(*this, *bm_packet, "parser", "ingress"); parser->parse(bm_packet.get()); - if (phv->has_field("standard_metadata.parser_error")) + if (p.parserError.Exists()) { - phv->get_field("standard_metadata.parser_error").set(bm_packet->get_error_code().get()); + p.parserError.In(phv).set(bm_packet->get_error_code().get()); } - if (phv->has_field("standard_metadata.checksum_error")) + if (p.checksumError.Exists()) { - phv->get_field("standard_metadata.checksum_error") - .set(bm_packet->get_checksum_error() ? 1 : 0); + p.checksumError.In(phv).set(bm_packet->get_checksum_error() ? 1 : 0); } ingress_mau->apply(bm_packet.get()); @@ -701,7 +702,7 @@ P4CoreV1model::HandleIngressPipeline() bm_packet->reset_exit(); - bm::Field& f_egress_spec = phv->get_field("standard_metadata.egress_spec"); + bm::Field& f_egress_spec = p.egressSpec.In(phv); uint32_t egress_spec = f_egress_spec.get_uint(); auto clone_mirror_session_id = RegisterAccess::get_clone_mirror_session_id(bm_packet.get()); @@ -712,10 +713,9 @@ P4CoreV1model::HandleIngressPipeline() // detect mcast support, if this is true we assume that other fields needed // for mcast are also defined - if (phv->has_field("intrinsic_metadata.mcast_grp")) + if (p.mcastGrp.Exists()) { - bm::Field& f_mgid = phv->get_field("intrinsic_metadata.mcast_grp"); - mgid = f_mgid.get_uint(); + mgid = p.mcastGrp.In(phv).get_uint(); } // INGRESS CLONING @@ -750,9 +750,7 @@ P4CoreV1model::HandleIngressPipeline() // to ensure re-parsing gives the same result as the original parse. // TODO(https://github.com/p4lang/behavioral-model/issues/795): other // standard metadata should be preserved as well. - bm_packet_copy->get_phv() - ->get_field("standard_metadata.ingress_port") - .set(ingress_port); + p.ingressPort.In(bm_packet_copy->get_phv()).set(ingress_port); parser->parse(bm_packet_copy.get()); CopyFieldList(bm_packet, bm_packet_copy, @@ -798,7 +796,7 @@ P4CoreV1model::HandleIngressPipeline() CopyFieldList(bm_packet, bm_packet_copy, PKT_INSTANCE_TYPE_RESUBMIT, field_list_id); RegisterAccess::clear_all(bm_packet_copy.get()); bm_packet_copy->set_register(RegisterAccess::PACKET_LENGTH_REG_IDX, ingress_packet_size); - phv_copy->get_field("standard_metadata.packet_length").set(ingress_packet_size); + p.packetLength.In(phv_copy).set(ingress_packet_size); if (!AdmitToIngress(InputBuffer::PacketType::RESUBMIT, std::move(bm_packet_copy))) { @@ -811,8 +809,7 @@ P4CoreV1model::HandleIngressPipeline() if (mgid != 0) { NS_LOG_DEBUG("Multicast requested for packet"); - auto& f_instance_type = phv->get_field("standard_metadata.instance_type"); - f_instance_type.set(PKT_INSTANCE_TYPE_REPLICATION); + p.instanceType.In(phv).set(PKT_INSTANCE_TYPE_REPLICATION); MulticastPacket(bm_packet.get(), mgid); // when doing MulticastPacket, we discard the original packet return; @@ -827,8 +824,7 @@ P4CoreV1model::HandleIngressPipeline() NS_LOG_DEBUG("Dropping packet at the end of ingress"); return; } - auto& f_instance_type = phv->get_field("standard_metadata.instance_type"); - f_instance_type.set(PKT_INSTANCE_TYPE_NORMAL); + p.instanceType.In(phv).set(PKT_INSTANCE_TYPE_NORMAL); NS_LOG_DEBUG("Packet ID: " << bm_packet->get_packet_id() << ", Size: " << bm_packet->get_data_size() @@ -861,25 +857,23 @@ P4CoreV1model::EnqueueNow(uint32_t egress_port, std::unique_ptr&& pa packet->set_egress_port(egress_port); bm::PHV* phv = packet->get_phv(); + const ProgramObjects& p = Program(phv); // What the queue scheduler needs to know about the packet P4QueueMetadata meta; - meta.priority = phv->has_field("intrinsic_metadata.priority") - ? phv->get_field("intrinsic_metadata.priority").get() - : 0u; - for (size_t i = 0; i < m_inputFields.size(); i++) + meta.priority = p.priority.Exists() ? p.priority.In(phv).get() : 0u; + for (size_t i = 0; i < p.inputFields.size(); i++) { - if (!m_inputFields[i].empty()) + if (p.inputFields[i].Exists()) { - meta.fields[i] = phv->get_field(m_inputFields[i]).get(); + meta.fields[i] = p.inputFields[i].In(phv).get(); } } if (m_enableQueueingMetadata) { - phv->get_field("queueing_metadata.enq_timestamp").set(GetTimeStamp()); - phv->get_field("queueing_metadata.enq_qdepth") - .set(m_queueScheduler->GetEnqueueDepth(egress_port, meta)); + p.enqTimestamp.In(phv).set(GetTimeStamp()); + p.enqQdepth.In(phv).set(m_queueScheduler->GetEnqueueDepth(egress_port, meta)); } std::unique_ptr pushedOut; @@ -956,13 +950,14 @@ P4CoreV1model::MulticastPacket(bm::Packet* packet, unsigned int mgid) { NS_LOG_FUNCTION(this); auto* phv = packet->get_phv(); - auto& f_rid = phv->get_field("intrinsic_metadata.egress_rid"); + const ProgramObjects& p = Program(phv); + auto& f_rid = Required(p.egressRid, "intrinsic_metadata.egress_rid").In(phv); // As in simple_switch, the LAG hash of the P4 program (lag_hash in // standard_metadata) selects the member port of each LAG in the group uint64_t lag_hash = 0; - if (phv->has_field("intrinsic_metadata.lag_hash")) + if (p.lagHash.Exists()) { - lag_hash = phv->get_field("intrinsic_metadata.lag_hash").get(); + lag_hash = p.lagHash.In(phv).get(); } const auto pre_out = m_pre->replicate({mgid, lag_hash}); auto packet_size = packet->get_register(RegisterAccess::PACKET_LENGTH_REG_IDX); @@ -988,7 +983,7 @@ P4CoreV1model::CopyFieldList(const std::unique_ptr& packet, phv_copy->reset_metadata(); bm::FieldList* field_list = this->get_field_list(fieldListId); field_list->copy_fields_between_phvs(phv_copy, packet->get_phv()); - phv_copy->get_field("standard_metadata.instance_type").set(copyType); + Program(phv_copy).instanceType.In(phv_copy).set(copyType); } int @@ -1185,6 +1180,108 @@ P4CoreV1model::FindMetadataField(const std::string& config, return ""; } +const P4CoreV1model::ProgramObjects& +P4CoreV1model::Program(bm::PHV* phv) +{ + if (m_program.found) + { + // Every PHV until the next swap is the program's (ProgramSwapped()) + NS_ASSERT_MSG(phv->num_headers() == m_program.headers, + "a PHV of another program: the program changed without ProgramSwapped()"); + return m_program; + } + // Once per program: at the first packet after the start and after a swap + // (ProgramSwapped(), which swaps only when the switch holds no packet, so + // every PHV from then on is the new program's) + ProgramObjects p; + p.parser = get_parser("parser"); + p.ingress = get_pipeline("ingress"); + p.egress = get_pipeline("egress"); + p.deparser = get_deparser("deparser"); + // simple_switch requires these of every v1model program + const char* const required[] = {"standard_metadata.ingress_port", + "standard_metadata.packet_length", + "standard_metadata.instance_type", + "standard_metadata.egress_spec", + "standard_metadata.egress_port"}; + PhvField* const requiredFields[] = {&p.ingressPort, + &p.packetLength, + &p.instanceType, + &p.egressSpec, + &p.egressPort}; + for (size_t i = 0; i < std::size(required); i++) + { + *requiredFields[i] = Required(FindField(phv, required[i]), required[i]); + } + p.parserError = FindField(phv, "standard_metadata.parser_error"); + p.checksumError = FindField(phv, "standard_metadata.checksum_error"); + p.ingressTimestamp = FindField(phv, "intrinsic_metadata.ingress_global_timestamp"); + p.egressTimestamp = FindField(phv, "intrinsic_metadata.egress_global_timestamp"); + p.mcastGrp = FindField(phv, "intrinsic_metadata.mcast_grp"); + p.priority = FindField(phv, "intrinsic_metadata.priority"); + p.egressRid = FindField(phv, "intrinsic_metadata.egress_rid"); + p.lagHash = FindField(phv, "intrinsic_metadata.lag_hash"); + p.enqTimestamp = FindField(phv, "queueing_metadata.enq_timestamp"); + p.enqQdepth = FindField(phv, "queueing_metadata.enq_qdepth"); + p.deqTimedelta = FindField(phv, "queueing_metadata.deq_timedelta"); + p.deqQdepth = FindField(phv, "queueing_metadata.deq_qdepth"); + p.qid = FindField(phv, "queueing_metadata.qid"); + if (m_enableQueueingMetadata) + { + Required(p.enqTimestamp, "queueing_metadata.enq_timestamp"); + Required(p.enqQdepth, "queueing_metadata.enq_qdepth"); + Required(p.deqTimedelta, "queueing_metadata.deq_timedelta"); + Required(p.deqQdepth, "queueing_metadata.deq_qdepth"); + } + // The scheduler's fields; ResolveSchedulerFields() found the names + for (const std::string& name : m_inputFields) + { + p.inputFields.push_back(name.empty() ? PhvField{} : Required(FindField(phv, name), name)); + } + for (const std::string& name : m_outputFields) + { + p.outputFields.push_back(name.empty() ? PhvField{} : Required(FindField(phv, name), name)); + } + p.found = true; + p.headers = phv->num_headers(); + m_program = std::move(p); + NS_LOG_INFO("Switch ID " << m_p4SwitchId << ": found the fields and objects of the program"); + return m_program; +} + +P4CoreV1model::PhvField +P4CoreV1model::FindField(bm::PHV* phv, const std::string& name) +{ + PhvField found; + if (name.empty() || !phv->has_field(name)) + { + return found; + } + // The name may be an alias (intrinsic_metadata.ingress_global_timestamp is + // standard_metadata.ingress_global_timestamp): find the field's header + const bm::Field& field = phv->get_field(name); + int index = 0; + for (auto it = phv->header_begin(); it != phv->header_end(); ++it, ++index) + { + int offset = it->get_field_offset(field); + if (offset >= 0) + { + found.header = index; + found.offset = offset; + return found; + } + } + return found; +} + +P4CoreV1model::PhvField +P4CoreV1model::Required(PhvField field, std::string_view name) const +{ + NS_ABORT_MSG_IF(!field.Exists(), + "Switch ID " << m_p4SwitchId << ": the P4 program has no field " << name); + return field; +} + // --------------------------------------------------------------------------- // VOQ + fabric Traffic Manager (opt-in) integration // --------------------------------------------------------------------------- @@ -1215,12 +1312,11 @@ P4CoreV1model::EnqueueToTrafficManager(uint32_t egress_port, std::unique_ptrset_egress_port(egress_port); bm::PHV* phv = packet->get_phv(); + const ProgramObjects& p = Program(phv); // Priority 0..7 from the P4 program (7 = highest), matching the Traffic // Manager's priority convention. Clamp defensively. - size_t priority = phv->has_field("intrinsic_metadata.priority") - ? phv->get_field("intrinsic_metadata.priority").get() - : 0u; + size_t priority = p.priority.Exists() ? p.priority.In(phv).get() : 0u; if (priority >= P4_TM_NUM_PRIORITIES) { priority = P4_TM_NUM_PRIORITIES - 1; @@ -1231,10 +1327,9 @@ P4CoreV1model::EnqueueToTrafficManager(uint32_t egress_port, std::unique_ptrget_field("queueing_metadata.enq_timestamp").set(GetTimeStamp()); - phv->get_field("queueing_metadata.enq_qdepth") - .set(m_trafficManager->VoqLength(in_port, egress_port, - static_cast(priority))); + p.enqTimestamp.In(phv).set(GetTimeStamp()); + p.enqQdepth.In(phv).set( + m_trafficManager->VoqLength(in_port, egress_port, static_cast(priority))); } auto payload = std::make_unique(std::move(packet)); @@ -1269,33 +1364,32 @@ P4CoreV1model::TmTransmit(uint32_t outPort, uint8_t priority, std::unique_ptrget_phv(); - bm::Pipeline* egress_mau = this->get_pipeline("egress"); - bm::Deparser* deparser = this->get_deparser("deparser"); + const ProgramObjects& p = Program(phv); + bm::Pipeline* egress_mau = p.egress; + bm::Deparser* deparser = p.deparser; - if (phv->has_field("intrinsic_metadata.egress_global_timestamp")) + if (p.egressTimestamp.Exists()) { - phv->get_field("intrinsic_metadata.egress_global_timestamp").set(GetTimeStamp()); + p.egressTimestamp.In(phv).set(GetTimeStamp()); } if (m_enableQueueingMetadata) { - uint64_t enq_timestamp = phv->get_field("queueing_metadata.enq_timestamp").get(); - phv->get_field("queueing_metadata.deq_timedelta").set(GetTimeStamp() - enq_timestamp); - phv->get_field("queueing_metadata.deq_qdepth") - .set(m_trafficManager->EgressLength(outPort, priority)); - if (phv->has_field("queueing_metadata.qid") && priority < m_nbQueuesPerPort) + uint64_t enq_timestamp = p.enqTimestamp.In(phv).get(); + p.deqTimedelta.In(phv).set(GetTimeStamp() - enq_timestamp); + p.deqQdepth.In(phv).set(m_trafficManager->EgressLength(outPort, priority)); + if (p.qid.Exists() && priority < m_nbQueuesPerPort) { - phv->get_field("queueing_metadata.qid").set(priority); + p.qid.In(phv).set(priority); } } - phv->get_field("standard_metadata.egress_port").set(outPort); + p.egressPort.In(phv).set(outPort); - bm::Field& f_egress_spec = phv->get_field("standard_metadata.egress_spec"); + bm::Field& f_egress_spec = p.egressSpec.In(phv); f_egress_spec.set(0); - phv->get_field("standard_metadata.packet_length") - .set(bm_packet->get_register(RegisterAccess::PACKET_LENGTH_REG_IDX)); + p.packetLength.In(phv).set(bm_packet->get_register(RegisterAccess::PACKET_LENGTH_REG_IDX)); egress_mau->apply(bm_packet.get()); @@ -1318,8 +1412,7 @@ P4CoreV1model::TmTransmit(uint32_t outPort, uint8_t priority, std::unique_ptrget_phv(); bm::FieldList* field_list = this->get_field_list(clone_field_list); field_list->copy_fields_between_phvs(phv_copy, phv); - phv_copy->get_field("standard_metadata.instance_type") - .set(PKT_INSTANCE_TYPE_EGRESS_CLONE); + p.instanceType.In(phv_copy).set(PKT_INSTANCE_TYPE_EGRESS_CLONE); auto packet_size = bm_packet->get_register(RegisterAccess::PACKET_LENGTH_REG_IDX); RegisterAccess::clear_all(packet_copy.get()); packet_copy->set_register(RegisterAccess::PACKET_LENGTH_REG_IDX, packet_size); @@ -1361,11 +1454,11 @@ P4CoreV1model::TmTransmit(uint32_t outPort, uint8_t priority, std::unique_ptrget_phv(); phv_copy->reset_metadata(); field_list->copy_fields_between_phvs(phv_copy, phv); - phv_copy->get_field("standard_metadata.instance_type").set(PKT_INSTANCE_TYPE_RECIRC); + p.instanceType.In(phv_copy).set(PKT_INSTANCE_TYPE_RECIRC); size_t packet_size = packet_copy->get_data_size(); RegisterAccess::clear_all(packet_copy.get()); packet_copy->set_register(RegisterAccess::PACKET_LENGTH_REG_IDX, packet_size); - phv_copy->get_field("standard_metadata.packet_length").set(packet_size); + p.packetLength.In(phv_copy).set(packet_size); packet_copy->set_ingress_length(packet_size); if (!AdmitToIngress(InputBuffer::PacketType::RECIRCULATE, std::move(packet_copy))) { diff --git a/model/p4-core-v1model.h b/model/p4-core-v1model.h index fb694c7..fab8bad 100644 --- a/model/p4-core-v1model.h +++ b/model/p4-core-v1model.h @@ -28,6 +28,8 @@ #include "ns3/switched-ethernet-channel.h" #include +#include +#include #include #include #include @@ -204,6 +206,88 @@ class P4CoreV1model : public P4SwitchCore /// end the simulation if one is missing void ResolveSchedulerFields(); + /// A field of the PHV, found by its name once per program: the index of its + /// header in the PHV and its offset in the header. Every PHV of a program + /// has the same headers, so these find the field in any of them without + /// the string hash and map lookup of PHV::get_field(name). + struct PhvField + { + int header{-1}; ///< the header's index in the PHV; -1: the program has no such field + int offset{0}; ///< the field's offset in its header + + /// @return the program has the field + bool Exists() const + { + return header >= 0; + } + + /// @param phv a PHV of the program + /// @return the field in \p phv + bm::Field& In(bm::PHV* phv) const + { + return phv->get_field(static_cast(header), offset); + } + }; + + /** + * @brief What the core uses of the loaded program on every packet, found by + * name once per program (Program()): its parser, pipelines and deparser, and + * the standard, intrinsic and queueing metadata fields and the scheduler's + * fields. A program swap makes the core find them again. + */ + struct ProgramObjects + { + bool found{false}; ///< found for the loaded program + size_t headers{0}; ///< the headers of the program's PHV (a check) + bm::Parser* parser{nullptr}; ///< "parser" + bm::Pipeline* ingress{nullptr}; ///< "ingress" + bm::Pipeline* egress{nullptr}; ///< "egress" + bm::Deparser* deparser{nullptr}; ///< "deparser" + PhvField ingressPort; ///< standard_metadata.ingress_port + PhvField packetLength; ///< standard_metadata.packet_length + PhvField instanceType; ///< standard_metadata.instance_type + PhvField egressSpec; ///< standard_metadata.egress_spec + PhvField egressPort; ///< standard_metadata.egress_port + PhvField parserError; ///< standard_metadata.parser_error + PhvField checksumError; ///< standard_metadata.checksum_error + PhvField ingressTimestamp; ///< intrinsic_metadata.ingress_global_timestamp + PhvField egressTimestamp; ///< intrinsic_metadata.egress_global_timestamp + PhvField mcastGrp; ///< intrinsic_metadata.mcast_grp + PhvField priority; ///< intrinsic_metadata.priority + PhvField egressRid; ///< intrinsic_metadata.egress_rid + PhvField lagHash; ///< intrinsic_metadata.lag_hash + PhvField enqTimestamp; ///< queueing_metadata.enq_timestamp + PhvField enqQdepth; ///< queueing_metadata.enq_qdepth + PhvField deqTimedelta; ///< queueing_metadata.deq_timedelta + PhvField deqQdepth; ///< queueing_metadata.deq_qdepth + PhvField qid; ///< queueing_metadata.qid + std::vector inputFields; ///< the scheduler's input fields (m_inputFields) + std::vector outputFields; ///< the scheduler's output fields (m_outputFields) + }; + + ProgramObjects m_program; ///< found for the loaded program, once a packet came + + /** + * @param phv a PHV of the loaded program + * @return the program's objects, found with \p phv if they are not yet + */ + const ProgramObjects& Program(bm::PHV* phv); + + /** + * @brief Find a field by name in a PHV + * @param phv a PHV of the program + * @param name the field's name, also an alias (intrinsic_metadata.*); empty: none + * @return its header and offset; header -1 if the program has no such field + */ + static PhvField FindField(bm::PHV* phv, const std::string& name); + + /** + * @param field a field of the program + * @param name its name, for the message + * @return \p field; ends the simulation if the program has no such field + */ + PhvField Required(PhvField field, std::string_view name) const; + /** * @brief Put \p packet into the input buffer and let the ingress pipeline * take it as SwitchRate allows (see P4SwitchCore::StartIngress()). diff --git a/test/Readme.md b/test/Readme.md index 8c81565..f461a40 100644 --- a/test/Readme.md +++ b/test/Readme.md @@ -15,7 +15,7 @@ No environment variable is needed, and suites can run in parallel. ## Suites -24 suites, 260 test cases. The first seven do not need BMv2. +24 suites, 261 test cases. The first seven do not need BMv2. | Suite | Checks | |---|---| @@ -27,7 +27,7 @@ No environment variable is needed, and suites can run in parallel. | `p4-queue` | egress queue: capacity, rate, FIFO, per-port rate, priorities | | `p4-traffic-manager` | the VOQ + fabric traffic manager | | `p4sim` | v1model, PSA and PNA load their program; Thrift ports; `BmLogLevel` and its default, `off`; errors in a flow table are printed with file and line; a switch runs commands again during the simulation; the deprecated `ChannelType` and `EnableTracing` are still accepted | -| `p4-packet` | frames sent into a switch and the frames that leave it, on v1model, PNA, PSA and the pipeline core; a frame from a host on a switched-Ethernet port enters on that port; the PSA and PNA externs `Counter`, `Meter`, `Hash` and `InternetChecksum`, and `Random`, which p4c compiles into v1model's `random()`; `random()` follows ns-3's seed and run, with an engine per switch; the pipeline core warns about the multicast, clones, resubmit and recirculation that it ignores | +| `p4-packet` | frames sent into a switch and the frames that leave it, on v1model, PNA, PSA and the pipeline core; a frame from a host on a switched-Ethernet port enters on that port; the PSA and PNA externs `Counter`, `Meter`, `Hash` and `InternetChecksum`, and `Random`, which p4c compiles into v1model's `random()`; `random()` follows ns-3's seed and run, with an engine per switch; v1model gives the program the ingress and egress timestamps and the parser error (`PacketTooShort`, `NoError`); the pipeline core warns about the multicast, clones, resubmit and recirculation that it ignores | | `p4-externs` | a meter extern of a PSA or PNA program counts simulation time (rates set by `psa_switch_CLI` or `P4RuntimeApi`); `P4RuntimeApi` reads, writes and resets a PSA counter extern and sets, reads and unsets meter rates, by index and for the whole array | | `p4-controller` | `P4Controller`, read back from the switch: flow entries on v1model, PSA, PNA and the pipeline core, action profiles and a meter array on v1model (the rates read through `P4Controller` too), mirroring sessions on v1model and PSA; `P4RuntimeApi` with a null output argument fails; the mirroring, queue and time commands of `simple_switch_CLI` and `psa_switch_CLI`; `StartThriftServer` with a flow table loaded in the process; the Thrift port of a destroyed switch answers with an error | | `p4-flow-table-loader` | the in-process flow-table loader against the runtime CLI: a flow table goes into two switches, one each way, and everything its commands can change (entries with key, priority, timeout, action and data, direct counters and meters, default entries, multicast groups, nodes and LAGs, mirroring sessions, queue depths and rates, registers, counters, meters) and the errors printed must be the same. [`p4src/flow_table/flowtable_v1model.txt`](p4src/flow_table/flowtable_v1model.txt) holds every command, match kind (exact, lpm, ternary, optional, range) and value format, and the CLI's errors; also a `valid` key (in a program the test generates), PSA, its externs, PNA and the pipeline core; a file with a command that only the CLI runs, or a value that ends the CLI, goes to the CLI as a whole | diff --git a/test/p4-packet-test-suite.cc b/test/p4-packet-test-suite.cc index bae1846..42f1ec0 100644 --- a/test/p4-packet-test-suite.cc +++ b/test/p4-packet-test-suite.cc @@ -1007,6 +1007,9 @@ static class P4PacketTestSuite : public TestSuite P4SIM_TEST_QUICK); AddTestCase(new StfTestCase("bounds", "v1model", P4SWITCH_ARCH_V1MODEL, "truncate.stf"), P4SIM_TEST_QUICK); + // The timestamps and the parser error that the switch writes for the program + AddTestCase(new StfTestCase("metadata", "v1model", P4SWITCH_ARCH_V1MODEL, "timestamps.stf"), + P4SIM_TEST_QUICK); // The pipeline core warns about the requests it ignores (EtherTypes as in // the .stf files of these programs) const std::vector> warnings = { diff --git a/test/p4src/metadata/metadata_v1model.json b/test/p4src/metadata/metadata_v1model.json new file mode 100644 index 0000000..27c6720 --- /dev/null +++ b/test/p4src/metadata/metadata_v1model.json @@ -0,0 +1,890 @@ +{ + "header_types" : [ + { + "name" : "scalars_0", + "id" : 0, + "fields" : [ + ["tmp", 8, false], + ["tmp_0", 8, false] + ] + }, + { + "name" : "standard_metadata", + "id" : 1, + "fields" : [ + ["ingress_port", 9, false], + ["egress_spec", 9, false], + ["egress_port", 9, false], + ["instance_type", 32, false], + ["packet_length", 32, false], + ["enq_timestamp", 32, false], + ["enq_qdepth", 19, false], + ["deq_timedelta", 32, false], + ["deq_qdepth", 19, false], + ["ingress_global_timestamp", 48, false], + ["egress_global_timestamp", 48, false], + ["mcast_grp", 16, false], + ["egress_rid", 16, false], + ["checksum_error", 1, false], + ["parser_error", 32, false], + ["priority", 3, false], + ["lag_hash", 16, false], + ["_padding", 3, false] + ] + }, + { + "name" : "ethernet_t", + "id" : 2, + "fields" : [ + ["dstAddr", 48, false], + ["srcAddr", 48, false], + ["etherType", 16, false] + ] + }, + { + "name" : "info_t", + "id" : 3, + "fields" : [ + ["ingress_ts", 48, false], + ["egress_ts", 48, false], + ["too_short", 8, false], + ["no_error", 8, false] + ] + }, + { + "name" : "extra_t", + "id" : 4, + "fields" : [ + ["x", 512, false] + ] + } + ], + "headers" : [ + { + "name" : "scalars", + "id" : 0, + "header_type" : "scalars_0", + "metadata" : true, + "pi_omit" : true + }, + { + "name" : "standard_metadata", + "id" : 1, + "header_type" : "standard_metadata", + "metadata" : true, + "pi_omit" : true + }, + { + "name" : "ethernet", + "id" : 2, + "header_type" : "ethernet_t", + "metadata" : false, + "pi_omit" : true + }, + { + "name" : "info", + "id" : 3, + "header_type" : "info_t", + "metadata" : false, + "pi_omit" : true + }, + { + "name" : "extra", + "id" : 4, + "header_type" : "extra_t", + "metadata" : false, + "pi_omit" : true + } + ], + "header_stacks" : [], + "header_union_types" : [], + "header_unions" : [], + "header_union_stacks" : [], + "field_lists" : [], + "errors" : [ + ["NoError", 0], + ["PacketTooShort", 1], + ["NoMatch", 2], + ["StackOutOfBounds", 3], + ["HeaderTooShort", 4], + ["ParserTimeout", 5], + ["ParserInvalidArgument", 6] + ], + "enums" : [], + "parsers" : [ + { + "name" : "parser", + "id" : 0, + "init_state" : "start", + "parse_states" : [ + { + "name" : "start", + "id" : 0, + "parser_ops" : [ + { + "parameters" : [ + { + "type" : "regular", + "value" : "ethernet" + } + ], + "op" : "extract" + } + ], + "transitions" : [ + { + "type" : "hexstr", + "value" : "0x88b6", + "mask" : null, + "next_state" : "parse_info" + }, + { + "type" : "default", + "value" : null, + "mask" : null, + "next_state" : null + } + ], + "transition_key" : [ + { + "type" : "field", + "value" : ["ethernet", "etherType"] + } + ] + }, + { + "name" : "parse_info", + "id" : 1, + "parser_ops" : [ + { + "parameters" : [ + { + "type" : "regular", + "value" : "info" + } + ], + "op" : "extract" + }, + { + "parameters" : [ + { + "type" : "regular", + "value" : "extra" + } + ], + "op" : "extract" + } + ], + "transitions" : [ + { + "type" : "default", + "value" : null, + "mask" : null, + "next_state" : null + } + ], + "transition_key" : [] + } + ] + } + ], + "parse_vsets" : [], + "deparsers" : [ + { + "name" : "deparser", + "id" : 0, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 83, + "column" : 8, + "source_fragment" : "MyDeparser" + }, + "order" : ["ethernet", "info", "extra"], + "primitives" : [] + } + ], + "meter_arrays" : [], + "counter_arrays" : [], + "register_arrays" : [], + "calculations" : [], + "learn_lists" : [], + "actions" : [ + { + "name" : "metadata_v1model64", + "id" : 0, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["scalars", "tmp"] + }, + { + "type" : "hexstr", + "value" : "0x01" + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 64, + "column" : 78, + "source_fragment" : "8w1" + } + } + ] + }, + { + "name" : "metadata_v1model64_0", + "id" : 1, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["scalars", "tmp"] + }, + { + "type" : "hexstr", + "value" : "0x00" + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 64, + "column" : 84, + "source_fragment" : "8w0" + } + } + ] + }, + { + "name" : "metadata_v1model63", + "id" : 2, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["info", "ingress_ts"] + }, + { + "type" : "field", + "value" : ["standard_metadata", "ingress_global_timestamp"] + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 63, + "column" : 12, + "source_fragment" : "hdr.info.ingress_ts = smeta.ingress_global_timestamp" + } + } + ] + }, + { + "name" : "metadata_v1model65", + "id" : 3, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["scalars", "tmp_0"] + }, + { + "type" : "hexstr", + "value" : "0x01" + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 65, + "column" : 70, + "source_fragment" : "8w1" + } + } + ] + }, + { + "name" : "metadata_v1model65_0", + "id" : 4, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["scalars", "tmp_0"] + }, + { + "type" : "hexstr", + "value" : "0x00" + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 65, + "column" : 76, + "source_fragment" : "8w0" + } + } + ] + }, + { + "name" : "metadata_v1model64_1", + "id" : 5, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["info", "too_short"] + }, + { + "type" : "field", + "value" : ["scalars", "tmp"] + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 64, + "column" : 12, + "source_fragment" : "hdr.info.too_short = smeta.parser_error == error.PacketTooShort ? 8w1 : 8w0" + } + } + ] + }, + { + "name" : "metadata_v1model65_1", + "id" : 6, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["info", "no_error"] + }, + { + "type" : "field", + "value" : ["scalars", "tmp_0"] + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 65, + "column" : 12, + "source_fragment" : "hdr.info.no_error = smeta.parser_error == error.NoError ? 8w1 : 8w0" + } + } + ] + }, + { + "name" : "metadata_v1model61", + "id" : 7, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["standard_metadata", "egress_spec"] + }, + { + "type" : "hexstr", + "value" : "0x0001" + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 61, + "column" : 8, + "source_fragment" : "smeta.egress_spec = 1" + } + } + ] + }, + { + "name" : "metadata_v1model74", + "id" : 8, + "runtime_data" : [], + "primitives" : [ + { + "op" : "assign", + "parameters" : [ + { + "type" : "field", + "value" : ["info", "egress_ts"] + }, + { + "type" : "field", + "value" : ["standard_metadata", "egress_global_timestamp"] + } + ], + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 74, + "column" : 12, + "source_fragment" : "hdr.info.egress_ts = smeta.egress_global_timestamp" + } + } + ] + } + ], + "pipelines" : [ + { + "name" : "ingress", + "id" : 0, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 58, + "column" : 8, + "source_fragment" : "MyIngress" + }, + "init_table" : "tbl_metadata_v1model61", + "tables" : [ + { + "name" : "tbl_metadata_v1model61", + "id" : 0, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 61, + "column" : 26, + "source_fragment" : "=" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [7], + "actions" : ["metadata_v1model61"], + "base_default_next" : "node_3", + "next_tables" : { + "metadata_v1model61" : "node_3" + }, + "default_entry" : { + "action_id" : 7, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + }, + { + "name" : "tbl_metadata_v1model63", + "id" : 1, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 63, + "column" : 32, + "source_fragment" : "=" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [2], + "actions" : ["metadata_v1model63"], + "base_default_next" : "node_5", + "next_tables" : { + "metadata_v1model63" : "node_5" + }, + "default_entry" : { + "action_id" : 2, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + }, + { + "name" : "tbl_metadata_v1model64", + "id" : 2, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 64, + "column" : 78, + "source_fragment" : "8w1" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [0], + "actions" : ["metadata_v1model64"], + "base_default_next" : "tbl_metadata_v1model64_1", + "next_tables" : { + "metadata_v1model64" : "tbl_metadata_v1model64_1" + }, + "default_entry" : { + "action_id" : 0, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + }, + { + "name" : "tbl_metadata_v1model64_0", + "id" : 3, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 64, + "column" : 84, + "source_fragment" : "8w0" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [1], + "actions" : ["metadata_v1model64_0"], + "base_default_next" : "tbl_metadata_v1model64_1", + "next_tables" : { + "metadata_v1model64_0" : "tbl_metadata_v1model64_1" + }, + "default_entry" : { + "action_id" : 1, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + }, + { + "name" : "tbl_metadata_v1model64_1", + "id" : 4, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 64, + "column" : 31, + "source_fragment" : "=" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [5], + "actions" : ["metadata_v1model64_1"], + "base_default_next" : "node_9", + "next_tables" : { + "metadata_v1model64_1" : "node_9" + }, + "default_entry" : { + "action_id" : 5, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + }, + { + "name" : "tbl_metadata_v1model65", + "id" : 5, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 65, + "column" : 70, + "source_fragment" : "8w1" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [3], + "actions" : ["metadata_v1model65"], + "base_default_next" : "tbl_metadata_v1model65_1", + "next_tables" : { + "metadata_v1model65" : "tbl_metadata_v1model65_1" + }, + "default_entry" : { + "action_id" : 3, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + }, + { + "name" : "tbl_metadata_v1model65_0", + "id" : 6, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 65, + "column" : 76, + "source_fragment" : "8w0" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [4], + "actions" : ["metadata_v1model65_0"], + "base_default_next" : "tbl_metadata_v1model65_1", + "next_tables" : { + "metadata_v1model65_0" : "tbl_metadata_v1model65_1" + }, + "default_entry" : { + "action_id" : 4, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + }, + { + "name" : "tbl_metadata_v1model65_1", + "id" : 7, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 65, + "column" : 30, + "source_fragment" : "=" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [6], + "actions" : ["metadata_v1model65_1"], + "base_default_next" : null, + "next_tables" : { + "metadata_v1model65_1" : null + }, + "default_entry" : { + "action_id" : 6, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + } + ], + "action_profiles" : [], + "conditionals" : [ + { + "name" : "node_3", + "id" : 0, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 62, + "column" : 12, + "source_fragment" : "hdr.info.isValid()" + }, + "expression" : { + "type" : "expression", + "value" : { + "op" : "d2b", + "left" : null, + "right" : { + "type" : "field", + "value" : ["info", "$valid$"] + } + } + }, + "false_next" : null, + "true_next" : "tbl_metadata_v1model63" + }, + { + "name" : "node_5", + "id" : 1, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 64, + "column" : 33, + "source_fragment" : "smeta.parser_error == error.PacketTooShort" + }, + "expression" : { + "type" : "expression", + "value" : { + "op" : "==", + "left" : { + "type" : "field", + "value" : ["standard_metadata", "parser_error"] + }, + "right" : { + "type" : "hexstr", + "value" : "0x1" + } + } + }, + "true_next" : "tbl_metadata_v1model64", + "false_next" : "tbl_metadata_v1model64_0" + }, + { + "name" : "node_9", + "id" : 2, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 65, + "column" : 32, + "source_fragment" : "smeta.parser_error == error.NoError" + }, + "expression" : { + "type" : "expression", + "value" : { + "op" : "==", + "left" : { + "type" : "field", + "value" : ["standard_metadata", "parser_error"] + }, + "right" : { + "type" : "hexstr", + "value" : "0x0" + } + } + }, + "true_next" : "tbl_metadata_v1model65", + "false_next" : "tbl_metadata_v1model65_0" + } + ] + }, + { + "name" : "egress", + "id" : 1, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 70, + "column" : 8, + "source_fragment" : "MyEgress" + }, + "init_table" : "node_15", + "tables" : [ + { + "name" : "tbl_metadata_v1model74", + "id" : 8, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 74, + "column" : 31, + "source_fragment" : "=" + }, + "key" : [], + "match_type" : "exact", + "type" : "simple", + "max_size" : 1024, + "with_counters" : false, + "support_timeout" : false, + "direct_meters" : null, + "action_ids" : [8], + "actions" : ["metadata_v1model74"], + "base_default_next" : null, + "next_tables" : { + "metadata_v1model74" : null + }, + "default_entry" : { + "action_id" : 8, + "action_const" : true, + "action_data" : [], + "action_entry_const" : true + } + } + ], + "action_profiles" : [], + "conditionals" : [ + { + "name" : "node_15", + "id" : 3, + "source_info" : { + "filename" : "metadata_v1model.p4", + "line" : 73, + "column" : 12, + "source_fragment" : "hdr.info.isValid()" + }, + "expression" : { + "type" : "expression", + "value" : { + "op" : "d2b", + "left" : null, + "right" : { + "type" : "field", + "value" : ["info", "$valid$"] + } + } + }, + "false_next" : null, + "true_next" : "tbl_metadata_v1model74" + } + ] + } + ], + "checksums" : [], + "force_arith" : [], + "extern_instances" : [], + "field_aliases" : [ + [ + "queueing_metadata.enq_timestamp", + ["standard_metadata", "enq_timestamp"] + ], + [ + "queueing_metadata.enq_qdepth", + ["standard_metadata", "enq_qdepth"] + ], + [ + "queueing_metadata.deq_timedelta", + ["standard_metadata", "deq_timedelta"] + ], + [ + "queueing_metadata.deq_qdepth", + ["standard_metadata", "deq_qdepth"] + ], + [ + "intrinsic_metadata.ingress_global_timestamp", + ["standard_metadata", "ingress_global_timestamp"] + ], + [ + "intrinsic_metadata.egress_global_timestamp", + ["standard_metadata", "egress_global_timestamp"] + ], + [ + "intrinsic_metadata.mcast_grp", + ["standard_metadata", "mcast_grp"] + ], + [ + "intrinsic_metadata.egress_rid", + ["standard_metadata", "egress_rid"] + ], + [ + "intrinsic_metadata.priority", + ["standard_metadata", "priority"] + ], + [ + "intrinsic_metadata.lag_hash", + ["standard_metadata", "lag_hash"] + ] + ], + "program" : "metadata_v1model.p4", + "__meta__" : { + "version" : [2, 23], + "compiler" : "https://github.com/p4lang/p4c" + } +} \ No newline at end of file diff --git a/test/p4src/metadata/metadata_v1model.p4 b/test/p4src/metadata/metadata_v1model.p4 new file mode 100644 index 0000000..d30cf13 --- /dev/null +++ b/test/p4src/metadata/metadata_v1model.p4 @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 TU Dresden. Author: Mingyu Ma + +// The metadata that the switch writes for the program (suite p4-packet, +// timestamps.stf): a frame of EtherType 0x88B6 carries header info, which the +// program fills with the ingress and egress timestamps and with whether the +// parser found the frame too short for header extra, which follows info. + +#include +#include + +header ethernet_t { + bit<48> dstAddr; + bit<48> srcAddr; + bit<16> etherType; +} + +header info_t { + bit<48> ingress_ts; // ingress_global_timestamp + bit<48> egress_ts; // egress_global_timestamp + bit<8> too_short; // 1: parser_error is PacketTooShort + bit<8> no_error; // 1: parser_error is NoError +} + +header extra_t { + bit<512> x; // 64 bytes: a frame without it stays too short when padded to 60 bytes +} + +struct headers_t { + ethernet_t ethernet; + info_t info; + extra_t extra; +} + +struct metadata_t { +} + +parser MyParser(packet_in pkt, out headers_t hdr, inout metadata_t meta, + inout standard_metadata_t smeta) { + state start { + pkt.extract(hdr.ethernet); + transition select(hdr.ethernet.etherType) { + 0x88B6: parse_info; + default: accept; + } + } + state parse_info { + pkt.extract(hdr.info); + pkt.extract(hdr.extra); + transition accept; + } +} + +control MyVerifyChecksum(inout headers_t hdr, inout metadata_t meta) { + apply { } +} + +control MyIngress(inout headers_t hdr, inout metadata_t meta, + inout standard_metadata_t smeta) { + apply { + smeta.egress_spec = 1; + if (hdr.info.isValid()) { + hdr.info.ingress_ts = smeta.ingress_global_timestamp; + hdr.info.too_short = smeta.parser_error == error.PacketTooShort ? 8w1 : 8w0; + hdr.info.no_error = smeta.parser_error == error.NoError ? 8w1 : 8w0; + } + } +} + +control MyEgress(inout headers_t hdr, inout metadata_t meta, + inout standard_metadata_t smeta) { + apply { + if (hdr.info.isValid()) { + hdr.info.egress_ts = smeta.egress_global_timestamp; + } + } +} + +control MyComputeChecksum(inout headers_t hdr, inout metadata_t meta) { + apply { } +} + +control MyDeparser(packet_out pkt, in headers_t hdr) { + apply { + pkt.emit(hdr.ethernet); + pkt.emit(hdr.info); + pkt.emit(hdr.extra); + } +} + +V1Switch(MyParser(), MyVerifyChecksum(), MyIngress(), MyEgress(), MyComputeChecksum(), + MyDeparser()) main; diff --git a/test/p4src/metadata/timestamps.stf b/test/p4src/metadata/timestamps.stf new file mode 100644 index 0000000..dcd35e4 --- /dev/null +++ b/test/p4src/metadata/timestamps.stf @@ -0,0 +1,14 @@ +# The ingress and egress timestamps (ns since the switch started) and the parser +# error that the switch gives the program (metadata_v1model.p4). The frame of +# 1000 us lacks header extra: PacketTooShort; the one of 2000 us has it: NoError. +# The hosts send without delay, so both timestamps are the time of sending +# (1,000,000 ns = 0xf4240, 2,000,000 ns = 0x1e8480), checked to 256 ns: the last +# two nibbles are open. + +at 1000 +packet 0 000000000001 000000000010 88b6 000000000000 000000000000 00 00 +expect 1 000000000001 000000000010 88b6 0000000f42** 0000000f42** 01 00 + +at 2000 +packet 0 000000000001 000000000010 88b6 000000000000 000000000000 00 00 ABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABAB +expect 1 000000000001 000000000010 88b6 0000001e84** 0000001e84** 00 01 ABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABAB