DPDK-dev Archive on lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH 0/7] pcapng: fixes, timestamps and stdio output
@ 2026-12-01 22:41 Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 1/7] graph: fix double close of pcapng file Stephen Hemminger
                   ` (7 more replies)
  0 siblings, 8 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger

This covers the pcapng library, plus one EAL addition that the
timestamp changes build on.

The first two patches are independent bug fixes and are marked for stable,

The next four patches deal with time. The conversion from TSC to
nanoseconds since the epoch was living in pcapng, although nothing
about it is specific to packet capture. EAL now takes the reference
point at init and exposes rte_tsc_to_ns(), and pcapng uses that
instead of its own copy. The conversion now happens when the packet
is copied, so the timestamp in the mbuf is already epoch nanoseconds
and no longer has to come from the TSC. rte_pcapng_copy_ts() lets an
application pass the time of the packet directly, for example a
hardware Rx timestamp. The user-timestamp support is based on a patch
from Marek Kasiewicz and Dawid Wesierski.

The pcapng test was comparing file timestamps against
clock_gettime(CLOCK_REALTIME), which measures NTP slew against the
calibrated TSC rate rather than anything about pcapng. It now bounds
the window with rte_tsc_to_ns() so both sides come from the same
reference point, and also checks that timestamps never go backwards.

The last patch replaces writev with stdio. Writing to a FILE * makes
it possible to capture to a pipe or a compressed stream, and lets the
application decide on buffering and when to fflush, which matters for
a live reader like Wireshark. Writing packets also becomes
multi-thread safe because stdio does the locking.
rte_pcapng_fdopen() keeps its old behavior: the stream it creates is
flushed at the end of each write call, so data still reaches the file
before the call returns.

Dawid Wesierski (1):
  pcapng: add user-supplied timestamp support

Stephen Hemminger (6):
  graph: fix double close of pcapng file
  pcapng: call writev as needed on highly segmented mbuf
  eal: add function to convert TSC to epoch time
  pcapng: use EAL TSC to epoch conversion
  test/pcapng: compare timestamps in one clock domain
  pcapng: use stdio for output

 app/test/test_cycles.c                 |  34 +++
 app/test/test_pcapng.c                 | 356 +++++++++++++++----------
 doc/api/doxy-api-index.md              |   1 +
 doc/guides/prog_guide/pcapng_lib.rst   |   4 +
 doc/guides/rel_notes/release_27_03.rst |  19 ++
 lib/eal/common/eal_common_timer.c      |  59 ++++
 lib/eal/include/rte_time.h             |  34 +++
 lib/eal/windows/include/rte_os_shim.h  |   6 +
 lib/graph/graph_pcap.c                 |   4 +-
 lib/pcapng/rte_pcapng.c                | 314 +++++++++++-----------
 lib/pcapng/rte_pcapng.h                | 100 ++++++-
 11 files changed, 628 insertions(+), 303 deletions(-)

-- 
2.53.0


^ permalink raw reply	[flat|nested] 16+ messages in thread

* [PATCH 1/7] graph: fix double close of pcapng file
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
@ 2026-12-01 22:41 ` Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 2/7] pcapng: call writev as needed on highly segmented mbuf Stephen Hemminger
                   ` (6 subsequent siblings)
  7 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev
  Cc: Stephen Hemminger, stable, Jerin Jacob, Kiran Kumar K,
	Nithin Dabilpuram, Zhirun Yan, Amit Prakash Shukla

If adding an interface to the capture file failed, the error path
called rte_pcapng_close(), which closes the file descriptor,
and then closed the same descriptor again.

Only close the descriptor directly if rte_pcapng_fdopen() failed.

Fixes: df5908c98abc ("graph: fix pcapng file support")
Cc: stable@dpdk.org

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 lib/graph/graph_pcap.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/lib/graph/graph_pcap.c b/lib/graph/graph_pcap.c
index 78859ec2d4..07678d967d 100644
--- a/lib/graph/graph_pcap.c
+++ b/lib/graph/graph_pcap.c
@@ -128,11 +128,13 @@ graph_pcap_file_open(const char *filename)
 done:
 	return 0;
 error:
+	/* once rte_pcapng_fdopen() succeeds, the fd is closed by rte_pcapng_close() */
 	if (pcapng_fd != NULL) {
 		rte_pcapng_close(pcapng_fd);
 		pcapng_fd = NULL;
+	} else {
+		close(fd);
 	}
-	close(fd);
 	return -1;
 }
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH 2/7] pcapng: call writev as needed on highly segmented mbuf
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 1/7] graph: fix double close of pcapng file Stephen Hemminger
@ 2026-12-01 22:41 ` Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 3/7] eal: add function to convert TSC to epoch time Stephen Hemminger
                   ` (5 subsequent siblings)
  7 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger, stable, Reshma Pattan, Mário Kuka

It is possible to have an mbuf with more segments than the
max number of io vectors (1024 on Linux). This is an odd corner
case but it is allowed by DPDK since maximum number of segments
per mbuf is UINT16_MAX.

The old check assumed a single mbuf chain always fit in the
io vector, so a chain longer than IOV_MAX overran the stack
array. Consolidate the checks so now when io vector gets full
it is written. A packet may now be split across writev calls;
the previous flush at packet boundaries was incidental and not
a documented guarantee.

Bugzilla ID: 2133
Fixes: 0744f1c9f991 ("pcapng: fix write more packets than IOV_MAX limit")
Cc: stable@dpdk.org

Reported-by: Anthropic OSS scanner (ANT-2026-DC6DT4HP)
Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 lib/pcapng/rte_pcapng.c | 39 +++++++++++++++++++--------------------
 1 file changed, 19 insertions(+), 20 deletions(-)

diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index df38e4819c..ce71b07d93 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -706,20 +706,6 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		epb->timestamp_hi = timestamp >> 32;
 		epb->timestamp_lo = (uint32_t)timestamp;
 
-		/*
-		 * Handle case of highly fragmented and large burst size
-		 * Note: this assumes that max segments per mbuf < IOV_MAX
-		 */
-		if (unlikely(cnt + m->nb_segs >= IOV_MAX)) {
-			ret = writev(self->outfd, iov, cnt);
-			if (unlikely(ret < 0)) {
-				rte_errno = errno;
-				return -1;
-			}
-			total += ret;
-			cnt = 0;
-		}
-
 		/*
 		 * The DPDK port is recorded during pcapng_copy.
 		 * Map that to PCAPNG interface in file.
@@ -727,16 +713,29 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		do {
 			iov[cnt].iov_base = rte_pktmbuf_mtod(m, void *);
 			iov[cnt].iov_len = rte_pktmbuf_data_len(m);
-			++cnt;
+
+			/* If current iov is maxed out then send it */
+			if (++cnt == IOV_MAX) {
+				ret = writev(self->outfd, iov, cnt);
+				if (unlikely(ret < 0)) {
+					rte_errno = errno;
+					return -1;
+				}
+				cnt = 0;
+				total += ret;
+			}
 		} while ((m = m->next));
 	}
 
-	ret = writev(self->outfd, iov, cnt);
-	if (unlikely(ret < 0)) {
-		rte_errno = errno;
-		return -1;
+	if (likely(cnt > 0)) {
+		ret = writev(self->outfd, iov, cnt);
+		if (unlikely(ret < 0)) {
+			rte_errno = errno;
+			return -1;
+		}
+		total += ret;
 	}
-	return total + ret;
+	return total;
 }
 
 /* Create new pcapng writer handle */
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH 3/7] eal: add function to convert TSC to epoch time
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 1/7] graph: fix double close of pcapng file Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 2/7] pcapng: call writev as needed on highly segmented mbuf Stephen Hemminger
@ 2026-12-01 22:41 ` Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 4/7] pcapng: use EAL TSC to epoch conversion Stephen Hemminger
                   ` (4 subsequent siblings)
  7 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger

The pcapng library converts the TSC into nanoseconds since 1/1/1970,
because that is what the pcapng file format records. Nothing about
that conversion is specific to packet capture: it needs the TSC
frequency and a reference point relating the TSC to the wall clock,
both of which EAL already has or can take at init.

Record the TSC alongside a CLOCK_REALTIME reading while the TSC
frequency is being determined, and add rte_tsc_to_ns() to convert any
TSC value using that reference point. The seconds are computed before
the remainder is scaled, so the multiply by NS_PER_S cannot overflow.
A test converts values up to ten days out, where scaling the whole
cycle count would wrap.

The reference point is taken per process rather than shared through the
memory config, so a secondary process may differ from the primary by
the sampling error.

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_cycles.c                 | 34 +++++++++++++++
 doc/api/doxy-api-index.md              |  1 +
 doc/guides/rel_notes/release_27_03.rst |  6 +++
 lib/eal/common/eal_common_timer.c      | 59 ++++++++++++++++++++++++++
 lib/eal/include/rte_time.h             | 34 +++++++++++++++
 5 files changed, 134 insertions(+)

diff --git a/app/test/test_cycles.c b/app/test/test_cycles.c
index 68a31ac450..84ecd09fdb 100644
--- a/app/test/test_cycles.c
+++ b/app/test/test_cycles.c
@@ -2,11 +2,13 @@
  * Copyright(c) 2010-2014 Intel Corporation
  */
 
+#include <inttypes.h>
 #include <stdio.h>
 #include <stdint.h>
 
 #include <rte_common.h>
 #include <rte_cycles.h>
+#include <rte_time.h>
 
 #include "test.h"
 
@@ -54,3 +56,35 @@ test_user_delay_us(void)
 }
 
 REGISTER_FAST_TEST(user_delay_us, NOHUGE_OK, ASAN_OK, test_user_delay_us);
+
+/*
+ * Scaling a cycle count by NS_PER_S overflows past a few seconds worth
+ * of cycles, so check that converting a TSC value well into the future
+ * still advances by the expected amount.
+ */
+static int
+test_tsc_to_ns(void)
+{
+	static const unsigned int offsets[] = { 1, 8, 3600, 10 * 86400 };
+	uint64_t hz = rte_get_tsc_hz();
+	uint64_t tsc = rte_get_tsc_cycles();
+	uint64_t base = rte_tsc_to_ns(tsc);
+	unsigned int i;
+
+	TEST_ASSERT(hz != 0, "TSC frequency is zero");
+
+	for (i = 0; i < RTE_DIM(offsets); i++) {
+		uint64_t want = (uint64_t)offsets[i] * NS_PER_S;
+		uint64_t got = rte_tsc_to_ns(tsc +
+				(uint64_t)offsets[i] * hz) - base;
+
+		/* Allow a nanosecond either way for the division. */
+		TEST_ASSERT(got + 1 >= want && got <= want + 1,
+			    "+%u s: got %"PRIu64" want %"PRIu64,
+			    offsets[i], got, want);
+	}
+
+	return 0;
+}
+
+REGISTER_FAST_TEST(tsc_to_ns_autotest, NOHUGE_OK, ASAN_OK, test_tsc_to_ns);
diff --git a/doc/api/doxy-api-index.md b/doc/api/doxy-api-index.md
index 974f2d48ab..62d5db1b3b 100644
--- a/doc/api/doxy-api-index.md
+++ b/doc/api/doxy-api-index.md
@@ -81,6 +81,7 @@ The public API headers are grouped by topics:
 
 - **timers**:
   [cycles](@ref rte_cycles.h),
+  [time](@ref rte_time.h),
   [timer](@ref rte_timer.h),
   [alarm](@ref rte_alarm.h)
 
diff --git a/doc/guides/rel_notes/release_27_03.rst b/doc/guides/rel_notes/release_27_03.rst
index a91813faca..63bb5ad42d 100644
--- a/doc/guides/rel_notes/release_27_03.rst
+++ b/doc/guides/rel_notes/release_27_03.rst
@@ -55,6 +55,12 @@ New Features
      Also, make sure to start the actual text at the margin.
      =======================================================
 
+* **Added API to convert TSC to epoch time.**
+
+  Added the experimental ``rte_tsc_to_ns()`` function in ``rte_time.h``
+  to convert a TSC value into nanoseconds since 1/1/1970,
+  using a reference point recorded during EAL initialization.
+
 
 Removed Items
 -------------
diff --git a/lib/eal/common/eal_common_timer.c b/lib/eal/common/eal_common_timer.c
index 67ede70c62..e1871189ea 100644
--- a/lib/eal/common/eal_common_timer.c
+++ b/lib/eal/common/eal_common_timer.c
@@ -8,8 +8,10 @@
 #include <rte_common.h>
 #include <rte_log.h>
 #include <rte_cycles.h>
+#include <rte_os_shim.h>
 #include <rte_pause.h>
 #include <rte_eal.h>
+#include <rte_time.h>
 
 #include <eal_export.h>
 #include "eal_private.h"
@@ -18,6 +20,10 @@
 /* The frequency of the RDTSC timer resolution */
 static uint64_t eal_tsc_resolution_hz;
 
+/* Reference point relating the TSC to the wall clock, taken at init */
+static uint64_t eal_tsc_base;
+static uint64_t eal_epoch_ns;
+
 /* Pointer to user delay function */
 RTE_EXPORT_SYMBOL(rte_delay_us)
 void (*rte_delay_us)(unsigned int) = NULL;
@@ -39,6 +45,36 @@ rte_get_tsc_hz(void)
 	return eal_tsc_resolution_hz;
 }
 
+/*
+ * Convert a count of cycles to nanoseconds.
+ *
+ * Compute the whole seconds first, so that the remainder is always
+ * less than the frequency and scaling it by NS_PER_S cannot overflow.
+ */
+static uint64_t
+cycles_to_ns(uint64_t cycles)
+{
+	uint64_t secs = cycles / eal_tsc_resolution_hz;
+	uint64_t rem = cycles % eal_tsc_resolution_hz;
+
+	return secs * NS_PER_S + (rem * NS_PER_S) / eal_tsc_resolution_hz;
+}
+
+RTE_EXPORT_EXPERIMENTAL_SYMBOL(rte_tsc_to_ns, 27.03)
+uint64_t
+rte_tsc_to_ns(uint64_t tsc)
+{
+	/*
+	 * A caller may convert a TSC value sampled before the reference
+	 * point was taken, so handle both directions on an unsigned
+	 * magnitude.
+	 */
+	if (unlikely(tsc < eal_tsc_base))
+		return eal_epoch_ns - cycles_to_ns(eal_tsc_base - tsc);
+
+	return eal_epoch_ns + cycles_to_ns(tsc - eal_tsc_base);
+}
+
 static uint64_t
 estimate_tsc_freq(void)
 {
@@ -52,6 +88,27 @@ estimate_tsc_freq(void)
 	return RTE_ALIGN_MUL_NEAR(rte_rdtsc() - start, CYC_PER_10MHZ);
 }
 
+/*
+ * Record the TSC value matching a wall clock reading, so that any TSC
+ * value can later be expressed as nanoseconds since the Unix epoch.
+ * Read the TSC either side of the clock to halve the sampling error.
+ */
+static void
+init_tsc_base(void)
+{
+	struct timespec ts;
+	uint64_t cycles;
+
+	cycles = rte_get_tsc_cycles();
+	if (clock_gettime(CLOCK_REALTIME, &ts) < 0) {
+		EAL_LOG(WARNING, "Could not read wall clock,"
+			" TSC to epoch conversion unavailable");
+		return;
+	}
+	eal_tsc_base = (cycles + rte_get_tsc_cycles()) / 2;
+	eal_epoch_ns = rte_timespec_to_ns(&ts);
+}
+
 int
 init_tsc_freq(void)
 {
@@ -71,6 +128,7 @@ init_tsc_freq(void)
 		}
 
 		eal_tsc_resolution_hz = mcfg->tsc_hz;
+		init_tsc_base();
 		return 0;
 	}
 
@@ -87,6 +145,7 @@ init_tsc_freq(void)
 	EAL_LOG(DEBUG, "TSC frequency is ~%" PRIu64 " KHz", freq / 1000);
 	eal_tsc_resolution_hz = freq;
 	mcfg->tsc_hz = freq;
+	init_tsc_base();
 	return 0;
 }
 
diff --git a/lib/eal/include/rte_time.h b/lib/eal/include/rte_time.h
index c5c3a233e4..3122e062ab 100644
--- a/lib/eal/include/rte_time.h
+++ b/lib/eal/include/rte_time.h
@@ -5,9 +5,17 @@
 #ifndef _RTE_TIME_H_
 #define _RTE_TIME_H_
 
+/**
+ * @file
+ *
+ * Time and cycle counter conversion.
+ */
+
 #include <stdint.h>
 #include <time.h>
 
+#include <rte_compat.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -102,6 +110,32 @@ rte_ns_to_timespec(uint64_t nsec)
 	return ts;
 }
 
+/**
+ * @warning
+ * @b EXPERIMENTAL: this API may change without prior notice.
+ *
+ * Convert a TSC value into nanoseconds since the Unix epoch.
+ *
+ * EAL records the TSC alongside a CLOCK_REALTIME reading during
+ * initialization, and this converts using that reference point and the
+ * TSC frequency.  Values sampled before initialization are also handled,
+ * and the result tracks the wall clock as it was at init: later changes
+ * to the system time are not reflected.
+ *
+ * Each process takes its own reference point, so values converted in a
+ * secondary process may differ from the primary by the sampling error.
+ *
+ * Must be called after rte_eal_init(), which fails if the TSC frequency
+ * cannot be determined.
+ *
+ * @param tsc
+ *   A value read from rte_get_tsc_cycles() or rte_rdtsc().
+ * @return
+ *   Nanoseconds since 1/1/1970.
+ */
+__rte_experimental
+uint64_t rte_tsc_to_ns(uint64_t tsc);
+
 #ifdef __cplusplus
 }
 #endif
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH 4/7] pcapng: use EAL TSC to epoch conversion
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                   ` (2 preceding siblings ...)
  2026-12-01 22:41 ` [PATCH 3/7] eal: add function to convert TSC to epoch time Stephen Hemminger
@ 2026-12-01 22:41 ` Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 5/7] pcapng: add user-supplied timestamp support Stephen Hemminger
                   ` (3 subsequent siblings)
  7 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger, Reshma Pattan

The pcapng library carried its own TSC to nanoseconds conversion along
with the reference point it needs: the TSC and wall clock sampled when
the capture file was opened. EAL now records an equivalent reference
point at init and exposes rte_tsc_to_ns(), so the local copy is
redundant.

Convert timestamps with rte_tsc_to_ns() and drop the per-handle
reference point. The interface statistics block still reports when the
file was opened rather than when EAL started.

Timestamps are now converted when the packet is copied rather than
when it is written, so test_long_timestamp can no longer reach large
deltas by rewriting the cycle count in the block header. Drop it; the
overflow it covered is tested directly on rte_tsc_to_ns().

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c  | 145 ++--------------------------------------
 lib/pcapng/rte_pcapng.c |  63 +++--------------
 2 files changed, 12 insertions(+), 196 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 688b58794e..3e190888b6 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -467,47 +467,6 @@ valid_pcapng_file(const char *file_name, uint64_t started, unsigned int expected
 	return ret;
 }
 
-/* Record the timestamp of the first packet in the file. */
-static void
-first_timestamp_cb(u_char *user, const struct pcap_pkthdr *h,
-		   const u_char *bytes __rte_unused)
-{
-	uint64_t *ts_ns = (uint64_t *)user;
-
-	/* File has nanosecond precision, so tv_usec holds ns. */
-	if (*ts_ns == 0)
-		*ts_ns = (uint64_t)h->ts.tv_sec * NS_PER_S + h->ts.tv_usec;
-}
-
-static int
-read_one_timestamp(const char *file_name, uint64_t *ts_ns)
-{
-	char errbuf[PCAP_ERRBUF_SIZE];
-	pcap_t *pcap;
-	int ret;
-
-	*ts_ns = 0;
-	pcap = pcap_open_offline_with_tstamp_precision(file_name,
-						       PCAP_TSTAMP_PRECISION_NANO,
-						       errbuf);
-	if (pcap == NULL) {
-		printf("pcap_open_offline('%s') failed: %s\n",
-			file_name, errbuf);
-		return -1;
-	}
-
-	ret = pcap_loop(pcap, 0, first_timestamp_cb, (u_char *)ts_ns);
-	if (ret != 0)
-		printf("pcap_loop: failed: %s\n", pcap_geterr(pcap));
-	pcap_close(pcap);
-
-	if (ret == 0 && *ts_ns == 0) {
-		printf("no packet found in %s\n", file_name);
-		return -1;
-	}
-	return ret;
-}
-
 static int
 test_add_interface(void)
 {
@@ -648,8 +607,8 @@ test_write_before_open(void)
 	mbuf1_prepare(&mbfs);
 	mbuf1_resize(&mbfs, rte_rand_max(MAX_DATA_SIZE));
 
-	/* Copy packets BEFORE opening the pcapng file.
-	 * This exercises the negative TSC delta path.
+	/* Copy packets BEFORE opening the pcapng file, so their
+	 * timestamps precede the capture start time.
 	 */
 	for (i = 0; i < (int)count; i++) {
 		clones[i] = rte_pcapng_copy(port_id, 0, &mbfs.mb[0], mp,
@@ -662,7 +621,7 @@ test_write_before_open(void)
 		}
 	}
 
-	/* Small delay so fdopen's tsc_base is measurably after the copies */
+	/* Small delay so the capture start is measurably after the copies */
 	rte_delay_us_block(100);
 
 	now = current_timestamp();
@@ -689,7 +648,7 @@ test_write_before_open(void)
 		goto fail;
 	}
 
-	/* Write the pre-captured packets — timestamps precede tsc_base */
+	/* Write the pre-captured packets */
 	len = rte_pcapng_write_packets(pcapng, clones, count);
 	rte_pktmbuf_free_bulk(clones, count);
 	if (len <= 0) {
@@ -721,101 +680,6 @@ test_cleanup(void)
 	rte_vdev_uninit(null_dev);
 }
 
-/*
- * Converting a cycle count to nanoseconds overflows past
- * UINT64_MAX / NS_PER_S cycles, which is only a few seconds of real
- * capture.  Forge the timestamp in the block header to reach large
- * deltas without waiting.
- */
-static int
-test_long_timestamp(void)
-{
-	/* seconds into the future */
-	static const unsigned int offsets[] = { 1, 8, 3600, 10 * 86400 };
-	struct pcapng_test_hdr {
-		uint32_t block_type;
-		uint32_t block_length;
-		uint32_t interface_id;
-		uint32_t timestamp_hi;
-		uint32_t timestamp_lo;
-	} *epb;
-	struct dummy_mbuf mbfs;
-	uint64_t hz = rte_get_tsc_hz();
-	unsigned int i;
-
-	TEST_ASSERT(hz != 0, "TSC frequency is zero");
-
-	mbuf1_prepare(&mbfs);
-	mbuf1_resize(&mbfs, 512);
-
-	for (i = 0; i < RTE_DIM(offsets); i++) {
-		char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
-		uint64_t cycles, base_ns, want_ns, got_ns, diff;
-		struct rte_mbuf *mc;
-		rte_pcapng_t *pcapng;
-		int ret, tmp_fd;
-		ssize_t len;
-
-		mc = rte_pcapng_copy(port_id, 0, &mbfs.mb[0], mp,
-				     rte_pktmbuf_pkt_len(&mbfs.mb[0]),
-				     RTE_PCAPNG_DIRECTION_IN, NULL);
-		TEST_ASSERT(mc != NULL, "rte_pcapng_copy failed");
-
-		tmp_fd = mkstemps(file_name, strlen(".pcapng"));
-		if (tmp_fd == -1) {
-			rte_pktmbuf_free(mc);
-			TEST_ASSERT(false, "mkstemps() failed");
-		}
-
-		base_ns = current_timestamp();
-		pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "longts", NULL);
-		if (pcapng == NULL) {
-			close(tmp_fd);
-			rte_pktmbuf_free(mc);
-			TEST_ASSERT(false, "rte_pcapng_fdopen failed");
-		}
-
-		ret = rte_pcapng_add_interface(pcapng, port_id, DLT_EN10MB,
-					       NULL, NULL, NULL);
-		if (ret < 0) {
-			rte_pcapng_close(pcapng);
-			rte_pktmbuf_free(mc);
-			TEST_ASSERT(false, "can not add port %u", port_id);
-		}
-
-		/* Conversion happens on write, so move the capture time. */
-		epb = rte_pktmbuf_mtod(mc, struct pcapng_test_hdr *);
-		cycles = (uint64_t)epb->timestamp_hi << 32;
-		cycles += epb->timestamp_lo;
-		cycles += (uint64_t)offsets[i] * hz;
-		epb->timestamp_hi = cycles >> 32;
-		epb->timestamp_lo = (uint32_t)cycles;
-
-		len = rte_pcapng_write_packets(pcapng, &mc, 1);
-		rte_pktmbuf_free(mc);
-		rte_pcapng_close(pcapng);
-		TEST_ASSERT(len > 0, "write failed at +%u s", offsets[i]);
-
-		ret = read_one_timestamp(file_name, &got_ns);
-		TEST_ASSERT(ret == 0, "can not read back +%u s", offsets[i]);
-
-		/* An overflow wraps and misses by the whole offset. */
-		want_ns = base_ns + (uint64_t)offsets[i] * NS_PER_S;
-		diff = (got_ns > want_ns) ? got_ns - want_ns : want_ns - got_ns;
-		if (diff > 2 * NS_PER_S)
-			printf("at +%u s: got %"PRIu64" want %"PRIu64"\n",
-			       offsets[i], got_ns, want_ns);
-		else
-			remove(file_name);
-
-		TEST_ASSERT(diff <= 2 * NS_PER_S,
-			    "timestamp off by %"PRIu64" ns at +%u s",
-			    diff, offsets[i]);
-	}
-
-	return 0;
-}
-
 static struct
 unit_test_suite test_pcapng_suite  = {
 	.setup = test_setup,
@@ -825,7 +689,6 @@ unit_test_suite test_pcapng_suite  = {
 		TEST_CASE(test_add_interface),
 		TEST_CASE(test_write_packets),
 		TEST_CASE(test_write_before_open),
-		TEST_CASE(test_long_timestamp),
 		TEST_CASES_END()
 	}
 };
diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index ce71b07d93..f09253ab94 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -40,8 +40,7 @@
 struct rte_pcapng {
 	int  outfd;		/* output file */
 	unsigned int ports;	/* number of interfaces added */
-	uint64_t offset_ns;	/* ns since 1/1/1970 when initialized */
-	uint64_t tsc_base;	/* TSC when started */
+	uint64_t start_time;	/* ns since 1/1/1970 when opened */
 
 	/* DPDK port id to interface index in file */
 	uint32_t port_index[RTE_MAX_ETHPORTS];
@@ -97,39 +96,6 @@ static ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
 #define if_indextoname(ifindex, ifname) NULL
 #endif
 
-/*
- * Convert a count of cycles to nanoseconds.
- *
- * Compute the whole seconds first, so that the remainder is always
- * less than the frequency and scaling it by NS_PER_S cannot wrap.
- */
-static uint64_t
-pcapng_cycles_to_ns(uint64_t delta)
-{
-	const uint64_t hz = rte_get_tsc_hz();
-	uint64_t secs = delta / hz;
-	uint64_t rem = delta % hz;
-
-	return secs * NS_PER_S + (rem * NS_PER_S) / hz;
-}
-
-/* Convert from TSC (CPU cycles) to nanoseconds */
-static uint64_t
-pcapng_timestamp(const rte_pcapng_t *self, uint64_t cycles)
-{
-	/*
-	 * A packet may be copied before the file was opened, so the TSC
-	 * can be behind the reference point.  Handle both directions on
-	 * an unsigned magnitude.
-	 */
-	if (unlikely(cycles < self->tsc_base))
-		return self->offset_ns -
-			pcapng_cycles_to_ns(self->tsc_base - cycles);
-
-	return self->offset_ns +
-		pcapng_cycles_to_ns(cycles - self->tsc_base);
-}
-
 /* length of option including padding */
 static uint16_t pcapng_optlen(uint16_t len)
 {
@@ -361,7 +327,7 @@ rte_pcapng_write_stats(rte_pcapng_t *self, uint16_t port_id,
 {
 	struct pcapng_statistics *hdr;
 	struct pcapng_option *opt;
-	uint64_t start_time = self->offset_ns;
+	uint64_t start_time = self->start_time;
 	uint64_t sample_time;
 	uint32_t optlen, len;
 	uint32_t *buf;
@@ -414,7 +380,7 @@ rte_pcapng_write_stats(rte_pcapng_t *self, uint16_t port_id,
 	hdr->block_length = len;
 	hdr->interface_id = self->port_index[port_id];
 
-	sample_time = pcapng_timestamp(self, rte_get_tsc_cycles());
+	sample_time = rte_tsc_to_ns(rte_get_tsc_cycles());
 	hdr->timestamp_hi = sample_time >> 32;
 	hdr->timestamp_lo = (uint32_t)sample_time;
 
@@ -652,10 +618,11 @@ rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 	/* Interface index is filled in later during write */
 	mc->port = port_id;
 
-	/* Put timestamp in cycles here - adjust in packet write */
-	timestamp = rte_get_tsc_cycles();
+	/* Put timestamp in nanoseconds */
+	timestamp = rte_tsc_to_ns(rte_get_tsc_cycles());
 	epb->timestamp_hi = timestamp >> 32;
 	epb->timestamp_lo = (uint32_t)timestamp;
+
 	epb->capture_length = pkt_len;
 	epb->original_length = orig_len;
 
@@ -682,7 +649,6 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 	for (i = 0; i < nb_pkts; i++) {
 		struct rte_mbuf *m = pkts[i];
 		struct pcapng_enhance_packet_block *epb;
-		uint64_t cycles, timestamp;
 
 		/* sanity check that is really a pcapng mbuf */
 		epb = rte_pktmbuf_mtod(m, struct pcapng_enhance_packet_block *);
@@ -699,13 +665,6 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 			return -1;
 		}
 
-		/* adjust timestamp recorded in packet */
-		cycles = (uint64_t)epb->timestamp_hi << 32;
-		cycles += epb->timestamp_lo;
-		timestamp = pcapng_timestamp(self, cycles);
-		epb->timestamp_hi = timestamp >> 32;
-		epb->timestamp_lo = (uint32_t)timestamp;
-
 		/*
 		 * The DPDK port is recorded during pcapng_copy.
 		 * Map that to PCAPNG interface in file.
@@ -747,8 +706,6 @@ rte_pcapng_fdopen(int fd,
 {
 	unsigned int i;
 	rte_pcapng_t *self;
-	struct timespec ts;
-	uint64_t cycles;
 	int ret;
 
 	if ((osname && strlen(osname) > PCAPNG_STR_MAX) ||
@@ -768,17 +725,13 @@ rte_pcapng_fdopen(int fd,
 	self->outfd = fd;
 	self->ports = 0;
 
-	/* If Hz is zero, something is seriously broken. */
+	/* Timestamps come from the TSC; if Hz is zero it is unusable. */
 	if (rte_get_tsc_hz() == 0) {
 		rte_errno = ENODEV;
 		goto fail;
 	}
 
-	/* record start time in ns since 1/1/1970 */
-	cycles = rte_get_tsc_cycles();
-	clock_gettime(CLOCK_REALTIME, &ts);
-	self->tsc_base = (cycles + rte_get_tsc_cycles()) / 2;
-	self->offset_ns = rte_timespec_to_ns(&ts);
+	self->start_time = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	for (i = 0; i < RTE_MAX_ETHPORTS; i++)
 		self->port_index[i] = UINT32_MAX;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH 5/7] pcapng: add user-supplied timestamp support
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                   ` (3 preceding siblings ...)
  2026-12-01 22:41 ` [PATCH 4/7] pcapng: use EAL TSC to epoch conversion Stephen Hemminger
@ 2026-12-01 22:41 ` Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 6/7] test/pcapng: compare timestamps in one clock domain Stephen Hemminger
                   ` (2 subsequent siblings)
  7 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev; +Cc: Dawid Wesierski, Marek Kasiewicz, Stephen Hemminger,
	Reshma Pattan

From: Dawid Wesierski <dawid.wesierski@intel.com>

An application may have a better time for a packet than the TSC at
copy time, for example a hardware Rx timestamp, but rte_pcapng_copy()
always timestamps with the TSC.

Add rte_pcapng_copy_ts(), which takes the time of the packet in
nanoseconds since the Unix epoch and stores it as given.
rte_pcapng_copy() becomes a wrapper that converts the TSC with
rte_tsc_to_ns() and passes the result, so both entry points share one
implementation.

rte_pcapng_copy() keeps its signature, so no API or ABI is broken and
no deprecation notice is needed. The new function is experimental.

Signed-off-by: Marek Kasiewicz <marek.kasiewicz@intel.com>
Signed-off-by: Dawid Wesierski <dawid.wesierski@intel.com>
Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c                 | 89 ++++++++++++++++++++++++++
 doc/guides/prog_guide/pcapng_lib.rst   |  4 ++
 doc/guides/rel_notes/release_27_03.rst |  7 ++
 lib/pcapng/rte_pcapng.c                | 39 +++++++----
 lib/pcapng/rte_pcapng.h                | 50 ++++++++++++++-
 5 files changed, 177 insertions(+), 12 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 3e190888b6..7e19aa4096 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -18,6 +18,7 @@
 #endif
 
 #include <rte_bus_vdev.h>
+#include <rte_errno.h>
 #include <rte_ethdev.h>
 #include <rte_ether.h>
 #include <rte_ip.h>
@@ -673,6 +674,93 @@ test_write_before_open(void)
 	return -1;
 }
 
+static int
+test_pcapng_timestamp(void)
+{
+	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
+	char errbuf[PCAP_ERRBUF_SIZE];
+	rte_pcapng_t *pcapng = NULL;
+	struct dummy_mbuf mbfs;
+	struct pcap_pkthdr h;
+	struct rte_mbuf *mc;
+	uint64_t pcap_ts, ns;
+	pcap_t *pcap;
+	int ret, tmp_fd;
+
+	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
+	if (tmp_fd == -1) {
+		perror("mkstemps() failure");
+		return -1;
+	}
+
+	pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "pcapng_ts_test", NULL);
+	if (pcapng == NULL) {
+		printf("rte_pcapng_fdopen failed\n");
+		close(tmp_fd);
+		goto fail;
+	}
+
+	ret = rte_pcapng_add_interface(pcapng, port_id, DLT_EN10MB, NULL, NULL, NULL);
+	if (ret < 0) {
+		printf("can not add port %u\n", port_id);
+		goto fail;
+	}
+
+	mbuf1_prepare(&mbfs);
+
+	/* One second ahead, so that it cannot be the TSC of the copy */
+	pcap_ts = current_timestamp() + NS_PER_S;
+	mc = rte_pcapng_copy_ts(port_id, 0, &mbfs.mb[0], mp,
+				rte_pktmbuf_pkt_len(&mbfs.mb[0]),
+				RTE_PCAPNG_DIRECTION_IN, "custom_ts", pcap_ts);
+	if (mc == NULL) {
+		printf("rte_pcapng_copy_ts failed\n");
+		goto fail;
+	}
+
+	ret = rte_pcapng_write_packets(pcapng, &mc, 1);
+	rte_pktmbuf_free(mc);
+	if (ret <= 0) {
+		printf("Write of custom timestamp packet failed\n");
+		goto fail;
+	}
+
+	rte_pcapng_close(pcapng);
+	pcapng = NULL;
+
+	pcap = pcap_open_offline_with_tstamp_precision(file_name,
+						       PCAP_TSTAMP_PRECISION_NANO,
+						       errbuf);
+	if (pcap == NULL) {
+		printf("pcap_open_offline failed: %s\n", errbuf);
+		goto fail;
+	}
+
+	if (pcap_next(pcap, &h) == NULL) {
+		printf("No packets in file\n");
+		pcap_close(pcap);
+		goto fail;
+	}
+	pcap_close(pcap);
+
+	/* With nanosecond precision, tv_usec holds nanoseconds. */
+	ns = (uint64_t)h.ts.tv_sec * NS_PER_S + h.ts.tv_usec;
+	if (ns != pcap_ts) {
+		printf("Timestamp mismatch: expected %"PRIu64" got %"PRIu64"\n",
+		       pcap_ts, ns);
+		goto fail;
+	}
+
+	remove(file_name);
+	return 0;
+
+fail:
+	if (pcapng)
+		rte_pcapng_close(pcapng);
+	remove(file_name);
+	return -1;
+}
+
 static void
 test_cleanup(void)
 {
@@ -689,6 +777,7 @@ unit_test_suite test_pcapng_suite  = {
 		TEST_CASE(test_add_interface),
 		TEST_CASE(test_write_packets),
 		TEST_CASE(test_write_before_open),
+		TEST_CASE(test_pcapng_timestamp),
 		TEST_CASES_END()
 	}
 };
diff --git a/doc/guides/prog_guide/pcapng_lib.rst b/doc/guides/prog_guide/pcapng_lib.rst
index d18ebdbd1f..598cc6c93b 100644
--- a/doc/guides/prog_guide/pcapng_lib.rst
+++ b/doc/guides/prog_guide/pcapng_lib.rst
@@ -32,6 +32,10 @@ to determine the lower bound based on MTU.
 Collecting packets is done in two parts.
 The function ``rte_pcapng_copy`` is used to format and copy mbuf data
 and ``rte_pcapng_write_packets`` writes a burst of packets to the output file.
+The timestamp of each packet is the TSC at the time of ``rte_pcapng_copy``.
+An application that has a better time for the packet,
+for example a hardware timestamp,
+can give it in nanoseconds to ``rte_pcapng_copy_ts`` instead.
 
 The function ``rte_pcapng_write_stats`` can be used
 to write statistics information into the output file.
diff --git a/doc/guides/rel_notes/release_27_03.rst b/doc/guides/rel_notes/release_27_03.rst
index 63bb5ad42d..726c5b1e3f 100644
--- a/doc/guides/rel_notes/release_27_03.rst
+++ b/doc/guides/rel_notes/release_27_03.rst
@@ -61,6 +61,13 @@ New Features
   to convert a TSC value into nanoseconds since 1/1/1970,
   using a reference point recorded during EAL initialization.
 
+* **Added pcapng support for user-supplied timestamps.**
+
+  Added the experimental ``rte_pcapng_copy_ts()`` function,
+  which takes the time of the packet in nanoseconds since the Unix epoch,
+  for example a hardware Rx timestamp.
+  ``rte_pcapng_copy()`` is unchanged and still uses the TSC at copy time.
+
 
 Removed Items
 -------------
diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index f09253ab94..d6f50c2fc0 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -473,20 +473,25 @@ pcapng_vlan_insert(struct rte_mbuf *m, uint16_t ether_type, uint16_t tci)
  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  */
 
-/* Make a copy of original mbuf with pcapng header and options */
-RTE_EXPORT_SYMBOL(rte_pcapng_copy)
+/*
+ * Make a copy of original mbuf with pcapng header and options.
+ *
+ * The timestamp is the caller's time of the packet, in nanoseconds
+ * since the Unix epoch, and is stored as given.
+ */
+RTE_EXPORT_EXPERIMENTAL_SYMBOL(rte_pcapng_copy_ts, 27.03)
 struct rte_mbuf *
-rte_pcapng_copy(uint16_t port_id, uint32_t queue,
-		const struct rte_mbuf *md,
-		struct rte_mempool *mp,
-		uint32_t length,
-		enum rte_pcapng_direction direction,
-		const char *comment)
+rte_pcapng_copy_ts(uint16_t port_id, uint32_t queue,
+		   const struct rte_mbuf *md,
+		   struct rte_mempool *mp,
+		   uint32_t length,
+		   enum rte_pcapng_direction direction,
+		   const char *comment,
+		   uint64_t timestamp)
 {
 	struct pcapng_enhance_packet_block *epb;
 	uint32_t orig_len, pkt_len, padding, flags;
 	struct pcapng_option *opt;
-	uint64_t timestamp;
 	uint16_t optlen;
 	struct rte_mbuf *mc;
 	bool rss_hash;
@@ -618,8 +623,6 @@ rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 	/* Interface index is filled in later during write */
 	mc->port = port_id;
 
-	/* Put timestamp in nanoseconds */
-	timestamp = rte_tsc_to_ns(rte_get_tsc_cycles());
 	epb->timestamp_hi = timestamp >> 32;
 	epb->timestamp_lo = (uint32_t)timestamp;
 
@@ -636,6 +639,20 @@ rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 	return NULL;
 }
 
+RTE_EXPORT_SYMBOL(rte_pcapng_copy)
+struct rte_mbuf *
+rte_pcapng_copy(uint16_t port_id, uint32_t queue,
+		const struct rte_mbuf *md,
+		struct rte_mempool *mp,
+		uint32_t length,
+		enum rte_pcapng_direction direction,
+		const char *comment)
+{
+	return rte_pcapng_copy_ts(port_id, queue, md, mp, length,
+				  direction, comment,
+				  rte_tsc_to_ns(rte_get_tsc_cycles()));
+}
+
 /* Write pre-formatted packets to file. */
 RTE_EXPORT_SYMBOL(rte_pcapng_write_packets)
 ssize_t
diff --git a/lib/pcapng/rte_pcapng.h b/lib/pcapng/rte_pcapng.h
index d8d328f710..647c9d6c2b 100644
--- a/lib/pcapng/rte_pcapng.h
+++ b/lib/pcapng/rte_pcapng.h
@@ -133,12 +133,60 @@ enum rte_pcapng_direction {
  * @return
  *   - The pointer to the new mbuf formatted for pcapng_write
  *   - NULL on error such as invalid port or out of memory.
+ *
+ * The packet is timestamped with the TSC at the time of the copy,
+ * converted to epoch time.
+ * Use rte_pcapng_copy_ts() to give the time of the packet directly.
  */
 struct rte_mbuf *
 rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 		const struct rte_mbuf *m, struct rte_mempool *mp,
 		uint32_t length,
-		enum rte_pcapng_direction direction, const char *comment);
+		enum rte_pcapng_direction direction,
+		const char *comment);
+
+/**
+ * @warning
+ * @b EXPERIMENTAL: this API may change without prior notice.
+ *
+ * Format an mbuf for writing to file, with the time of the packet.
+ *
+ * Same as rte_pcapng_copy(), except that the caller gives the time of
+ * the packet instead of it being taken from the TSC at copy time.
+ *
+ * @param port_id
+ *   The Ethernet port on which packet was received
+ *   or is going to be transmitted.
+ * @param queue
+ *   The queue on the Ethernet port where packet was received
+ *   or is going to be transmitted.
+ * @param mp
+ *   The mempool from which the "clone" mbufs are allocated.
+ * @param m
+ *   The mbuf to copy
+ * @param length
+ *   The upper limit on bytes to copy.  Passing UINT32_MAX
+ *   means all data (after offset).
+ * @param direction
+ *   The direction of the packet: receive, transmit or unknown.
+ * @param comment
+ *   Optional per packet comment.
+ *   Truncated to UINT16_MAX characters.
+ * @param timestamp
+ *   Time of the packet in nanoseconds since the Unix epoch,
+ *   for example a hardware timestamp.
+ *
+ * @return
+ *   - The pointer to the new mbuf formatted for pcapng_write
+ *   - NULL on error such as invalid port or out of memory.
+ */
+__rte_experimental
+struct rte_mbuf *
+rte_pcapng_copy_ts(uint16_t port_id, uint32_t queue,
+		   const struct rte_mbuf *m, struct rte_mempool *mp,
+		   uint32_t length,
+		   enum rte_pcapng_direction direction,
+		   const char *comment, uint64_t timestamp);
 
 
 /**
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH 6/7] test/pcapng: compare timestamps in one clock domain
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                   ` (4 preceding siblings ...)
  2026-12-01 22:41 ` [PATCH 5/7] pcapng: add user-supplied timestamp support Stephen Hemminger
@ 2026-12-01 22:41 ` Stephen Hemminger
  2026-12-01 22:41 ` [PATCH 7/7] pcapng: use stdio for output Stephen Hemminger
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
  7 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger, Reshma Pattan

The pcapng test bounded the packet timestamps it read back using
clock_gettime(CLOCK_REALTIME) sampled around the capture, but the
timestamps in the file come from the TSC converted with the reference
point EAL records at init. Comparing the two measures the drift
between the calibrated TSC rate and NTP's slewing of the wall clock,
which grows with process uptime. Packets were reported a few tens of
microseconds before the start of the window.

Bound the window with rte_tsc_to_ns() so both sides of the comparison
come from the same reference point.

What matters for analysis is the time between packets rather than the
absolute offset, so also check that the timestamps never go backwards.
A reference point that moved during the capture would show up as a
negative delta, which no test covered before.

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c | 30 ++++++++++++++++++++++++++----
 1 file changed, 26 insertions(+), 4 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 7e19aa4096..0cf5d469e5 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -350,6 +350,7 @@ struct pkt_print_ctx {
 	unsigned int count;
 	uint64_t start_ns;
 	uint64_t end_ns;
+	uint64_t prev_ns;
 };
 
 static void
@@ -398,6 +399,19 @@ parse_pcap_packet(u_char *user, const struct pcap_pkthdr *h,
 		goto error;
 	}
 
+	/*
+	 * Packets are stamped from the TSC and written in order, so the
+	 * time between them must never go backwards. A reference point
+	 * that moved mid-capture, for example by following a wall clock
+	 * step, would show up here as a negative delta.
+	 */
+	if (ns < ctx->prev_ns) {
+		printf("Timestamp went backwards by %"PRIu64" ns\n",
+		       ctx->prev_ns - ns);
+		goto error;
+	}
+	ctx->prev_ns = ns;
+
 	if (!rte_is_broadcast_ether_addr(&eh->dst_addr)) {
 		printf("Destination is not broadcast\n");
 		goto error;
@@ -441,8 +455,16 @@ valid_pcapng_file(const char *file_name, uint64_t started, unsigned int expected
 	struct pkt_print_ctx ctx = { };
 	int ret;
 
+	/*
+	 * Packet timestamps come from the TSC converted with the reference
+	 * point EAL took at init. Comparing them against CLOCK_REALTIME
+	 * read now would measure the drift between the calibrated TSC rate
+	 * and NTP's slewing of the wall clock, so bound the window using
+	 * the same conversion the library uses.
+	 */
 	ctx.start_ns = started;
-	ctx.end_ns = current_timestamp() + NS_PER_S;
+	ctx.end_ns = rte_tsc_to_ns(rte_get_tsc_cycles()) + NS_PER_S;
+	ctx.prev_ns = started;
 
 	ctx.pcap = pcap_open_offline_with_tstamp_precision(file_name,
 							   PCAP_TSTAMP_PRECISION_NANO,
@@ -474,7 +496,7 @@ test_add_interface(void)
 	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
 	static rte_pcapng_t *pcapng;
 	int ret, tmp_fd;
-	uint64_t now = current_timestamp();
+	uint64_t now = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
 	if (tmp_fd == -1) {
@@ -535,7 +557,7 @@ test_write_packets(void)
 	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
 	rte_pcapng_t *pcapng = NULL;
 	int ret, tmp_fd, count;
-	uint64_t now = current_timestamp();
+	uint64_t now = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
 	if (tmp_fd == -1) {
@@ -625,7 +647,7 @@ test_write_before_open(void)
 	/* Small delay so the capture start is measurably after the copies */
 	rte_delay_us_block(100);
 
-	now = current_timestamp();
+	now = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
 	if (tmp_fd == -1) {
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH 7/7] pcapng: use stdio for output
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                   ` (5 preceding siblings ...)
  2026-12-01 22:41 ` [PATCH 6/7] test/pcapng: compare timestamps in one clock domain Stephen Hemminger
@ 2026-12-01 22:41 ` Stephen Hemminger
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
  7 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-01 22:41 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger, Reshma Pattan, Dmitry Kozlyuk

The pcapng library was using writev to write directly to the file.
This optimizes the number of system calls but makes it hard to
support other output methods such as compression.

Add rte_pcapng_fopen() to open by stdio stream, and reimplement
rte_pcapng_fdopen() on top of it.

The stream created by rte_pcapng_fdopen() is fully buffered and
flushed at the end of each write call, so data is in the file when
the call returns as it was before. With rte_pcapng_fopen() the
application owns the stream and can call fflush() when needed, for
example for live readers like Wireshark.

Writing packets with rte_pcapng_write_packets now becomes
fully multi-thread safe.

Windows has the stdio locking functions under different names,
add shims for those and for dup().

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c                 | 112 ++++++++++++-
 doc/guides/rel_notes/release_27_03.rst |   6 +
 lib/eal/windows/include/rte_os_shim.h  |   6 +
 lib/pcapng/rte_pcapng.c                | 213 ++++++++++++++-----------
 lib/pcapng/rte_pcapng.h                |  50 +++++-
 5 files changed, 287 insertions(+), 100 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 0cf5d469e5..b39c5636f1 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -2,7 +2,9 @@
  * Copyright (c) 2021 Microsoft Corporation
  */
 
+#include <errno.h>
 #include <inttypes.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -551,8 +553,39 @@ test_add_interface(void)
 	return -1;
 }
 
+/* Open capture file with either rte_pcapng_fdopen() or rte_pcapng_fopen() */
+static rte_pcapng_t *
+open_pcapng(int tmp_fd, bool use_stdio, const char *appname)
+{
+	rte_pcapng_t *pcapng;
+	FILE *f;
+
+	if (!use_stdio) {
+		pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, appname, NULL);
+		if (pcapng == NULL) {
+			printf("rte_pcapng_fdopen failed: %s\n", rte_strerror(rte_errno));
+			close(tmp_fd);
+		}
+		return pcapng;
+	}
+
+	f = fdopen(tmp_fd, "wb");
+	if (f == NULL) {
+		perror("fdopen() failure");
+		close(tmp_fd);
+		return NULL;
+	}
+
+	pcapng = rte_pcapng_fopen(f, NULL, NULL, appname, NULL);
+	if (pcapng == NULL) {
+		printf("rte_pcapng_fopen failed: %s\n", rte_strerror(rte_errno));
+		fclose(f);
+	}
+	return pcapng;
+}
+
 static int
-test_write_packets(void)
+write_packets(bool use_stdio)
 {
 	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
 	rte_pcapng_t *pcapng = NULL;
@@ -567,12 +600,9 @@ test_write_packets(void)
 	printf("pcapng: output file %s\n", file_name);
 
 	/* open a test capture file */
-	pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "pcapng_test", NULL);
-	if (pcapng == NULL) {
-		printf("rte_pcapng_fdopen failed\n");
-		close(tmp_fd);
+	pcapng = open_pcapng(tmp_fd, use_stdio, "pcapng_test");
+	if (pcapng == NULL)
 		goto fail;
-	}
 
 	/* Add interface to the file */
 	ret = rte_pcapng_add_interface(pcapng, port_id, DLT_EN10MB,
@@ -615,6 +645,74 @@ test_write_packets(void)
 	return -1;
 }
 
+static int
+test_write_packets(void)
+{
+	return write_packets(false);
+}
+
+static int
+test_write_packets_fopen(void)
+{
+	return write_packets(true);
+}
+
+/*
+ * When open fails the caller still owns the file descriptor
+ * or stdio handle, it must not be closed by the library.
+ */
+static int
+test_open_fail(void)
+{
+	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
+	const size_t len = UINT16_MAX + 1;
+	rte_pcapng_t *pcapng;
+	char *comment;
+	FILE *f;
+	int tmp_fd;
+
+	pcapng = rte_pcapng_fopen(NULL, NULL, NULL, "pcapng_fail", NULL);
+	TEST_ASSERT_NULL(pcapng, "rte_pcapng_fopen(NULL) should fail");
+	TEST_ASSERT_EQUAL(rte_errno, EINVAL, "expected EINVAL got %d", rte_errno);
+
+	/* comment longer than pcapng option allows */
+	comment = malloc(len + 1);
+	TEST_ASSERT_NOT_NULL(comment, "malloc failed");
+	memset(comment, 'x', len);
+	comment[len] = '\0';
+
+	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
+	if (tmp_fd == -1) {
+		free(comment);
+		TEST_ASSERT(false, "mkstemps() failed");
+	}
+	remove(file_name);
+
+	pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "pcapng_fail", comment);
+	if (pcapng != NULL) {
+		rte_pcapng_close(pcapng);
+		free(comment);
+		TEST_ASSERT(false, "rte_pcapng_fdopen with long comment should fail");
+	}
+
+	f = fdopen(tmp_fd, "wb");
+	if (f == NULL) {
+		close(tmp_fd);
+		free(comment);
+		TEST_ASSERT(false, "fd closed by failed rte_pcapng_fdopen");
+	}
+
+	pcapng = rte_pcapng_fopen(f, NULL, NULL, "pcapng_fail", comment);
+	free(comment);
+	if (pcapng != NULL) {
+		rte_pcapng_close(pcapng);
+		TEST_ASSERT(false, "rte_pcapng_fopen with long comment should fail");
+	}
+
+	TEST_ASSERT_SUCCESS(fclose(f), "FILE closed by failed rte_pcapng_fopen");
+	return TEST_SUCCESS;
+}
+
 static int
 test_write_before_open(void)
 {
@@ -798,6 +896,8 @@ unit_test_suite test_pcapng_suite  = {
 	.unit_test_cases = {
 		TEST_CASE(test_add_interface),
 		TEST_CASE(test_write_packets),
+		TEST_CASE(test_write_packets_fopen),
+		TEST_CASE(test_open_fail),
 		TEST_CASE(test_write_before_open),
 		TEST_CASE(test_pcapng_timestamp),
 		TEST_CASES_END()
diff --git a/doc/guides/rel_notes/release_27_03.rst b/doc/guides/rel_notes/release_27_03.rst
index 726c5b1e3f..479d7bd7f9 100644
--- a/doc/guides/rel_notes/release_27_03.rst
+++ b/doc/guides/rel_notes/release_27_03.rst
@@ -68,6 +68,12 @@ New Features
   for example a hardware Rx timestamp.
   ``rte_pcapng_copy()`` is unchanged and still uses the TSC at copy time.
 
+* **Added pcapng API to capture to a stdio stream.**
+
+  Added the experimental ``rte_pcapng_fopen()`` function,
+  which takes an already open ``FILE *`` instead of a file descriptor.
+  This allows capturing to a pipe or a compressed stream.
+
 
 Removed Items
 -------------
diff --git a/lib/eal/windows/include/rte_os_shim.h b/lib/eal/windows/include/rte_os_shim.h
index 44664a5062..b55f365b69 100644
--- a/lib/eal/windows/include/rte_os_shim.h
+++ b/lib/eal/windows/include/rte_os_shim.h
@@ -34,6 +34,12 @@
 #define fileno(f) _fileno(f)
 #define isatty(fd) _isatty(fd)
 #define access(path, mode) _access(path, mode)
+#define dup(fd) _dup(fd)
+
+/* Windows spells the stdio locking functions with a leading underscore. */
+#define flockfile(f) _lock_file(f)
+#define funlockfile(f) _unlock_file(f)
+#define fwrite_unlocked(ptr, size, n, f) _fwrite_nolock(ptr, size, n, f)
 
 #define IPVERSION	4
 
diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index d6f50c2fc0..271b24cd41 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -12,7 +12,6 @@
 
 #ifndef RTE_EXEC_ENV_WINDOWS
 #include <net/if.h>
-#include <sys/uio.h>
 #endif
 
 #include <bus_driver.h>
@@ -33,12 +32,17 @@
 /* conversion from DPDK speed to PCAPNG */
 #define PCAPNG_MBPS_SPEED 1000000ull
 
+/* stream buffer size used by rte_pcapng_fdopen() */
+#define PCAPNG_BUF_SIZE	(64 * 1024)
+
 /* upper bound for strings in pcapng option data */
 #define PCAPNG_STR_MAX	UINT16_MAX
 
 /* Format of the capture file handle */
 struct rte_pcapng {
-	int  outfd;		/* output file */
+	FILE *outf;		/* output file */
+	int fd;			/* from rte_pcapng_fdopen(), else -1 */
+	bool autoflush;		/* flush the stream after each write */
 	unsigned int ports;	/* number of interfaces added */
 	uint64_t start_time;	/* ns since 1/1/1970 when opened */
 
@@ -47,50 +51,6 @@ struct rte_pcapng {
 };
 
 #ifdef RTE_EXEC_ENV_WINDOWS
-/*
- * Windows does not have writev() call.
- * Emulate this by copying to a new buffer.
- * The copy is necessary since pcapng needs to be thread-safe
- * and do atomic write operations.
- */
-
-#define IOV_MAX 128
-struct iovec {
-	void   *iov_base;
-	size_t  iov_len;
-};
-
-static ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
-{
-	size_t bytes = 0;
-	uint8_t *ptr;
-	void *tmp_buf;
-	ssize_t ret;
-	int i;
-
-	for (i = 0; i < iovcnt; i++)
-		bytes += iov[i].iov_len;
-
-	if (unlikely(bytes == 0))
-		return 0;
-
-	tmp_buf = malloc(bytes);
-	if (unlikely(tmp_buf == NULL)) {
-		errno = ENOMEM;
-		return -1;
-	}
-
-	ptr = tmp_buf;
-	for (i = 0; i < iovcnt; i++) {
-		rte_memcpy(ptr, iov[i].iov_base, iov[i].iov_len);
-		ptr += iov[i].iov_len;
-	}
-
-	ret = write(fd, tmp_buf, bytes);
-	free(tmp_buf);
-	return ret;
-}
-
 #define IF_NAMESIZE	16
 /* compatibility wrapper because name is optional */
 #define if_indextoname(ifindex, ifname) NULL
@@ -116,6 +76,22 @@ pcapng_add_option(struct pcapng_option *popt, uint16_t code,
 	return (struct pcapng_option *)((uint8_t *)popt + pcapng_optlen(len));
 }
 
+/* Write a whole block to the file. */
+static int
+pcapng_write_block(rte_pcapng_t *self, const void *buf, size_t len)
+{
+	if (fwrite(buf, len, 1, self->outf) != 1) {
+		rte_errno = errno;
+		return -1;
+	}
+
+	if (self->autoflush && fflush(self->outf) != 0) {
+		rte_errno = errno;
+		return -1;
+	}
+	return 0;
+}
+
 /*
  * Write required initial section header describing the capture
  */
@@ -145,8 +121,10 @@ pcapng_section_block(rte_pcapng_t *self,
 	len += sizeof(uint32_t);
 
 	buf = malloc(len);
-	if (buf == NULL)
-		return -ENOMEM;
+	if (buf == NULL) {
+		rte_errno = ENOMEM;
+		return -1;
+	}
 
 	hdr = (struct pcapng_section_header *)buf;
 	*hdr = (struct pcapng_section_header) {
@@ -179,9 +157,9 @@ pcapng_section_block(rte_pcapng_t *self,
 	/* clone block_length after option */
 	memcpy(opt, &hdr->block_length, sizeof(uint32_t));
 
-	ret = write(self->outfd, buf, len);
+	ret = pcapng_write_block(self, buf, len);
 	free(buf);
-	return ret < 0 ? -errno : 0;
+	return ret;
 }
 
 /* Write an interface block for a DPDK port */
@@ -306,14 +284,15 @@ rte_pcapng_add_interface(rte_pcapng_t *self, uint16_t port, uint16_t link_type,
 	/* clone block_length after options */
 	memcpy(opt, &hdr->block_length, sizeof(uint32_t));
 
-	ret = write(self->outfd, buf, len);
+	ret = pcapng_write_block(self, buf, len);
 	free(buf);
+	if (ret < 0)
+		return -1;
 
 	/* remember the file index only after successful write */
-	if (ret > 0)
-		self->port_index[port] = self->ports++;
+	self->port_index[port] = self->ports++;
 
-	return ret;
+	return len;
 }
 
 /*
@@ -387,9 +366,9 @@ rte_pcapng_write_stats(rte_pcapng_t *self, uint16_t port_id,
 	/* clone block_length after option */
 	memcpy(opt, &len, sizeof(uint32_t));
 
-	ret = write(self->outfd, buf, len);
+	ret = pcapng_write_block(self, buf, len);
 	free(buf);
-	return ret;
+	return ret < 0 ? -1 : (ssize_t)len;
 }
 
 RTE_EXPORT_SYMBOL(rte_pcapng_mbuf_size)
@@ -659,11 +638,12 @@ ssize_t
 rte_pcapng_write_packets(rte_pcapng_t *self,
 			 struct rte_mbuf *pkts[], uint16_t nb_pkts)
 {
-	struct iovec iov[IOV_MAX];
-	unsigned int i, cnt = 0;
-	ssize_t ret, total = 0;
+	FILE *outf = self->outf;
+	ssize_t total = 0;
 
-	for (i = 0; i < nb_pkts; i++) {
+	flockfile(outf);
+
+	for (unsigned int i = 0; i < nb_pkts; i++) {
 		struct rte_mbuf *m = pkts[i];
 		struct pcapng_enhance_packet_block *epb;
 
@@ -672,14 +652,14 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		if (unlikely(epb->block_type != PCAPNG_ENHANCED_PACKET_BLOCK ||
 			     epb->block_length != rte_pktmbuf_pkt_len(m))) {
 			rte_errno = EINVAL;
-			return -1;
+			goto fail;
 		}
 
 		/* check that this interface was added. */
 		epb->interface_id = self->port_index[m->port];
 		if (unlikely(epb->interface_id > RTE_MAX_ETHPORTS)) {
 			rte_errno = EINVAL;
-			return -1;
+			goto fail;
 		}
 
 		/*
@@ -687,45 +667,46 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		 * Map that to PCAPNG interface in file.
 		 */
 		do {
-			iov[cnt].iov_base = rte_pktmbuf_mtod(m, void *);
-			iov[cnt].iov_len = rte_pktmbuf_data_len(m);
-
-			/* If current iov is maxed out then send it */
-			if (++cnt == IOV_MAX) {
-				ret = writev(self->outfd, iov, cnt);
-				if (unlikely(ret < 0)) {
-					rte_errno = errno;
-					return -1;
-				}
-				cnt = 0;
-				total += ret;
+			size_t len = rte_pktmbuf_data_len(m);
+
+			if (unlikely(fwrite_unlocked(rte_pktmbuf_mtod(m, void *),
+						     1, len, outf) != len)) {
+				rte_errno = errno;
+				goto fail;
 			}
+			total += len;
 		} while ((m = m->next));
 	}
 
-	if (likely(cnt > 0)) {
-		ret = writev(self->outfd, iov, cnt);
-		if (unlikely(ret < 0)) {
-			rte_errno = errno;
-			return -1;
-		}
-		total += ret;
+	/*
+	 * Buffered data may still be short of the device, so the flush is
+	 * where a write error such as ENOSPC is seen.
+	 */
+	if (self->autoflush && unlikely(fflush(outf) != 0)) {
+		rte_errno = errno;
+		goto fail;
 	}
+
+	funlockfile(outf);
 	return total;
+
+fail:
+	funlockfile(outf);
+	return -1;
 }
 
 /* Create new pcapng writer handle */
-RTE_EXPORT_SYMBOL(rte_pcapng_fdopen)
+RTE_EXPORT_EXPERIMENTAL_SYMBOL(rte_pcapng_fopen, 27.03)
 rte_pcapng_t *
-rte_pcapng_fdopen(int fd,
-		  const char *osname, const char *hardware,
-		  const char *appname, const char *comment)
+rte_pcapng_fopen(FILE *f,
+		 const char *osname, const char *hardware,
+		 const char *appname, const char *comment)
 {
 	unsigned int i;
 	rte_pcapng_t *self;
-	int ret;
 
-	if ((osname && strlen(osname) > PCAPNG_STR_MAX) ||
+	if (f == NULL ||
+	    (osname && strlen(osname) > PCAPNG_STR_MAX) ||
 	    (hardware && strlen(hardware) > PCAPNG_STR_MAX) ||
 	    (appname && strlen(appname) > PCAPNG_STR_MAX) ||
 	    (comment && strlen(comment) > PCAPNG_STR_MAX)) {
@@ -739,7 +720,9 @@ rte_pcapng_fdopen(int fd,
 		return NULL;
 	}
 
-	self->outfd = fd;
+	self->outf = f;
+	self->fd = -1;
+	self->autoflush = false;
 	self->ports = 0;
 
 	/* Timestamps come from the TSC; if Hz is zero it is unusable. */
@@ -753,11 +736,8 @@ rte_pcapng_fdopen(int fd,
 	for (i = 0; i < RTE_MAX_ETHPORTS; i++)
 		self->port_index[i] = UINT32_MAX;
 
-	ret = pcapng_section_block(self, osname, hardware, appname, comment);
-	if (ret < 0) {
-		rte_errno = -ret;
+	if (pcapng_section_block(self, osname, hardware, appname, comment) < 0)
 		goto fail;
-	}
 
 	return self;
 fail:
@@ -765,12 +745,59 @@ rte_pcapng_fdopen(int fd,
 	return NULL;
 }
 
+RTE_EXPORT_SYMBOL(rte_pcapng_fdopen)
+rte_pcapng_t *
+rte_pcapng_fdopen(int fd,
+		  const char *osname, const char *hardware,
+		  const char *appname, const char *comment)
+{
+	rte_pcapng_t *self;
+	FILE *f;
+	int nfd;
+
+	/*
+	 * On failure the caller still owns fd and will close it,
+	 * so give stdio a duplicate that can be closed here.
+	 */
+	nfd = dup(fd);
+	if (nfd < 0) {
+		rte_errno = errno;
+		return NULL;
+	}
+
+	f = fdopen(nfd, "wb");
+	if (f == NULL) {
+		rte_errno = errno;
+		close(nfd);
+		return NULL;
+	}
+
+	/*
+	 * Buffer a whole burst rather than writing per mbuf segment, and
+	 * keep the previous behavior that data is in the file when the
+	 * write call returns by flushing at the end of each call.
+	 */
+	setvbuf(f, NULL, _IOFBF, PCAPNG_BUF_SIZE);
+
+	self = rte_pcapng_fopen(f, osname, hardware, appname, comment);
+	if (self == NULL) {
+		fclose(f);
+		return NULL;
+	}
+
+	self->fd = fd;
+	self->autoflush = true;
+	return self;
+}
+
 RTE_EXPORT_SYMBOL(rte_pcapng_close)
 void
 rte_pcapng_close(rte_pcapng_t *self)
 {
 	if (self) {
-		close(self->outfd);
+		fclose(self->outf);
+		if (self->fd >= 0)
+			close(self->fd);
 		free(self);
 	}
 }
diff --git a/lib/pcapng/rte_pcapng.h b/lib/pcapng/rte_pcapng.h
index 647c9d6c2b..2259b3e8ad 100644
--- a/lib/pcapng/rte_pcapng.h
+++ b/lib/pcapng/rte_pcapng.h
@@ -20,6 +20,7 @@
 #define _RTE_PCAPNG_H_
 
 #include <stdint.h>
+#include <stdio.h>
 #include <sys/types.h>
 
 #include <rte_mempool.h>
@@ -39,8 +40,12 @@ typedef struct rte_pcapng rte_pcapng_t;
 /**
  * Write data to existing open file
  *
+ * The stream is flushed after each write, so data is in the file
+ * when the write call returns.
+ *
  * @param fd
- *   file descriptor
+ *   file descriptor, closed by rte_pcapng_close().
+ *   On failure it is left open and the caller must close it.
  * @param osname
  *   Optional description of the operating system.
  *   Examples: "Debian 11", "Windows Server 22"
@@ -60,9 +65,43 @@ rte_pcapng_fdopen(int fd,
 		  const char *osname, const char *hardware,
 		  const char *appname, const char *comment);
 
+/**
+ * @warning
+ * @b EXPERIMENTAL: this API may change without prior notice.
+ *
+ * Write data to existing open file
+ *
+ * @param f
+ *   stdio file handle, closed by rte_pcapng_close().
+ *   On failure it is left open and the caller must close it.
+ * @param osname
+ *   Optional description of the operating system.
+ *   Examples: "Debian 11", "Windows Server 22"
+ * @param hardware
+ *   Optional description of the hardware used to create this file.
+ *   Examples: "x86 Virtual Machine"
+ * @param appname
+ *   Optional: application name recorded in the pcapng file.
+ *   Example: "dpdk-dumpcap 1.0 (DPDK 20.11)"
+ * @param comment
+ *   Optional comment to add to file header.
+ * @return
+ *   handle to library, or NULL in case of error (and rte_errno is set).
+ */
+__rte_experimental
+rte_pcapng_t *
+rte_pcapng_fopen(FILE *f,
+		 const char *osname, const char *hardware,
+		 const char *appname, const char *comment);
+
 /**
  * Close capture file
  *
+ * The stream is closed, which flushes anything still buffered.
+ * Errors from that final flush are not reported, so an application
+ * that needs to detect a full or failing device should call fflush()
+ * on its own stream before closing.
+ *
  * @param self
  *  handle to library
  */
@@ -211,6 +250,15 @@ rte_pcapng_mbuf_size(uint32_t length);
  * Do not pass original mbufs from transmit or receive
  * or file will be invalid pcapng format.
  *
+ * When opened with rte_pcapng_fdopen() the stream is flushed before
+ * returning, so the data is in the file.
+ * When opened with rte_pcapng_fopen() the stream's buffering is used,
+ * and the application can call fflush() when the data needs to
+ * be in the file, for example for a live reader.
+ *
+ * This function uses stdio locking, so multiple threads may write
+ * packets to the same handle.
+ *
  * @param self
  *  The handle to the packet capture file
  * @param pkts
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output
  2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                   ` (6 preceding siblings ...)
  2026-12-01 22:41 ` [PATCH 7/7] pcapng: use stdio for output Stephen Hemminger
@ 2026-12-02 17:49 ` Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 1/7] graph: fix double close of pcapng file Stephen Hemminger
                     ` (6 more replies)
  7 siblings, 7 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger

Mostly pcapng, with one graph fix and one EAL addition.

The first two patches are unrelated bug fixes marked for stable.

The user-timestamp patch is based on an earlier submission from Marek
Kasiewicz and Dawid Wesierski.

v2 - fix windows os shim

Dawid Wesierski (1):
  pcapng: add user-supplied timestamp support

Stephen Hemminger (6):
  graph: fix double close of pcapng file
  pcapng: call writev as needed on highly segmented mbuf
  eal: add function to convert TSC to epoch time
  pcapng: use EAL TSC to epoch conversion
  test/pcapng: compare timestamps in one clock domain
  pcapng: use stdio for output

 app/test/test_cycles.c                 |  34 +++
 app/test/test_pcapng.c                 | 356 +++++++++++++++----------
 doc/api/doxy-api-index.md              |   1 +
 doc/guides/prog_guide/pcapng_lib.rst   |   4 +
 doc/guides/rel_notes/release_27_03.rst |  19 ++
 lib/eal/common/eal_common_timer.c      |  59 ++++
 lib/eal/include/rte_time.h             |  34 +++
 lib/eal/windows/include/rte_os_shim.h  |   7 +
 lib/graph/graph_pcap.c                 |   4 +-
 lib/pcapng/rte_pcapng.c                | 314 +++++++++++-----------
 lib/pcapng/rte_pcapng.h                | 100 ++++++-
 11 files changed, 629 insertions(+), 303 deletions(-)

-- 
2.53.0


^ permalink raw reply	[flat|nested] 16+ messages in thread

* [PATCH v2 1/7] graph: fix double close of pcapng file
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
@ 2026-12-02 17:49   ` Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 2/7] pcapng: call writev as needed on highly segmented mbuf Stephen Hemminger
                     ` (5 subsequent siblings)
  6 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger, stable

If adding an interface to the capture file failed, the error path
called rte_pcapng_close(), which closes the file descriptor,
and then closed the same descriptor again.

Only close the descriptor directly if rte_pcapng_fdopen() failed.

Fixes: df5908c98abc ("graph: fix pcapng file support")
Cc: stable@dpdk.org

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 lib/graph/graph_pcap.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/lib/graph/graph_pcap.c b/lib/graph/graph_pcap.c
index 78859ec2d4..07678d967d 100644
--- a/lib/graph/graph_pcap.c
+++ b/lib/graph/graph_pcap.c
@@ -128,11 +128,13 @@ graph_pcap_file_open(const char *filename)
 done:
 	return 0;
 error:
+	/* once rte_pcapng_fdopen() succeeds, the fd is closed by rte_pcapng_close() */
 	if (pcapng_fd != NULL) {
 		rte_pcapng_close(pcapng_fd);
 		pcapng_fd = NULL;
+	} else {
+		close(fd);
 	}
-	close(fd);
 	return -1;
 }
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH v2 2/7] pcapng: call writev as needed on highly segmented mbuf
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 1/7] graph: fix double close of pcapng file Stephen Hemminger
@ 2026-12-02 17:49   ` Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 3/7] eal: add function to convert TSC to epoch time Stephen Hemminger
                     ` (4 subsequent siblings)
  6 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger, stable

It is possible to have an mbuf with more segments than the
max number of io vectors (1024 on Linux). This is an odd corner
case but it is allowed by DPDK since maximum number of segments
per mbuf is UINT16_MAX.

The old check assumed a single mbuf chain always fit in the
io vector, so a chain longer than IOV_MAX overran the stack
array. Consolidate the checks so now when io vector gets full
it is written. A packet may now be split across writev calls;
the previous flush at packet boundaries was incidental and not
a documented guarantee.

Bugzilla ID: 2133
Fixes: 0744f1c9f991 ("pcapng: fix write more packets than IOV_MAX limit")
Cc: stable@dpdk.org

Reported-by: Anthropic OSS scanner (ANT-2026-DC6DT4HP)
Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 lib/pcapng/rte_pcapng.c | 39 +++++++++++++++++++--------------------
 1 file changed, 19 insertions(+), 20 deletions(-)

diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index df38e4819c..ce71b07d93 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -706,20 +706,6 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		epb->timestamp_hi = timestamp >> 32;
 		epb->timestamp_lo = (uint32_t)timestamp;
 
-		/*
-		 * Handle case of highly fragmented and large burst size
-		 * Note: this assumes that max segments per mbuf < IOV_MAX
-		 */
-		if (unlikely(cnt + m->nb_segs >= IOV_MAX)) {
-			ret = writev(self->outfd, iov, cnt);
-			if (unlikely(ret < 0)) {
-				rte_errno = errno;
-				return -1;
-			}
-			total += ret;
-			cnt = 0;
-		}
-
 		/*
 		 * The DPDK port is recorded during pcapng_copy.
 		 * Map that to PCAPNG interface in file.
@@ -727,16 +713,29 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		do {
 			iov[cnt].iov_base = rte_pktmbuf_mtod(m, void *);
 			iov[cnt].iov_len = rte_pktmbuf_data_len(m);
-			++cnt;
+
+			/* If current iov is maxed out then send it */
+			if (++cnt == IOV_MAX) {
+				ret = writev(self->outfd, iov, cnt);
+				if (unlikely(ret < 0)) {
+					rte_errno = errno;
+					return -1;
+				}
+				cnt = 0;
+				total += ret;
+			}
 		} while ((m = m->next));
 	}
 
-	ret = writev(self->outfd, iov, cnt);
-	if (unlikely(ret < 0)) {
-		rte_errno = errno;
-		return -1;
+	if (likely(cnt > 0)) {
+		ret = writev(self->outfd, iov, cnt);
+		if (unlikely(ret < 0)) {
+			rte_errno = errno;
+			return -1;
+		}
+		total += ret;
 	}
-	return total + ret;
+	return total;
 }
 
 /* Create new pcapng writer handle */
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH v2 3/7] eal: add function to convert TSC to epoch time
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 1/7] graph: fix double close of pcapng file Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 2/7] pcapng: call writev as needed on highly segmented mbuf Stephen Hemminger
@ 2026-12-02 17:49   ` Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 4/7] pcapng: use EAL TSC to epoch conversion Stephen Hemminger
                     ` (3 subsequent siblings)
  6 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger

The pcapng library converts the TSC into nanoseconds since 1/1/1970,
because that is what the pcapng file format records. Nothing about
that conversion is specific to packet capture: it needs the TSC
frequency and a reference point relating the TSC to the wall clock,
both of which EAL already has or can take at init.

Record the TSC alongside a CLOCK_REALTIME reading while the TSC
frequency is being determined, and add rte_tsc_to_ns() to convert any
TSC value using that reference point. The seconds are computed before
the remainder is scaled, so the multiply by NS_PER_S cannot overflow.
A test converts values up to ten days out, where scaling the whole
cycle count would wrap.

The reference point is taken per process rather than shared through the
memory config, so a secondary process may differ from the primary by
the sampling error.

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_cycles.c                 | 34 +++++++++++++++
 doc/api/doxy-api-index.md              |  1 +
 doc/guides/rel_notes/release_27_03.rst |  6 +++
 lib/eal/common/eal_common_timer.c      | 59 ++++++++++++++++++++++++++
 lib/eal/include/rte_time.h             | 34 +++++++++++++++
 5 files changed, 134 insertions(+)

diff --git a/app/test/test_cycles.c b/app/test/test_cycles.c
index 68a31ac450..84ecd09fdb 100644
--- a/app/test/test_cycles.c
+++ b/app/test/test_cycles.c
@@ -2,11 +2,13 @@
  * Copyright(c) 2010-2014 Intel Corporation
  */
 
+#include <inttypes.h>
 #include <stdio.h>
 #include <stdint.h>
 
 #include <rte_common.h>
 #include <rte_cycles.h>
+#include <rte_time.h>
 
 #include "test.h"
 
@@ -54,3 +56,35 @@ test_user_delay_us(void)
 }
 
 REGISTER_FAST_TEST(user_delay_us, NOHUGE_OK, ASAN_OK, test_user_delay_us);
+
+/*
+ * Scaling a cycle count by NS_PER_S overflows past a few seconds worth
+ * of cycles, so check that converting a TSC value well into the future
+ * still advances by the expected amount.
+ */
+static int
+test_tsc_to_ns(void)
+{
+	static const unsigned int offsets[] = { 1, 8, 3600, 10 * 86400 };
+	uint64_t hz = rte_get_tsc_hz();
+	uint64_t tsc = rte_get_tsc_cycles();
+	uint64_t base = rte_tsc_to_ns(tsc);
+	unsigned int i;
+
+	TEST_ASSERT(hz != 0, "TSC frequency is zero");
+
+	for (i = 0; i < RTE_DIM(offsets); i++) {
+		uint64_t want = (uint64_t)offsets[i] * NS_PER_S;
+		uint64_t got = rte_tsc_to_ns(tsc +
+				(uint64_t)offsets[i] * hz) - base;
+
+		/* Allow a nanosecond either way for the division. */
+		TEST_ASSERT(got + 1 >= want && got <= want + 1,
+			    "+%u s: got %"PRIu64" want %"PRIu64,
+			    offsets[i], got, want);
+	}
+
+	return 0;
+}
+
+REGISTER_FAST_TEST(tsc_to_ns_autotest, NOHUGE_OK, ASAN_OK, test_tsc_to_ns);
diff --git a/doc/api/doxy-api-index.md b/doc/api/doxy-api-index.md
index 974f2d48ab..62d5db1b3b 100644
--- a/doc/api/doxy-api-index.md
+++ b/doc/api/doxy-api-index.md
@@ -81,6 +81,7 @@ The public API headers are grouped by topics:
 
 - **timers**:
   [cycles](@ref rte_cycles.h),
+  [time](@ref rte_time.h),
   [timer](@ref rte_timer.h),
   [alarm](@ref rte_alarm.h)
 
diff --git a/doc/guides/rel_notes/release_27_03.rst b/doc/guides/rel_notes/release_27_03.rst
index a91813faca..63bb5ad42d 100644
--- a/doc/guides/rel_notes/release_27_03.rst
+++ b/doc/guides/rel_notes/release_27_03.rst
@@ -55,6 +55,12 @@ New Features
      Also, make sure to start the actual text at the margin.
      =======================================================
 
+* **Added API to convert TSC to epoch time.**
+
+  Added the experimental ``rte_tsc_to_ns()`` function in ``rte_time.h``
+  to convert a TSC value into nanoseconds since 1/1/1970,
+  using a reference point recorded during EAL initialization.
+
 
 Removed Items
 -------------
diff --git a/lib/eal/common/eal_common_timer.c b/lib/eal/common/eal_common_timer.c
index 67ede70c62..e1871189ea 100644
--- a/lib/eal/common/eal_common_timer.c
+++ b/lib/eal/common/eal_common_timer.c
@@ -8,8 +8,10 @@
 #include <rte_common.h>
 #include <rte_log.h>
 #include <rte_cycles.h>
+#include <rte_os_shim.h>
 #include <rte_pause.h>
 #include <rte_eal.h>
+#include <rte_time.h>
 
 #include <eal_export.h>
 #include "eal_private.h"
@@ -18,6 +20,10 @@
 /* The frequency of the RDTSC timer resolution */
 static uint64_t eal_tsc_resolution_hz;
 
+/* Reference point relating the TSC to the wall clock, taken at init */
+static uint64_t eal_tsc_base;
+static uint64_t eal_epoch_ns;
+
 /* Pointer to user delay function */
 RTE_EXPORT_SYMBOL(rte_delay_us)
 void (*rte_delay_us)(unsigned int) = NULL;
@@ -39,6 +45,36 @@ rte_get_tsc_hz(void)
 	return eal_tsc_resolution_hz;
 }
 
+/*
+ * Convert a count of cycles to nanoseconds.
+ *
+ * Compute the whole seconds first, so that the remainder is always
+ * less than the frequency and scaling it by NS_PER_S cannot overflow.
+ */
+static uint64_t
+cycles_to_ns(uint64_t cycles)
+{
+	uint64_t secs = cycles / eal_tsc_resolution_hz;
+	uint64_t rem = cycles % eal_tsc_resolution_hz;
+
+	return secs * NS_PER_S + (rem * NS_PER_S) / eal_tsc_resolution_hz;
+}
+
+RTE_EXPORT_EXPERIMENTAL_SYMBOL(rte_tsc_to_ns, 27.03)
+uint64_t
+rte_tsc_to_ns(uint64_t tsc)
+{
+	/*
+	 * A caller may convert a TSC value sampled before the reference
+	 * point was taken, so handle both directions on an unsigned
+	 * magnitude.
+	 */
+	if (unlikely(tsc < eal_tsc_base))
+		return eal_epoch_ns - cycles_to_ns(eal_tsc_base - tsc);
+
+	return eal_epoch_ns + cycles_to_ns(tsc - eal_tsc_base);
+}
+
 static uint64_t
 estimate_tsc_freq(void)
 {
@@ -52,6 +88,27 @@ estimate_tsc_freq(void)
 	return RTE_ALIGN_MUL_NEAR(rte_rdtsc() - start, CYC_PER_10MHZ);
 }
 
+/*
+ * Record the TSC value matching a wall clock reading, so that any TSC
+ * value can later be expressed as nanoseconds since the Unix epoch.
+ * Read the TSC either side of the clock to halve the sampling error.
+ */
+static void
+init_tsc_base(void)
+{
+	struct timespec ts;
+	uint64_t cycles;
+
+	cycles = rte_get_tsc_cycles();
+	if (clock_gettime(CLOCK_REALTIME, &ts) < 0) {
+		EAL_LOG(WARNING, "Could not read wall clock,"
+			" TSC to epoch conversion unavailable");
+		return;
+	}
+	eal_tsc_base = (cycles + rte_get_tsc_cycles()) / 2;
+	eal_epoch_ns = rte_timespec_to_ns(&ts);
+}
+
 int
 init_tsc_freq(void)
 {
@@ -71,6 +128,7 @@ init_tsc_freq(void)
 		}
 
 		eal_tsc_resolution_hz = mcfg->tsc_hz;
+		init_tsc_base();
 		return 0;
 	}
 
@@ -87,6 +145,7 @@ init_tsc_freq(void)
 	EAL_LOG(DEBUG, "TSC frequency is ~%" PRIu64 " KHz", freq / 1000);
 	eal_tsc_resolution_hz = freq;
 	mcfg->tsc_hz = freq;
+	init_tsc_base();
 	return 0;
 }
 
diff --git a/lib/eal/include/rte_time.h b/lib/eal/include/rte_time.h
index c5c3a233e4..3122e062ab 100644
--- a/lib/eal/include/rte_time.h
+++ b/lib/eal/include/rte_time.h
@@ -5,9 +5,17 @@
 #ifndef _RTE_TIME_H_
 #define _RTE_TIME_H_
 
+/**
+ * @file
+ *
+ * Time and cycle counter conversion.
+ */
+
 #include <stdint.h>
 #include <time.h>
 
+#include <rte_compat.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -102,6 +110,32 @@ rte_ns_to_timespec(uint64_t nsec)
 	return ts;
 }
 
+/**
+ * @warning
+ * @b EXPERIMENTAL: this API may change without prior notice.
+ *
+ * Convert a TSC value into nanoseconds since the Unix epoch.
+ *
+ * EAL records the TSC alongside a CLOCK_REALTIME reading during
+ * initialization, and this converts using that reference point and the
+ * TSC frequency.  Values sampled before initialization are also handled,
+ * and the result tracks the wall clock as it was at init: later changes
+ * to the system time are not reflected.
+ *
+ * Each process takes its own reference point, so values converted in a
+ * secondary process may differ from the primary by the sampling error.
+ *
+ * Must be called after rte_eal_init(), which fails if the TSC frequency
+ * cannot be determined.
+ *
+ * @param tsc
+ *   A value read from rte_get_tsc_cycles() or rte_rdtsc().
+ * @return
+ *   Nanoseconds since 1/1/1970.
+ */
+__rte_experimental
+uint64_t rte_tsc_to_ns(uint64_t tsc);
+
 #ifdef __cplusplus
 }
 #endif
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH v2 4/7] pcapng: use EAL TSC to epoch conversion
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                     ` (2 preceding siblings ...)
  2026-12-02 17:49   ` [PATCH v2 3/7] eal: add function to convert TSC to epoch time Stephen Hemminger
@ 2026-12-02 17:49   ` Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 5/7] pcapng: add user-supplied timestamp support Stephen Hemminger
                     ` (2 subsequent siblings)
  6 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger

The pcapng library carried its own TSC to nanoseconds conversion along
with the reference point it needs: the TSC and wall clock sampled when
the capture file was opened. EAL now records an equivalent reference
point at init and exposes rte_tsc_to_ns(), so the local copy is
redundant.

Convert timestamps with rte_tsc_to_ns() and drop the per-handle
reference point. The interface statistics block still reports when the
file was opened rather than when EAL started.

Timestamps are now converted when the packet is copied rather than
when it is written, so test_long_timestamp can no longer reach large
deltas by rewriting the cycle count in the block header. Drop it; the
overflow it covered is tested directly on rte_tsc_to_ns().

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c  | 145 ++--------------------------------------
 lib/pcapng/rte_pcapng.c |  63 +++--------------
 2 files changed, 12 insertions(+), 196 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 688b58794e..3e190888b6 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -467,47 +467,6 @@ valid_pcapng_file(const char *file_name, uint64_t started, unsigned int expected
 	return ret;
 }
 
-/* Record the timestamp of the first packet in the file. */
-static void
-first_timestamp_cb(u_char *user, const struct pcap_pkthdr *h,
-		   const u_char *bytes __rte_unused)
-{
-	uint64_t *ts_ns = (uint64_t *)user;
-
-	/* File has nanosecond precision, so tv_usec holds ns. */
-	if (*ts_ns == 0)
-		*ts_ns = (uint64_t)h->ts.tv_sec * NS_PER_S + h->ts.tv_usec;
-}
-
-static int
-read_one_timestamp(const char *file_name, uint64_t *ts_ns)
-{
-	char errbuf[PCAP_ERRBUF_SIZE];
-	pcap_t *pcap;
-	int ret;
-
-	*ts_ns = 0;
-	pcap = pcap_open_offline_with_tstamp_precision(file_name,
-						       PCAP_TSTAMP_PRECISION_NANO,
-						       errbuf);
-	if (pcap == NULL) {
-		printf("pcap_open_offline('%s') failed: %s\n",
-			file_name, errbuf);
-		return -1;
-	}
-
-	ret = pcap_loop(pcap, 0, first_timestamp_cb, (u_char *)ts_ns);
-	if (ret != 0)
-		printf("pcap_loop: failed: %s\n", pcap_geterr(pcap));
-	pcap_close(pcap);
-
-	if (ret == 0 && *ts_ns == 0) {
-		printf("no packet found in %s\n", file_name);
-		return -1;
-	}
-	return ret;
-}
-
 static int
 test_add_interface(void)
 {
@@ -648,8 +607,8 @@ test_write_before_open(void)
 	mbuf1_prepare(&mbfs);
 	mbuf1_resize(&mbfs, rte_rand_max(MAX_DATA_SIZE));
 
-	/* Copy packets BEFORE opening the pcapng file.
-	 * This exercises the negative TSC delta path.
+	/* Copy packets BEFORE opening the pcapng file, so their
+	 * timestamps precede the capture start time.
 	 */
 	for (i = 0; i < (int)count; i++) {
 		clones[i] = rte_pcapng_copy(port_id, 0, &mbfs.mb[0], mp,
@@ -662,7 +621,7 @@ test_write_before_open(void)
 		}
 	}
 
-	/* Small delay so fdopen's tsc_base is measurably after the copies */
+	/* Small delay so the capture start is measurably after the copies */
 	rte_delay_us_block(100);
 
 	now = current_timestamp();
@@ -689,7 +648,7 @@ test_write_before_open(void)
 		goto fail;
 	}
 
-	/* Write the pre-captured packets — timestamps precede tsc_base */
+	/* Write the pre-captured packets */
 	len = rte_pcapng_write_packets(pcapng, clones, count);
 	rte_pktmbuf_free_bulk(clones, count);
 	if (len <= 0) {
@@ -721,101 +680,6 @@ test_cleanup(void)
 	rte_vdev_uninit(null_dev);
 }
 
-/*
- * Converting a cycle count to nanoseconds overflows past
- * UINT64_MAX / NS_PER_S cycles, which is only a few seconds of real
- * capture.  Forge the timestamp in the block header to reach large
- * deltas without waiting.
- */
-static int
-test_long_timestamp(void)
-{
-	/* seconds into the future */
-	static const unsigned int offsets[] = { 1, 8, 3600, 10 * 86400 };
-	struct pcapng_test_hdr {
-		uint32_t block_type;
-		uint32_t block_length;
-		uint32_t interface_id;
-		uint32_t timestamp_hi;
-		uint32_t timestamp_lo;
-	} *epb;
-	struct dummy_mbuf mbfs;
-	uint64_t hz = rte_get_tsc_hz();
-	unsigned int i;
-
-	TEST_ASSERT(hz != 0, "TSC frequency is zero");
-
-	mbuf1_prepare(&mbfs);
-	mbuf1_resize(&mbfs, 512);
-
-	for (i = 0; i < RTE_DIM(offsets); i++) {
-		char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
-		uint64_t cycles, base_ns, want_ns, got_ns, diff;
-		struct rte_mbuf *mc;
-		rte_pcapng_t *pcapng;
-		int ret, tmp_fd;
-		ssize_t len;
-
-		mc = rte_pcapng_copy(port_id, 0, &mbfs.mb[0], mp,
-				     rte_pktmbuf_pkt_len(&mbfs.mb[0]),
-				     RTE_PCAPNG_DIRECTION_IN, NULL);
-		TEST_ASSERT(mc != NULL, "rte_pcapng_copy failed");
-
-		tmp_fd = mkstemps(file_name, strlen(".pcapng"));
-		if (tmp_fd == -1) {
-			rte_pktmbuf_free(mc);
-			TEST_ASSERT(false, "mkstemps() failed");
-		}
-
-		base_ns = current_timestamp();
-		pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "longts", NULL);
-		if (pcapng == NULL) {
-			close(tmp_fd);
-			rte_pktmbuf_free(mc);
-			TEST_ASSERT(false, "rte_pcapng_fdopen failed");
-		}
-
-		ret = rte_pcapng_add_interface(pcapng, port_id, DLT_EN10MB,
-					       NULL, NULL, NULL);
-		if (ret < 0) {
-			rte_pcapng_close(pcapng);
-			rte_pktmbuf_free(mc);
-			TEST_ASSERT(false, "can not add port %u", port_id);
-		}
-
-		/* Conversion happens on write, so move the capture time. */
-		epb = rte_pktmbuf_mtod(mc, struct pcapng_test_hdr *);
-		cycles = (uint64_t)epb->timestamp_hi << 32;
-		cycles += epb->timestamp_lo;
-		cycles += (uint64_t)offsets[i] * hz;
-		epb->timestamp_hi = cycles >> 32;
-		epb->timestamp_lo = (uint32_t)cycles;
-
-		len = rte_pcapng_write_packets(pcapng, &mc, 1);
-		rte_pktmbuf_free(mc);
-		rte_pcapng_close(pcapng);
-		TEST_ASSERT(len > 0, "write failed at +%u s", offsets[i]);
-
-		ret = read_one_timestamp(file_name, &got_ns);
-		TEST_ASSERT(ret == 0, "can not read back +%u s", offsets[i]);
-
-		/* An overflow wraps and misses by the whole offset. */
-		want_ns = base_ns + (uint64_t)offsets[i] * NS_PER_S;
-		diff = (got_ns > want_ns) ? got_ns - want_ns : want_ns - got_ns;
-		if (diff > 2 * NS_PER_S)
-			printf("at +%u s: got %"PRIu64" want %"PRIu64"\n",
-			       offsets[i], got_ns, want_ns);
-		else
-			remove(file_name);
-
-		TEST_ASSERT(diff <= 2 * NS_PER_S,
-			    "timestamp off by %"PRIu64" ns at +%u s",
-			    diff, offsets[i]);
-	}
-
-	return 0;
-}
-
 static struct
 unit_test_suite test_pcapng_suite  = {
 	.setup = test_setup,
@@ -825,7 +689,6 @@ unit_test_suite test_pcapng_suite  = {
 		TEST_CASE(test_add_interface),
 		TEST_CASE(test_write_packets),
 		TEST_CASE(test_write_before_open),
-		TEST_CASE(test_long_timestamp),
 		TEST_CASES_END()
 	}
 };
diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index ce71b07d93..f09253ab94 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -40,8 +40,7 @@
 struct rte_pcapng {
 	int  outfd;		/* output file */
 	unsigned int ports;	/* number of interfaces added */
-	uint64_t offset_ns;	/* ns since 1/1/1970 when initialized */
-	uint64_t tsc_base;	/* TSC when started */
+	uint64_t start_time;	/* ns since 1/1/1970 when opened */
 
 	/* DPDK port id to interface index in file */
 	uint32_t port_index[RTE_MAX_ETHPORTS];
@@ -97,39 +96,6 @@ static ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
 #define if_indextoname(ifindex, ifname) NULL
 #endif
 
-/*
- * Convert a count of cycles to nanoseconds.
- *
- * Compute the whole seconds first, so that the remainder is always
- * less than the frequency and scaling it by NS_PER_S cannot wrap.
- */
-static uint64_t
-pcapng_cycles_to_ns(uint64_t delta)
-{
-	const uint64_t hz = rte_get_tsc_hz();
-	uint64_t secs = delta / hz;
-	uint64_t rem = delta % hz;
-
-	return secs * NS_PER_S + (rem * NS_PER_S) / hz;
-}
-
-/* Convert from TSC (CPU cycles) to nanoseconds */
-static uint64_t
-pcapng_timestamp(const rte_pcapng_t *self, uint64_t cycles)
-{
-	/*
-	 * A packet may be copied before the file was opened, so the TSC
-	 * can be behind the reference point.  Handle both directions on
-	 * an unsigned magnitude.
-	 */
-	if (unlikely(cycles < self->tsc_base))
-		return self->offset_ns -
-			pcapng_cycles_to_ns(self->tsc_base - cycles);
-
-	return self->offset_ns +
-		pcapng_cycles_to_ns(cycles - self->tsc_base);
-}
-
 /* length of option including padding */
 static uint16_t pcapng_optlen(uint16_t len)
 {
@@ -361,7 +327,7 @@ rte_pcapng_write_stats(rte_pcapng_t *self, uint16_t port_id,
 {
 	struct pcapng_statistics *hdr;
 	struct pcapng_option *opt;
-	uint64_t start_time = self->offset_ns;
+	uint64_t start_time = self->start_time;
 	uint64_t sample_time;
 	uint32_t optlen, len;
 	uint32_t *buf;
@@ -414,7 +380,7 @@ rte_pcapng_write_stats(rte_pcapng_t *self, uint16_t port_id,
 	hdr->block_length = len;
 	hdr->interface_id = self->port_index[port_id];
 
-	sample_time = pcapng_timestamp(self, rte_get_tsc_cycles());
+	sample_time = rte_tsc_to_ns(rte_get_tsc_cycles());
 	hdr->timestamp_hi = sample_time >> 32;
 	hdr->timestamp_lo = (uint32_t)sample_time;
 
@@ -652,10 +618,11 @@ rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 	/* Interface index is filled in later during write */
 	mc->port = port_id;
 
-	/* Put timestamp in cycles here - adjust in packet write */
-	timestamp = rte_get_tsc_cycles();
+	/* Put timestamp in nanoseconds */
+	timestamp = rte_tsc_to_ns(rte_get_tsc_cycles());
 	epb->timestamp_hi = timestamp >> 32;
 	epb->timestamp_lo = (uint32_t)timestamp;
+
 	epb->capture_length = pkt_len;
 	epb->original_length = orig_len;
 
@@ -682,7 +649,6 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 	for (i = 0; i < nb_pkts; i++) {
 		struct rte_mbuf *m = pkts[i];
 		struct pcapng_enhance_packet_block *epb;
-		uint64_t cycles, timestamp;
 
 		/* sanity check that is really a pcapng mbuf */
 		epb = rte_pktmbuf_mtod(m, struct pcapng_enhance_packet_block *);
@@ -699,13 +665,6 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 			return -1;
 		}
 
-		/* adjust timestamp recorded in packet */
-		cycles = (uint64_t)epb->timestamp_hi << 32;
-		cycles += epb->timestamp_lo;
-		timestamp = pcapng_timestamp(self, cycles);
-		epb->timestamp_hi = timestamp >> 32;
-		epb->timestamp_lo = (uint32_t)timestamp;
-
 		/*
 		 * The DPDK port is recorded during pcapng_copy.
 		 * Map that to PCAPNG interface in file.
@@ -747,8 +706,6 @@ rte_pcapng_fdopen(int fd,
 {
 	unsigned int i;
 	rte_pcapng_t *self;
-	struct timespec ts;
-	uint64_t cycles;
 	int ret;
 
 	if ((osname && strlen(osname) > PCAPNG_STR_MAX) ||
@@ -768,17 +725,13 @@ rte_pcapng_fdopen(int fd,
 	self->outfd = fd;
 	self->ports = 0;
 
-	/* If Hz is zero, something is seriously broken. */
+	/* Timestamps come from the TSC; if Hz is zero it is unusable. */
 	if (rte_get_tsc_hz() == 0) {
 		rte_errno = ENODEV;
 		goto fail;
 	}
 
-	/* record start time in ns since 1/1/1970 */
-	cycles = rte_get_tsc_cycles();
-	clock_gettime(CLOCK_REALTIME, &ts);
-	self->tsc_base = (cycles + rte_get_tsc_cycles()) / 2;
-	self->offset_ns = rte_timespec_to_ns(&ts);
+	self->start_time = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	for (i = 0; i < RTE_MAX_ETHPORTS; i++)
 		self->port_index[i] = UINT32_MAX;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH v2 5/7] pcapng: add user-supplied timestamp support
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                     ` (3 preceding siblings ...)
  2026-12-02 17:49   ` [PATCH v2 4/7] pcapng: use EAL TSC to epoch conversion Stephen Hemminger
@ 2026-12-02 17:49   ` Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 6/7] test/pcapng: compare timestamps in one clock domain Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 7/7] pcapng: use stdio for output Stephen Hemminger
  6 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Dawid Wesierski, Marek Kasiewicz, Stephen Hemminger

From: Dawid Wesierski <dawid.wesierski@intel.com>

An application may have a better time for a packet than the TSC at
copy time, for example a hardware Rx timestamp, but rte_pcapng_copy()
always timestamps with the TSC.

Add rte_pcapng_copy_ts(), which takes the time of the packet in
nanoseconds since the Unix epoch and stores it as given.
rte_pcapng_copy() becomes a wrapper that converts the TSC with
rte_tsc_to_ns() and passes the result, so both entry points share one
implementation.

rte_pcapng_copy() keeps its signature, so no API or ABI is broken and
no deprecation notice is needed. The new function is experimental.

Signed-off-by: Marek Kasiewicz <marek.kasiewicz@intel.com>
Signed-off-by: Dawid Wesierski <dawid.wesierski@intel.com>
Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c                 | 89 ++++++++++++++++++++++++++
 doc/guides/prog_guide/pcapng_lib.rst   |  4 ++
 doc/guides/rel_notes/release_27_03.rst |  7 ++
 lib/pcapng/rte_pcapng.c                | 39 +++++++----
 lib/pcapng/rte_pcapng.h                | 50 ++++++++++++++-
 5 files changed, 177 insertions(+), 12 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 3e190888b6..7e19aa4096 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -18,6 +18,7 @@
 #endif
 
 #include <rte_bus_vdev.h>
+#include <rte_errno.h>
 #include <rte_ethdev.h>
 #include <rte_ether.h>
 #include <rte_ip.h>
@@ -673,6 +674,93 @@ test_write_before_open(void)
 	return -1;
 }
 
+static int
+test_pcapng_timestamp(void)
+{
+	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
+	char errbuf[PCAP_ERRBUF_SIZE];
+	rte_pcapng_t *pcapng = NULL;
+	struct dummy_mbuf mbfs;
+	struct pcap_pkthdr h;
+	struct rte_mbuf *mc;
+	uint64_t pcap_ts, ns;
+	pcap_t *pcap;
+	int ret, tmp_fd;
+
+	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
+	if (tmp_fd == -1) {
+		perror("mkstemps() failure");
+		return -1;
+	}
+
+	pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "pcapng_ts_test", NULL);
+	if (pcapng == NULL) {
+		printf("rte_pcapng_fdopen failed\n");
+		close(tmp_fd);
+		goto fail;
+	}
+
+	ret = rte_pcapng_add_interface(pcapng, port_id, DLT_EN10MB, NULL, NULL, NULL);
+	if (ret < 0) {
+		printf("can not add port %u\n", port_id);
+		goto fail;
+	}
+
+	mbuf1_prepare(&mbfs);
+
+	/* One second ahead, so that it cannot be the TSC of the copy */
+	pcap_ts = current_timestamp() + NS_PER_S;
+	mc = rte_pcapng_copy_ts(port_id, 0, &mbfs.mb[0], mp,
+				rte_pktmbuf_pkt_len(&mbfs.mb[0]),
+				RTE_PCAPNG_DIRECTION_IN, "custom_ts", pcap_ts);
+	if (mc == NULL) {
+		printf("rte_pcapng_copy_ts failed\n");
+		goto fail;
+	}
+
+	ret = rte_pcapng_write_packets(pcapng, &mc, 1);
+	rte_pktmbuf_free(mc);
+	if (ret <= 0) {
+		printf("Write of custom timestamp packet failed\n");
+		goto fail;
+	}
+
+	rte_pcapng_close(pcapng);
+	pcapng = NULL;
+
+	pcap = pcap_open_offline_with_tstamp_precision(file_name,
+						       PCAP_TSTAMP_PRECISION_NANO,
+						       errbuf);
+	if (pcap == NULL) {
+		printf("pcap_open_offline failed: %s\n", errbuf);
+		goto fail;
+	}
+
+	if (pcap_next(pcap, &h) == NULL) {
+		printf("No packets in file\n");
+		pcap_close(pcap);
+		goto fail;
+	}
+	pcap_close(pcap);
+
+	/* With nanosecond precision, tv_usec holds nanoseconds. */
+	ns = (uint64_t)h.ts.tv_sec * NS_PER_S + h.ts.tv_usec;
+	if (ns != pcap_ts) {
+		printf("Timestamp mismatch: expected %"PRIu64" got %"PRIu64"\n",
+		       pcap_ts, ns);
+		goto fail;
+	}
+
+	remove(file_name);
+	return 0;
+
+fail:
+	if (pcapng)
+		rte_pcapng_close(pcapng);
+	remove(file_name);
+	return -1;
+}
+
 static void
 test_cleanup(void)
 {
@@ -689,6 +777,7 @@ unit_test_suite test_pcapng_suite  = {
 		TEST_CASE(test_add_interface),
 		TEST_CASE(test_write_packets),
 		TEST_CASE(test_write_before_open),
+		TEST_CASE(test_pcapng_timestamp),
 		TEST_CASES_END()
 	}
 };
diff --git a/doc/guides/prog_guide/pcapng_lib.rst b/doc/guides/prog_guide/pcapng_lib.rst
index d18ebdbd1f..598cc6c93b 100644
--- a/doc/guides/prog_guide/pcapng_lib.rst
+++ b/doc/guides/prog_guide/pcapng_lib.rst
@@ -32,6 +32,10 @@ to determine the lower bound based on MTU.
 Collecting packets is done in two parts.
 The function ``rte_pcapng_copy`` is used to format and copy mbuf data
 and ``rte_pcapng_write_packets`` writes a burst of packets to the output file.
+The timestamp of each packet is the TSC at the time of ``rte_pcapng_copy``.
+An application that has a better time for the packet,
+for example a hardware timestamp,
+can give it in nanoseconds to ``rte_pcapng_copy_ts`` instead.
 
 The function ``rte_pcapng_write_stats`` can be used
 to write statistics information into the output file.
diff --git a/doc/guides/rel_notes/release_27_03.rst b/doc/guides/rel_notes/release_27_03.rst
index 63bb5ad42d..726c5b1e3f 100644
--- a/doc/guides/rel_notes/release_27_03.rst
+++ b/doc/guides/rel_notes/release_27_03.rst
@@ -61,6 +61,13 @@ New Features
   to convert a TSC value into nanoseconds since 1/1/1970,
   using a reference point recorded during EAL initialization.
 
+* **Added pcapng support for user-supplied timestamps.**
+
+  Added the experimental ``rte_pcapng_copy_ts()`` function,
+  which takes the time of the packet in nanoseconds since the Unix epoch,
+  for example a hardware Rx timestamp.
+  ``rte_pcapng_copy()`` is unchanged and still uses the TSC at copy time.
+
 
 Removed Items
 -------------
diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index f09253ab94..d6f50c2fc0 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -473,20 +473,25 @@ pcapng_vlan_insert(struct rte_mbuf *m, uint16_t ether_type, uint16_t tci)
  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  */
 
-/* Make a copy of original mbuf with pcapng header and options */
-RTE_EXPORT_SYMBOL(rte_pcapng_copy)
+/*
+ * Make a copy of original mbuf with pcapng header and options.
+ *
+ * The timestamp is the caller's time of the packet, in nanoseconds
+ * since the Unix epoch, and is stored as given.
+ */
+RTE_EXPORT_EXPERIMENTAL_SYMBOL(rte_pcapng_copy_ts, 27.03)
 struct rte_mbuf *
-rte_pcapng_copy(uint16_t port_id, uint32_t queue,
-		const struct rte_mbuf *md,
-		struct rte_mempool *mp,
-		uint32_t length,
-		enum rte_pcapng_direction direction,
-		const char *comment)
+rte_pcapng_copy_ts(uint16_t port_id, uint32_t queue,
+		   const struct rte_mbuf *md,
+		   struct rte_mempool *mp,
+		   uint32_t length,
+		   enum rte_pcapng_direction direction,
+		   const char *comment,
+		   uint64_t timestamp)
 {
 	struct pcapng_enhance_packet_block *epb;
 	uint32_t orig_len, pkt_len, padding, flags;
 	struct pcapng_option *opt;
-	uint64_t timestamp;
 	uint16_t optlen;
 	struct rte_mbuf *mc;
 	bool rss_hash;
@@ -618,8 +623,6 @@ rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 	/* Interface index is filled in later during write */
 	mc->port = port_id;
 
-	/* Put timestamp in nanoseconds */
-	timestamp = rte_tsc_to_ns(rte_get_tsc_cycles());
 	epb->timestamp_hi = timestamp >> 32;
 	epb->timestamp_lo = (uint32_t)timestamp;
 
@@ -636,6 +639,20 @@ rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 	return NULL;
 }
 
+RTE_EXPORT_SYMBOL(rte_pcapng_copy)
+struct rte_mbuf *
+rte_pcapng_copy(uint16_t port_id, uint32_t queue,
+		const struct rte_mbuf *md,
+		struct rte_mempool *mp,
+		uint32_t length,
+		enum rte_pcapng_direction direction,
+		const char *comment)
+{
+	return rte_pcapng_copy_ts(port_id, queue, md, mp, length,
+				  direction, comment,
+				  rte_tsc_to_ns(rte_get_tsc_cycles()));
+}
+
 /* Write pre-formatted packets to file. */
 RTE_EXPORT_SYMBOL(rte_pcapng_write_packets)
 ssize_t
diff --git a/lib/pcapng/rte_pcapng.h b/lib/pcapng/rte_pcapng.h
index d8d328f710..647c9d6c2b 100644
--- a/lib/pcapng/rte_pcapng.h
+++ b/lib/pcapng/rte_pcapng.h
@@ -133,12 +133,60 @@ enum rte_pcapng_direction {
  * @return
  *   - The pointer to the new mbuf formatted for pcapng_write
  *   - NULL on error such as invalid port or out of memory.
+ *
+ * The packet is timestamped with the TSC at the time of the copy,
+ * converted to epoch time.
+ * Use rte_pcapng_copy_ts() to give the time of the packet directly.
  */
 struct rte_mbuf *
 rte_pcapng_copy(uint16_t port_id, uint32_t queue,
 		const struct rte_mbuf *m, struct rte_mempool *mp,
 		uint32_t length,
-		enum rte_pcapng_direction direction, const char *comment);
+		enum rte_pcapng_direction direction,
+		const char *comment);
+
+/**
+ * @warning
+ * @b EXPERIMENTAL: this API may change without prior notice.
+ *
+ * Format an mbuf for writing to file, with the time of the packet.
+ *
+ * Same as rte_pcapng_copy(), except that the caller gives the time of
+ * the packet instead of it being taken from the TSC at copy time.
+ *
+ * @param port_id
+ *   The Ethernet port on which packet was received
+ *   or is going to be transmitted.
+ * @param queue
+ *   The queue on the Ethernet port where packet was received
+ *   or is going to be transmitted.
+ * @param mp
+ *   The mempool from which the "clone" mbufs are allocated.
+ * @param m
+ *   The mbuf to copy
+ * @param length
+ *   The upper limit on bytes to copy.  Passing UINT32_MAX
+ *   means all data (after offset).
+ * @param direction
+ *   The direction of the packet: receive, transmit or unknown.
+ * @param comment
+ *   Optional per packet comment.
+ *   Truncated to UINT16_MAX characters.
+ * @param timestamp
+ *   Time of the packet in nanoseconds since the Unix epoch,
+ *   for example a hardware timestamp.
+ *
+ * @return
+ *   - The pointer to the new mbuf formatted for pcapng_write
+ *   - NULL on error such as invalid port or out of memory.
+ */
+__rte_experimental
+struct rte_mbuf *
+rte_pcapng_copy_ts(uint16_t port_id, uint32_t queue,
+		   const struct rte_mbuf *m, struct rte_mempool *mp,
+		   uint32_t length,
+		   enum rte_pcapng_direction direction,
+		   const char *comment, uint64_t timestamp);
 
 
 /**
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH v2 6/7] test/pcapng: compare timestamps in one clock domain
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                     ` (4 preceding siblings ...)
  2026-12-02 17:49   ` [PATCH v2 5/7] pcapng: add user-supplied timestamp support Stephen Hemminger
@ 2026-12-02 17:49   ` Stephen Hemminger
  2026-12-02 17:49   ` [PATCH v2 7/7] pcapng: use stdio for output Stephen Hemminger
  6 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger

The pcapng test bounded the packet timestamps it read back using
clock_gettime(CLOCK_REALTIME) sampled around the capture, but the
timestamps in the file come from the TSC converted with the reference
point EAL records at init. Comparing the two measures the drift
between the calibrated TSC rate and NTP's slewing of the wall clock,
which grows with process uptime. Packets were reported a few tens of
microseconds before the start of the window.

Bound the window with rte_tsc_to_ns() so both sides of the comparison
come from the same reference point.

What matters for analysis is the time between packets rather than the
absolute offset, so also check that the timestamps never go backwards.
A reference point that moved during the capture would show up as a
negative delta, which no test covered before.

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c | 30 ++++++++++++++++++++++++++----
 1 file changed, 26 insertions(+), 4 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 7e19aa4096..0cf5d469e5 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -350,6 +350,7 @@ struct pkt_print_ctx {
 	unsigned int count;
 	uint64_t start_ns;
 	uint64_t end_ns;
+	uint64_t prev_ns;
 };
 
 static void
@@ -398,6 +399,19 @@ parse_pcap_packet(u_char *user, const struct pcap_pkthdr *h,
 		goto error;
 	}
 
+	/*
+	 * Packets are stamped from the TSC and written in order, so the
+	 * time between them must never go backwards. A reference point
+	 * that moved mid-capture, for example by following a wall clock
+	 * step, would show up here as a negative delta.
+	 */
+	if (ns < ctx->prev_ns) {
+		printf("Timestamp went backwards by %"PRIu64" ns\n",
+		       ctx->prev_ns - ns);
+		goto error;
+	}
+	ctx->prev_ns = ns;
+
 	if (!rte_is_broadcast_ether_addr(&eh->dst_addr)) {
 		printf("Destination is not broadcast\n");
 		goto error;
@@ -441,8 +455,16 @@ valid_pcapng_file(const char *file_name, uint64_t started, unsigned int expected
 	struct pkt_print_ctx ctx = { };
 	int ret;
 
+	/*
+	 * Packet timestamps come from the TSC converted with the reference
+	 * point EAL took at init. Comparing them against CLOCK_REALTIME
+	 * read now would measure the drift between the calibrated TSC rate
+	 * and NTP's slewing of the wall clock, so bound the window using
+	 * the same conversion the library uses.
+	 */
 	ctx.start_ns = started;
-	ctx.end_ns = current_timestamp() + NS_PER_S;
+	ctx.end_ns = rte_tsc_to_ns(rte_get_tsc_cycles()) + NS_PER_S;
+	ctx.prev_ns = started;
 
 	ctx.pcap = pcap_open_offline_with_tstamp_precision(file_name,
 							   PCAP_TSTAMP_PRECISION_NANO,
@@ -474,7 +496,7 @@ test_add_interface(void)
 	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
 	static rte_pcapng_t *pcapng;
 	int ret, tmp_fd;
-	uint64_t now = current_timestamp();
+	uint64_t now = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
 	if (tmp_fd == -1) {
@@ -535,7 +557,7 @@ test_write_packets(void)
 	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
 	rte_pcapng_t *pcapng = NULL;
 	int ret, tmp_fd, count;
-	uint64_t now = current_timestamp();
+	uint64_t now = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
 	if (tmp_fd == -1) {
@@ -625,7 +647,7 @@ test_write_before_open(void)
 	/* Small delay so the capture start is measurably after the copies */
 	rte_delay_us_block(100);
 
-	now = current_timestamp();
+	now = rte_tsc_to_ns(rte_get_tsc_cycles());
 
 	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
 	if (tmp_fd == -1) {
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH v2 7/7] pcapng: use stdio for output
  2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
                     ` (5 preceding siblings ...)
  2026-12-02 17:49   ` [PATCH v2 6/7] test/pcapng: compare timestamps in one clock domain Stephen Hemminger
@ 2026-12-02 17:49   ` Stephen Hemminger
  6 siblings, 0 replies; 16+ messages in thread
From: Stephen Hemminger @ 2026-12-02 17:49 UTC (permalink / raw)
  To: dev; +Cc: Stephen Hemminger

The pcapng library was using writev to write directly to the file.
This optimizes the number of system calls but makes it hard to
support other output methods such as compression.

Add rte_pcapng_fopen() to open by stdio stream, and reimplement
rte_pcapng_fdopen() on top of it.

The stream created by rte_pcapng_fdopen() is fully buffered and
flushed at the end of each write call, so data is in the file when
the call returns as it was before. With rte_pcapng_fopen() the
application owns the stream and can call fflush() when needed, for
example for live readers like Wireshark.

Writing packets with rte_pcapng_write_packets now becomes
fully multi-thread safe.

Windows has the stdio locking functions under different names, and
deprecates the POSIX spelling of dup() and fdopen(), so add shims
for those.

Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
 app/test/test_pcapng.c                 | 112 ++++++++++++-
 doc/guides/rel_notes/release_27_03.rst |   6 +
 lib/eal/windows/include/rte_os_shim.h  |   7 +
 lib/pcapng/rte_pcapng.c                | 213 ++++++++++++++-----------
 lib/pcapng/rte_pcapng.h                |  50 +++++-
 5 files changed, 288 insertions(+), 100 deletions(-)

diff --git a/app/test/test_pcapng.c b/app/test/test_pcapng.c
index 0cf5d469e5..b39c5636f1 100644
--- a/app/test/test_pcapng.c
+++ b/app/test/test_pcapng.c
@@ -2,7 +2,9 @@
  * Copyright (c) 2021 Microsoft Corporation
  */
 
+#include <errno.h>
 #include <inttypes.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -551,8 +553,39 @@ test_add_interface(void)
 	return -1;
 }
 
+/* Open capture file with either rte_pcapng_fdopen() or rte_pcapng_fopen() */
+static rte_pcapng_t *
+open_pcapng(int tmp_fd, bool use_stdio, const char *appname)
+{
+	rte_pcapng_t *pcapng;
+	FILE *f;
+
+	if (!use_stdio) {
+		pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, appname, NULL);
+		if (pcapng == NULL) {
+			printf("rte_pcapng_fdopen failed: %s\n", rte_strerror(rte_errno));
+			close(tmp_fd);
+		}
+		return pcapng;
+	}
+
+	f = fdopen(tmp_fd, "wb");
+	if (f == NULL) {
+		perror("fdopen() failure");
+		close(tmp_fd);
+		return NULL;
+	}
+
+	pcapng = rte_pcapng_fopen(f, NULL, NULL, appname, NULL);
+	if (pcapng == NULL) {
+		printf("rte_pcapng_fopen failed: %s\n", rte_strerror(rte_errno));
+		fclose(f);
+	}
+	return pcapng;
+}
+
 static int
-test_write_packets(void)
+write_packets(bool use_stdio)
 {
 	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
 	rte_pcapng_t *pcapng = NULL;
@@ -567,12 +600,9 @@ test_write_packets(void)
 	printf("pcapng: output file %s\n", file_name);
 
 	/* open a test capture file */
-	pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "pcapng_test", NULL);
-	if (pcapng == NULL) {
-		printf("rte_pcapng_fdopen failed\n");
-		close(tmp_fd);
+	pcapng = open_pcapng(tmp_fd, use_stdio, "pcapng_test");
+	if (pcapng == NULL)
 		goto fail;
-	}
 
 	/* Add interface to the file */
 	ret = rte_pcapng_add_interface(pcapng, port_id, DLT_EN10MB,
@@ -615,6 +645,74 @@ test_write_packets(void)
 	return -1;
 }
 
+static int
+test_write_packets(void)
+{
+	return write_packets(false);
+}
+
+static int
+test_write_packets_fopen(void)
+{
+	return write_packets(true);
+}
+
+/*
+ * When open fails the caller still owns the file descriptor
+ * or stdio handle, it must not be closed by the library.
+ */
+static int
+test_open_fail(void)
+{
+	char file_name[PATH_MAX] = "/tmp/pcapng_test_XXXXXX.pcapng";
+	const size_t len = UINT16_MAX + 1;
+	rte_pcapng_t *pcapng;
+	char *comment;
+	FILE *f;
+	int tmp_fd;
+
+	pcapng = rte_pcapng_fopen(NULL, NULL, NULL, "pcapng_fail", NULL);
+	TEST_ASSERT_NULL(pcapng, "rte_pcapng_fopen(NULL) should fail");
+	TEST_ASSERT_EQUAL(rte_errno, EINVAL, "expected EINVAL got %d", rte_errno);
+
+	/* comment longer than pcapng option allows */
+	comment = malloc(len + 1);
+	TEST_ASSERT_NOT_NULL(comment, "malloc failed");
+	memset(comment, 'x', len);
+	comment[len] = '\0';
+
+	tmp_fd = mkstemps(file_name, strlen(".pcapng"));
+	if (tmp_fd == -1) {
+		free(comment);
+		TEST_ASSERT(false, "mkstemps() failed");
+	}
+	remove(file_name);
+
+	pcapng = rte_pcapng_fdopen(tmp_fd, NULL, NULL, "pcapng_fail", comment);
+	if (pcapng != NULL) {
+		rte_pcapng_close(pcapng);
+		free(comment);
+		TEST_ASSERT(false, "rte_pcapng_fdopen with long comment should fail");
+	}
+
+	f = fdopen(tmp_fd, "wb");
+	if (f == NULL) {
+		close(tmp_fd);
+		free(comment);
+		TEST_ASSERT(false, "fd closed by failed rte_pcapng_fdopen");
+	}
+
+	pcapng = rte_pcapng_fopen(f, NULL, NULL, "pcapng_fail", comment);
+	free(comment);
+	if (pcapng != NULL) {
+		rte_pcapng_close(pcapng);
+		TEST_ASSERT(false, "rte_pcapng_fopen with long comment should fail");
+	}
+
+	TEST_ASSERT_SUCCESS(fclose(f), "FILE closed by failed rte_pcapng_fopen");
+	return TEST_SUCCESS;
+}
+
 static int
 test_write_before_open(void)
 {
@@ -798,6 +896,8 @@ unit_test_suite test_pcapng_suite  = {
 	.unit_test_cases = {
 		TEST_CASE(test_add_interface),
 		TEST_CASE(test_write_packets),
+		TEST_CASE(test_write_packets_fopen),
+		TEST_CASE(test_open_fail),
 		TEST_CASE(test_write_before_open),
 		TEST_CASE(test_pcapng_timestamp),
 		TEST_CASES_END()
diff --git a/doc/guides/rel_notes/release_27_03.rst b/doc/guides/rel_notes/release_27_03.rst
index 726c5b1e3f..479d7bd7f9 100644
--- a/doc/guides/rel_notes/release_27_03.rst
+++ b/doc/guides/rel_notes/release_27_03.rst
@@ -68,6 +68,12 @@ New Features
   for example a hardware Rx timestamp.
   ``rte_pcapng_copy()`` is unchanged and still uses the TSC at copy time.
 
+* **Added pcapng API to capture to a stdio stream.**
+
+  Added the experimental ``rte_pcapng_fopen()`` function,
+  which takes an already open ``FILE *`` instead of a file descriptor.
+  This allows capturing to a pipe or a compressed stream.
+
 
 Removed Items
 -------------
diff --git a/lib/eal/windows/include/rte_os_shim.h b/lib/eal/windows/include/rte_os_shim.h
index 44664a5062..edef8eb283 100644
--- a/lib/eal/windows/include/rte_os_shim.h
+++ b/lib/eal/windows/include/rte_os_shim.h
@@ -34,6 +34,13 @@
 #define fileno(f) _fileno(f)
 #define isatty(fd) _isatty(fd)
 #define access(path, mode) _access(path, mode)
+#define dup(fd) _dup(fd)
+#define fdopen(fd, mode) _fdopen(fd, mode)
+
+/* Windows spells the stdio locking functions with a leading underscore. */
+#define flockfile(f) _lock_file(f)
+#define funlockfile(f) _unlock_file(f)
+#define fwrite_unlocked(ptr, size, n, f) _fwrite_nolock(ptr, size, n, f)
 
 #define IPVERSION	4
 
diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index d6f50c2fc0..271b24cd41 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -12,7 +12,6 @@
 
 #ifndef RTE_EXEC_ENV_WINDOWS
 #include <net/if.h>
-#include <sys/uio.h>
 #endif
 
 #include <bus_driver.h>
@@ -33,12 +32,17 @@
 /* conversion from DPDK speed to PCAPNG */
 #define PCAPNG_MBPS_SPEED 1000000ull
 
+/* stream buffer size used by rte_pcapng_fdopen() */
+#define PCAPNG_BUF_SIZE	(64 * 1024)
+
 /* upper bound for strings in pcapng option data */
 #define PCAPNG_STR_MAX	UINT16_MAX
 
 /* Format of the capture file handle */
 struct rte_pcapng {
-	int  outfd;		/* output file */
+	FILE *outf;		/* output file */
+	int fd;			/* from rte_pcapng_fdopen(), else -1 */
+	bool autoflush;		/* flush the stream after each write */
 	unsigned int ports;	/* number of interfaces added */
 	uint64_t start_time;	/* ns since 1/1/1970 when opened */
 
@@ -47,50 +51,6 @@ struct rte_pcapng {
 };
 
 #ifdef RTE_EXEC_ENV_WINDOWS
-/*
- * Windows does not have writev() call.
- * Emulate this by copying to a new buffer.
- * The copy is necessary since pcapng needs to be thread-safe
- * and do atomic write operations.
- */
-
-#define IOV_MAX 128
-struct iovec {
-	void   *iov_base;
-	size_t  iov_len;
-};
-
-static ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
-{
-	size_t bytes = 0;
-	uint8_t *ptr;
-	void *tmp_buf;
-	ssize_t ret;
-	int i;
-
-	for (i = 0; i < iovcnt; i++)
-		bytes += iov[i].iov_len;
-
-	if (unlikely(bytes == 0))
-		return 0;
-
-	tmp_buf = malloc(bytes);
-	if (unlikely(tmp_buf == NULL)) {
-		errno = ENOMEM;
-		return -1;
-	}
-
-	ptr = tmp_buf;
-	for (i = 0; i < iovcnt; i++) {
-		rte_memcpy(ptr, iov[i].iov_base, iov[i].iov_len);
-		ptr += iov[i].iov_len;
-	}
-
-	ret = write(fd, tmp_buf, bytes);
-	free(tmp_buf);
-	return ret;
-}
-
 #define IF_NAMESIZE	16
 /* compatibility wrapper because name is optional */
 #define if_indextoname(ifindex, ifname) NULL
@@ -116,6 +76,22 @@ pcapng_add_option(struct pcapng_option *popt, uint16_t code,
 	return (struct pcapng_option *)((uint8_t *)popt + pcapng_optlen(len));
 }
 
+/* Write a whole block to the file. */
+static int
+pcapng_write_block(rte_pcapng_t *self, const void *buf, size_t len)
+{
+	if (fwrite(buf, len, 1, self->outf) != 1) {
+		rte_errno = errno;
+		return -1;
+	}
+
+	if (self->autoflush && fflush(self->outf) != 0) {
+		rte_errno = errno;
+		return -1;
+	}
+	return 0;
+}
+
 /*
  * Write required initial section header describing the capture
  */
@@ -145,8 +121,10 @@ pcapng_section_block(rte_pcapng_t *self,
 	len += sizeof(uint32_t);
 
 	buf = malloc(len);
-	if (buf == NULL)
-		return -ENOMEM;
+	if (buf == NULL) {
+		rte_errno = ENOMEM;
+		return -1;
+	}
 
 	hdr = (struct pcapng_section_header *)buf;
 	*hdr = (struct pcapng_section_header) {
@@ -179,9 +157,9 @@ pcapng_section_block(rte_pcapng_t *self,
 	/* clone block_length after option */
 	memcpy(opt, &hdr->block_length, sizeof(uint32_t));
 
-	ret = write(self->outfd, buf, len);
+	ret = pcapng_write_block(self, buf, len);
 	free(buf);
-	return ret < 0 ? -errno : 0;
+	return ret;
 }
 
 /* Write an interface block for a DPDK port */
@@ -306,14 +284,15 @@ rte_pcapng_add_interface(rte_pcapng_t *self, uint16_t port, uint16_t link_type,
 	/* clone block_length after options */
 	memcpy(opt, &hdr->block_length, sizeof(uint32_t));
 
-	ret = write(self->outfd, buf, len);
+	ret = pcapng_write_block(self, buf, len);
 	free(buf);
+	if (ret < 0)
+		return -1;
 
 	/* remember the file index only after successful write */
-	if (ret > 0)
-		self->port_index[port] = self->ports++;
+	self->port_index[port] = self->ports++;
 
-	return ret;
+	return len;
 }
 
 /*
@@ -387,9 +366,9 @@ rte_pcapng_write_stats(rte_pcapng_t *self, uint16_t port_id,
 	/* clone block_length after option */
 	memcpy(opt, &len, sizeof(uint32_t));
 
-	ret = write(self->outfd, buf, len);
+	ret = pcapng_write_block(self, buf, len);
 	free(buf);
-	return ret;
+	return ret < 0 ? -1 : (ssize_t)len;
 }
 
 RTE_EXPORT_SYMBOL(rte_pcapng_mbuf_size)
@@ -659,11 +638,12 @@ ssize_t
 rte_pcapng_write_packets(rte_pcapng_t *self,
 			 struct rte_mbuf *pkts[], uint16_t nb_pkts)
 {
-	struct iovec iov[IOV_MAX];
-	unsigned int i, cnt = 0;
-	ssize_t ret, total = 0;
+	FILE *outf = self->outf;
+	ssize_t total = 0;
 
-	for (i = 0; i < nb_pkts; i++) {
+	flockfile(outf);
+
+	for (unsigned int i = 0; i < nb_pkts; i++) {
 		struct rte_mbuf *m = pkts[i];
 		struct pcapng_enhance_packet_block *epb;
 
@@ -672,14 +652,14 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		if (unlikely(epb->block_type != PCAPNG_ENHANCED_PACKET_BLOCK ||
 			     epb->block_length != rte_pktmbuf_pkt_len(m))) {
 			rte_errno = EINVAL;
-			return -1;
+			goto fail;
 		}
 
 		/* check that this interface was added. */
 		epb->interface_id = self->port_index[m->port];
 		if (unlikely(epb->interface_id > RTE_MAX_ETHPORTS)) {
 			rte_errno = EINVAL;
-			return -1;
+			goto fail;
 		}
 
 		/*
@@ -687,45 +667,46 @@ rte_pcapng_write_packets(rte_pcapng_t *self,
 		 * Map that to PCAPNG interface in file.
 		 */
 		do {
-			iov[cnt].iov_base = rte_pktmbuf_mtod(m, void *);
-			iov[cnt].iov_len = rte_pktmbuf_data_len(m);
-
-			/* If current iov is maxed out then send it */
-			if (++cnt == IOV_MAX) {
-				ret = writev(self->outfd, iov, cnt);
-				if (unlikely(ret < 0)) {
-					rte_errno = errno;
-					return -1;
-				}
-				cnt = 0;
-				total += ret;
+			size_t len = rte_pktmbuf_data_len(m);
+
+			if (unlikely(fwrite_unlocked(rte_pktmbuf_mtod(m, void *),
+						     1, len, outf) != len)) {
+				rte_errno = errno;
+				goto fail;
 			}
+			total += len;
 		} while ((m = m->next));
 	}
 
-	if (likely(cnt > 0)) {
-		ret = writev(self->outfd, iov, cnt);
-		if (unlikely(ret < 0)) {
-			rte_errno = errno;
-			return -1;
-		}
-		total += ret;
+	/*
+	 * Buffered data may still be short of the device, so the flush is
+	 * where a write error such as ENOSPC is seen.
+	 */
+	if (self->autoflush && unlikely(fflush(outf) != 0)) {
+		rte_errno = errno;
+		goto fail;
 	}
+
+	funlockfile(outf);
 	return total;
+
+fail:
+	funlockfile(outf);
+	return -1;
 }
 
 /* Create new pcapng writer handle */
-RTE_EXPORT_SYMBOL(rte_pcapng_fdopen)
+RTE_EXPORT_EXPERIMENTAL_SYMBOL(rte_pcapng_fopen, 27.03)
 rte_pcapng_t *
-rte_pcapng_fdopen(int fd,
-		  const char *osname, const char *hardware,
-		  const char *appname, const char *comment)
+rte_pcapng_fopen(FILE *f,
+		 const char *osname, const char *hardware,
+		 const char *appname, const char *comment)
 {
 	unsigned int i;
 	rte_pcapng_t *self;
-	int ret;
 
-	if ((osname && strlen(osname) > PCAPNG_STR_MAX) ||
+	if (f == NULL ||
+	    (osname && strlen(osname) > PCAPNG_STR_MAX) ||
 	    (hardware && strlen(hardware) > PCAPNG_STR_MAX) ||
 	    (appname && strlen(appname) > PCAPNG_STR_MAX) ||
 	    (comment && strlen(comment) > PCAPNG_STR_MAX)) {
@@ -739,7 +720,9 @@ rte_pcapng_fdopen(int fd,
 		return NULL;
 	}
 
-	self->outfd = fd;
+	self->outf = f;
+	self->fd = -1;
+	self->autoflush = false;
 	self->ports = 0;
 
 	/* Timestamps come from the TSC; if Hz is zero it is unusable. */
@@ -753,11 +736,8 @@ rte_pcapng_fdopen(int fd,
 	for (i = 0; i < RTE_MAX_ETHPORTS; i++)
 		self->port_index[i] = UINT32_MAX;
 
-	ret = pcapng_section_block(self, osname, hardware, appname, comment);
-	if (ret < 0) {
-		rte_errno = -ret;
+	if (pcapng_section_block(self, osname, hardware, appname, comment) < 0)
 		goto fail;
-	}
 
 	return self;
 fail:
@@ -765,12 +745,59 @@ rte_pcapng_fdopen(int fd,
 	return NULL;
 }
 
+RTE_EXPORT_SYMBOL(rte_pcapng_fdopen)
+rte_pcapng_t *
+rte_pcapng_fdopen(int fd,
+		  const char *osname, const char *hardware,
+		  const char *appname, const char *comment)
+{
+	rte_pcapng_t *self;
+	FILE *f;
+	int nfd;
+
+	/*
+	 * On failure the caller still owns fd and will close it,
+	 * so give stdio a duplicate that can be closed here.
+	 */
+	nfd = dup(fd);
+	if (nfd < 0) {
+		rte_errno = errno;
+		return NULL;
+	}
+
+	f = fdopen(nfd, "wb");
+	if (f == NULL) {
+		rte_errno = errno;
+		close(nfd);
+		return NULL;
+	}
+
+	/*
+	 * Buffer a whole burst rather than writing per mbuf segment, and
+	 * keep the previous behavior that data is in the file when the
+	 * write call returns by flushing at the end of each call.
+	 */
+	setvbuf(f, NULL, _IOFBF, PCAPNG_BUF_SIZE);
+
+	self = rte_pcapng_fopen(f, osname, hardware, appname, comment);
+	if (self == NULL) {
+		fclose(f);
+		return NULL;
+	}
+
+	self->fd = fd;
+	self->autoflush = true;
+	return self;
+}
+
 RTE_EXPORT_SYMBOL(rte_pcapng_close)
 void
 rte_pcapng_close(rte_pcapng_t *self)
 {
 	if (self) {
-		close(self->outfd);
+		fclose(self->outf);
+		if (self->fd >= 0)
+			close(self->fd);
 		free(self);
 	}
 }
diff --git a/lib/pcapng/rte_pcapng.h b/lib/pcapng/rte_pcapng.h
index 647c9d6c2b..2259b3e8ad 100644
--- a/lib/pcapng/rte_pcapng.h
+++ b/lib/pcapng/rte_pcapng.h
@@ -20,6 +20,7 @@
 #define _RTE_PCAPNG_H_
 
 #include <stdint.h>
+#include <stdio.h>
 #include <sys/types.h>
 
 #include <rte_mempool.h>
@@ -39,8 +40,12 @@ typedef struct rte_pcapng rte_pcapng_t;
 /**
  * Write data to existing open file
  *
+ * The stream is flushed after each write, so data is in the file
+ * when the write call returns.
+ *
  * @param fd
- *   file descriptor
+ *   file descriptor, closed by rte_pcapng_close().
+ *   On failure it is left open and the caller must close it.
  * @param osname
  *   Optional description of the operating system.
  *   Examples: "Debian 11", "Windows Server 22"
@@ -60,9 +65,43 @@ rte_pcapng_fdopen(int fd,
 		  const char *osname, const char *hardware,
 		  const char *appname, const char *comment);
 
+/**
+ * @warning
+ * @b EXPERIMENTAL: this API may change without prior notice.
+ *
+ * Write data to existing open file
+ *
+ * @param f
+ *   stdio file handle, closed by rte_pcapng_close().
+ *   On failure it is left open and the caller must close it.
+ * @param osname
+ *   Optional description of the operating system.
+ *   Examples: "Debian 11", "Windows Server 22"
+ * @param hardware
+ *   Optional description of the hardware used to create this file.
+ *   Examples: "x86 Virtual Machine"
+ * @param appname
+ *   Optional: application name recorded in the pcapng file.
+ *   Example: "dpdk-dumpcap 1.0 (DPDK 20.11)"
+ * @param comment
+ *   Optional comment to add to file header.
+ * @return
+ *   handle to library, or NULL in case of error (and rte_errno is set).
+ */
+__rte_experimental
+rte_pcapng_t *
+rte_pcapng_fopen(FILE *f,
+		 const char *osname, const char *hardware,
+		 const char *appname, const char *comment);
+
 /**
  * Close capture file
  *
+ * The stream is closed, which flushes anything still buffered.
+ * Errors from that final flush are not reported, so an application
+ * that needs to detect a full or failing device should call fflush()
+ * on its own stream before closing.
+ *
  * @param self
  *  handle to library
  */
@@ -211,6 +250,15 @@ rte_pcapng_mbuf_size(uint32_t length);
  * Do not pass original mbufs from transmit or receive
  * or file will be invalid pcapng format.
  *
+ * When opened with rte_pcapng_fdopen() the stream is flushed before
+ * returning, so the data is in the file.
+ * When opened with rte_pcapng_fopen() the stream's buffering is used,
+ * and the application can call fflush() when the data needs to
+ * be in the file, for example for a live reader.
+ *
+ * This function uses stdio locking, so multiple threads may write
+ * packets to the same handle.
+ *
  * @param self
  *  The handle to the packet capture file
  * @param pkts
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 16+ messages in thread

end of thread, other threads:[~2026-12-02 17:51 UTC | newest]

Thread overview: 16+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01 22:41 [PATCH 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
2026-12-01 22:41 ` [PATCH 1/7] graph: fix double close of pcapng file Stephen Hemminger
2026-12-01 22:41 ` [PATCH 2/7] pcapng: call writev as needed on highly segmented mbuf Stephen Hemminger
2026-12-01 22:41 ` [PATCH 3/7] eal: add function to convert TSC to epoch time Stephen Hemminger
2026-12-01 22:41 ` [PATCH 4/7] pcapng: use EAL TSC to epoch conversion Stephen Hemminger
2026-12-01 22:41 ` [PATCH 5/7] pcapng: add user-supplied timestamp support Stephen Hemminger
2026-12-01 22:41 ` [PATCH 6/7] test/pcapng: compare timestamps in one clock domain Stephen Hemminger
2026-12-01 22:41 ` [PATCH 7/7] pcapng: use stdio for output Stephen Hemminger
2026-12-02 17:49 ` [PATCH v2 0/7] pcapng: fixes, timestamps and stdio output Stephen Hemminger
2026-12-02 17:49   ` [PATCH v2 1/7] graph: fix double close of pcapng file Stephen Hemminger
2026-12-02 17:49   ` [PATCH v2 2/7] pcapng: call writev as needed on highly segmented mbuf Stephen Hemminger
2026-12-02 17:49   ` [PATCH v2 3/7] eal: add function to convert TSC to epoch time Stephen Hemminger
2026-12-02 17:49   ` [PATCH v2 4/7] pcapng: use EAL TSC to epoch conversion Stephen Hemminger
2026-12-02 17:49   ` [PATCH v2 5/7] pcapng: add user-supplied timestamp support Stephen Hemminger
2026-12-02 17:49   ` [PATCH v2 6/7] test/pcapng: compare timestamps in one clock domain Stephen Hemminger
2026-12-02 17:49   ` [PATCH v2 7/7] pcapng: use stdio for output Stephen Hemminger

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox